2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.providers.downloads;
19 import android.content.ContentProvider;
20 import android.content.ContentValues;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.UriMatcher;
24 import android.content.pm.PackageManager;
25 import android.database.CrossProcessCursor;
26 import android.database.Cursor;
27 import android.database.CursorWindow;
28 import android.database.CursorWrapper;
29 import android.database.sqlite.SQLiteDatabase;
30 import android.database.sqlite.SQLiteOpenHelper;
31 import android.database.sqlite.SQLiteQueryBuilder;
32 import android.database.SQLException;
33 import android.net.Uri;
34 import android.os.Binder;
35 import android.os.ParcelFileDescriptor;
36 import android.os.Process;
37 import android.provider.Downloads;
38 import android.util.Config;
39 import android.util.Log;
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.util.HashSet;
48 * Allows application to interact with the download manager.
50 public final class DownloadProvider extends ContentProvider {
52 /** Database filename */
53 private static final String DB_NAME = "downloads.db";
54 /** Current database version */
55 private static final int DB_VERSION = 100;
56 /** Database version from which upgrading is a nop */
57 private static final int DB_VERSION_NOP_UPGRADE_FROM = 31;
58 /** Database version to which upgrading is a nop */
59 private static final int DB_VERSION_NOP_UPGRADE_TO = 100;
60 /** Name of table in the database */
61 private static final String DB_TABLE = "downloads";
63 /** MIME type for the entire download list */
64 private static final String DOWNLOAD_LIST_TYPE = "vnd.android.cursor.dir/download";
65 /** MIME type for an individual download */
66 private static final String DOWNLOAD_TYPE = "vnd.android.cursor.item/download";
68 /** URI matcher used to recognize URIs sent by applications */
69 private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
70 /** URI matcher constant for the URI of the entire download list */
71 private static final int DOWNLOADS = 1;
72 /** URI matcher constant for the URI of an individual download */
73 private static final int DOWNLOADS_ID = 2;
75 sURIMatcher.addURI("downloads", "download", DOWNLOADS);
76 sURIMatcher.addURI("downloads", "download/#", DOWNLOADS_ID);
79 private static final String[] sAppReadableColumnsArray = new String[] {
87 Downloads.LAST_MODIFICATION,
88 Downloads.NOTIFICATION_PACKAGE,
89 Downloads.NOTIFICATION_CLASS,
90 Downloads.TOTAL_BYTES,
91 Downloads.CURRENT_BYTES,
96 private static HashSet<String> sAppReadableColumnsSet;
98 sAppReadableColumnsSet = new HashSet<String>();
99 for (int i = 0; i < sAppReadableColumnsArray.length; ++i) {
100 sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]);
104 /** The database that lies underneath this content provider */
105 private SQLiteOpenHelper mOpenHelper = null;
108 * Creates and updated database on demand when opening it.
109 * Helper class to create database the first time the provider is
110 * initialized and upgrade it when a new version of the provider needs
111 * an updated version of the database.
113 private final class DatabaseHelper extends SQLiteOpenHelper {
115 public DatabaseHelper(final Context context) {
116 super(context, DB_NAME, null, DB_VERSION);
120 * Creates database the first time we try to open it.
123 public void onCreate(final SQLiteDatabase db) {
124 if (Constants.LOGVV) {
125 Log.v(Constants.TAG, "populating new database");
130 /* (not a javadoc comment)
131 * Checks data integrity when opening the database.
135 * public void onOpen(final SQLiteDatabase db) {
141 * Updates the database format when a content provider is used
142 * with a database that was created with a different format.
144 // Note: technically, this could also be a downgrade, so if we want
145 // to gracefully handle upgrades we should be careful about
146 // what to do on downgrades.
148 public void onUpgrade(final SQLiteDatabase db, int oldV, final int newV) {
149 if (oldV == DB_VERSION_NOP_UPGRADE_FROM) {
150 if (newV == DB_VERSION_NOP_UPGRADE_TO) { // that's a no-op upgrade.
153 // NOP_FROM and NOP_TO are identical, just in different codelines. Upgrading
154 // from NOP_FROM is the same as upgrading from NOP_TO.
155 oldV = DB_VERSION_NOP_UPGRADE_TO;
157 Log.i(Constants.TAG, "Upgrading downloads database from version " + oldV + " to " + newV
158 + ", which will destroy all old data");
165 * Initializes the content provider when it is created.
168 public boolean onCreate() {
169 mOpenHelper = new DatabaseHelper(getContext());
174 * Returns the content-provider-style MIME types of the various
175 * types accessible through this content provider.
178 public String getType(final Uri uri) {
179 int match = sURIMatcher.match(uri);
182 return DOWNLOAD_LIST_TYPE;
185 return DOWNLOAD_TYPE;
188 if (Constants.LOGV) {
189 Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri);
191 throw new IllegalArgumentException("Unknown URI: " + uri);
197 * Creates the table that'll hold the download information.
199 private void createTable(SQLiteDatabase db) {
201 db.execSQL("CREATE TABLE " + DB_TABLE + "(" +
202 Downloads._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
203 Downloads.URI + " TEXT, " +
204 Constants.RETRY_AFTER___REDIRECT_COUNT + " INTEGER, " +
205 Downloads.APP_DATA + " TEXT, " +
206 Downloads.NO_INTEGRITY + " BOOLEAN, " +
207 Downloads.FILENAME_HINT + " TEXT, " +
208 Constants.OTA_UPDATE + " BOOLEAN, " +
209 Downloads._DATA + " TEXT, " +
210 Downloads.MIMETYPE + " TEXT, " +
211 Downloads.DESTINATION + " INTEGER, " +
212 Constants.NO_SYSTEM_FILES + " BOOLEAN, " +
213 Downloads.VISIBILITY + " INTEGER, " +
214 Downloads.CONTROL + " INTEGER, " +
215 Downloads.STATUS + " INTEGER, " +
216 Constants.FAILED_CONNECTIONS + " INTEGER, " +
217 Downloads.LAST_MODIFICATION + " BIGINT, " +
218 Downloads.NOTIFICATION_PACKAGE + " TEXT, " +
219 Downloads.NOTIFICATION_CLASS + " TEXT, " +
220 Downloads.NOTIFICATION_EXTRAS + " TEXT, " +
221 Downloads.COOKIE_DATA + " TEXT, " +
222 Downloads.USER_AGENT + " TEXT, " +
223 Downloads.REFERER + " TEXT, " +
224 Downloads.TOTAL_BYTES + " INTEGER, " +
225 Downloads.CURRENT_BYTES + " INTEGER, " +
226 Constants.ETAG + " TEXT, " +
227 Constants.UID + " INTEGER, " +
228 Downloads.OTHER_UID + " INTEGER, " +
229 Downloads.TITLE + " TEXT, " +
230 Downloads.DESCRIPTION + " TEXT, " +
231 Constants.MEDIA_SCANNED + " BOOLEAN);");
232 } catch (SQLException ex) {
233 Log.e(Constants.TAG, "couldn't create table in downloads database");
239 * Deletes the table that holds the download information.
241 private void dropTable(SQLiteDatabase db) {
243 db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
244 } catch (SQLException ex) {
245 Log.e(Constants.TAG, "couldn't drop table in downloads database");
251 * Inserts a row in the database
254 public Uri insert(final Uri uri, final ContentValues values) {
255 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
257 if (sURIMatcher.match(uri) != DOWNLOADS) {
259 Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);
261 throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
264 ContentValues filteredValues = new ContentValues();
266 copyString(Downloads.URI, values, filteredValues);
267 copyString(Downloads.APP_DATA, values, filteredValues);
268 copyBoolean(Downloads.NO_INTEGRITY, values, filteredValues);
269 copyString(Downloads.FILENAME_HINT, values, filteredValues);
270 copyString(Downloads.MIMETYPE, values, filteredValues);
271 Integer i = values.getAsInteger(Downloads.DESTINATION);
273 if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED)
274 != PackageManager.PERMISSION_GRANTED
275 && i != Downloads.DESTINATION_EXTERNAL
276 && i != Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE) {
277 throw new SecurityException("unauthorized destination code");
279 filteredValues.put(Downloads.DESTINATION, i);
280 if (i != Downloads.DESTINATION_EXTERNAL &&
281 values.getAsInteger(Downloads.VISIBILITY) == null) {
282 filteredValues.put(Downloads.VISIBILITY, Downloads.VISIBILITY_HIDDEN);
285 copyInteger(Downloads.VISIBILITY, values, filteredValues);
286 copyInteger(Downloads.CONTROL, values, filteredValues);
287 filteredValues.put(Downloads.STATUS, Downloads.STATUS_PENDING);
288 filteredValues.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis());
289 String pckg = values.getAsString(Downloads.NOTIFICATION_PACKAGE);
290 String clazz = values.getAsString(Downloads.NOTIFICATION_CLASS);
291 if (pckg != null && clazz != null) {
292 int uid = Binder.getCallingUid();
295 getContext().getPackageManager().getApplicationInfo(pckg, 0).uid == uid) {
296 filteredValues.put(Downloads.NOTIFICATION_PACKAGE, pckg);
297 filteredValues.put(Downloads.NOTIFICATION_CLASS, clazz);
299 } catch (PackageManager.NameNotFoundException ex) {
300 /* ignored for now */
303 copyString(Downloads.NOTIFICATION_EXTRAS, values, filteredValues);
304 copyString(Downloads.COOKIE_DATA, values, filteredValues);
305 copyString(Downloads.USER_AGENT, values, filteredValues);
306 copyString(Downloads.REFERER, values, filteredValues);
307 if (getContext().checkCallingPermission(Downloads.PERMISSION_ACCESS_ADVANCED)
308 == PackageManager.PERMISSION_GRANTED) {
309 copyInteger(Downloads.OTHER_UID, values, filteredValues);
311 filteredValues.put(Constants.UID, Binder.getCallingUid());
312 if (Binder.getCallingUid() == 0) {
313 copyInteger(Constants.UID, values, filteredValues);
315 copyString(Downloads.TITLE, values, filteredValues);
316 copyString(Downloads.DESCRIPTION, values, filteredValues);
318 if (Constants.LOGVV) {
319 Log.v(Constants.TAG, "initiating download with UID "
320 + filteredValues.getAsInteger(Constants.UID));
321 if (filteredValues.containsKey(Downloads.OTHER_UID)) {
322 Log.v(Constants.TAG, "other UID " +
323 filteredValues.getAsInteger(Downloads.OTHER_UID));
327 Context context = getContext();
328 context.startService(new Intent(context, DownloadService.class));
330 long rowID = db.insert(DB_TABLE, null, filteredValues);
335 context.startService(new Intent(context, DownloadService.class));
336 ret = Uri.parse(Downloads.CONTENT_URI + "/" + rowID);
337 context.getContentResolver().notifyChange(uri, null);
340 Log.d(Constants.TAG, "couldn't insert into downloads database");
348 * Starts a database query
351 public Cursor query(final Uri uri, String[] projection,
352 final String selection, final String[] selectionArgs,
355 Helpers.validateSelection(selection, sAppReadableColumnsSet);
357 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
359 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
361 int match = sURIMatcher.match(uri);
362 boolean emptyWhere = true;
365 qb.setTables(DB_TABLE);
369 qb.setTables(DB_TABLE);
370 qb.appendWhere(Downloads._ID + "=");
371 qb.appendWhere(uri.getPathSegments().get(1));
376 if (Constants.LOGV) {
377 Log.v(Constants.TAG, "querying unknown URI: " + uri);
379 throw new IllegalArgumentException("Unknown URI: " + uri);
383 if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
385 qb.appendWhere(" AND ");
387 qb.appendWhere("( " + Constants.UID + "=" + Binder.getCallingUid() + " OR "
388 + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )");
391 if (projection == null) {
392 projection = sAppReadableColumnsArray;
394 for (int i = 0; i < projection.length; ++i) {
395 if (!sAppReadableColumnsSet.contains(projection[i])) {
396 throw new IllegalArgumentException(
397 "column " + projection[i] + " is not allowed in queries");
403 if (Constants.LOGVV) {
404 java.lang.StringBuilder sb = new java.lang.StringBuilder();
405 sb.append("starting query, database is ");
410 if (projection == null) {
411 sb.append("projection is null; ");
412 } else if (projection.length == 0) {
413 sb.append("projection is empty; ");
415 for (int i = 0; i < projection.length; ++i) {
416 sb.append("projection[");
419 sb.append(projection[i]);
423 sb.append("selection is ");
424 sb.append(selection);
426 if (selectionArgs == null) {
427 sb.append("selectionArgs is null; ");
428 } else if (selectionArgs.length == 0) {
429 sb.append("selectionArgs is empty; ");
431 for (int i = 0; i < selectionArgs.length; ++i) {
432 sb.append("selectionArgs[");
435 sb.append(selectionArgs[i]);
439 sb.append("sort is ");
442 Log.v(Constants.TAG, sb.toString());
445 Cursor ret = qb.query(db, projection, selection, selectionArgs,
449 ret = new ReadOnlyCursorWrapper(ret);
453 ret.setNotificationUri(getContext().getContentResolver(), uri);
454 if (Constants.LOGVV) {
456 "created cursor " + ret + " on behalf of " + Binder.getCallingPid());
459 if (Constants.LOGV) {
460 Log.v(Constants.TAG, "query failed in downloads database");
468 * Updates a row in the database
471 public int update(final Uri uri, final ContentValues values,
472 final String where, final String[] whereArgs) {
474 Helpers.validateSelection(where, sAppReadableColumnsSet);
476 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
480 boolean startService = false;
482 ContentValues filteredValues;
483 if (Binder.getCallingPid() != Process.myPid()) {
484 filteredValues = new ContentValues();
485 copyString(Downloads.APP_DATA, values, filteredValues);
486 copyInteger(Downloads.VISIBILITY, values, filteredValues);
487 Integer i = values.getAsInteger(Downloads.CONTROL);
489 filteredValues.put(Downloads.CONTROL, i);
492 copyInteger(Downloads.CONTROL, values, filteredValues);
493 copyString(Downloads.TITLE, values, filteredValues);
494 copyString(Downloads.DESCRIPTION, values, filteredValues);
496 filteredValues = values;
498 int match = sURIMatcher.match(uri);
504 if (match == DOWNLOADS) {
505 myWhere = "( " + where + " )";
507 myWhere = "( " + where + " ) AND ";
512 if (match == DOWNLOADS_ID) {
513 String segment = uri.getPathSegments().get(1);
514 rowId = Long.parseLong(segment);
515 myWhere += " ( " + Downloads._ID + " = " + rowId + " ) ";
517 if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
518 myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR "
519 + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )";
521 if (filteredValues.size() > 0) {
522 count = db.update(DB_TABLE, filteredValues, myWhere, whereArgs);
530 Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri);
532 throw new UnsupportedOperationException("Cannot update URI: " + uri);
535 getContext().getContentResolver().notifyChange(uri, null);
537 Context context = getContext();
538 context.startService(new Intent(context, DownloadService.class));
544 * Deletes a row in the database
547 public int delete(final Uri uri, final String where,
548 final String[] whereArgs) {
550 Helpers.validateSelection(where, sAppReadableColumnsSet);
552 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
554 int match = sURIMatcher.match(uri);
560 if (match == DOWNLOADS) {
561 myWhere = "( " + where + " )";
563 myWhere = "( " + where + " ) AND ";
568 if (match == DOWNLOADS_ID) {
569 String segment = uri.getPathSegments().get(1);
570 long rowId = Long.parseLong(segment);
571 myWhere += " ( " + Downloads._ID + " = " + rowId + " ) ";
573 if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
574 myWhere += " AND ( " + Constants.UID + "=" + Binder.getCallingUid() + " OR "
575 + Downloads.OTHER_UID + "=" + Binder.getCallingUid() + " )";
577 count = db.delete(DB_TABLE, myWhere, whereArgs);
582 Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri);
584 throw new UnsupportedOperationException("Cannot delete URI: " + uri);
587 getContext().getContentResolver().notifyChange(uri, null);
592 * Remotely opens a file
595 public ParcelFileDescriptor openFile(Uri uri, String mode)
596 throws FileNotFoundException {
597 if (Constants.LOGVV) {
598 Log.v(Constants.TAG, "openFile uri: " + uri + ", mode: " + mode
599 + ", uid: " + Binder.getCallingUid());
600 Cursor cursor = query(Downloads.CONTENT_URI, new String[] { "_id" }, null, null, "_id");
601 if (cursor == null) {
602 Log.v(Constants.TAG, "null cursor in openFile");
604 if (!cursor.moveToFirst()) {
605 Log.v(Constants.TAG, "empty cursor in openFile");
608 Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available");
609 } while(cursor.moveToNext());
613 cursor = query(uri, new String[] { "_data" }, null, null, null);
614 if (cursor == null) {
615 Log.v(Constants.TAG, "null cursor in openFile");
617 if (!cursor.moveToFirst()) {
618 Log.v(Constants.TAG, "empty cursor in openFile");
620 String filename = cursor.getString(0);
621 Log.v(Constants.TAG, "filename in openFile: " + filename);
622 if (new java.io.File(filename).isFile()) {
623 Log.v(Constants.TAG, "file exists in openFile");
630 // This logic is mostly copied form openFileHelper. If openFileHelper eventually
631 // gets split into small bits (to extract the filename and the modebits),
632 // this code could use the separate bits and be deeply simplified.
633 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
634 int count = (c != null) ? c.getCount() : 0;
636 // If there is not exactly one result, throw an appropriate exception.
641 throw new FileNotFoundException("No entry for " + uri);
643 throw new FileNotFoundException("Multiple items at " + uri);
647 String path = c.getString(0);
650 throw new FileNotFoundException("No filename found.");
652 if (!Helpers.isFilenameValid(path)) {
653 throw new FileNotFoundException("Invalid filename.");
656 if (!"r".equals(mode)) {
657 throw new FileNotFoundException("Bad mode for " + uri + ": " + mode);
659 ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path),
660 ParcelFileDescriptor.MODE_READ_ONLY);
663 if (Constants.LOGV) {
664 Log.v(Constants.TAG, "couldn't open file");
666 throw new FileNotFoundException("couldn't open file");
668 ContentValues values = new ContentValues();
669 values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis());
670 update(uri, values, null, null);
675 private static final void copyInteger(String key, ContentValues from, ContentValues to) {
676 Integer i = from.getAsInteger(key);
682 private static final void copyBoolean(String key, ContentValues from, ContentValues to) {
683 Boolean b = from.getAsBoolean(key);
689 private static final void copyString(String key, ContentValues from, ContentValues to) {
690 String s = from.getAsString(key);
696 private class ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor {
697 public ReadOnlyCursorWrapper(Cursor cursor) {
699 mCursor = (CrossProcessCursor) cursor;
702 public boolean deleteRow() {
703 throw new SecurityException("Download manager cursors are read-only");
706 public boolean commitUpdates() {
707 throw new SecurityException("Download manager cursors are read-only");
710 public void fillWindow(int pos, CursorWindow window) {
711 mCursor.fillWindow(pos, window);
714 public CursorWindow getWindow() {
715 return mCursor.getWindow();
718 public boolean onMove(int oldPosition, int newPosition) {
719 return mCursor.onMove(oldPosition, newPosition);
722 private CrossProcessCursor mCursor;