SettingsProvider.java revision 4f7e2e334e4ca5f1a67baf4bdd40cd080b954161
1/* 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 19import java.io.FileNotFoundException; 20import java.security.SecureRandom; 21import java.util.HashMap; 22import java.util.HashSet; 23import java.util.List; 24import java.util.Map; 25import java.util.concurrent.atomic.AtomicBoolean; 26import java.util.concurrent.atomic.AtomicInteger; 27 28import android.app.ActivityManager; 29import android.app.AppOpsManager; 30import android.app.backup.BackupManager; 31import android.content.BroadcastReceiver; 32import android.content.ContentProvider; 33import android.content.ContentUris; 34import android.content.ContentValues; 35import android.content.Context; 36import android.content.Intent; 37import android.content.IntentFilter; 38import android.content.pm.PackageManager; 39import android.content.pm.UserInfo; 40import android.content.res.AssetFileDescriptor; 41import android.database.AbstractCursor; 42import android.database.Cursor; 43import android.database.sqlite.SQLiteDatabase; 44import android.database.sqlite.SQLiteException; 45import android.database.sqlite.SQLiteQueryBuilder; 46import android.media.RingtoneManager; 47import android.net.Uri; 48import android.os.Binder; 49import android.os.Bundle; 50import android.os.DropBoxManager; 51import android.os.FileObserver; 52import android.os.ParcelFileDescriptor; 53import android.os.Process; 54import android.os.SystemProperties; 55import android.os.UserHandle; 56import android.os.UserManager; 57import android.provider.MediaStore; 58import android.provider.Settings; 59import android.text.TextUtils; 60import android.util.Log; 61import android.util.LruCache; 62import android.util.Slog; 63import android.util.SparseArray; 64 65public class SettingsProvider extends ContentProvider { 66 private static final String TAG = "SettingsProvider"; 67 private static final boolean LOCAL_LOGV = false; 68 69 private static final boolean USER_CHECK_THROWS = true; 70 71 private static final String TABLE_SYSTEM = "system"; 72 private static final String TABLE_SECURE = "secure"; 73 private static final String TABLE_GLOBAL = "global"; 74 private static final String TABLE_FAVORITES = "favorites"; 75 private static final String TABLE_OLD_FAVORITES = "old_favorites"; 76 77 private static final String[] COLUMN_VALUE = new String[] { "value" }; 78 79 // Caches for each user's settings, access-ordered for acting as LRU. 80 // Guarded by themselves. 81 private static final int MAX_CACHE_ENTRIES = 200; 82 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); 87 88 // The count of how many known (handled by SettingsProvider) 89 // database mutations are currently being handled for this user. 90 // Used by file observers to not reload the database when it's ourselves 91 // modifying it. 92 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight 93 = new SparseArray<AtomicInteger>(); 94 95 // Each defined user has their own settings 96 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>(); 97 98 // Keep the list of managed profiles synced here 99 private List<UserInfo> mManagedProfiles = null; 100 101 // 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 106 private static final Bundle NULL_SETTING = Bundle.forPair("value", null); 107 108 // 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 112 private UserManager mUserManager; 113 private BackupManager mBackupManager; 114 115 /** 116 * 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; 120 121 // Settings that cannot be modified if associated user restrictions are enabled. 122 static final Map<String, String> sRestrictedKeys; 123 124 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid"; 125 126 static final HashSet<String> sSecureCloneToManagedKeys; 127 static final HashSet<String> sSystemCloneToManagedKeys; 128 129 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>(); 134 Settings.Secure.getMovedKeys(sSecureGlobalKeys); 135 136 // Keys from the 'system' table now moved to 'global' 137 // These must match Settings.System.MOVED_TO_GLOBAL 138 sSystemGlobalKeys = new HashSet<String>(); 139 Settings.System.getNonLegacyMovedKeys(sSystemGlobalKeys); 140 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); 145 sRestrictedKeys.put(Settings.Secure.INSTALL_NON_MARKET_APPS, 146 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); 152 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 } 161 } 162 163 private boolean settingMovedToGlobal(final String name) { 164 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name); 165 } 166 167 /** 168 * Decode a content URL into the table, projection, and arguments 169 * used to access the corresponding database rows. 170 */ 171 private static class SqlArguments { 172 public String table; 173 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) { 179 // of the form content://settings/secure, arbitrary where clause 180 this.table = url.getPathSegments().get(0); 181 if (!DatabaseHelper.isValidTable(this.table)) { 182 throw new IllegalArgumentException("Bad root path: " + this.table); 183 } 184 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 { 191 // of the form content://settings/secure/element_name, no where clause 192 this.table = url.getPathSegments().get(0); 193 if (!DatabaseHelper.isValidTable(this.table)) { 194 throw new IllegalArgumentException("Bad root path: " + this.table); 195 } 196 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) || 197 TABLE_GLOBAL.equals(this.table)) { 198 this.where = Settings.NameValueTable.NAME + "=?"; 199 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 } 207 } else { 208 // of the form content://bookmarks/19 209 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); 219 if (!DatabaseHelper.isValidTable(this.table)) { 220 throw new IllegalArgumentException("Bad root path: " + this.table); 221 } 222 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); 242 if (TABLE_SYSTEM.equals(table) || 243 TABLE_SECURE.equals(table) || 244 TABLE_GLOBAL.equals(table)) { 245 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 */ 259 private void sendNotify(Uri uri, int userHandle) { 260 // 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 264 boolean backedUpDataChanged = false; 265 String property = null, table = uri.getPathSegments().get(0); 266 final boolean isGlobal = table.equals(TABLE_GLOBAL); 267 if (table.equals(TABLE_SYSTEM)) { 268 property = Settings.System.SYS_PROP_SETTING_VERSION; 269 backedUpDataChanged = true; 270 } else if (table.equals(TABLE_SECURE)) { 271 property = Settings.Secure.SYS_PROP_SETTING_VERSION; 272 backedUpDataChanged = true; 273 } else if (isGlobal) { 274 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global 275 backedUpDataChanged = true; 276 } 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 284 // Inform the backup manager about a data change 285 if (backedUpDataChanged) { 286 mBackupManager.dataChanged(); 287 } 288 // Now send the notification through the content framework. 289 290 String notify = uri.getQueryParameter("notify"); 291 if (notify == null || "true".equals(notify)) { 292 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle; 293 final long oldId = Binder.clearCallingIdentity(); 294 try { 295 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget); 296 } finally { 297 Binder.restoreCallingIdentity(oldId); 298 } 299 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri); 300 } 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) { 311 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) && 312 getContext().checkCallingOrSelfPermission( 313 android.Manifest.permission.WRITE_SECURE_SETTINGS) != 314 PackageManager.PERMISSION_GRANTED) { 315 throw new SecurityException( 316 String.format("Permission denial: writing to secure settings requires %1$s", 317 android.Manifest.permission.WRITE_SECURE_SETTINGS)); 318 } 319 } 320 321 private void checkUserRestrictions(String setting) { 322 String userRestriction = sRestrictedKeys.get(setting); 323 if (!TextUtils.isEmpty(userRestriction) 324 && mUserManager.hasUserRestriction(userRestriction)) { 325 throw new SecurityException( 326 "Permission denial: user is restricted from changing this setting."); 327 } 328 } 329 330 // 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. 337 private static SparseArray<SettingsFileObserver> sObserverInstances 338 = new SparseArray<SettingsFileObserver>(); 339 private class SettingsFileObserver extends FileObserver { 340 private final AtomicBoolean mIsDirty = new AtomicBoolean(false); 341 private final int mUserHandle; 342 private final String mPath; 343 344 public SettingsFileObserver(int userHandle, String path) { 345 super(path, FileObserver.CLOSE_WRITE | 346 FileObserver.CREATE | FileObserver.DELETE | 347 FileObserver.MOVED_TO | FileObserver.MODIFY); 348 mUserHandle = userHandle; 349 mPath = path; 350 } 351 352 public void onEvent(int event, String path) { 353 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get(); 354 if (modsInFlight > 0) { 355 // our own modification. 356 return; 357 } 358 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath 359 + "; event=" + event); 360 if (!mIsDirty.compareAndSet(false, true)) { 361 // already handled. (we get a few update events 362 // during an sqlite write) 363 return; 364 } 365 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath); 366 fullyPopulateCaches(mUserHandle); 367 mIsDirty.set(false); 368 } 369 } 370 371 @Override 372 public boolean onCreate() { 373 mBackupManager = new BackupManager(getContext()); 374 mUserManager = UserManager.get(getContext()); 375 376 setAppOps(AppOpsManager.OP_NONE, AppOpsManager.OP_WRITE_SETTINGS); 377 establishDbTracking(UserHandle.USER_OWNER); 378 379 IntentFilter userFilter = new IntentFilter(); 380 userFilter.addAction(Intent.ACTION_USER_REMOVED); 381 userFilter.addAction(Intent.ACTION_USER_ADDED); 382 getContext().registerReceiver(new BroadcastReceiver() { 383 @Override 384 public void onReceive(Context context, Intent intent) { 385 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 386 UserHandle.USER_OWNER); 387 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) { 388 onUserRemoved(userHandle); 389 } else if (intent.getAction().equals(Intent.ACTION_USER_ADDED)) { 390 onProfilesChanged(); 391 } 392 } 393 }, userFilter); 394 395 onProfilesChanged(); 396 397 return true; 398 } 399 400 void onUserRemoved(int userHandle) { 401 synchronized (this) { 402 // the db file itself will be deleted automatically, but we need to tear down 403 // our caches and other internal bookkeeping. 404 FileObserver observer = sObserverInstances.get(userHandle); 405 if (observer != null) { 406 observer.stopWatching(); 407 sObserverInstances.delete(userHandle); 408 } 409 410 mOpenHelpers.delete(userHandle); 411 sSystemCaches.delete(userHandle); 412 sSecureCaches.delete(userHandle); 413 sKnownMutationsInFlight.delete(userHandle); 414 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 } 440 } 441 } 442 443 private void establishDbTracking(int userHandle) { 444 if (LOCAL_LOGV) { 445 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle); 446 } 447 448 DatabaseHelper dbhelper; 449 450 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. 467 SQLiteDatabase db = dbhelper.getWritableDatabase(); 468 469 // 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 } 480 481 ensureAndroidIdIsSet(userHandle); 482 483 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)); 512 } 513 514 // Slurp all values (if sane in number & size) into cache. 515 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) { 516 SQLiteDatabase db = dbHelper.getReadableDatabase(); 517 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) { 524 cache.evictAll(); 525 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 } 539 if (LOCAL_LOGV) Log.d(TAG, "cache for settings table '" + table 540 + "' rows=" + rows + "; fullycached=" + cache.fullyMatchesDisk()); 541 } 542 } finally { 543 c.close(); 544 } 545 } 546 547 private boolean ensureAndroidIdIsSet(int userHandle) { 548 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI, 549 new String[] { Settings.NameValueTable.VALUE }, 550 Settings.NameValueTable.NAME + "=?", 551 new String[] { Settings.Secure.ANDROID_ID }, null, 552 userHandle); 553 try { 554 final String value = c.moveToNext() ? c.getString(0) : null; 555 if (value == null) { 556 // 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 563 final SecureRandom random = new SecureRandom(); 564 final String newAndroidIdValue = Long.toHexString(random.nextLong()); 565 final ContentValues values = new ContentValues(); 566 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID); 567 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue); 568 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle); 569 if (uri == null) { 570 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle); 571 return false; 572 } 573 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue 574 + "] for user " + userHandle); 575 // Write a dropbox entry if it's a restricted profile 576 if (user.isRestricted()) { 577 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 } 585 } 586 return true; 587 } finally { 588 c.close(); 589 } 590 } 591 592 // Lazy-initialize the settings caches for non-primary users 593 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) { 594 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it 595 return which.get(callingUser); 596 } 597 598 // Lazy initialize the database helper and caches for this user, if necessary 599 private DatabaseHelper getOrEstablishDatabase(int callingUser) { 600 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 608 long oldId = Binder.clearCallingIdentity(); 609 try { 610 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser); 611 if (null == dbHelper) { 612 establishDbTracking(callingUser); 613 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 649 /** 650 * 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 /** 668 * Fast path that avoids the use of chatty remoted Cursors. 669 */ 670 @Override 671 public Bundle call(String method, String request, Bundle args) { 672 int callingUser = UserHandle.getCallingUserId(); 673 if (args != null) { 674 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser); 675 if (reqUser != callingUser) { 676 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); 680 } 681 } 682 683 // 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; 688 689 // Get methods 690 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) { 691 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser); 692 if (isManagedProfile(callingUser) && sSystemCloneToManagedKeys.contains(request)) { 693 callingUser = UserHandle.USER_OWNER; 694 } 695 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); 701 if (isManagedProfile(callingUser) && sSecureCloneToManagedKeys.contains(request)) { 702 callingUser = UserHandle.USER_OWNER; 703 } 704 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 } 715 716 // 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) 719 ? 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(), 732 getCallingPackage()) != AppOpsManager.MODE_ALLOWED) { 733 return null; 734 } 735 736 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)) { 740 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 } 751 insertForUser(Settings.System.CONTENT_URI, values, callingUser); 752 // 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 } 769 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) { 770 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 } 781 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser); 782 // 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 } 799 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) { 800 if (LOCAL_LOGV) { 801 Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " 802 + callingUser); 803 } 804 insertForUser(Settings.Global.CONTENT_URI, values, callingUser); 805 } else { 806 Slog.w(TAG, "call() with invalid method: " + method); 807 } 808 809 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. 814 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 } 820 synchronized (cache) { 821 Bundle value = cache.get(key); 822 if (value != null) { 823 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; 835 } 836 } 837 838 SQLiteDatabase db = dbHelper.getReadableDatabase(); 839 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(); 845 return cache.putIfAbsent(key, cursor.getString(0)); 846 } 847 } catch (SQLiteException e) { 848 Log.w(TAG, "settings lookup error", e); 849 return null; 850 } finally { 851 if (cursor != null) cursor.close(); 852 } 853 cache.putIfAbsent(key, null); 854 return NULL_SETTING; 855 } 856 857 @Override 858 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) { 859 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId()); 860 } 861 862 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs, 863 String sort, int forUser) { 864 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser); 865 SqlArguments args = new SqlArguments(url, where, whereArgs); 866 DatabaseHelper dbH; 867 dbH = getOrEstablishDatabase( 868 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser); 869 SQLiteDatabase db = dbH.getReadableDatabase(); 870 871 // 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 876 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 } 889 890 SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); 891 qb.setTables(args.table); 892 893 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort); 894 // 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 } 904 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) { 921 final int callingUser = UserHandle.getCallingUserId(); 922 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser); 923 SqlArguments args = new SqlArguments(uri); 924 if (TABLE_FAVORITES.equals(args.table)) { 925 return 0; 926 } 927 checkWritePermissions(args); 928 SettingsCache cache = cacheForTable(callingUser, args.table); 929 930 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser); 931 mutationCount.incrementAndGet(); 932 DatabaseHelper dbH = getOrEstablishDatabase( 933 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser); 934 SQLiteDatabase db = dbH.getWritableDatabase(); 935 db.beginTransaction(); 936 try { 937 int numValues = values.length; 938 for (int i = 0; i < numValues; i++) { 939 checkUserRestrictions(values[i].getAsString(Settings.Secure.NAME)); 940 if (db.insert(args.table, null, values[i]) < 0) return 0; 941 SettingsCache.populate(cache, values[i]); 942 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]); 943 } 944 db.setTransactionSuccessful(); 945 } finally { 946 db.endTransaction(); 947 mutationCount.decrementAndGet(); 948 } 949 950 sendNotify(uri, callingUser); 951 return values.length; 952 } 953 954 /* 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. 959 * 960 * @returns whether the database needs to be updated or not, also modifying 961 * 'initialValues' if needed. 962 */ 963 private boolean parseProviderList(Uri url, ContentValues initialValues, int desiredUser) { 964 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 + "\'"; 976 Cursor cursor = queryForUser(url, columns, where, null, null, desiredUser); 977 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 1001 // remove leading or trailing comma 1002 if (index > 0) { 1003 index--; 1004 } else if (end < providers.length()) { 1005 end++; 1006 } 1007 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 } 1022 1023 return true; 1024 } 1025 1026 @Override 1027 public Uri insert(Uri url, ContentValues initialValues) { 1028 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) { 1036 getContext().enforceCallingOrSelfPermission( 1037 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 1044 SqlArguments args = new SqlArguments(url); 1045 if (TABLE_FAVORITES.equals(args.table)) { 1046 return null; 1047 } 1048 1049 // 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)) { 1053 if (!parseProviderList(url, initialValues, desiredUserHandle)) return null; 1054 } 1055 1056 // 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 1067 // Check write permissions only after determining which table the insert will touch 1068 checkWritePermissions(args); 1069 1070 checkUserRestrictions(name); 1071 1072 // 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); 1078 String value = initialValues.getAsString(Settings.NameValueTable.VALUE); 1079 if (SettingsCache.isRedundantSetValue(cache, name, value)) { 1080 return Uri.withAppendedPath(url, name); 1081 } 1082 1083 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle); 1084 mutationCount.incrementAndGet(); 1085 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle); 1086 SQLiteDatabase db = dbH.getWritableDatabase(); 1087 final long rowId = db.insert(args.table, null, initialValues); 1088 mutationCount.decrementAndGet(); 1089 if (rowId <= 0) return null; 1090 1091 SettingsCache.populate(cache, initialValues); // before we notify 1092 1093 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues 1094 + " for user " + desiredUserHandle); 1095 // Note that we use the original url here, not the potentially-rewritten table name 1096 url = getUriFor(url, initialValues, rowId); 1097 sendNotify(url, desiredUserHandle); 1098 return url; 1099 } 1100 1101 @Override 1102 public int delete(Uri url, String where, String[] whereArgs) { 1103 int callingUser = UserHandle.getCallingUserId(); 1104 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser); 1105 SqlArguments args = new SqlArguments(url, where, whereArgs); 1106 if (TABLE_FAVORITES.equals(args.table)) { 1107 return 0; 1108 } else if (TABLE_OLD_FAVORITES.equals(args.table)) { 1109 args.table = TABLE_FAVORITES; 1110 } else if (TABLE_GLOBAL.equals(args.table)) { 1111 callingUser = UserHandle.USER_OWNER; 1112 } 1113 checkWritePermissions(args); 1114 1115 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser); 1116 mutationCount.incrementAndGet(); 1117 DatabaseHelper dbH = getOrEstablishDatabase(callingUser); 1118 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); 1126 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) { 1132 // 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. 1137 int callingUser = UserHandle.getCallingUserId(); 1138 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser); 1139 SqlArguments args = new SqlArguments(url, where, whereArgs); 1140 if (TABLE_FAVORITES.equals(args.table)) { 1141 return 0; 1142 } else if (TABLE_GLOBAL.equals(args.table)) { 1143 callingUser = UserHandle.USER_OWNER; 1144 } 1145 checkWritePermissions(args); 1146 checkUserRestrictions(initialValues.getAsString(Settings.Secure.NAME)); 1147 1148 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser); 1149 mutationCount.incrementAndGet(); 1150 DatabaseHelper dbH = getOrEstablishDatabase(callingUser); 1151 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); 1159 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 1169 * default ringtone's Uri (if it is in the media provider). 1170 */ 1171 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(); 1175 1176 // Get the current value for the default sound 1177 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType); 1178 1179 if (soundUri != null) { 1180 // Proxy the openFile call to media provider 1181 String authority = soundUri.getAuthority(); 1182 if (authority.equals(MediaStore.AUTHORITY)) { 1183 return context.getContentResolver().openFileDescriptor(soundUri, mode); 1184 } 1185 } 1186 } 1187 1188 return super.openFile(uri, mode); 1189 } 1190 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 1197 * default ringtone's Uri (if it is in the media provider). 1198 */ 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) { 1208 // Proxy the openFile call to media provider 1209 String authority = soundUri.getAuthority(); 1210 if (authority.equals(MediaStore.AUTHORITY)) { 1211 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 } 1237 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 */ 1243 private static final class SettingsCache extends LruCache<String, Bundle> { 1244 1245 private final String mCacheName; 1246 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped. 1247 1248 public SettingsCache(String name) { 1249 super(MAX_CACHE_ENTRIES); 1250 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 } 1266 } 1267 1268 @Override 1269 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) { 1270 if (evicted) { 1271 mCacheFullyMatchesDisk = false; 1272 } 1273 } 1274 1275 /** 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) { 1286 if (get(key) == null) { 1287 put(key, bundle); 1288 } 1289 } 1290 } 1291 return bundle; 1292 } 1293 1294 /** 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); 1307 cache.populate(name, value); 1308 } 1309 1310 public void populate(String name, String value) { 1311 synchronized (this) { 1312 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) { 1313 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value)); 1314 } else { 1315 put(name, TOO_LARGE_TO_CACHE_MARKER); 1316 } 1317 } 1318 } 1319 1320 /** 1321 * 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 } 1336 } 1337} 1338