SettingsProvider.java revision 1bd62bd3ca4d098196e91b43799d4010c1d26623
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.io.UnsupportedEncodingException;
21import java.security.NoSuchAlgorithmException;
22import java.security.SecureRandom;
23import java.util.LinkedHashMap;
24import java.util.Map;
25
26import android.app.backup.BackupManager;
27import android.content.ContentProvider;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.pm.PackageManager;
32import android.content.res.AssetFileDescriptor;
33import android.database.Cursor;
34import android.database.sqlite.SQLiteDatabase;
35import android.database.sqlite.SQLiteException;
36import android.database.sqlite.SQLiteQueryBuilder;
37import android.media.RingtoneManager;
38import android.net.Uri;
39import android.os.Bundle;
40import 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
48public class SettingsProvider extends ContentProvider {
49    private static final String TAG = "SettingsProvider";
50    private static final boolean LOCAL_LOGV = false;
51
52    private static final String TABLE_FAVORITES = "favorites";
53    private static final String TABLE_OLD_FAVORITES = "old_favorites";
54
55    private static final String[] COLUMN_VALUE = new String[] { "value" };
56
57    // 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
63    private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
64
65    protected DatabaseHelper mOpenHelper;
66    private BackupManager mBackupManager;
67
68    /**
69     * Decode a content URL into the table, projection, and arguments
70     * used to access the corresponding database rows.
71     */
72    private static class SqlArguments {
73        public String table;
74        public final String where;
75        public final String[] args;
76
77        /** Operate on existing rows. */
78        SqlArguments(Uri url, String where, String[] args) {
79            if (url.getPathSegments().size() == 1) {
80                this.table = url.getPathSegments().get(0);
81                this.where = where;
82                this.args = args;
83            } else if (url.getPathSegments().size() != 2) {
84                throw new IllegalArgumentException("Invalid URI: " + url);
85            } else if (!TextUtils.isEmpty(where)) {
86                throw new UnsupportedOperationException("WHERE clause not supported: " + url);
87            } else {
88                this.table = url.getPathSegments().get(0);
89                if ("system".equals(this.table) || "secure".equals(this.table)) {
90                    this.where = Settings.NameValueTable.NAME + "=?";
91                    this.args = new String[] { url.getPathSegments().get(1) };
92                } else {
93                    this.where = "_id=" + ContentUris.parseId(url);
94                    this.args = null;
95                }
96            }
97        }
98
99        /** Insert new rows (no where clause allowed). */
100        SqlArguments(Uri url) {
101            if (url.getPathSegments().size() == 1) {
102                this.table = url.getPathSegments().get(0);
103                this.where = null;
104                this.args = null;
105            } else {
106                throw new IllegalArgumentException("Invalid URI: " + url);
107            }
108        }
109    }
110
111    /**
112     * Get the content URI of a row added to a table.
113     * @param tableUri of the entire table
114     * @param values found in the row
115     * @param rowId of the row
116     * @return the content URI for this particular row
117     */
118    private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
119        if (tableUri.getPathSegments().size() != 1) {
120            throw new IllegalArgumentException("Invalid URI: " + tableUri);
121        }
122        String table = tableUri.getPathSegments().get(0);
123        if ("system".equals(table) || "secure".equals(table)) {
124            String name = values.getAsString(Settings.NameValueTable.NAME);
125            return Uri.withAppendedPath(tableUri, name);
126        } else {
127            return ContentUris.withAppendedId(tableUri, rowId);
128        }
129    }
130
131    /**
132     * Send a notification when a particular content URI changes.
133     * Modify the system property used to communicate the version of
134     * this table, for tables which have such a property.  (The Settings
135     * contract class uses these to provide client-side caches.)
136     * @param uri to send notifications for
137     */
138    private void sendNotify(Uri uri) {
139        // Update the system property *first*, so if someone is listening for
140        // a notification and then using the contract class to get their data,
141        // the system property will be updated and they'll get the new data.
142
143        boolean backedUpDataChanged = false;
144        String property = null, table = uri.getPathSegments().get(0);
145        if (table.equals("system")) {
146            property = Settings.System.SYS_PROP_SETTING_VERSION;
147            backedUpDataChanged = true;
148        } else if (table.equals("secure")) {
149            property = Settings.Secure.SYS_PROP_SETTING_VERSION;
150            backedUpDataChanged = true;
151        }
152
153        if (property != null) {
154            long version = SystemProperties.getLong(property, 0) + 1;
155            if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
156            SystemProperties.set(property, Long.toString(version));
157        }
158
159        // Inform the backup manager about a data change
160        if (backedUpDataChanged) {
161            mBackupManager.dataChanged();
162        }
163        // Now send the notification through the content framework.
164
165        String notify = uri.getQueryParameter("notify");
166        if (notify == null || "true".equals(notify)) {
167            getContext().getContentResolver().notifyChange(uri, null);
168            if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
169        } else {
170            if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
171        }
172    }
173
174    /**
175     * Make sure the caller has permission to write this data.
176     * @param args supplied by the caller
177     * @throws SecurityException if the caller is forbidden to write.
178     */
179    private void checkWritePermissions(SqlArguments args) {
180        if ("secure".equals(args.table) &&
181            getContext().checkCallingOrSelfPermission(
182                    android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
183            PackageManager.PERMISSION_GRANTED) {
184            throw new SecurityException(
185                    String.format("Permission denial: writing to secure settings requires %1$s",
186                                  android.Manifest.permission.WRITE_SECURE_SETTINGS));
187        }
188    }
189
190    @Override
191    public boolean onCreate() {
192        mOpenHelper = new DatabaseHelper(getContext());
193        mBackupManager = new BackupManager(getContext());
194
195        if (!ensureAndroidIdIsSet()) {
196            return false;
197        }
198
199        return true;
200    }
201
202    private boolean ensureAndroidIdIsSet() {
203        final Cursor c = query(Settings.Secure.CONTENT_URI,
204                new String[] { Settings.NameValueTable.VALUE },
205                Settings.NameValueTable.NAME + "=?",
206                new String[] { Settings.Secure.ANDROID_ID }, null);
207        try {
208            final String value = c.moveToNext() ? c.getString(0) : null;
209            if (value == null) {
210                final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
211                String serial = SystemProperties.get("ro.serialno");
212                if (serial != null) {
213                    try {
214                        random.setSeed(serial.getBytes("UTF-8"));
215                    } catch (UnsupportedEncodingException ignore) {
216                        // stick with default seed
217                    }
218                }
219                final String newAndroidIdValue = Long.toHexString(random.nextLong());
220                Log.d(TAG, "Generated and saved new ANDROID_ID");
221                final ContentValues values = new ContentValues();
222                values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
223                values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
224                final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
225                if (uri == null) {
226                    return false;
227                }
228            }
229            return true;
230        } catch (NoSuchAlgorithmException e) {
231            return false;
232        } finally {
233            c.close();
234        }
235    }
236
237    /**
238     * Fast path that avoids the use of chatty remoted Cursors.
239     */
240    @Override
241    public Bundle call(String method, String request, Bundle args) {
242        if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
243            return lookupValue("system", sSystemCache, request);
244        }
245        if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
246            return lookupValue("secure", sSecureCache, request);
247        }
248        return null;
249    }
250
251    // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
252    // possibly with a null value, or null on failure.
253    private Bundle lookupValue(String table, SettingsCache cache, String key) {
254        synchronized (cache) {
255            if (cache.containsKey(key)) {
256                return cache.get(key);
257            }
258        }
259
260        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
261        Cursor cursor = null;
262        try {
263            cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
264                              null, null, null, null);
265            if (cursor != null && cursor.getCount() == 1) {
266                cursor.moveToFirst();
267                String value = cursor.getString(0);
268                Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
269                cache.putIfAbsentLocked(key, bundle);
270                return bundle;
271            }
272        } catch (SQLiteException e) {
273            Log.w(TAG, "settings lookup error", e);
274            return null;
275        } finally {
276            if (cursor != null) cursor.close();
277        }
278        cache.putIfAbsentLocked(key, NULL_SETTING);
279        return NULL_SETTING;
280    }
281
282    @Override
283    public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
284        SqlArguments args = new SqlArguments(url, where, whereArgs);
285        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
286
287        // The favorites table was moved from this provider to a provider inside Home
288        // Home still need to query this table to upgrade from pre-cupcake builds
289        // However, a cupcake+ build with no data does not contain this table which will
290        // cause an exception in the SQL stack. The following line is a special case to
291        // let the caller of the query have a chance to recover and avoid the exception
292        if (TABLE_FAVORITES.equals(args.table)) {
293            return null;
294        } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
295            args.table = TABLE_FAVORITES;
296            Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
297            if (cursor != null) {
298                boolean exists = cursor.getCount() > 0;
299                cursor.close();
300                if (!exists) return null;
301            } else {
302                return null;
303            }
304        }
305
306        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
307        qb.setTables(args.table);
308
309        Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
310        ret.setNotificationUri(getContext().getContentResolver(), url);
311        return ret;
312    }
313
314    @Override
315    public String getType(Uri url) {
316        // If SqlArguments supplies a where clause, then it must be an item
317        // (because we aren't supplying our own where clause).
318        SqlArguments args = new SqlArguments(url, null, null);
319        if (TextUtils.isEmpty(args.where)) {
320            return "vnd.android.cursor.dir/" + args.table;
321        } else {
322            return "vnd.android.cursor.item/" + args.table;
323        }
324    }
325
326    @Override
327    public int bulkInsert(Uri uri, ContentValues[] values) {
328        SqlArguments args = new SqlArguments(uri);
329        if (TABLE_FAVORITES.equals(args.table)) {
330            return 0;
331        }
332        checkWritePermissions(args);
333        SettingsCache cache = SettingsCache.forTable(args.table);
334
335        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
336        db.beginTransaction();
337        try {
338            int numValues = values.length;
339            for (int i = 0; i < numValues; i++) {
340                if (db.insert(args.table, null, values[i]) < 0) return 0;
341                SettingsCache.populate(cache, values[i]);
342                if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
343            }
344            db.setTransactionSuccessful();
345        } finally {
346            db.endTransaction();
347        }
348
349        sendNotify(uri);
350        return values.length;
351    }
352
353    /*
354     * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
355     * This setting contains a list of the currently enabled location providers.
356     * But helper functions in android.providers.Settings can enable or disable
357     * a single provider by using a "+" or "-" prefix before the provider name.
358     *
359     * @returns whether the database needs to be updated or not, also modifying
360     *     'initialValues' if needed.
361     */
362    private boolean parseProviderList(Uri url, ContentValues initialValues) {
363        String value = initialValues.getAsString(Settings.Secure.VALUE);
364        String newProviders = null;
365        if (value != null && value.length() > 1) {
366            char prefix = value.charAt(0);
367            if (prefix == '+' || prefix == '-') {
368                // skip prefix
369                value = value.substring(1);
370
371                // read list of enabled providers into "providers"
372                String providers = "";
373                String[] columns = {Settings.Secure.VALUE};
374                String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
375                Cursor cursor = query(url, columns, where, null, null);
376                if (cursor != null && cursor.getCount() == 1) {
377                    try {
378                        cursor.moveToFirst();
379                        providers = cursor.getString(0);
380                    } finally {
381                        cursor.close();
382                    }
383                }
384
385                int index = providers.indexOf(value);
386                int end = index + value.length();
387                // check for commas to avoid matching on partial string
388                if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
389                if (end < providers.length() && providers.charAt(end) != ',') index = -1;
390
391                if (prefix == '+' && index < 0) {
392                    // append the provider to the list if not present
393                    if (providers.length() == 0) {
394                        newProviders = value;
395                    } else {
396                        newProviders = providers + ',' + value;
397                    }
398                } else if (prefix == '-' && index >= 0) {
399                    // remove the provider from the list if present
400                    // remove leading and trailing commas
401                    if (index > 0) index--;
402                    if (end < providers.length()) end++;
403
404                    newProviders = providers.substring(0, index);
405                    if (end < providers.length()) {
406                        newProviders += providers.substring(end);
407                    }
408                } else {
409                    // nothing changed, so no need to update the database
410                    return false;
411                }
412
413                if (newProviders != null) {
414                    initialValues.put(Settings.Secure.VALUE, newProviders);
415                }
416            }
417        }
418
419        return true;
420    }
421
422    @Override
423    public Uri insert(Uri url, ContentValues initialValues) {
424        SqlArguments args = new SqlArguments(url);
425        if (TABLE_FAVORITES.equals(args.table)) {
426            return null;
427        }
428        checkWritePermissions(args);
429
430        // Special case LOCATION_PROVIDERS_ALLOWED.
431        // Support enabling/disabling a single provider (using "+" or "-" prefix)
432        String name = initialValues.getAsString(Settings.Secure.NAME);
433        if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
434            if (!parseProviderList(url, initialValues)) return null;
435        }
436
437        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
438        final long rowId = db.insert(args.table, null, initialValues);
439        if (rowId <= 0) return null;
440
441        SettingsCache cache = SettingsCache.forTable(args.table);
442        SettingsCache.populate(cache, initialValues);  // before we notify
443
444        if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
445        url = getUriFor(url, initialValues, rowId);
446        sendNotify(url);
447        return url;
448    }
449
450    @Override
451    public int delete(Uri url, String where, String[] whereArgs) {
452        SqlArguments args = new SqlArguments(url, where, whereArgs);
453        if (TABLE_FAVORITES.equals(args.table)) {
454            return 0;
455        } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
456            args.table = TABLE_FAVORITES;
457        }
458        checkWritePermissions(args);
459
460        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
461        int count = db.delete(args.table, args.where, args.args);
462        if (count > 0) {
463            SettingsCache.wipe(args.table);  // before we notify
464            sendNotify(url);
465        }
466        if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
467        return count;
468    }
469
470    @Override
471    public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
472        SqlArguments args = new SqlArguments(url, where, whereArgs);
473        if (TABLE_FAVORITES.equals(args.table)) {
474            return 0;
475        }
476        checkWritePermissions(args);
477
478        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
479        int count = db.update(args.table, initialValues, args.where, args.args);
480        if (count > 0) {
481            SettingsCache.wipe(args.table);  // before we notify
482            sendNotify(url);
483        }
484        if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
485        return count;
486    }
487
488    @Override
489    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
490
491        /*
492         * When a client attempts to openFile the default ringtone or
493         * notification setting Uri, we will proxy the call to the current
494         * default ringtone's Uri (if it is in the DRM or media provider).
495         */
496        int ringtoneType = RingtoneManager.getDefaultType(uri);
497        // Above call returns -1 if the Uri doesn't match a default type
498        if (ringtoneType != -1) {
499            Context context = getContext();
500
501            // Get the current value for the default sound
502            Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
503
504            if (soundUri != null) {
505                // Only proxy the openFile call to drm or media providers
506                String authority = soundUri.getAuthority();
507                boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
508                if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
509
510                    if (isDrmAuthority) {
511                        try {
512                            // Check DRM access permission here, since once we
513                            // do the below call the DRM will be checking our
514                            // permission, not our caller's permission
515                            DrmStore.enforceAccessDrmPermission(context);
516                        } catch (SecurityException e) {
517                            throw new FileNotFoundException(e.getMessage());
518                        }
519                    }
520
521                    return context.getContentResolver().openFileDescriptor(soundUri, mode);
522                }
523            }
524        }
525
526        return super.openFile(uri, mode);
527    }
528
529    @Override
530    public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
531
532        /*
533         * When a client attempts to openFile the default ringtone or
534         * notification setting Uri, we will proxy the call to the current
535         * default ringtone's Uri (if it is in the DRM or media provider).
536         */
537        int ringtoneType = RingtoneManager.getDefaultType(uri);
538        // Above call returns -1 if the Uri doesn't match a default type
539        if (ringtoneType != -1) {
540            Context context = getContext();
541
542            // Get the current value for the default sound
543            Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
544
545            if (soundUri != null) {
546                // Only proxy the openFile call to drm or media providers
547                String authority = soundUri.getAuthority();
548                boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
549                if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
550
551                    if (isDrmAuthority) {
552                        try {
553                            // Check DRM access permission here, since once we
554                            // do the below call the DRM will be checking our
555                            // permission, not our caller's permission
556                            DrmStore.enforceAccessDrmPermission(context);
557                        } catch (SecurityException e) {
558                            throw new FileNotFoundException(e.getMessage());
559                        }
560                    }
561
562                    ParcelFileDescriptor pfd = null;
563                    try {
564                        pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
565                        return new AssetFileDescriptor(pfd, 0, -1);
566                    } catch (FileNotFoundException ex) {
567                        // fall through and open the fallback ringtone below
568                    }
569                }
570
571                try {
572                    return super.openAssetFile(soundUri, mode);
573                } catch (FileNotFoundException ex) {
574                    // Since a non-null Uri was specified, but couldn't be opened,
575                    // fall back to the built-in ringtone.
576                    return context.getResources().openRawResourceFd(
577                            com.android.internal.R.raw.fallbackring);
578                }
579            }
580            // no need to fall through and have openFile() try again, since we
581            // already know that will fail.
582            throw new FileNotFoundException(); // or return null ?
583        }
584
585        // Note that this will end up calling openFile() above.
586        return super.openAssetFile(uri, mode);
587    }
588
589    /**
590     * In-memory LRU Cache of system and secure settings, along with
591     * associated helper functions to keep cache coherent with the
592     * database.
593     */
594    private static final class SettingsCache extends LinkedHashMap<String, Bundle> {
595        public SettingsCache() {
596            super(MAX_CACHE_ENTRIES, 0.75f /* load factor */, true /* access ordered */);
597        }
598
599        @Override
600        protected boolean removeEldestEntry(Map.Entry eldest) {
601            return size() > MAX_CACHE_ENTRIES;
602        }
603
604        public void putIfAbsentLocked(String key, Bundle value) {
605            synchronized (this) {
606                if (containsKey(key)) {
607                    // Lost a race.
608                    return;
609                }
610                put(key, value);
611            }
612        }
613
614        public static SettingsCache forTable(String tableName) {
615            if ("system".equals(tableName)) {
616                return SettingsProvider.sSystemCache;
617            }
618            if ("secure".equals(tableName)) {
619                return SettingsProvider.sSecureCache;
620            }
621            return null;
622        }
623
624        /**
625         * Populates a key in a given (possibly-null) cache.
626         */
627        public static void populate(SettingsCache cache, ContentValues contentValues) {
628            if (cache == null) {
629                return;
630            }
631            String name = contentValues.getAsString(Settings.NameValueTable.NAME);
632            if (name == null) {
633                Log.w(TAG, "null name populating settings cache.");
634                return;
635            }
636            String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
637            synchronized (cache) {
638                cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
639            }
640        }
641
642        /**
643         * Used for wiping a whole cache on deletes when we're not
644         * sure what exactly was deleted or changed.
645         */
646        public static void wipe(String tableName) {
647            SettingsCache cache = SettingsCache.forTable(tableName);
648            if (cache == null) {
649                return;
650            }
651            synchronized (cache) {
652                cache.clear();
653            }
654        }
655
656    }
657}
658