OSDN Git Service

Code drop from //branches/cupcake/...@124589
[android-x86/packages-providers-DownloadProvider.git] / src / com / android / providers / downloads / DownloadProvider.java
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
17 package com.android.providers.downloads;
18
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;
40
41 import java.io.File;
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.util.HashSet;
45
46
47 /**
48  * Allows application to interact with the download manager.
49  */
50 public final class DownloadProvider extends ContentProvider {
51
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";
62
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";
67
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;
74     static {
75         sURIMatcher.addURI("downloads", "download", DOWNLOADS);
76         sURIMatcher.addURI("downloads", "download/#", DOWNLOADS_ID);
77     }
78
79     private static final String[] sAppReadableColumnsArray = new String[] {
80         Downloads._ID,
81         Downloads.APP_DATA,
82         Downloads._DATA,
83         Downloads.MIMETYPE,
84         Downloads.VISIBILITY,
85         Downloads.CONTROL,
86         Downloads.STATUS,
87         Downloads.LAST_MODIFICATION,
88         Downloads.NOTIFICATION_PACKAGE,
89         Downloads.NOTIFICATION_CLASS,
90         Downloads.TOTAL_BYTES,
91         Downloads.CURRENT_BYTES,
92         Downloads.TITLE,
93         Downloads.DESCRIPTION
94     };
95
96     private static HashSet<String> sAppReadableColumnsSet;
97     static {
98         sAppReadableColumnsSet = new HashSet<String>();
99         for (int i = 0; i < sAppReadableColumnsArray.length; ++i) {
100             sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]);
101         }
102     }
103
104     /** The database that lies underneath this content provider */
105     private SQLiteOpenHelper mOpenHelper = null;
106
107     /**
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.
112      */
113     private final class DatabaseHelper extends SQLiteOpenHelper {
114
115         public DatabaseHelper(final Context context) {
116             super(context, DB_NAME, null, DB_VERSION);
117         }
118
119         /**
120          * Creates database the first time we try to open it.
121          */
122         @Override
123         public void onCreate(final SQLiteDatabase db) {
124             if (Constants.LOGVV) {
125                 Log.v(Constants.TAG, "populating new database");
126             }
127             createTable(db);
128         }
129
130         /* (not a javadoc comment)
131          * Checks data integrity when opening the database.
132          */
133         /*
134          * @Override
135          * public void onOpen(final SQLiteDatabase db) {
136          *     super.onOpen(db);
137          * }
138          */
139
140         /**
141          * Updates the database format when a content provider is used
142          * with a database that was created with a different format.
143          */
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.
147         @Override
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.
151                     return;
152                 }
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;
156             }
157             Log.i(Constants.TAG, "Upgrading downloads database from version " + oldV + " to " + newV
158                     + ", which will destroy all old data");
159             dropTable(db);
160             createTable(db);
161         }
162     }
163
164     /**
165      * Initializes the content provider when it is created.
166      */
167     @Override
168     public boolean onCreate() {
169         mOpenHelper = new DatabaseHelper(getContext());
170         return true;
171     }
172
173     /**
174      * Returns the content-provider-style MIME types of the various
175      * types accessible through this content provider.
176      */
177     @Override
178     public String getType(final Uri uri) {
179         int match = sURIMatcher.match(uri);
180         switch (match) {
181             case DOWNLOADS: {
182                 return DOWNLOAD_LIST_TYPE;
183             }
184             case DOWNLOADS_ID: {
185                 return DOWNLOAD_TYPE;
186             }
187             default: {
188                 if (Constants.LOGV) {
189                     Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri);
190                 }
191                 throw new IllegalArgumentException("Unknown URI: " + uri);
192             }
193         }
194     }
195
196     /**
197      * Creates the table that'll hold the download information.
198      */
199     private void createTable(SQLiteDatabase db) {
200         try {
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");
234             throw ex;
235         }
236     }
237
238     /**
239      * Deletes the table that holds the download information.
240      */
241     private void dropTable(SQLiteDatabase db) {
242         try {
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");
246             throw ex;
247         }
248     }
249
250     /**
251      * Inserts a row in the database
252      */
253     @Override
254     public Uri insert(final Uri uri, final ContentValues values) {
255         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
256
257         if (sURIMatcher.match(uri) != DOWNLOADS) {
258             if (Config.LOGD) {
259                 Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);
260             }
261             throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
262         }
263
264         ContentValues filteredValues = new ContentValues();
265
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);
272         if (i != null) {
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");
278             }
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);
283             }
284         }
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();
293             try {
294                 if (uid == 0 ||
295                         getContext().getPackageManager().getApplicationInfo(pckg, 0).uid == uid) {
296                     filteredValues.put(Downloads.NOTIFICATION_PACKAGE, pckg);
297                     filteredValues.put(Downloads.NOTIFICATION_CLASS, clazz);
298                 }
299             } catch (PackageManager.NameNotFoundException ex) {
300                 /* ignored for now */
301             }
302         }
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);
310         }
311         filteredValues.put(Constants.UID, Binder.getCallingUid());
312         if (Binder.getCallingUid() == 0) {
313             copyInteger(Constants.UID, values, filteredValues);
314         }
315         copyString(Downloads.TITLE, values, filteredValues);
316         copyString(Downloads.DESCRIPTION, values, filteredValues);
317
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));
324             }
325         }
326
327         Context context = getContext();
328         context.startService(new Intent(context, DownloadService.class));
329
330         long rowID = db.insert(DB_TABLE, null, filteredValues);
331
332         Uri ret = null;
333
334         if (rowID != -1) {
335             context.startService(new Intent(context, DownloadService.class));
336             ret = Uri.parse(Downloads.CONTENT_URI + "/" + rowID);
337             context.getContentResolver().notifyChange(uri, null);
338         } else {
339             if (Config.LOGD) {
340                 Log.d(Constants.TAG, "couldn't insert into downloads database");
341             }
342         }
343
344         return ret;
345     }
346
347     /**
348      * Starts a database query
349      */
350     @Override
351     public Cursor query(final Uri uri, String[] projection,
352              final String selection, final String[] selectionArgs,
353              final String sort) {
354
355         Helpers.validateSelection(selection, sAppReadableColumnsSet);
356
357         SQLiteDatabase db = mOpenHelper.getReadableDatabase();
358
359         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
360
361         int match = sURIMatcher.match(uri);
362         boolean emptyWhere = true;
363         switch (match) {
364             case DOWNLOADS: {
365                 qb.setTables(DB_TABLE);
366                 break;
367             }
368             case DOWNLOADS_ID: {
369                 qb.setTables(DB_TABLE);
370                 qb.appendWhere(Downloads._ID + "=");
371                 qb.appendWhere(uri.getPathSegments().get(1));
372                 emptyWhere = false;
373                 break;
374             }
375             default: {
376                 if (Constants.LOGV) {
377                     Log.v(Constants.TAG, "querying unknown URI: " + uri);
378                 }
379                 throw new IllegalArgumentException("Unknown URI: " + uri);
380             }
381         }
382
383         if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
384             if (!emptyWhere) {
385                 qb.appendWhere(" AND ");
386             }
387             qb.appendWhere("( " + Constants.UID + "=" +  Binder.getCallingUid() + " OR "
388                     + Downloads.OTHER_UID + "=" +  Binder.getCallingUid() + " )");
389             emptyWhere = false;
390
391             if (projection == null) {
392                 projection = sAppReadableColumnsArray;
393             } else {
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");
398                     }
399                 }
400             }
401         }
402
403         if (Constants.LOGVV) {
404             java.lang.StringBuilder sb = new java.lang.StringBuilder();
405             sb.append("starting query, database is ");
406             if (db != null) {
407                 sb.append("not ");
408             }
409             sb.append("null; ");
410             if (projection == null) {
411                 sb.append("projection is null; ");
412             } else if (projection.length == 0) {
413                 sb.append("projection is empty; ");
414             } else {
415                 for (int i = 0; i < projection.length; ++i) {
416                     sb.append("projection[");
417                     sb.append(i);
418                     sb.append("] is ");
419                     sb.append(projection[i]);
420                     sb.append("; ");
421                 }
422             }
423             sb.append("selection is ");
424             sb.append(selection);
425             sb.append("; ");
426             if (selectionArgs == null) {
427                 sb.append("selectionArgs is null; ");
428             } else if (selectionArgs.length == 0) {
429                 sb.append("selectionArgs is empty; ");
430             } else {
431                 for (int i = 0; i < selectionArgs.length; ++i) {
432                     sb.append("selectionArgs[");
433                     sb.append(i);
434                     sb.append("] is ");
435                     sb.append(selectionArgs[i]);
436                     sb.append("; ");
437                 }
438             }
439             sb.append("sort is ");
440             sb.append(sort);
441             sb.append(".");
442             Log.v(Constants.TAG, sb.toString());
443         }
444
445         Cursor ret = qb.query(db, projection, selection, selectionArgs,
446                               null, null, sort);
447
448         if (ret != null) {
449            ret = new ReadOnlyCursorWrapper(ret);
450         }
451
452         if (ret != null) {
453             ret.setNotificationUri(getContext().getContentResolver(), uri);
454             if (Constants.LOGVV) {
455                 Log.v(Constants.TAG,
456                         "created cursor " + ret + " on behalf of " + Binder.getCallingPid());
457             }
458         } else {
459             if (Constants.LOGV) {
460                 Log.v(Constants.TAG, "query failed in downloads database");
461             }
462         }
463
464         return ret;
465     }
466
467     /**
468      * Updates a row in the database
469      */
470     @Override
471     public int update(final Uri uri, final ContentValues values,
472             final String where, final String[] whereArgs) {
473
474         Helpers.validateSelection(where, sAppReadableColumnsSet);
475
476         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
477
478         int count;
479         long rowId = 0;
480         boolean startService = false;
481
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);
488             if (i != null) {
489                 filteredValues.put(Downloads.CONTROL, i);
490                 startService = true;
491             }
492             copyInteger(Downloads.CONTROL, values, filteredValues);
493             copyString(Downloads.TITLE, values, filteredValues);
494             copyString(Downloads.DESCRIPTION, values, filteredValues);
495         } else {
496             filteredValues = values;
497         }
498         int match = sURIMatcher.match(uri);
499         switch (match) {
500             case DOWNLOADS:
501             case DOWNLOADS_ID: {
502                 String myWhere;
503                 if (where != null) {
504                     if (match == DOWNLOADS) {
505                         myWhere = "( " + where + " )";
506                     } else {
507                         myWhere = "( " + where + " ) AND ";
508                     }
509                 } else {
510                     myWhere = "";
511                 }
512                 if (match == DOWNLOADS_ID) {
513                     String segment = uri.getPathSegments().get(1);
514                     rowId = Long.parseLong(segment);
515                     myWhere += " ( " + Downloads._ID + " = " + rowId + " ) ";
516                 }
517                 if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
518                     myWhere += " AND ( " + Constants.UID + "=" +  Binder.getCallingUid() + " OR "
519                             + Downloads.OTHER_UID + "=" +  Binder.getCallingUid() + " )";
520                 }
521                 if (filteredValues.size() > 0) {
522                     count = db.update(DB_TABLE, filteredValues, myWhere, whereArgs);
523                 } else {
524                     count = 0;
525                 }
526                 break;
527             }
528             default: {
529                 if (Config.LOGD) {
530                     Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri);
531                 }
532                 throw new UnsupportedOperationException("Cannot update URI: " + uri);
533             }
534         }
535         getContext().getContentResolver().notifyChange(uri, null);
536         if (startService) {
537             Context context = getContext();
538             context.startService(new Intent(context, DownloadService.class));
539         }
540         return count;
541     }
542
543     /**
544      * Deletes a row in the database
545      */
546     @Override
547     public int delete(final Uri uri, final String where,
548             final String[] whereArgs) {
549
550         Helpers.validateSelection(where, sAppReadableColumnsSet);
551
552         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
553         int count;
554         int match = sURIMatcher.match(uri);
555         switch (match) {
556             case DOWNLOADS:
557             case DOWNLOADS_ID: {
558                 String myWhere;
559                 if (where != null) {
560                     if (match == DOWNLOADS) {
561                         myWhere = "( " + where + " )";
562                     } else {
563                         myWhere = "( " + where + " ) AND ";
564                     }
565                 } else {
566                     myWhere = "";
567                 }
568                 if (match == DOWNLOADS_ID) {
569                     String segment = uri.getPathSegments().get(1);
570                     long rowId = Long.parseLong(segment);
571                     myWhere += " ( " + Downloads._ID + " = " + rowId + " ) ";
572                 }
573                 if (Binder.getCallingPid() != Process.myPid() && Binder.getCallingUid() != 0) {
574                     myWhere += " AND ( " + Constants.UID + "=" +  Binder.getCallingUid() + " OR "
575                             + Downloads.OTHER_UID + "=" +  Binder.getCallingUid() + " )";
576                 }
577                 count = db.delete(DB_TABLE, myWhere, whereArgs);
578                 break;
579             }
580             default: {
581                 if (Config.LOGD) {
582                     Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri);
583                 }
584                 throw new UnsupportedOperationException("Cannot delete URI: " + uri);
585             }
586         }
587         getContext().getContentResolver().notifyChange(uri, null);
588         return count;
589     }
590
591     /**
592      * Remotely opens a file
593      */
594     @Override
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");
603             } else {
604                 if (!cursor.moveToFirst()) {
605                     Log.v(Constants.TAG, "empty cursor in openFile");
606                 } else {
607                     do {
608                         Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available");
609                     } while(cursor.moveToNext());
610                 }
611                 cursor.close();
612             }
613             cursor = query(uri, new String[] { "_data" }, null, null, null);
614             if (cursor == null) {
615                 Log.v(Constants.TAG, "null cursor in openFile");
616             } else {
617                 if (!cursor.moveToFirst()) {
618                     Log.v(Constants.TAG, "empty cursor in openFile");
619                 } else {
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");
624                     }
625                 }
626                cursor.close();
627             }
628         }
629
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;
635         if (count != 1) {
636             // If there is not exactly one result, throw an appropriate exception.
637             if (c != null) {
638                 c.close();
639             }
640             if (count == 0) {
641                 throw new FileNotFoundException("No entry for " + uri);
642             }
643             throw new FileNotFoundException("Multiple items at " + uri);
644         }
645
646         c.moveToFirst();
647         String path = c.getString(0);
648         c.close();
649         if (path == null) {
650             throw new FileNotFoundException("No filename found.");
651         }
652         if (!Helpers.isFilenameValid(path)) {
653             throw new FileNotFoundException("Invalid filename.");
654         }
655
656         if (!"r".equals(mode)) {
657             throw new FileNotFoundException("Bad mode for " + uri + ": " + mode);
658         }
659         ParcelFileDescriptor ret = ParcelFileDescriptor.open(new File(path),
660                 ParcelFileDescriptor.MODE_READ_ONLY);
661
662         if (ret == null) {
663             if (Constants.LOGV) {
664                 Log.v(Constants.TAG, "couldn't open file");
665             }
666             throw new FileNotFoundException("couldn't open file");
667         } else {
668             ContentValues values = new ContentValues();
669             values.put(Downloads.LAST_MODIFICATION, System.currentTimeMillis());
670             update(uri, values, null, null);
671         }
672         return ret;
673     }
674
675     private static final void copyInteger(String key, ContentValues from, ContentValues to) {
676         Integer i = from.getAsInteger(key);
677         if (i != null) {
678             to.put(key, i);
679         }
680     }
681
682     private static final void copyBoolean(String key, ContentValues from, ContentValues to) {
683         Boolean b = from.getAsBoolean(key);
684         if (b != null) {
685             to.put(key, b);
686         }
687     }
688
689     private static final void copyString(String key, ContentValues from, ContentValues to) {
690         String s = from.getAsString(key);
691         if (s != null) {
692             to.put(key, s);
693         }
694     }
695
696     private class ReadOnlyCursorWrapper extends CursorWrapper implements CrossProcessCursor {
697         public ReadOnlyCursorWrapper(Cursor cursor) {
698             super(cursor);
699             mCursor = (CrossProcessCursor) cursor;
700         }
701
702         public boolean deleteRow() {
703             throw new SecurityException("Download manager cursors are read-only");
704         }
705
706         public boolean commitUpdates() {
707             throw new SecurityException("Download manager cursors are read-only");
708         }
709
710         public void fillWindow(int pos, CursorWindow window) {
711             mCursor.fillWindow(pos, window);
712         }
713
714         public CursorWindow getWindow() {
715             return mCursor.getWindow();
716         }
717
718         public boolean onMove(int oldPosition, int newPosition) {
719             return mCursor.onMove(oldPosition, newPosition);
720         }
721
722         private CrossProcessCursor mCursor;
723     }
724
725 }