blob: 4372cd89e086803370af624796206d8751cadb4b [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.io.UnsupportedEncodingException;
Fred Quintanac70239e2009-12-17 10:28:33 -080021import java.security.NoSuchAlgorithmException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080022import java.security.SecureRandom;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080023import java.util.LinkedHashMap;
24import java.util.Map;
-b master501eec92009-07-06 13:53:11 -070025
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.BackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentProvider;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070032import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.database.Cursor;
34import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080035import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.sqlite.SQLiteQueryBuilder;
37import android.media.RingtoneManager;
38import android.net.Uri;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080039import android.os.Bundle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.os.ParcelFileDescriptor;
41import android.os.SystemProperties;
42import android.provider.DrmStore;
43import android.provider.MediaStore;
44import android.provider.Settings;
45import android.text.TextUtils;
46import android.util.Log;
47
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048public class SettingsProvider extends ContentProvider {
49 private static final String TAG = "SettingsProvider";
50 private static final boolean LOCAL_LOGV = false;
51
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 private static final String TABLE_FAVORITES = "favorites";
53 private static final String TABLE_OLD_FAVORITES = "old_favorites";
54
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080055 private static final String[] COLUMN_VALUE = new String[] { "value" };
56
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080057 // Cache for settings, access-ordered for acting as LRU.
58 // Guarded by themselves.
59 private static final int MAX_CACHE_ENTRIES = 50;
60 private static final SettingsCache sSystemCache = new SettingsCache();
61 private static final SettingsCache sSecureCache = new SettingsCache();
62
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080063 // Over this size we don't reject loading or saving settings but
64 // we do consider them broken/malicious and don't keep them in
65 // memory at least:
66 private static final int MAX_CACHE_ENTRY_SIZE = 500;
67
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080068 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
69
James Wylder074da8f2009-02-25 08:38:31 -060070 protected DatabaseHelper mOpenHelper;
Amith Yamasani8823c0a82009-07-07 14:30:17 -070071 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070072
73 /**
74 * Decode a content URL into the table, projection, and arguments
75 * used to access the corresponding database rows.
76 */
77 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070079 public final String where;
80 public final String[] args;
81
82 /** Operate on existing rows. */
83 SqlArguments(Uri url, String where, String[] args) {
84 if (url.getPathSegments().size() == 1) {
85 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -070086 if (!DatabaseHelper.isValidTable(this.table)) {
87 throw new IllegalArgumentException("Bad root path: " + this.table);
88 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070089 this.where = where;
90 this.args = args;
91 } else if (url.getPathSegments().size() != 2) {
92 throw new IllegalArgumentException("Invalid URI: " + url);
93 } else if (!TextUtils.isEmpty(where)) {
94 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
95 } else {
96 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -070097 if (!DatabaseHelper.isValidTable(this.table)) {
98 throw new IllegalArgumentException("Bad root path: " + this.table);
99 }
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800100 if ("system".equals(this.table) || "secure".equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700101 this.where = Settings.NameValueTable.NAME + "=?";
102 this.args = new String[] { url.getPathSegments().get(1) };
103 } else {
104 this.where = "_id=" + ContentUris.parseId(url);
105 this.args = null;
106 }
107 }
108 }
109
110 /** Insert new rows (no where clause allowed). */
111 SqlArguments(Uri url) {
112 if (url.getPathSegments().size() == 1) {
113 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700114 if (!DatabaseHelper.isValidTable(this.table)) {
115 throw new IllegalArgumentException("Bad root path: " + this.table);
116 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700117 this.where = null;
118 this.args = null;
119 } else {
120 throw new IllegalArgumentException("Invalid URI: " + url);
121 }
122 }
123 }
124
125 /**
126 * Get the content URI of a row added to a table.
127 * @param tableUri of the entire table
128 * @param values found in the row
129 * @param rowId of the row
130 * @return the content URI for this particular row
131 */
132 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
133 if (tableUri.getPathSegments().size() != 1) {
134 throw new IllegalArgumentException("Invalid URI: " + tableUri);
135 }
136 String table = tableUri.getPathSegments().get(0);
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800137 if ("system".equals(table) || "secure".equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138 String name = values.getAsString(Settings.NameValueTable.NAME);
139 return Uri.withAppendedPath(tableUri, name);
140 } else {
141 return ContentUris.withAppendedId(tableUri, rowId);
142 }
143 }
144
145 /**
146 * Send a notification when a particular content URI changes.
147 * Modify the system property used to communicate the version of
148 * this table, for tables which have such a property. (The Settings
149 * contract class uses these to provide client-side caches.)
150 * @param uri to send notifications for
151 */
152 private void sendNotify(Uri uri) {
153 // Update the system property *first*, so if someone is listening for
154 // a notification and then using the contract class to get their data,
155 // the system property will be updated and they'll get the new data.
156
Amith Yamasanid1582142009-07-08 20:04:55 -0700157 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700158 String property = null, table = uri.getPathSegments().get(0);
159 if (table.equals("system")) {
160 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700161 backedUpDataChanged = true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800162 } else if (table.equals("secure")) {
163 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700164 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165 }
166
167 if (property != null) {
168 long version = SystemProperties.getLong(property, 0) + 1;
169 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
170 SystemProperties.set(property, Long.toString(version));
171 }
172
-b master501eec92009-07-06 13:53:11 -0700173 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700174 if (backedUpDataChanged) {
175 mBackupManager.dataChanged();
176 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700177 // Now send the notification through the content framework.
178
179 String notify = uri.getQueryParameter("notify");
180 if (notify == null || "true".equals(notify)) {
181 getContext().getContentResolver().notifyChange(uri, null);
182 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
183 } else {
184 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
185 }
186 }
187
188 /**
189 * Make sure the caller has permission to write this data.
190 * @param args supplied by the caller
191 * @throws SecurityException if the caller is forbidden to write.
192 */
193 private void checkWritePermissions(SqlArguments args) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800194 if ("secure".equals(args.table) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800195 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800196 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
197 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700198 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800199 String.format("Permission denial: writing to secure settings requires %1$s",
200 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700201 }
202 }
203
204 @Override
205 public boolean onCreate() {
206 mOpenHelper = new DatabaseHelper(getContext());
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700207 mBackupManager = new BackupManager(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800208
209 if (!ensureAndroidIdIsSet()) {
210 return false;
211 }
212
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700213 return true;
214 }
215
Fred Quintanac70239e2009-12-17 10:28:33 -0800216 private boolean ensureAndroidIdIsSet() {
217 final Cursor c = query(Settings.Secure.CONTENT_URI,
218 new String[] { Settings.NameValueTable.VALUE },
219 Settings.NameValueTable.NAME + "=?",
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800220 new String[] { Settings.Secure.ANDROID_ID }, null);
Fred Quintanac70239e2009-12-17 10:28:33 -0800221 try {
222 final String value = c.moveToNext() ? c.getString(0) : null;
223 if (value == null) {
224 final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
Doug Zongker4f8ff392010-02-03 10:36:40 -0800225 String serial = SystemProperties.get("ro.serialno");
226 if (serial != null) {
227 try {
228 random.setSeed(serial.getBytes("UTF-8"));
229 } catch (UnsupportedEncodingException ignore) {
230 // stick with default seed
231 }
232 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800233 final String newAndroidIdValue = Long.toHexString(random.nextLong());
234 Log.d(TAG, "Generated and saved new ANDROID_ID");
235 final ContentValues values = new ContentValues();
236 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
237 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
238 final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
239 if (uri == null) {
240 return false;
241 }
242 }
243 return true;
244 } catch (NoSuchAlgorithmException e) {
245 return false;
246 } finally {
247 c.close();
248 }
249 }
250
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800251 /**
252 * Fast path that avoids the use of chatty remoted Cursors.
253 */
254 @Override
255 public Bundle call(String method, String request, Bundle args) {
256 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800257 return lookupValue("system", sSystemCache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800258 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800259 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800260 return lookupValue("secure", sSecureCache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800261 }
262 return null;
263 }
264
265 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
266 // possibly with a null value, or null on failure.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800267 private Bundle lookupValue(String table, SettingsCache cache, String key) {
268 synchronized (cache) {
269 if (cache.containsKey(key)) {
270 return cache.get(key);
271 }
272 }
273
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800274 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
275 Cursor cursor = null;
276 try {
277 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
278 null, null, null, null);
279 if (cursor != null && cursor.getCount() == 1) {
280 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800281 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800282 }
283 } catch (SQLiteException e) {
284 Log.w(TAG, "settings lookup error", e);
285 return null;
286 } finally {
287 if (cursor != null) cursor.close();
288 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800289 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800290 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800291 }
292
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293 @Override
294 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
295 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
297
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800298 // The favorites table was moved from this provider to a provider inside Home
299 // Home still need to query this table to upgrade from pre-cupcake builds
300 // However, a cupcake+ build with no data does not contain this table which will
301 // cause an exception in the SQL stack. The following line is a special case to
302 // 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 -0800303 if (TABLE_FAVORITES.equals(args.table)) {
304 return null;
305 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
306 args.table = TABLE_FAVORITES;
307 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
308 if (cursor != null) {
309 boolean exists = cursor.getCount() > 0;
310 cursor.close();
311 if (!exists) return null;
312 } else {
313 return null;
314 }
315 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800316
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700317 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
318 qb.setTables(args.table);
319
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700320 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
321 ret.setNotificationUri(getContext().getContentResolver(), url);
322 return ret;
323 }
324
325 @Override
326 public String getType(Uri url) {
327 // If SqlArguments supplies a where clause, then it must be an item
328 // (because we aren't supplying our own where clause).
329 SqlArguments args = new SqlArguments(url, null, null);
330 if (TextUtils.isEmpty(args.where)) {
331 return "vnd.android.cursor.dir/" + args.table;
332 } else {
333 return "vnd.android.cursor.item/" + args.table;
334 }
335 }
336
337 @Override
338 public int bulkInsert(Uri uri, ContentValues[] values) {
339 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 if (TABLE_FAVORITES.equals(args.table)) {
341 return 0;
342 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700343 checkWritePermissions(args);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800344 SettingsCache cache = SettingsCache.forTable(args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700345
346 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
347 db.beginTransaction();
348 try {
349 int numValues = values.length;
350 for (int i = 0; i < numValues; i++) {
351 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800352 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
354 }
355 db.setTransactionSuccessful();
356 } finally {
357 db.endTransaction();
358 }
359
360 sendNotify(uri);
361 return values.length;
362 }
363
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700364 /*
365 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
366 * This setting contains a list of the currently enabled location providers.
367 * But helper functions in android.providers.Settings can enable or disable
368 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800369 *
370 * @returns whether the database needs to be updated or not, also modifying
371 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700372 */
373 private boolean parseProviderList(Uri url, ContentValues initialValues) {
374 String value = initialValues.getAsString(Settings.Secure.VALUE);
375 String newProviders = null;
376 if (value != null && value.length() > 1) {
377 char prefix = value.charAt(0);
378 if (prefix == '+' || prefix == '-') {
379 // skip prefix
380 value = value.substring(1);
381
382 // read list of enabled providers into "providers"
383 String providers = "";
384 String[] columns = {Settings.Secure.VALUE};
385 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
386 Cursor cursor = query(url, columns, where, null, null);
387 if (cursor != null && cursor.getCount() == 1) {
388 try {
389 cursor.moveToFirst();
390 providers = cursor.getString(0);
391 } finally {
392 cursor.close();
393 }
394 }
395
396 int index = providers.indexOf(value);
397 int end = index + value.length();
398 // check for commas to avoid matching on partial string
399 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
400 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
401
402 if (prefix == '+' && index < 0) {
403 // append the provider to the list if not present
404 if (providers.length() == 0) {
405 newProviders = value;
406 } else {
407 newProviders = providers + ',' + value;
408 }
409 } else if (prefix == '-' && index >= 0) {
410 // remove the provider from the list if present
411 // remove leading and trailing commas
412 if (index > 0) index--;
413 if (end < providers.length()) end++;
414
415 newProviders = providers.substring(0, index);
416 if (end < providers.length()) {
417 newProviders += providers.substring(end);
418 }
419 } else {
420 // nothing changed, so no need to update the database
421 return false;
422 }
423
424 if (newProviders != null) {
425 initialValues.put(Settings.Secure.VALUE, newProviders);
426 }
427 }
428 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800429
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700430 return true;
431 }
432
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700433 @Override
434 public Uri insert(Uri url, ContentValues initialValues) {
435 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 if (TABLE_FAVORITES.equals(args.table)) {
437 return null;
438 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700439 checkWritePermissions(args);
440
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700441 // Special case LOCATION_PROVIDERS_ALLOWED.
442 // Support enabling/disabling a single provider (using "+" or "-" prefix)
443 String name = initialValues.getAsString(Settings.Secure.NAME);
444 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
445 if (!parseProviderList(url, initialValues)) return null;
446 }
447
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800448 SettingsCache cache = SettingsCache.forTable(args.table);
449 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
450 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
451 return Uri.withAppendedPath(url, name);
452 }
453
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
455 final long rowId = db.insert(args.table, null, initialValues);
456 if (rowId <= 0) return null;
457
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800458 SettingsCache.populate(cache, initialValues); // before we notify
459
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700460 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
461 url = getUriFor(url, initialValues, rowId);
462 sendNotify(url);
463 return url;
464 }
465
466 @Override
467 public int delete(Uri url, String where, String[] whereArgs) {
468 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 if (TABLE_FAVORITES.equals(args.table)) {
470 return 0;
471 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
472 args.table = TABLE_FAVORITES;
473 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474 checkWritePermissions(args);
475
476 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
477 int count = db.delete(args.table, args.where, args.args);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800478 if (count > 0) {
479 SettingsCache.wipe(args.table); // before we notify
480 sendNotify(url);
481 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
483 return count;
484 }
485
486 @Override
487 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
488 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 if (TABLE_FAVORITES.equals(args.table)) {
490 return 0;
491 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700492 checkWritePermissions(args);
493
494 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
495 int count = db.update(args.table, initialValues, args.where, args.args);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800496 if (count > 0) {
497 SettingsCache.wipe(args.table); // before we notify
498 sendNotify(url);
499 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
501 return count;
502 }
503
504 @Override
505 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
506
507 /*
508 * When a client attempts to openFile the default ringtone or
509 * notification setting Uri, we will proxy the call to the current
510 * default ringtone's Uri (if it is in the DRM or media provider).
511 */
512 int ringtoneType = RingtoneManager.getDefaultType(uri);
513 // Above call returns -1 if the Uri doesn't match a default type
514 if (ringtoneType != -1) {
515 Context context = getContext();
516
517 // Get the current value for the default sound
518 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700519
Marco Nelissen69f593c2009-07-28 09:55:04 -0700520 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700521 // Only proxy the openFile call to drm or media providers
522 String authority = soundUri.getAuthority();
523 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
524 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
525
526 if (isDrmAuthority) {
527 try {
528 // Check DRM access permission here, since once we
529 // do the below call the DRM will be checking our
530 // permission, not our caller's permission
531 DrmStore.enforceAccessDrmPermission(context);
532 } catch (SecurityException e) {
533 throw new FileNotFoundException(e.getMessage());
534 }
535 }
536
537 return context.getContentResolver().openFileDescriptor(soundUri, mode);
538 }
539 }
540 }
541
542 return super.openFile(uri, mode);
543 }
Marco Nelissen69f593c2009-07-28 09:55:04 -0700544
545 @Override
546 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
547
548 /*
549 * When a client attempts to openFile the default ringtone or
550 * notification setting Uri, we will proxy the call to the current
551 * default ringtone's Uri (if it is in the DRM or media provider).
552 */
553 int ringtoneType = RingtoneManager.getDefaultType(uri);
554 // Above call returns -1 if the Uri doesn't match a default type
555 if (ringtoneType != -1) {
556 Context context = getContext();
557
558 // Get the current value for the default sound
559 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
560
561 if (soundUri != null) {
562 // Only proxy the openFile call to drm or media providers
563 String authority = soundUri.getAuthority();
564 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
565 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
566
567 if (isDrmAuthority) {
568 try {
569 // Check DRM access permission here, since once we
570 // do the below call the DRM will be checking our
571 // permission, not our caller's permission
572 DrmStore.enforceAccessDrmPermission(context);
573 } catch (SecurityException e) {
574 throw new FileNotFoundException(e.getMessage());
575 }
576 }
577
578 ParcelFileDescriptor pfd = null;
579 try {
580 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
581 return new AssetFileDescriptor(pfd, 0, -1);
582 } catch (FileNotFoundException ex) {
583 // fall through and open the fallback ringtone below
584 }
585 }
586
587 try {
588 return super.openAssetFile(soundUri, mode);
589 } catch (FileNotFoundException ex) {
590 // Since a non-null Uri was specified, but couldn't be opened,
591 // fall back to the built-in ringtone.
592 return context.getResources().openRawResourceFd(
593 com.android.internal.R.raw.fallbackring);
594 }
595 }
596 // no need to fall through and have openFile() try again, since we
597 // already know that will fail.
598 throw new FileNotFoundException(); // or return null ?
599 }
600
601 // Note that this will end up calling openFile() above.
602 return super.openAssetFile(uri, mode);
603 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800604
605 /**
606 * In-memory LRU Cache of system and secure settings, along with
607 * associated helper functions to keep cache coherent with the
608 * database.
609 */
610 private static final class SettingsCache extends LinkedHashMap<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800611
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800612 public SettingsCache() {
613 super(MAX_CACHE_ENTRIES, 0.75f /* load factor */, true /* access ordered */);
614 }
615
616 @Override
617 protected boolean removeEldestEntry(Map.Entry eldest) {
618 return size() > MAX_CACHE_ENTRIES;
619 }
620
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800621 /**
622 * Atomic cache population, conditional on size of value and if
623 * we lost a race.
624 *
625 * @returns a Bundle to send back to the client from call(), even
626 * if we lost the race.
627 */
628 public Bundle putIfAbsent(String key, String value) {
629 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
630 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
631 synchronized (this) {
632 if (!containsKey(key)) {
633 put(key, bundle);
634 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800635 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800636 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800637 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800638 }
639
640 public static SettingsCache forTable(String tableName) {
641 if ("system".equals(tableName)) {
642 return SettingsProvider.sSystemCache;
643 }
644 if ("secure".equals(tableName)) {
645 return SettingsProvider.sSecureCache;
646 }
647 return null;
648 }
649
650 /**
651 * Populates a key in a given (possibly-null) cache.
652 */
653 public static void populate(SettingsCache cache, ContentValues contentValues) {
654 if (cache == null) {
655 return;
656 }
657 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
658 if (name == null) {
659 Log.w(TAG, "null name populating settings cache.");
660 return;
661 }
662 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
663 synchronized (cache) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800664 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
665 cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
666 } else {
667 cache.remove(name);
668 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800669 }
670 }
671
672 /**
673 * Used for wiping a whole cache on deletes when we're not
674 * sure what exactly was deleted or changed.
675 */
676 public static void wipe(String tableName) {
677 SettingsCache cache = SettingsCache.forTable(tableName);
678 if (cache == null) {
679 return;
680 }
681 synchronized (cache) {
682 cache.clear();
683 }
684 }
685
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800686 /**
687 * For suppressing duplicate/redundant settings inserts early,
688 * checking our cache first (but without faulting it in),
689 * before going to sqlite with the mutation.
690 */
691 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
692 if (cache == null) return false;
693 synchronized (cache) {
694 Bundle bundle = cache.get(name);
695 if (bundle == null) return false;
696 String oldValue = bundle.getPairValue();
697 if (oldValue == null && value == null) return true;
698 if ((oldValue == null) != (value == null)) return false;
699 return oldValue.equals(value);
700 }
701 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800702 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700703}