blob: 265d1386413618eadf0c8c3da5ff77c91b5ad826 [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;
Fred Quintanac70239e2009-12-17 10:28:33 -080020import java.util.Random;
21import java.security.SecureRandom;
22import java.security.NoSuchAlgorithmException;
-b master501eec92009-07-06 13:53:11 -070023
Amith Yamasani8823c0a82009-07-07 14:30:17 -070024import android.backup.BackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070025import android.content.ContentProvider;
26import android.content.ContentUris;
27import android.content.ContentValues;
28import android.content.Context;
29import android.content.pm.PackageManager;
Marco Nelissen69f593c2009-07-28 09:55:04 -070030import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.database.Cursor;
Fred Quintanac70239e2009-12-17 10:28:33 -080032import android.database.SQLException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070033import android.database.sqlite.SQLiteDatabase;
34import android.database.sqlite.SQLiteQueryBuilder;
Marco Nelissen69f593c2009-07-28 09:55:04 -070035import android.media.Ringtone;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.media.RingtoneManager;
37import android.net.Uri;
38import android.os.ParcelFileDescriptor;
-b master501eec92009-07-06 13:53:11 -070039import android.os.ServiceManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.os.SystemProperties;
41import android.provider.DrmStore;
42import android.provider.MediaStore;
43import android.provider.Settings;
44import android.text.TextUtils;
45import android.util.Log;
46
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047public class SettingsProvider extends ContentProvider {
48 private static final String TAG = "SettingsProvider";
49 private static final boolean LOCAL_LOGV = false;
50
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 private static final String TABLE_FAVORITES = "favorites";
52 private static final String TABLE_OLD_FAVORITES = "old_favorites";
53
James Wylder074da8f2009-02-25 08:38:31 -060054 protected DatabaseHelper mOpenHelper;
Amith Yamasani8823c0a82009-07-07 14:30:17 -070055 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070056
57 /**
58 * Decode a content URL into the table, projection, and arguments
59 * used to access the corresponding database rows.
60 */
61 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063 public final String where;
64 public final String[] args;
65
66 /** Operate on existing rows. */
67 SqlArguments(Uri url, String where, String[] args) {
68 if (url.getPathSegments().size() == 1) {
69 this.table = url.getPathSegments().get(0);
70 this.where = where;
71 this.args = args;
72 } else if (url.getPathSegments().size() != 2) {
73 throw new IllegalArgumentException("Invalid URI: " + url);
74 } else if (!TextUtils.isEmpty(where)) {
75 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
76 } else {
77 this.table = url.getPathSegments().get(0);
Doug Zongkeraed8f8e2010-01-07 18:07:50 -080078 if ("system".equals(this.table) || "secure".equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070079 this.where = Settings.NameValueTable.NAME + "=?";
80 this.args = new String[] { url.getPathSegments().get(1) };
81 } else {
82 this.where = "_id=" + ContentUris.parseId(url);
83 this.args = null;
84 }
85 }
86 }
87
88 /** Insert new rows (no where clause allowed). */
89 SqlArguments(Uri url) {
90 if (url.getPathSegments().size() == 1) {
91 this.table = url.getPathSegments().get(0);
92 this.where = null;
93 this.args = null;
94 } else {
95 throw new IllegalArgumentException("Invalid URI: " + url);
96 }
97 }
98 }
99
100 /**
101 * Get the content URI of a row added to a table.
102 * @param tableUri of the entire table
103 * @param values found in the row
104 * @param rowId of the row
105 * @return the content URI for this particular row
106 */
107 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
108 if (tableUri.getPathSegments().size() != 1) {
109 throw new IllegalArgumentException("Invalid URI: " + tableUri);
110 }
111 String table = tableUri.getPathSegments().get(0);
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800112 if ("system".equals(table) || "secure".equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700113 String name = values.getAsString(Settings.NameValueTable.NAME);
114 return Uri.withAppendedPath(tableUri, name);
115 } else {
116 return ContentUris.withAppendedId(tableUri, rowId);
117 }
118 }
119
120 /**
121 * Send a notification when a particular content URI changes.
122 * Modify the system property used to communicate the version of
123 * this table, for tables which have such a property. (The Settings
124 * contract class uses these to provide client-side caches.)
125 * @param uri to send notifications for
126 */
127 private void sendNotify(Uri uri) {
128 // Update the system property *first*, so if someone is listening for
129 // a notification and then using the contract class to get their data,
130 // the system property will be updated and they'll get the new data.
131
Amith Yamasanid1582142009-07-08 20:04:55 -0700132 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133 String property = null, table = uri.getPathSegments().get(0);
134 if (table.equals("system")) {
135 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700136 backedUpDataChanged = true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800137 } else if (table.equals("secure")) {
138 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700139 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140 }
141
142 if (property != null) {
143 long version = SystemProperties.getLong(property, 0) + 1;
144 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
145 SystemProperties.set(property, Long.toString(version));
146 }
147
-b master501eec92009-07-06 13:53:11 -0700148 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700149 if (backedUpDataChanged) {
150 mBackupManager.dataChanged();
151 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700152 // Now send the notification through the content framework.
153
154 String notify = uri.getQueryParameter("notify");
155 if (notify == null || "true".equals(notify)) {
156 getContext().getContentResolver().notifyChange(uri, null);
157 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
158 } else {
159 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
160 }
161 }
162
163 /**
164 * Make sure the caller has permission to write this data.
165 * @param args supplied by the caller
166 * @throws SecurityException if the caller is forbidden to write.
167 */
168 private void checkWritePermissions(SqlArguments args) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800169 if ("secure".equals(args.table) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800170 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800171 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
172 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700173 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800174 String.format("Permission denial: writing to secure settings requires %1$s",
175 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700176 }
177 }
178
179 @Override
180 public boolean onCreate() {
181 mOpenHelper = new DatabaseHelper(getContext());
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700182 mBackupManager = new BackupManager(getContext());
Fred Quintanac70239e2009-12-17 10:28:33 -0800183
184 if (!ensureAndroidIdIsSet()) {
185 return false;
186 }
187
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700188 return true;
189 }
190
Fred Quintanac70239e2009-12-17 10:28:33 -0800191 private boolean ensureAndroidIdIsSet() {
192 final Cursor c = query(Settings.Secure.CONTENT_URI,
193 new String[] { Settings.NameValueTable.VALUE },
194 Settings.NameValueTable.NAME + "=?",
195 new String[]{Settings.Secure.ANDROID_ID}, null);
196 try {
197 final String value = c.moveToNext() ? c.getString(0) : null;
198 if (value == null) {
199 final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
200 final String newAndroidIdValue = Long.toHexString(random.nextLong());
201 Log.d(TAG, "Generated and saved new ANDROID_ID");
202 final ContentValues values = new ContentValues();
203 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
204 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
205 final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
206 if (uri == null) {
207 return false;
208 }
209 }
210 return true;
211 } catch (NoSuchAlgorithmException e) {
212 return false;
213 } finally {
214 c.close();
215 }
216 }
217
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700218 @Override
219 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
220 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
222
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800223 // The favorites table was moved from this provider to a provider inside Home
224 // Home still need to query this table to upgrade from pre-cupcake builds
225 // However, a cupcake+ build with no data does not contain this table which will
226 // cause an exception in the SQL stack. The following line is a special case to
227 // 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 -0800228 if (TABLE_FAVORITES.equals(args.table)) {
229 return null;
230 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
231 args.table = TABLE_FAVORITES;
232 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
233 if (cursor != null) {
234 boolean exists = cursor.getCount() > 0;
235 cursor.close();
236 if (!exists) return null;
237 } else {
238 return null;
239 }
240 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800241
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
243 qb.setTables(args.table);
244
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
246 ret.setNotificationUri(getContext().getContentResolver(), url);
247 return ret;
248 }
249
250 @Override
251 public String getType(Uri url) {
252 // If SqlArguments supplies a where clause, then it must be an item
253 // (because we aren't supplying our own where clause).
254 SqlArguments args = new SqlArguments(url, null, null);
255 if (TextUtils.isEmpty(args.where)) {
256 return "vnd.android.cursor.dir/" + args.table;
257 } else {
258 return "vnd.android.cursor.item/" + args.table;
259 }
260 }
261
262 @Override
263 public int bulkInsert(Uri uri, ContentValues[] values) {
264 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 if (TABLE_FAVORITES.equals(args.table)) {
266 return 0;
267 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700268 checkWritePermissions(args);
269
270 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
271 db.beginTransaction();
272 try {
273 int numValues = values.length;
274 for (int i = 0; i < numValues; i++) {
275 if (db.insert(args.table, null, values[i]) < 0) return 0;
276 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
277 }
278 db.setTransactionSuccessful();
279 } finally {
280 db.endTransaction();
281 }
282
283 sendNotify(uri);
284 return values.length;
285 }
286
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700287 /*
288 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
289 * This setting contains a list of the currently enabled location providers.
290 * But helper functions in android.providers.Settings can enable or disable
291 * a single provider by using a "+" or "-" prefix before the provider name.
292 */
293 private boolean parseProviderList(Uri url, ContentValues initialValues) {
294 String value = initialValues.getAsString(Settings.Secure.VALUE);
295 String newProviders = null;
296 if (value != null && value.length() > 1) {
297 char prefix = value.charAt(0);
298 if (prefix == '+' || prefix == '-') {
299 // skip prefix
300 value = value.substring(1);
301
302 // read list of enabled providers into "providers"
303 String providers = "";
304 String[] columns = {Settings.Secure.VALUE};
305 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
306 Cursor cursor = query(url, columns, where, null, null);
307 if (cursor != null && cursor.getCount() == 1) {
308 try {
309 cursor.moveToFirst();
310 providers = cursor.getString(0);
311 } finally {
312 cursor.close();
313 }
314 }
315
316 int index = providers.indexOf(value);
317 int end = index + value.length();
318 // check for commas to avoid matching on partial string
319 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
320 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
321
322 if (prefix == '+' && index < 0) {
323 // append the provider to the list if not present
324 if (providers.length() == 0) {
325 newProviders = value;
326 } else {
327 newProviders = providers + ',' + value;
328 }
329 } else if (prefix == '-' && index >= 0) {
330 // remove the provider from the list if present
331 // remove leading and trailing commas
332 if (index > 0) index--;
333 if (end < providers.length()) end++;
334
335 newProviders = providers.substring(0, index);
336 if (end < providers.length()) {
337 newProviders += providers.substring(end);
338 }
339 } else {
340 // nothing changed, so no need to update the database
341 return false;
342 }
343
344 if (newProviders != null) {
345 initialValues.put(Settings.Secure.VALUE, newProviders);
346 }
347 }
348 }
349
350 return true;
351 }
352
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353 @Override
354 public Uri insert(Uri url, ContentValues initialValues) {
355 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 if (TABLE_FAVORITES.equals(args.table)) {
357 return null;
358 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 checkWritePermissions(args);
360
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700361 // Special case LOCATION_PROVIDERS_ALLOWED.
362 // Support enabling/disabling a single provider (using "+" or "-" prefix)
363 String name = initialValues.getAsString(Settings.Secure.NAME);
364 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
365 if (!parseProviderList(url, initialValues)) return null;
366 }
367
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
369 final long rowId = db.insert(args.table, null, initialValues);
370 if (rowId <= 0) return null;
371
372 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
373 url = getUriFor(url, initialValues, rowId);
374 sendNotify(url);
375 return url;
376 }
377
378 @Override
379 public int delete(Uri url, String where, String[] whereArgs) {
380 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 if (TABLE_FAVORITES.equals(args.table)) {
382 return 0;
383 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
384 args.table = TABLE_FAVORITES;
385 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386 checkWritePermissions(args);
387
388 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
389 int count = db.delete(args.table, args.where, args.args);
390 if (count > 0) sendNotify(url);
391 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
392 return count;
393 }
394
395 @Override
396 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
397 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 if (TABLE_FAVORITES.equals(args.table)) {
399 return 0;
400 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 checkWritePermissions(args);
402
403 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
404 int count = db.update(args.table, initialValues, args.where, args.args);
405 if (count > 0) sendNotify(url);
406 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
407 return count;
408 }
409
410 @Override
411 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
412
413 /*
414 * When a client attempts to openFile the default ringtone or
415 * notification setting Uri, we will proxy the call to the current
416 * default ringtone's Uri (if it is in the DRM or media provider).
417 */
418 int ringtoneType = RingtoneManager.getDefaultType(uri);
419 // Above call returns -1 if the Uri doesn't match a default type
420 if (ringtoneType != -1) {
421 Context context = getContext();
422
423 // Get the current value for the default sound
424 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700425
Marco Nelissen69f593c2009-07-28 09:55:04 -0700426 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700427 // Only proxy the openFile call to drm or media providers
428 String authority = soundUri.getAuthority();
429 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
430 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
431
432 if (isDrmAuthority) {
433 try {
434 // Check DRM access permission here, since once we
435 // do the below call the DRM will be checking our
436 // permission, not our caller's permission
437 DrmStore.enforceAccessDrmPermission(context);
438 } catch (SecurityException e) {
439 throw new FileNotFoundException(e.getMessage());
440 }
441 }
442
443 return context.getContentResolver().openFileDescriptor(soundUri, mode);
444 }
445 }
446 }
447
448 return super.openFile(uri, mode);
449 }
Marco Nelissen69f593c2009-07-28 09:55:04 -0700450
451 @Override
452 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
453
454 /*
455 * When a client attempts to openFile the default ringtone or
456 * notification setting Uri, we will proxy the call to the current
457 * default ringtone's Uri (if it is in the DRM or media provider).
458 */
459 int ringtoneType = RingtoneManager.getDefaultType(uri);
460 // Above call returns -1 if the Uri doesn't match a default type
461 if (ringtoneType != -1) {
462 Context context = getContext();
463
464 // Get the current value for the default sound
465 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
466
467 if (soundUri != null) {
468 // Only proxy the openFile call to drm or media providers
469 String authority = soundUri.getAuthority();
470 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
471 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
472
473 if (isDrmAuthority) {
474 try {
475 // Check DRM access permission here, since once we
476 // do the below call the DRM will be checking our
477 // permission, not our caller's permission
478 DrmStore.enforceAccessDrmPermission(context);
479 } catch (SecurityException e) {
480 throw new FileNotFoundException(e.getMessage());
481 }
482 }
483
484 ParcelFileDescriptor pfd = null;
485 try {
486 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
487 return new AssetFileDescriptor(pfd, 0, -1);
488 } catch (FileNotFoundException ex) {
489 // fall through and open the fallback ringtone below
490 }
491 }
492
493 try {
494 return super.openAssetFile(soundUri, mode);
495 } catch (FileNotFoundException ex) {
496 // Since a non-null Uri was specified, but couldn't be opened,
497 // fall back to the built-in ringtone.
498 return context.getResources().openRawResourceFd(
499 com.android.internal.R.raw.fallbackring);
500 }
501 }
502 // no need to fall through and have openFile() try again, since we
503 // already know that will fail.
504 throw new FileNotFoundException(); // or return null ?
505 }
506
507 // Note that this will end up calling openFile() above.
508 return super.openAssetFile(uri, mode);
509 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700510}