blob: 4ef21897ef6ee7306baf1626af3ab65b057087a8 [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;
Julia Reynolds5e458dd2014-07-07 16:07:01 -040021import java.util.HashMap;
Christopher Tate06efb532012-08-24 15:29:27 -070022import java.util.HashSet;
Amith Yamasani4f7e2e32014-08-14 18:49:48 -070023import java.util.List;
Julia Reynolds5e458dd2014-07-07 16:07:01 -040024import java.util.Map;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070025import java.util.concurrent.atomic.AtomicBoolean;
26import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070027
Christopher Tated5fe1472012-09-10 15:48:38 -070028import android.app.ActivityManager;
Dianne Hackborn961321f2013-02-05 17:22:41 -080029import android.app.AppOpsManager;
Christopher Tate45281862010-03-05 15:46:30 -080030import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070031import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentProvider;
33import android.content.ContentUris;
34import android.content.ContentValues;
35import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.Intent;
37import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070039import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070040import android.content.res.AssetFileDescriptor;
Christopher Tateafccaa82012-10-03 17:41:51 -070041import android.database.AbstractCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
43import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.database.sqlite.SQLiteQueryBuilder;
46import android.media.RingtoneManager;
47import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070048import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080049import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070050import android.os.DropBoxManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070051import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070053import android.os.Process;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.os.UserHandle;
56import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057import android.provider.MediaStore;
58import android.provider.Settings;
59import android.text.TextUtils;
60import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080061import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070062import android.util.Slog;
63import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070064
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065public class SettingsProvider extends ContentProvider {
66 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070067 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070068
Christopher Tate0da13572013-10-13 17:34:49 -070069 private static final boolean USER_CHECK_THROWS = true;
70
Christopher Tate06efb532012-08-24 15:29:27 -070071 private static final String TABLE_SYSTEM = "system";
72 private static final String TABLE_SECURE = "secure";
73 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 private static final String TABLE_FAVORITES = "favorites";
75 private static final String TABLE_OLD_FAVORITES = "old_favorites";
76
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080077 private static final String[] COLUMN_VALUE = new String[] { "value" };
78
Christopher Tate06efb532012-08-24 15:29:27 -070079 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080080 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070081 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070082 private static final SparseArray<SettingsCache> sSystemCaches
83 = new SparseArray<SettingsCache>();
84 private static final SparseArray<SettingsCache> sSecureCaches
85 = new SparseArray<SettingsCache>();
86 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070087
88 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070089 // database mutations are currently being handled for this user.
90 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070091 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070092 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
93 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080094
Christopher Tate78d2a662012-09-13 16:19:44 -070095 // Each defined user has their own settings
96 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
97
Amith Yamasani4f7e2e32014-08-14 18:49:48 -070098 // Keep the list of managed profiles synced here
99 private List<UserInfo> mManagedProfiles = null;
100
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800101 // Over this size we don't reject loading or saving settings but
102 // we do consider them broken/malicious and don't keep them in
103 // memory at least:
104 private static final int MAX_CACHE_ENTRY_SIZE = 500;
105
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800106 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
107
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700108 // Used as a sentinel value in an instance equality test when we
109 // want to cache the existence of a key, but not store its value.
110 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
111
Christopher Tate06efb532012-08-24 15:29:27 -0700112 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700113 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700114
115 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700116 * Settings which need to be treated as global/shared in multi-user environments.
117 */
118 static final HashSet<String> sSecureGlobalKeys;
119 static final HashSet<String> sSystemGlobalKeys;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700120
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400121 // Settings that cannot be modified if associated user restrictions are enabled.
122 static final Map<String, String> sRestrictedKeys;
123
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700124 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
125
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700126 static final HashSet<String> sSecureCloneToManagedKeys;
127 static final HashSet<String> sSystemCloneToManagedKeys;
128
Christopher Tate06efb532012-08-24 15:29:27 -0700129 static {
130 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
131 // table, shared across all users
132 // These must match Settings.Secure.MOVED_TO_GLOBAL
133 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700134 Settings.Secure.getMovedKeys(sSecureGlobalKeys);
Christopher Tate06efb532012-08-24 15:29:27 -0700135
136 // Keys from the 'system' table now moved to 'global'
137 // These must match Settings.System.MOVED_TO_GLOBAL
138 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate66488d62012-10-02 11:58:01 -0700139 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400140
141 sRestrictedKeys = new HashMap<String, String>();
142 sRestrictedKeys.put(Settings.Secure.LOCATION_MODE, UserManager.DISALLOW_SHARE_LOCATION);
143 sRestrictedKeys.put(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
144 UserManager.DISALLOW_SHARE_LOCATION);
Julia Reynolds25838502014-07-10 12:29:40 -0400145 sRestrictedKeys.put(Settings.Secure.INSTALL_NON_MARKET_APPS,
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400146 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
147 sRestrictedKeys.put(Settings.Global.ADB_ENABLED, UserManager.DISALLOW_DEBUGGING_FEATURES);
148 sRestrictedKeys.put(Settings.Global.PACKAGE_VERIFIER_ENABLE,
149 UserManager.ENSURE_VERIFY_APPS);
150 sRestrictedKeys.put(Settings.Global.PREFERRED_NETWORK_MODE,
151 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700152
153 sSecureCloneToManagedKeys = new HashSet<String>();
154 for (int i = 0; i < Settings.Secure.CLONE_TO_MANAGED_PROFILE.length; i++) {
155 sSecureCloneToManagedKeys.add(Settings.Secure.CLONE_TO_MANAGED_PROFILE[i]);
156 }
157 sSystemCloneToManagedKeys = new HashSet<String>();
158 for (int i = 0; i < Settings.System.CLONE_TO_MANAGED_PROFILE.length; i++) {
159 sSystemCloneToManagedKeys.add(Settings.System.CLONE_TO_MANAGED_PROFILE[i]);
160 }
Christopher Tate06efb532012-08-24 15:29:27 -0700161 }
162
163 private boolean settingMovedToGlobal(final String name) {
164 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
165 }
166
167 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700168 * Decode a content URL into the table, projection, and arguments
169 * used to access the corresponding database rows.
170 */
171 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700173 public final String where;
174 public final String[] args;
175
176 /** Operate on existing rows. */
177 SqlArguments(Uri url, String where, String[] args) {
178 if (url.getPathSegments().size() == 1) {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700179 // of the form content://settings/secure, arbitrary where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700180 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700181 if (!DatabaseHelper.isValidTable(this.table)) {
182 throw new IllegalArgumentException("Bad root path: " + this.table);
183 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700184 this.where = where;
185 this.args = args;
186 } else if (url.getPathSegments().size() != 2) {
187 throw new IllegalArgumentException("Invalid URI: " + url);
188 } else if (!TextUtils.isEmpty(where)) {
189 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
190 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700191 // of the form content://settings/secure/element_name, no where clause
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700192 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700193 if (!DatabaseHelper.isValidTable(this.table)) {
194 throw new IllegalArgumentException("Bad root path: " + this.table);
195 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700196 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
197 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700198 this.where = Settings.NameValueTable.NAME + "=?";
Christopher Tatec221d2b2012-10-03 18:33:52 -0700199 final String name = url.getPathSegments().get(1);
200 this.args = new String[] { name };
201 // Rewrite the table for known-migrated names
202 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
203 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
204 this.table = TABLE_GLOBAL;
205 }
206 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700207 } else {
Christopher Tatec221d2b2012-10-03 18:33:52 -0700208 // of the form content://bookmarks/19
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700209 this.where = "_id=" + ContentUris.parseId(url);
210 this.args = null;
211 }
212 }
213 }
214
215 /** Insert new rows (no where clause allowed). */
216 SqlArguments(Uri url) {
217 if (url.getPathSegments().size() == 1) {
218 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700219 if (!DatabaseHelper.isValidTable(this.table)) {
220 throw new IllegalArgumentException("Bad root path: " + this.table);
221 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700222 this.where = null;
223 this.args = null;
224 } else {
225 throw new IllegalArgumentException("Invalid URI: " + url);
226 }
227 }
228 }
229
230 /**
231 * Get the content URI of a row added to a table.
232 * @param tableUri of the entire table
233 * @param values found in the row
234 * @param rowId of the row
235 * @return the content URI for this particular row
236 */
237 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
238 if (tableUri.getPathSegments().size() != 1) {
239 throw new IllegalArgumentException("Invalid URI: " + tableUri);
240 }
241 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700242 if (TABLE_SYSTEM.equals(table) ||
243 TABLE_SECURE.equals(table) ||
244 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245 String name = values.getAsString(Settings.NameValueTable.NAME);
246 return Uri.withAppendedPath(tableUri, name);
247 } else {
248 return ContentUris.withAppendedId(tableUri, rowId);
249 }
250 }
251
252 /**
253 * Send a notification when a particular content URI changes.
254 * Modify the system property used to communicate the version of
255 * this table, for tables which have such a property. (The Settings
256 * contract class uses these to provide client-side caches.)
257 * @param uri to send notifications for
258 */
Christopher Tate06efb532012-08-24 15:29:27 -0700259 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 // Update the system property *first*, so if someone is listening for
261 // a notification and then using the contract class to get their data,
262 // the system property will be updated and they'll get the new data.
263
Amith Yamasanid1582142009-07-08 20:04:55 -0700264 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700265 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700266 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700267 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700268 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700269 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700270 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700271 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700272 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700273 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700274 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700275 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277
278 if (property != null) {
279 long version = SystemProperties.getLong(property, 0) + 1;
280 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
281 SystemProperties.set(property, Long.toString(version));
282 }
283
-b master501eec92009-07-06 13:53:11 -0700284 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700285 if (backedUpDataChanged) {
286 mBackupManager.dataChanged();
287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288 // Now send the notification through the content framework.
289
290 String notify = uri.getQueryParameter("notify");
291 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700292 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700293 final long oldId = Binder.clearCallingIdentity();
294 try {
295 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
296 } finally {
297 Binder.restoreCallingIdentity(oldId);
298 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700299 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700300 } else {
301 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
302 }
303 }
304
305 /**
306 * Make sure the caller has permission to write this data.
307 * @param args supplied by the caller
308 * @throws SecurityException if the caller is forbidden to write.
309 */
310 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700311 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800312 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800313 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
314 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700315 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800316 String.format("Permission denial: writing to secure settings requires %1$s",
317 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700318 }
319 }
320
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400321 private void checkUserRestrictions(String setting, int userId) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400322 String userRestriction = sRestrictedKeys.get(setting);
323 if (!TextUtils.isEmpty(userRestriction)
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400324 && mUserManager.hasUserRestriction(userRestriction, new UserHandle(userId))) {
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400325 throw new SecurityException(
326 "Permission denial: user is restricted from changing this setting.");
327 }
328 }
329
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700330 // FileObserver for external modifications to the database file.
331 // Note that this is for platform developers only with
332 // userdebug/eng builds who should be able to tinker with the
333 // sqlite database out from under the SettingsProvider, which is
334 // normally the exclusive owner of the database. But we keep this
335 // enabled all the time to minimize development-vs-user
336 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700337 private static SparseArray<SettingsFileObserver> sObserverInstances
338 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700339 private class SettingsFileObserver extends FileObserver {
340 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700341 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700342 private final String mPath;
343
Christopher Tate06efb532012-08-24 15:29:27 -0700344 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700345 super(path, FileObserver.CLOSE_WRITE |
346 FileObserver.CREATE | FileObserver.DELETE |
347 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700348 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700349 mPath = path;
350 }
351
352 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700353 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700354 if (modsInFlight > 0) {
355 // our own modification.
356 return;
357 }
Christopher Tate06efb532012-08-24 15:29:27 -0700358 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
359 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700360 if (!mIsDirty.compareAndSet(false, true)) {
361 // already handled. (we get a few update events
362 // during an sqlite write)
363 return;
364 }
Christopher Tate06efb532012-08-24 15:29:27 -0700365 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
366 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700367 mIsDirty.set(false);
368 }
369 }
370
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700371 @Override
372 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700373 mBackupManager = new BackupManager(getContext());
Amith Yamasani27db4682013-03-30 17:07:47 -0700374 mUserManager = UserManager.get(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800375
Dianne Hackborn961321f2013-02-05 17:22:41 -0800376 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS);
Christopher Tate78d2a662012-09-13 16:19:44 -0700377 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700378
Christopher Tate78d2a662012-09-13 16:19:44 -0700379 IntentFilter userFilter = new IntentFilter();
380 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700381 userFilter.addAction(Intent.ACTION_USER_ADDED);
Christopher Tate78d2a662012-09-13 16:19:44 -0700382 getContext().registerReceiver(new BroadcastReceiver() {
383 @Override
384 public void onReceive(Context context, Intent intent) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700385 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
386 UserHandle.USER_OWNER);
Christopher Tate78d2a662012-09-13 16:19:44 -0700387 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700388 onUserRemoved(userHandle);
389 } else if (intent.getAction().equals(Intent.ACTION_USER_ADDED)) {
390 onProfilesChanged();
Christopher Tate06efb532012-08-24 15:29:27 -0700391 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700392 }
393 }, userFilter);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700394
395 onProfilesChanged();
396
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700397 return true;
398 }
399
Christopher Tate06efb532012-08-24 15:29:27 -0700400 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700401 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700402 // the db file itself will be deleted automatically, but we need to tear down
403 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700404 FileObserver observer = sObserverInstances.get(userHandle);
405 if (observer != null) {
406 observer.stopWatching();
407 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700408 }
Christopher Tate06efb532012-08-24 15:29:27 -0700409
410 mOpenHelpers.delete(userHandle);
411 sSystemCaches.delete(userHandle);
412 sSecureCaches.delete(userHandle);
413 sKnownMutationsInFlight.delete(userHandle);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700414 onProfilesChanged();
415 }
416 }
417
418 /**
419 * Updates the list of managed profiles. It assumes that only the primary user
420 * can have managed profiles. Modify this code if that changes in the future.
421 */
422 void onProfilesChanged() {
423 synchronized (this) {
424 mManagedProfiles = mUserManager.getProfiles(UserHandle.USER_OWNER);
425 if (mManagedProfiles != null) {
426 // Remove the primary user from the list
427 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
428 if (mManagedProfiles.get(i).id == UserHandle.USER_OWNER) {
429 mManagedProfiles.remove(i);
430 }
431 }
432 // If there are no managed profiles, reset the variable
433 if (mManagedProfiles.size() == 0) {
434 mManagedProfiles = null;
435 }
436 }
437 if (LOCAL_LOGV) {
438 Slog.d(TAG, "Managed Profiles = " + mManagedProfiles);
439 }
Christopher Tate06efb532012-08-24 15:29:27 -0700440 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700441 }
442
Christopher Tate78d2a662012-09-13 16:19:44 -0700443 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700444 if (LOCAL_LOGV) {
445 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
446 }
447
Christopher Tate78d2a662012-09-13 16:19:44 -0700448 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700449
Christopher Tate78d2a662012-09-13 16:19:44 -0700450 synchronized (this) {
451 dbhelper = mOpenHelpers.get(userHandle);
452 if (dbhelper == null) {
453 dbhelper = new DatabaseHelper(getContext(), userHandle);
454 mOpenHelpers.append(userHandle, dbhelper);
455
456 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
457 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
458 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
459 }
460 }
461
462 // Initialization of the db *outside* the locks. It's possible that racing
463 // threads might wind up here, the second having read the cache entries
464 // written by the first, but that's benign: the SQLite helper implementation
465 // manages concurrency itself, and it's important that we not run the db
466 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700467 SQLiteDatabase db = dbhelper.getWritableDatabase();
468
Christopher Tate78d2a662012-09-13 16:19:44 -0700469 // Watch for external modifications to the database files,
470 // keeping our caches in sync. We synchronize the observer set
471 // separately, and of course it has to run after the db file
472 // itself was set up by the DatabaseHelper.
473 synchronized (sObserverInstances) {
474 if (sObserverInstances.get(userHandle) == null) {
475 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
476 sObserverInstances.append(userHandle, observer);
477 observer.startWatching();
478 }
479 }
Christopher Tate06efb532012-08-24 15:29:27 -0700480
Christopher Tate4dc7a682012-09-11 12:15:49 -0700481 ensureAndroidIdIsSet(userHandle);
482
Christopher Tate06efb532012-08-24 15:29:27 -0700483 startAsyncCachePopulation(userHandle);
484 }
485
486 class CachePrefetchThread extends Thread {
487 private int mUserHandle;
488
489 CachePrefetchThread(int userHandle) {
490 super("populate-settings-caches");
491 mUserHandle = userHandle;
492 }
493
494 @Override
495 public void run() {
496 fullyPopulateCaches(mUserHandle);
497 }
498 }
499
500 private void startAsyncCachePopulation(int userHandle) {
501 new CachePrefetchThread(userHandle).start();
502 }
503
504 private void fullyPopulateCaches(final int userHandle) {
505 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
506 // Only populate the globals cache once, for the owning user
507 if (userHandle == UserHandle.USER_OWNER) {
508 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
509 }
510 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
511 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700512 }
513
514 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700515 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
516 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700517 Cursor c = db.query(
518 table,
519 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
520 null, null, null, null, null,
521 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
522 try {
523 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800524 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700525 cache.setFullyMatchesDisk(true); // optimistic
526 int rows = 0;
527 while (c.moveToNext()) {
528 rows++;
529 String name = c.getString(0);
530 String value = c.getString(1);
531 cache.populate(name, value);
532 }
533 if (rows > MAX_CACHE_ENTRIES) {
534 // Somewhat redundant, as removeEldestEntry() will
535 // have already done this, but to be explicit:
536 cache.setFullyMatchesDisk(false);
537 Log.d(TAG, "row count exceeds max cache entries for table " + table);
538 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800539 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table
540 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk());
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700541 }
542 } finally {
543 c.close();
544 }
545 }
546
Christopher Tate4dc7a682012-09-11 12:15:49 -0700547 private boolean ensureAndroidIdIsSet(int userHandle) {
548 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800549 new String[] { Settings.NameValueTable.VALUE },
550 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700551 new String[] { Settings.Secure.ANDROID_ID }, null,
552 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800553 try {
554 final String value = c.moveToNext() ? c.getString(0) : null;
555 if (value == null) {
Christopher Tate38e7a602013-09-03 16:57:34 -0700556 // sanity-check the user before touching the db
557 final UserInfo user = mUserManager.getUserInfo(userHandle);
558 if (user == null) {
559 // can happen due to races when deleting users; treat as benign
560 return false;
561 }
562
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700563 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800564 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800565 final ContentValues values = new ContentValues();
566 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
567 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700568 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800569 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700570 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800571 return false;
572 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700573 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
574 + "] for user " + userHandle);
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700575 // Write a dropbox entry if it's a restricted profile
Christopher Tate38e7a602013-09-03 16:57:34 -0700576 if (user.isRestricted()) {
Amith Yamasani5cdf7f52013-06-27 15:12:01 -0700577 DropBoxManager dbm = (DropBoxManager)
578 getContext().getSystemService(Context.DROPBOX_SERVICE);
579 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
580 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
581 + ",restricted_profile_ssaid,"
582 + newAndroidIdValue + "\n");
583 }
584 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800585 }
586 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800587 } finally {
588 c.close();
589 }
590 }
591
Christopher Tate06efb532012-08-24 15:29:27 -0700592 // Lazy-initialize the settings caches for non-primary users
593 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700594 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
595 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700596 }
597
598 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700599 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate0da13572013-10-13 17:34:49 -0700600 if (callingUser >= Process.SYSTEM_UID) {
601 if (USER_CHECK_THROWS) {
602 throw new IllegalArgumentException("Uid rather than user handle: " + callingUser);
603 } else {
604 Slog.wtf(TAG, "establish db for uid rather than user: " + callingUser);
605 }
606 }
607
Christopher Tate06efb532012-08-24 15:29:27 -0700608 long oldId = Binder.clearCallingIdentity();
609 try {
610 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
611 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700612 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700613 dbHelper = mOpenHelpers.get(callingUser);
614 }
615 return dbHelper;
616 } finally {
617 Binder.restoreCallingIdentity(oldId);
618 }
619 }
620
621 public SettingsCache cacheForTable(final int callingUser, String tableName) {
622 if (TABLE_SYSTEM.equals(tableName)) {
623 return getOrConstructCache(callingUser, sSystemCaches);
624 }
625 if (TABLE_SECURE.equals(tableName)) {
626 return getOrConstructCache(callingUser, sSecureCaches);
627 }
628 if (TABLE_GLOBAL.equals(tableName)) {
629 return sGlobalCache;
630 }
631 return null;
632 }
633
634 /**
635 * Used for wiping a whole cache on deletes when we're not
636 * sure what exactly was deleted or changed.
637 */
638 public void invalidateCache(final int callingUser, String tableName) {
639 SettingsCache cache = cacheForTable(callingUser, tableName);
640 if (cache == null) {
641 return;
642 }
643 synchronized (cache) {
644 cache.evictAll();
645 cache.mCacheFullyMatchesDisk = false;
646 }
647 }
648
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800649 /**
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700650 * Checks if the calling user is a managed profile of the primary user.
651 * Currently only the primary user (USER_OWNER) can have managed profiles.
652 * @param callingUser the user trying to read/write settings
653 * @return true if it is a managed profile of the primary user
654 */
655 private boolean isManagedProfile(int callingUser) {
656 synchronized (this) {
657 if (mManagedProfiles == null) return false;
658 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
659 if (mManagedProfiles.get(i).id == callingUser) {
660 return true;
661 }
662 }
663 return false;
664 }
665 }
666
667 /**
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800668 * Fast path that avoids the use of chatty remoted Cursors.
669 */
670 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700671 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700672 int callingUser = UserHandle.getCallingUserId();
673 if (args != null) {
674 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
675 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700676 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
677 Binder.getCallingUid(), reqUser, false, true,
678 "get/set setting for user", null);
679 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700680 }
681 }
682
Christopher Tate61695ff2012-10-05 12:05:13 -0700683 // Note: we assume that get/put operations for moved-to-global names have already
684 // been directed to the new location on the caller side (otherwise we'd fix them
685 // up here).
686 DatabaseHelper dbHelper;
687 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700688
Christopher Tate61695ff2012-10-05 12:05:13 -0700689 // Get methods
690 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
691 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700692 if (isManagedProfile(callingUser) && sSystemCloneToManagedKeys.contains(request)) {
693 callingUser = UserHandle.USER_OWNER;
694 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700695 dbHelper = getOrEstablishDatabase(callingUser);
696 cache = sSystemCaches.get(callingUser);
697 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
698 }
699 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
700 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700701 if (isManagedProfile(callingUser) && sSecureCloneToManagedKeys.contains(request)) {
702 callingUser = UserHandle.USER_OWNER;
703 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700704 dbHelper = getOrEstablishDatabase(callingUser);
705 cache = sSecureCaches.get(callingUser);
706 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
707 }
708 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
709 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
710 // fast path: owner db & cache are immutable after onCreate() so we need not
711 // guard on the attempt to look them up
712 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
713 sGlobalCache, request);
714 }
Christopher Tate06efb532012-08-24 15:29:27 -0700715
Christopher Tate61695ff2012-10-05 12:05:13 -0700716 // Put methods - new value is in the args bundle under the key named by
717 // the Settings.NameValueTable.VALUE static.
718 final String newValue = (args == null)
Dianne Hackborn961321f2013-02-05 17:22:41 -0800719 ? null : args.getString(Settings.NameValueTable.VALUE);
720
721 // Framework can't do automatic permission checking for calls, so we need
722 // to do it here.
723 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.WRITE_SETTINGS)
724 != PackageManager.PERMISSION_GRANTED) {
725 throw new SecurityException(
726 String.format("Permission denial: writing to settings requires %1$s",
727 android.Manifest.permission.WRITE_SETTINGS));
728 }
729
730 // Also need to take care of app op.
731 if (getAppOpsManager().noteOp(AppOpsManager.OP_WRITE_SETTINGS, Binder.getCallingUid(),
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700732 getCallingPackage()) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn961321f2013-02-05 17:22:41 -0800733 return null;
734 }
Christopher Tate06efb532012-08-24 15:29:27 -0700735
Christopher Tate61695ff2012-10-05 12:05:13 -0700736 final ContentValues values = new ContentValues();
737 values.put(Settings.NameValueTable.NAME, request);
738 values.put(Settings.NameValueTable.VALUE, newValue);
739 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700740 if (LOCAL_LOGV) {
741 Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for "
742 + callingUser);
743 }
744 // Extra check for USER_OWNER to optimize for the 99%
745 if (callingUser != UserHandle.USER_OWNER && isManagedProfile(callingUser)) {
746 if (sSystemCloneToManagedKeys.contains(request)) {
747 // Don't write these settings
748 return null;
749 }
750 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700751 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700752 // Clone the settings to the managed profiles so that notifications can be sent out
753 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
754 && sSystemCloneToManagedKeys.contains(request)) {
755 final long token = Binder.clearCallingIdentity();
756 try {
757 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
758 if (LOCAL_LOGV) {
759 Slog.v(TAG, "putting to additional user "
760 + mManagedProfiles.get(i).id);
761 }
762 insertForUser(Settings.System.CONTENT_URI, values,
763 mManagedProfiles.get(i).id);
764 }
765 } finally {
766 Binder.restoreCallingIdentity(token);
767 }
768 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700769 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700770 if (LOCAL_LOGV) {
771 Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for "
772 + callingUser);
773 }
774 // Extra check for USER_OWNER to optimize for the 99%
775 if (callingUser != UserHandle.USER_OWNER && isManagedProfile(callingUser)) {
776 if (sSecureCloneToManagedKeys.contains(request)) {
777 // Don't write these settings
778 return null;
779 }
780 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700781 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700782 // Clone the settings to the managed profiles so that notifications can be sent out
783 if (callingUser == UserHandle.USER_OWNER && mManagedProfiles != null
784 && sSecureCloneToManagedKeys.contains(request)) {
785 final long token = Binder.clearCallingIdentity();
786 try {
787 for (int i = mManagedProfiles.size() - 1; i >= 0; i--) {
788 if (LOCAL_LOGV) {
789 Slog.v(TAG, "putting to additional user "
790 + mManagedProfiles.get(i).id);
791 }
792 insertForUser(Settings.Secure.CONTENT_URI, values,
793 mManagedProfiles.get(i).id);
794 }
795 } finally {
796 Binder.restoreCallingIdentity(token);
797 }
798 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700799 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
Amith Yamasani4f7e2e32014-08-14 18:49:48 -0700800 if (LOCAL_LOGV) {
801 Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for "
802 + callingUser);
803 }
Christopher Tate61695ff2012-10-05 12:05:13 -0700804 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
805 } else {
806 Slog.w(TAG, "call() with invalid method: " + method);
Christopher Tate06efb532012-08-24 15:29:27 -0700807 }
808
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800809 return null;
810 }
811
812 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
813 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700814 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
815 final SettingsCache cache, String key) {
816 if (cache == null) {
817 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
818 return null;
819 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800820 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800821 Bundle value = cache.get(key);
822 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700823 if (value != TOO_LARGE_TO_CACHE_MARKER) {
824 return value;
825 }
826 // else we fall through and read the value from disk
827 } else if (cache.fullyMatchesDisk()) {
828 // Fast path (very common). Don't even try touch disk
829 // if we know we've slurped it all in. Trying to
830 // touch the disk would mean waiting for yaffs2 to
831 // give us access, which could takes hundreds of
832 // milliseconds. And we're very likely being called
833 // from somebody's UI thread...
834 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800835 }
836 }
837
Christopher Tate06efb532012-08-24 15:29:27 -0700838 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800839 Cursor cursor = null;
840 try {
841 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
842 null, null, null, null);
843 if (cursor != null && cursor.getCount() == 1) {
844 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800845 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800846 }
847 } catch (SQLiteException e) {
848 Log.w(TAG, "settings lookup error", e);
849 return null;
850 } finally {
851 if (cursor != null) cursor.close();
852 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800853 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800854 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800855 }
856
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700857 @Override
858 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700859 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
860 }
861
Christopher Tateb7564452012-09-19 16:21:18 -0700862 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700863 String sort, int forUser) {
864 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700865 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700866 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700867 dbH = getOrEstablishDatabase(
868 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700869 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800871 // The favorites table was moved from this provider to a provider inside Home
872 // Home still need to query this table to upgrade from pre-cupcake builds
873 // However, a cupcake+ build with no data does not contain this table which will
874 // cause an exception in the SQL stack. The following line is a special case to
875 // 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 -0800876 if (TABLE_FAVORITES.equals(args.table)) {
877 return null;
878 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
879 args.table = TABLE_FAVORITES;
880 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
881 if (cursor != null) {
882 boolean exists = cursor.getCount() > 0;
883 cursor.close();
884 if (!exists) return null;
885 } else {
886 return null;
887 }
888 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800889
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700890 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
891 qb.setTables(args.table);
892
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700893 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
Christopher Tateafccaa82012-10-03 17:41:51 -0700894 // the default Cursor interface does not support per-user observation
895 try {
896 AbstractCursor c = (AbstractCursor) ret;
897 c.setNotificationUri(getContext().getContentResolver(), url, forUser);
898 } catch (ClassCastException e) {
899 // details of the concrete Cursor implementation have changed and this code has
900 // not been updated to match -- complain and fail hard.
901 Log.wtf(TAG, "Incompatible cursor derivation!");
902 throw e;
903 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700904 return ret;
905 }
906
907 @Override
908 public String getType(Uri url) {
909 // If SqlArguments supplies a where clause, then it must be an item
910 // (because we aren't supplying our own where clause).
911 SqlArguments args = new SqlArguments(url, null, null);
912 if (TextUtils.isEmpty(args.where)) {
913 return "vnd.android.cursor.dir/" + args.table;
914 } else {
915 return "vnd.android.cursor.item/" + args.table;
916 }
917 }
918
919 @Override
920 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700921 final int callingUser = UserHandle.getCallingUserId();
922 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700923 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 if (TABLE_FAVORITES.equals(args.table)) {
925 return 0;
926 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700927 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700928 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700929
Christopher Tate06efb532012-08-24 15:29:27 -0700930 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
931 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700932 DatabaseHelper dbH = getOrEstablishDatabase(
933 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700934 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700935 db.beginTransaction();
936 try {
937 int numValues = values.length;
938 for (int i = 0; i < numValues; i++) {
Julia Reynoldsb53453f2014-08-22 11:42:43 -0400939 checkUserRestrictions(values[i].getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700940 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800941 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700942 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
943 }
944 db.setTransactionSuccessful();
945 } finally {
946 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700947 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700948 }
949
Christopher Tate06efb532012-08-24 15:29:27 -0700950 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700951 return values.length;
952 }
953
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700954 /*
955 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
956 * This setting contains a list of the currently enabled location providers.
957 * But helper functions in android.providers.Settings can enable or disable
958 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800959 *
960 * @returns whether the database needs to be updated or not, also modifying
961 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700962 */
Maggie Benthalld2726582013-02-04 13:28:19 -0500963 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) {
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700964 String value = initialValues.getAsString(Settings.Secure.VALUE);
965 String newProviders = null;
966 if (value != null && value.length() > 1) {
967 char prefix = value.charAt(0);
968 if (prefix == '+' || prefix == '-') {
969 // skip prefix
970 value = value.substring(1);
971
972 // read list of enabled providers into "providers"
973 String providers = "";
974 String[] columns = {Settings.Secure.VALUE};
975 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
Maggie Benthalld2726582013-02-04 13:28:19 -0500976 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700977 if (cursor != null && cursor.getCount() == 1) {
978 try {
979 cursor.moveToFirst();
980 providers = cursor.getString(0);
981 } finally {
982 cursor.close();
983 }
984 }
985
986 int index = providers.indexOf(value);
987 int end = index + value.length();
988 // check for commas to avoid matching on partial string
989 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
990 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
991
992 if (prefix == '+' && index < 0) {
993 // append the provider to the list if not present
994 if (providers.length() == 0) {
995 newProviders = value;
996 } else {
997 newProviders = providers + ',' + value;
998 }
999 } else if (prefix == '-' && index >= 0) {
1000 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -04001001 // remove leading or trailing comma
1002 if (index > 0) {
1003 index--;
1004 } else if (end < providers.length()) {
1005 end++;
1006 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001007
1008 newProviders = providers.substring(0, index);
1009 if (end < providers.length()) {
1010 newProviders += providers.substring(end);
1011 }
1012 } else {
1013 // nothing changed, so no need to update the database
1014 return false;
1015 }
1016
1017 if (newProviders != null) {
1018 initialValues.put(Settings.Secure.VALUE, newProviders);
1019 }
1020 }
1021 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001022
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001023 return true;
1024 }
1025
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001026 @Override
1027 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -07001028 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
1029 }
1030
1031 // Settings.put*ForUser() always winds up here, so this is where we apply
1032 // policy around permission to write settings for other users.
1033 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
1034 final int callingUser = UserHandle.getCallingUserId();
1035 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001036 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -07001037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1038 "Not permitted to access settings for other users");
1039 }
1040
1041 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
1042 + " by " + callingUser);
1043
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001044 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (TABLE_FAVORITES.equals(args.table)) {
1046 return null;
1047 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001048
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001049 // Special case LOCATION_PROVIDERS_ALLOWED.
1050 // Support enabling/disabling a single provider (using "+" or "-" prefix)
1051 String name = initialValues.getAsString(Settings.Secure.NAME);
1052 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Maggie Benthalld2726582013-02-04 13:28:19 -05001053 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -07001054 }
1055
Christopher Tatec221d2b2012-10-03 18:33:52 -07001056 // If this is an insert() of a key that has been migrated to the global store,
1057 // redirect the operation to that store
1058 if (name != null) {
1059 if (sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name)) {
1060 if (!TABLE_GLOBAL.equals(args.table)) {
1061 if (LOCAL_LOGV) Slog.i(TAG, "Rewrite of insert() of now-global key " + name);
1062 }
1063 args.table = TABLE_GLOBAL; // next condition will rewrite the user handle
1064 }
1065 }
1066
Christopher Tate34637e52012-10-04 15:00:00 -07001067 // Check write permissions only after determining which table the insert will touch
1068 checkWritePermissions(args);
1069
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001070 checkUserRestrictions(name, desiredUserHandle);
Julia Reynolds5e458dd2014-07-07 16:07:01 -04001071
Christopher Tate06efb532012-08-24 15:29:27 -07001072 // The global table is stored under the owner, always
1073 if (TABLE_GLOBAL.equals(args.table)) {
1074 desiredUserHandle = UserHandle.USER_OWNER;
1075 }
1076
1077 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001078 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
1079 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
1080 return Uri.withAppendedPath(url, name);
1081 }
1082
Christopher Tate06efb532012-08-24 15:29:27 -07001083 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
1084 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001085 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001086 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001087 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -07001088 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001089 if (rowId <= 0) return null;
1090
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001091 SettingsCache.populate(cache, initialValues); // before we notify
1092
Christopher Tate78d2a662012-09-13 16:19:44 -07001093 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
1094 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -07001095 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001096 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -07001097 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001098 return url;
1099 }
1100
1101 @Override
1102 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -07001103 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001104 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001105 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 if (TABLE_FAVORITES.equals(args.table)) {
1107 return 0;
1108 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
1109 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001110 } else if (TABLE_GLOBAL.equals(args.table)) {
1111 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001113 checkWritePermissions(args);
1114
Christopher Tate06efb532012-08-24 15:29:27 -07001115 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1116 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001117 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001118 SQLiteDatabase db = dbH.getWritableDatabase();
1119 int count = db.delete(args.table, args.where, args.args);
1120 mutationCount.decrementAndGet();
1121 if (count > 0) {
1122 invalidateCache(callingUser, args.table); // before we notify
1123 sendNotify(url, callingUser);
1124 }
1125 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001126 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1127 return count;
1128 }
1129
1130 @Override
1131 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001132 // NOTE: update() is never called by the front-end Settings API, and updates that
1133 // wind up affecting rows in Secure that are globally shared will not have the
1134 // intended effect (the update will be invisible to the rest of the system).
1135 // This should have no practical effect, since writes to the Secure db can only
1136 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001137 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001138 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001139 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 if (TABLE_FAVORITES.equals(args.table)) {
1141 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001142 } else if (TABLE_GLOBAL.equals(args.table)) {
1143 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001145 checkWritePermissions(args);
Julia Reynoldsb53453f2014-08-22 11:42:43 -04001146 checkUserRestrictions(initialValues.getAsString(Settings.Secure.NAME), callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001147
Christopher Tate06efb532012-08-24 15:29:27 -07001148 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1149 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001150 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001151 SQLiteDatabase db = dbH.getWritableDatabase();
1152 int count = db.update(args.table, initialValues, args.where, args.args);
1153 mutationCount.decrementAndGet();
1154 if (count > 0) {
1155 invalidateCache(callingUser, args.table); // before we notify
1156 sendNotify(url, callingUser);
1157 }
1158 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001159 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1160 return count;
1161 }
1162
1163 @Override
1164 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1165
1166 /*
1167 * When a client attempts to openFile the default ringtone or
1168 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001169 * default ringtone's Uri (if it is in the media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001170 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001171 int ringtoneType = RingtoneManager.getDefaultType(uri);
1172 // Above call returns -1 if the Uri doesn't match a default type
1173 if (ringtoneType != -1) {
1174 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001175
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001176 // Get the current value for the default sound
1177 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001178
Marco Nelissen69f593c2009-07-28 09:55:04 -07001179 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001180 // Proxy the openFile call to media provider
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001181 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001182 if (authority.equals(MediaStore.AUTHORITY)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001183 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1184 }
1185 }
1186 }
1187
1188 return super.openFile(uri, mode);
1189 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001190
1191 @Override
1192 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1193
1194 /*
1195 * When a client attempts to openFile the default ringtone or
1196 * notification setting Uri, we will proxy the call to the current
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001197 * default ringtone's Uri (if it is in the media provider).
Marco Nelissen69f593c2009-07-28 09:55:04 -07001198 */
1199 int ringtoneType = RingtoneManager.getDefaultType(uri);
1200 // Above call returns -1 if the Uri doesn't match a default type
1201 if (ringtoneType != -1) {
1202 Context context = getContext();
1203
1204 // Get the current value for the default sound
1205 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1206
1207 if (soundUri != null) {
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001208 // Proxy the openFile call to media provider
Marco Nelissen69f593c2009-07-28 09:55:04 -07001209 String authority = soundUri.getAuthority();
Mike Lockwood853ad6f2013-04-29 16:12:23 -07001210 if (authority.equals(MediaStore.AUTHORITY)) {
Marco Nelissen69f593c2009-07-28 09:55:04 -07001211 ParcelFileDescriptor pfd = null;
1212 try {
1213 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1214 return new AssetFileDescriptor(pfd, 0, -1);
1215 } catch (FileNotFoundException ex) {
1216 // fall through and open the fallback ringtone below
1217 }
1218 }
1219
1220 try {
1221 return super.openAssetFile(soundUri, mode);
1222 } catch (FileNotFoundException ex) {
1223 // Since a non-null Uri was specified, but couldn't be opened,
1224 // fall back to the built-in ringtone.
1225 return context.getResources().openRawResourceFd(
1226 com.android.internal.R.raw.fallbackring);
1227 }
1228 }
1229 // no need to fall through and have openFile() try again, since we
1230 // already know that will fail.
1231 throw new FileNotFoundException(); // or return null ?
1232 }
1233
1234 // Note that this will end up calling openFile() above.
1235 return super.openAssetFile(uri, mode);
1236 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001237
1238 /**
1239 * In-memory LRU Cache of system and secure settings, along with
1240 * associated helper functions to keep cache coherent with the
1241 * database.
1242 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001243 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001244
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001245 private final String mCacheName;
1246 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1247
1248 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001249 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001250 mCacheName = name;
1251 }
1252
1253 /**
1254 * Is the whole database table slurped into this cache?
1255 */
1256 public boolean fullyMatchesDisk() {
1257 synchronized (this) {
1258 return mCacheFullyMatchesDisk;
1259 }
1260 }
1261
1262 public void setFullyMatchesDisk(boolean value) {
1263 synchronized (this) {
1264 mCacheFullyMatchesDisk = value;
1265 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001266 }
1267
1268 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001269 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1270 if (evicted) {
1271 mCacheFullyMatchesDisk = false;
1272 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001273 }
1274
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001275 /**
1276 * Atomic cache population, conditional on size of value and if
1277 * we lost a race.
1278 *
1279 * @returns a Bundle to send back to the client from call(), even
1280 * if we lost the race.
1281 */
1282 public Bundle putIfAbsent(String key, String value) {
1283 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1284 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1285 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001286 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001287 put(key, bundle);
1288 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001289 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001290 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001291 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001292 }
1293
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001294 /**
1295 * Populates a key in a given (possibly-null) cache.
1296 */
1297 public static void populate(SettingsCache cache, ContentValues contentValues) {
1298 if (cache == null) {
1299 return;
1300 }
1301 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1302 if (name == null) {
1303 Log.w(TAG, "null name populating settings cache.");
1304 return;
1305 }
1306 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001307 cache.populate(name, value);
1308 }
1309
1310 public void populate(String name, String value) {
1311 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001312 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001313 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001314 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001315 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001316 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001317 }
1318 }
1319
1320 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001321 * For suppressing duplicate/redundant settings inserts early,
1322 * checking our cache first (but without faulting it in),
1323 * before going to sqlite with the mutation.
1324 */
1325 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1326 if (cache == null) return false;
1327 synchronized (cache) {
1328 Bundle bundle = cache.get(name);
1329 if (bundle == null) return false;
1330 String oldValue = bundle.getPairValue();
1331 if (oldValue == null && value == null) return true;
1332 if ((oldValue == null) != (value == null)) return false;
1333 return oldValue.equals(value);
1334 }
1335 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001336 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001337}