• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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 android.support.v4.content;
18 
19 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20 import static org.xmlpull.v1.XmlPullParser.START_TAG;
21 
22 import android.content.ContentProvider;
23 import android.content.ContentValues;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.pm.PackageManager;
27 import android.content.pm.ProviderInfo;
28 import android.content.res.XmlResourceParser;
29 import android.database.Cursor;
30 import android.database.MatrixCursor;
31 import android.net.Uri;
32 import android.os.Environment;
33 import android.os.ParcelFileDescriptor;
34 import android.provider.OpenableColumns;
35 import android.support.annotation.GuardedBy;
36 import android.text.TextUtils;
37 import android.webkit.MimeTypeMap;
38 
39 import org.xmlpull.v1.XmlPullParserException;
40 
41 import java.io.File;
42 import java.io.FileNotFoundException;
43 import java.io.IOException;
44 import java.util.HashMap;
45 import java.util.Map;
46 
47 /**
48  * FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
49  * of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
50  * instead of a <code>file:///</code> {@link Uri}.
51  * <p>
52  * A content URI allows you to grant read and write access using
53  * temporary access permissions. When you create an {@link Intent} containing
54  * a content URI, in order to send the content URI
55  * to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
56  * permissions. These permissions are available to the client app for as long as the stack for
57  * a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
58  * {@link android.app.Service}, the permissions are available as long as the
59  * {@link android.app.Service} is running.
60  * <p>
61  * In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
62  * file system permissions of the underlying file. The permissions you provide become available to
63  * <em>any</em> app, and remain in effect until you change them. This level of access is
64  * fundamentally insecure.
65  * <p>
66  * The increased level of file access security offered by a content URI
67  * makes FileProvider a key part of Android's security infrastructure.
68  * <p>
69  * This overview of FileProvider includes the following topics:
70  * </p>
71  * <ol>
72  *     <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
73  *     <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
74  *     <li><a href="#GetUri">Retrieving the Content URI for a File</li>
75  *     <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
76  *     <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
77  * </ol>
78  * <h3 id="ProviderDefinition">Defining a FileProvider</h3>
79  * <p>
80  * Since the default functionality of FileProvider includes content URI generation for files, you
81  * don't need to define a subclass in code. Instead, you can include a FileProvider in your app
82  * by specifying it entirely in XML. To specify the FileProvider component itself, add a
83  * <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
84  * element to your app manifest. Set the <code>android:name</code> attribute to
85  * <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
86  * attribute to a URI authority based on a domain you control; for example, if you control the
87  * domain <code>mydomain.com</code> you should use the authority
88  * <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
89  * <code>false</code>; the FileProvider does not need to be public. Set the
90  * <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
91  * >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
92  * to grant temporary access to files. For example:
93  * <pre class="prettyprint">
94  *&lt;manifest&gt;
95  *    ...
96  *    &lt;application&gt;
97  *        ...
98  *        &lt;provider
99  *            android:name="android.support.v4.content.FileProvider"
100  *            android:authorities="com.mydomain.fileprovider"
101  *            android:exported="false"
102  *            android:grantUriPermissions="true"&gt;
103  *            ...
104  *        &lt;/provider&gt;
105  *        ...
106  *    &lt;/application&gt;
107  *&lt;/manifest&gt;</pre>
108  * <p>
109  * If you want to override any of the default behavior of FileProvider methods, extend
110  * the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
111  * attribute of the <code>&lt;provider&gt;</code> element.
112  * <h3 id="SpecifyFiles">Specifying Available Files</h3>
113  * A FileProvider can only generate a content URI for files in directories that you specify
114  * beforehand. To specify a directory, specify the its storage area and path in XML, using child
115  * elements of the <code>&lt;paths&gt;</code> element.
116  * For example, the following <code>paths</code> element tells FileProvider that you intend to
117  * request content URIs for the <code>images/</code> subdirectory of your private file area.
118  * <pre class="prettyprint">
119  *&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
120  *    &lt;files-path name="my_images" path="images/"/&gt;
121  *    ...
122  *&lt;/paths&gt;
123  *</pre>
124  * <p>
125  * The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements:
126  * </p>
127  * <dl>
128  *     <dt>
129  * <pre class="prettyprint">
130  *&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt;
131  *</pre>
132  *     </dt>
133  *     <dd>
134  *     Represents files in the <code>files/</code> subdirectory of your app's internal storage
135  *     area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
136  *     Context.getFilesDir()}.
137  *     </dd>
138  *     <dt>
139  * <pre>
140  *&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
141  *</pre>
142  *     <dt>
143  *     <dd>
144  *     Represents files in the cache subdirectory of your app's internal storage area. The root path
145  *     of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
146  *     getCacheDir()}.
147  *     </dd>
148  *     <dt>
149  * <pre class="prettyprint">
150  *&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt;
151  *</pre>
152  *     </dt>
153  *     <dd>
154  *     Represents files in the root of the external storage area. The root path of this subdirectory
155  *     is the same as the value returned by
156  *     {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}.
157  *     </dd>
158  *     <dt>
159  * <pre class="prettyprint">
160  *&lt;external-files-path name="<i>name</i>" path="<i>path</i>" /&gt;
161  *</pre>
162  *     </dt>
163  *     <dd>
164  *     Represents files in the root of your app's external storage area. The root path of this
165  *     subdirectory is the same as the value returned by
166  *     {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}.
167  *     </dd>
168  *     <dt>
169  * <pre class="prettyprint">
170  *&lt;external-cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
171  *</pre>
172  *     </dt>
173  *     <dd>
174  *     Represents files in the root of your app's external cache area. The root path of this
175  *     subdirectory is the same as the value returned by
176  *     {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}.
177  *     </dd>
178  * </dl>
179  * <p>
180  *     These child elements all use the same attributes:
181  * </p>
182  * <dl>
183  *     <dt>
184  *         <code>name="<i>name</i>"</code>
185  *     </dt>
186  *     <dd>
187  *         A URI path segment. To enforce security, this value hides the name of the subdirectory
188  *         you're sharing. The subdirectory name for this value is contained in the
189  *         <code>path</code> attribute.
190  *     </dd>
191  *     <dt>
192  *         <code>path="<i>path</i>"</code>
193  *     </dt>
194  *     <dd>
195  *         The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
196  *         segment, the <code>path</code> value is an actual subdirectory name. Notice that the
197  *         value refers to a <b>subdirectory</b>, not an individual file or files. You can't
198  *         share a single file by its file name, nor can you specify a subset of files using
199  *         wildcards.
200  *     </dd>
201  * </dl>
202  * <p>
203  * You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains
204  * files for which you want content URIs. For example, these XML elements specify two directories:
205  * <pre class="prettyprint">
206  *&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
207  *    &lt;files-path name="my_images" path="images/"/&gt;
208  *    &lt;files-path name="my_docs" path="docs/"/&gt;
209  *&lt;/paths&gt;
210  *</pre>
211  * <p>
212  * Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project.
213  * For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
214  * To link this file to the FileProvider, add a
215  * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element
216  * as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the
217  * <code>&lt;meta-data&gt;</code> element's "android:name" attribute to
218  * <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
219  * to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
220  * extension). For example:
221  * <pre class="prettyprint">
222  *&lt;provider
223  *    android:name="android.support.v4.content.FileProvider"
224  *    android:authorities="com.mydomain.fileprovider"
225  *    android:exported="false"
226  *    android:grantUriPermissions="true"&gt;
227  *    &lt;meta-data
228  *        android:name="android.support.FILE_PROVIDER_PATHS"
229  *        android:resource="&#64;xml/file_paths" /&gt;
230  *&lt;/provider&gt;
231  *</pre>
232  * <h3 id="GetUri">Generating the Content URI for a File</h3>
233  * <p>
234  * To share a file with another app using a content URI, your app has to generate the content URI.
235  * To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
236  * to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
237  * returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
238  * {@link android.content.Intent}. The client app that receives the content URI can open the file
239  * and access its contents by calling
240  * {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
241  * ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
242  * <p>
243  * For example, suppose your app is offering files to other apps with a FileProvider that has the
244  * authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
245  * <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
246  * add the following code:
247  * <pre class="prettyprint">
248  *File imagePath = new File(Context.getFilesDir(), "images");
249  *File newFile = new File(imagePath, "default_image.jpg");
250  *Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
251  *</pre>
252  * As a result of the previous snippet,
253  * {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
254  * <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
255  * <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
256  * To grant an access permission to a content URI returned from
257  * {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
258  * <ul>
259  * <li>
260  *     Call the method
261  *     {@link Context#grantUriPermission(String, Uri, int)
262  *     Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
263  *     {@link Uri}, using the desired mode flags. This grants temporary access permission for the
264  *     content URI to the specified package, according to the value of the
265  *     the <code>mode_flags</code> parameter, which you can set to
266  *     {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
267  *     or both. The permission remains in effect until you revoke it by calling
268  *     {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
269  *     reboots.
270  * </li>
271  * <li>
272  *     Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
273  * </li>
274  * <li>
275  *     Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
276  *     {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
277  *     {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
278  * </li>
279  * <li>
280  *     Finally, send the {@link Intent} to
281  *     another app. Most often, you do this by calling
282  *     {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
283  *     <p>
284  *     Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
285  *     {@link android.app.Activity} is active. When the stack finishes, the permissions are
286  *     automatically removed. Permissions granted to one {@link android.app.Activity} in a client
287  *     app are automatically extended to other components of that app.
288  *     </p>
289  * </li>
290  * </ul>
291  * <h3 id="ServeUri">Serving a Content URI to Another App</h3>
292  * <p>
293  * There are a variety of ways to serve the content URI for a file to a client app. One common way
294  * is for the client app to start your app by calling
295  * {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
296  * which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
297  * In response, your app can immediately return a content URI to the client app or present a user
298  * interface that allows the user to pick a file. In the latter case, once the user picks the file
299  * your app can return its content URI. In both cases, your app returns the content URI in an
300  * {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
301  * </p>
302  * <p>
303  *  You can also put the content URI in a {@link android.content.ClipData} object and then add the
304  *  object to an {@link Intent} you send to a client app. To do this, call
305  *  {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
306  *  add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
307  *  content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
308  *  to set temporary access permissions, the same permissions are applied to all of the content
309  *  URIs.
310  * </p>
311  * <p class="note">
312  *  <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
313  *  only available in platform version 16 (Android 4.1) and later. If you want to maintain
314  *  compatibility with previous versions, you should send one content URI at a time in the
315  *  {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
316  *  {@link Intent#setData setData()}.
317  * </p>
318  * <h3 id="">More Information</h3>
319  * <p>
320  *    To learn more about FileProvider, see the Android training class
321  *    <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
322  * </p>
323  */
324 public class FileProvider extends ContentProvider {
325     private static final String[] COLUMNS = {
326             OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };
327 
328     private static final String
329             META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
330 
331     private static final String TAG_ROOT_PATH = "root-path";
332     private static final String TAG_FILES_PATH = "files-path";
333     private static final String TAG_CACHE_PATH = "cache-path";
334     private static final String TAG_EXTERNAL = "external-path";
335     private static final String TAG_EXTERNAL_FILES = "external-files-path";
336     private static final String TAG_EXTERNAL_CACHE = "external-cache-path";
337 
338     private static final String ATTR_NAME = "name";
339     private static final String ATTR_PATH = "path";
340 
341     private static final File DEVICE_ROOT = new File("/");
342 
343     @GuardedBy("sCache")
344     private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
345 
346     private PathStrategy mStrategy;
347 
348     /**
349      * The default FileProvider implementation does not need to be initialized. If you want to
350      * override this method, you must provide your own subclass of FileProvider.
351      */
352     @Override
onCreate()353     public boolean onCreate() {
354         return true;
355     }
356 
357     /**
358      * After the FileProvider is instantiated, this method is called to provide the system with
359      * information about the provider.
360      *
361      * @param context A {@link Context} for the current component.
362      * @param info A {@link ProviderInfo} for the new provider.
363      */
364     @Override
attachInfo(Context context, ProviderInfo info)365     public void attachInfo(Context context, ProviderInfo info) {
366         super.attachInfo(context, info);
367 
368         // Sanity check our security
369         if (info.exported) {
370             throw new SecurityException("Provider must not be exported");
371         }
372         if (!info.grantUriPermissions) {
373             throw new SecurityException("Provider must grant uri permissions");
374         }
375 
376         mStrategy = getPathStrategy(context, info.authority);
377     }
378 
379     /**
380      * Return a content URI for a given {@link File}. Specific temporary
381      * permissions for the content URI can be set with
382      * {@link Context#grantUriPermission(String, Uri, int)}, or added
383      * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
384      * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
385      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
386      * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
387      * <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code>
388      * meta-data element. See the Class Overview for more information.
389      *
390      * @param context A {@link Context} for the current component.
391      * @param authority The authority of a {@link FileProvider} defined in a
392      *            {@code <provider>} element in your app's manifest.
393      * @param file A {@link File} pointing to the filename for which you want a
394      * <code>content</code> {@link Uri}.
395      * @return A content URI for the file.
396      * @throws IllegalArgumentException When the given {@link File} is outside
397      * the paths supported by the provider.
398      */
getUriForFile(Context context, String authority, File file)399     public static Uri getUriForFile(Context context, String authority, File file) {
400         final PathStrategy strategy = getPathStrategy(context, authority);
401         return strategy.getUriForFile(file);
402     }
403 
404     /**
405      * Use a content URI returned by
406      * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
407      * managed by the FileProvider.
408      * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}:
409      * <ul>
410      * <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li>
411      * <li>{@link android.provider.OpenableColumns#SIZE}</li>
412      * </ul>
413      * For more information, see
414      * {@link ContentProvider#query(Uri, String[], String, String[], String)
415      * ContentProvider.query()}.
416      *
417      * @param uri A content URI returned by {@link #getUriForFile}.
418      * @param projection The list of columns to put into the {@link Cursor}. If null all columns are
419      * included.
420      * @param selection Selection criteria to apply. If null then all data that matches the content
421      * URI is returned.
422      * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
423      * the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
424      * right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
425      * <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
426      * values are bound to <i>selection</i> as {@link java.lang.String} values.
427      * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
428      * the resulting {@link Cursor}.
429      * @return A {@link Cursor} containing the results of the query.
430      *
431      */
432     @Override
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)433     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
434             String sortOrder) {
435         // ContentProvider has already checked granted permissions
436         final File file = mStrategy.getFileForUri(uri);
437 
438         if (projection == null) {
439             projection = COLUMNS;
440         }
441 
442         String[] cols = new String[projection.length];
443         Object[] values = new Object[projection.length];
444         int i = 0;
445         for (String col : projection) {
446             if (OpenableColumns.DISPLAY_NAME.equals(col)) {
447                 cols[i] = OpenableColumns.DISPLAY_NAME;
448                 values[i++] = file.getName();
449             } else if (OpenableColumns.SIZE.equals(col)) {
450                 cols[i] = OpenableColumns.SIZE;
451                 values[i++] = file.length();
452             }
453         }
454 
455         cols = copyOf(cols, i);
456         values = copyOf(values, i);
457 
458         final MatrixCursor cursor = new MatrixCursor(cols, 1);
459         cursor.addRow(values);
460         return cursor;
461     }
462 
463     /**
464      * Returns the MIME type of a content URI returned by
465      * {@link #getUriForFile(Context, String, File) getUriForFile()}.
466      *
467      * @param uri A content URI returned by
468      * {@link #getUriForFile(Context, String, File) getUriForFile()}.
469      * @return If the associated file has an extension, the MIME type associated with that
470      * extension; otherwise <code>application/octet-stream</code>.
471      */
472     @Override
getType(Uri uri)473     public String getType(Uri uri) {
474         // ContentProvider has already checked granted permissions
475         final File file = mStrategy.getFileForUri(uri);
476 
477         final int lastDot = file.getName().lastIndexOf('.');
478         if (lastDot >= 0) {
479             final String extension = file.getName().substring(lastDot + 1);
480             final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
481             if (mime != null) {
482                 return mime;
483             }
484         }
485 
486         return "application/octet-stream";
487     }
488 
489     /**
490      * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
491      * subclass FileProvider if you want to provide different functionality.
492      */
493     @Override
insert(Uri uri, ContentValues values)494     public Uri insert(Uri uri, ContentValues values) {
495         throw new UnsupportedOperationException("No external inserts");
496     }
497 
498     /**
499      * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
500      * subclass FileProvider if you want to provide different functionality.
501      */
502     @Override
update(Uri uri, ContentValues values, String selection, String[] selectionArgs)503     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
504         throw new UnsupportedOperationException("No external updates");
505     }
506 
507     /**
508      * Deletes the file associated with the specified content URI, as
509      * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
510      * method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
511      *
512      * @param uri A content URI for a file, as returned by
513      * {@link #getUriForFile(Context, String, File) getUriForFile()}.
514      * @param selection Ignored. Set to {@code null}.
515      * @param selectionArgs Ignored. Set to {@code null}.
516      * @return 1 if the delete succeeds; otherwise, 0.
517      */
518     @Override
delete(Uri uri, String selection, String[] selectionArgs)519     public int delete(Uri uri, String selection, String[] selectionArgs) {
520         // ContentProvider has already checked granted permissions
521         final File file = mStrategy.getFileForUri(uri);
522         return file.delete() ? 1 : 0;
523     }
524 
525     /**
526      * By default, FileProvider automatically returns the
527      * {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
528      * {@link Uri}. To get the {@link ParcelFileDescriptor}, call
529      * {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
530      * ContentResolver.openFileDescriptor}.
531      *
532      * To override this method, you must provide your own subclass of FileProvider.
533      *
534      * @param uri A content URI associated with a file, as returned by
535      * {@link #getUriForFile(Context, String, File) getUriForFile()}.
536      * @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
537      * write access, or "rwt" for read and write access that truncates any existing file.
538      * @return A new {@link ParcelFileDescriptor} with which you can access the file.
539      */
540     @Override
openFile(Uri uri, String mode)541     public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
542         // ContentProvider has already checked granted permissions
543         final File file = mStrategy.getFileForUri(uri);
544         final int fileMode = modeToMode(mode);
545         return ParcelFileDescriptor.open(file, fileMode);
546     }
547 
548     /**
549      * Return {@link PathStrategy} for given authority, either by parsing or
550      * returning from cache.
551      */
getPathStrategy(Context context, String authority)552     private static PathStrategy getPathStrategy(Context context, String authority) {
553         PathStrategy strat;
554         synchronized (sCache) {
555             strat = sCache.get(authority);
556             if (strat == null) {
557                 try {
558                     strat = parsePathStrategy(context, authority);
559                 } catch (IOException e) {
560                     throw new IllegalArgumentException(
561                             "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
562                 } catch (XmlPullParserException e) {
563                     throw new IllegalArgumentException(
564                             "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
565                 }
566                 sCache.put(authority, strat);
567             }
568         }
569         return strat;
570     }
571 
572     /**
573      * Parse and return {@link PathStrategy} for given authority as defined in
574      * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
575      *
576      * @see #getPathStrategy(Context, String)
577      */
parsePathStrategy(Context context, String authority)578     private static PathStrategy parsePathStrategy(Context context, String authority)
579             throws IOException, XmlPullParserException {
580         final SimplePathStrategy strat = new SimplePathStrategy(authority);
581 
582         final ProviderInfo info = context.getPackageManager()
583                 .resolveContentProvider(authority, PackageManager.GET_META_DATA);
584         final XmlResourceParser in = info.loadXmlMetaData(
585                 context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
586         if (in == null) {
587             throw new IllegalArgumentException(
588                     "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
589         }
590 
591         int type;
592         while ((type = in.next()) != END_DOCUMENT) {
593             if (type == START_TAG) {
594                 final String tag = in.getName();
595 
596                 final String name = in.getAttributeValue(null, ATTR_NAME);
597                 String path = in.getAttributeValue(null, ATTR_PATH);
598 
599                 File target = null;
600                 if (TAG_ROOT_PATH.equals(tag)) {
601                     target = DEVICE_ROOT;
602                 } else if (TAG_FILES_PATH.equals(tag)) {
603                     target = context.getFilesDir();
604                 } else if (TAG_CACHE_PATH.equals(tag)) {
605                     target = context.getCacheDir();
606                 } else if (TAG_EXTERNAL.equals(tag)) {
607                     target = Environment.getExternalStorageDirectory();
608                 } else if (TAG_EXTERNAL_FILES.equals(tag)) {
609                     File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
610                     if (externalFilesDirs.length > 0) {
611                         target = externalFilesDirs[0];
612                     }
613                 } else if (TAG_EXTERNAL_CACHE.equals(tag)) {
614                     File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
615                     if (externalCacheDirs.length > 0) {
616                         target = externalCacheDirs[0];
617                     }
618                 }
619 
620                 if (target != null) {
621                     strat.addRoot(name, buildPath(target, path));
622                 }
623             }
624         }
625 
626         return strat;
627     }
628 
629     /**
630      * Strategy for mapping between {@link File} and {@link Uri}.
631      * <p>
632      * Strategies must be symmetric so that mapping a {@link File} to a
633      * {@link Uri} and then back to a {@link File} points at the original
634      * target.
635      * <p>
636      * Strategies must remain consistent across app launches, and not rely on
637      * dynamic state. This ensures that any generated {@link Uri} can still be
638      * resolved if your process is killed and later restarted.
639      *
640      * @see SimplePathStrategy
641      */
642     interface PathStrategy {
643         /**
644          * Return a {@link Uri} that represents the given {@link File}.
645          */
getUriForFile(File file)646         public Uri getUriForFile(File file);
647 
648         /**
649          * Return a {@link File} that represents the given {@link Uri}.
650          */
getFileForUri(Uri uri)651         public File getFileForUri(Uri uri);
652     }
653 
654     /**
655      * Strategy that provides access to files living under a narrow whitelist of
656      * filesystem roots. It will throw {@link SecurityException} if callers try
657      * accessing files outside the configured roots.
658      * <p>
659      * For example, if configured with
660      * {@code addRoot("myfiles", context.getFilesDir())}, then
661      * {@code context.getFileStreamPath("foo.txt")} would map to
662      * {@code content://myauthority/myfiles/foo.txt}.
663      */
664     static class SimplePathStrategy implements PathStrategy {
665         private final String mAuthority;
666         private final HashMap<String, File> mRoots = new HashMap<String, File>();
667 
SimplePathStrategy(String authority)668         public SimplePathStrategy(String authority) {
669             mAuthority = authority;
670         }
671 
672         /**
673          * Add a mapping from a name to a filesystem root. The provider only offers
674          * access to files that live under configured roots.
675          */
addRoot(String name, File root)676         public void addRoot(String name, File root) {
677             if (TextUtils.isEmpty(name)) {
678                 throw new IllegalArgumentException("Name must not be empty");
679             }
680 
681             try {
682                 // Resolve to canonical path to keep path checking fast
683                 root = root.getCanonicalFile();
684             } catch (IOException e) {
685                 throw new IllegalArgumentException(
686                         "Failed to resolve canonical path for " + root, e);
687             }
688 
689             mRoots.put(name, root);
690         }
691 
692         @Override
getUriForFile(File file)693         public Uri getUriForFile(File file) {
694             String path;
695             try {
696                 path = file.getCanonicalPath();
697             } catch (IOException e) {
698                 throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
699             }
700 
701             // Find the most-specific root path
702             Map.Entry<String, File> mostSpecific = null;
703             for (Map.Entry<String, File> root : mRoots.entrySet()) {
704                 final String rootPath = root.getValue().getPath();
705                 if (path.startsWith(rootPath) && (mostSpecific == null
706                         || rootPath.length() > mostSpecific.getValue().getPath().length())) {
707                     mostSpecific = root;
708                 }
709             }
710 
711             if (mostSpecific == null) {
712                 throw new IllegalArgumentException(
713                         "Failed to find configured root that contains " + path);
714             }
715 
716             // Start at first char of path under root
717             final String rootPath = mostSpecific.getValue().getPath();
718             if (rootPath.endsWith("/")) {
719                 path = path.substring(rootPath.length());
720             } else {
721                 path = path.substring(rootPath.length() + 1);
722             }
723 
724             // Encode the tag and path separately
725             path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
726             return new Uri.Builder().scheme("content")
727                     .authority(mAuthority).encodedPath(path).build();
728         }
729 
730         @Override
getFileForUri(Uri uri)731         public File getFileForUri(Uri uri) {
732             String path = uri.getEncodedPath();
733 
734             final int splitIndex = path.indexOf('/', 1);
735             final String tag = Uri.decode(path.substring(1, splitIndex));
736             path = Uri.decode(path.substring(splitIndex + 1));
737 
738             final File root = mRoots.get(tag);
739             if (root == null) {
740                 throw new IllegalArgumentException("Unable to find configured root for " + uri);
741             }
742 
743             File file = new File(root, path);
744             try {
745                 file = file.getCanonicalFile();
746             } catch (IOException e) {
747                 throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
748             }
749 
750             if (!file.getPath().startsWith(root.getPath())) {
751                 throw new SecurityException("Resolved path jumped beyond configured root");
752             }
753 
754             return file;
755         }
756     }
757 
758     /**
759      * Copied from ContentResolver.java
760      */
modeToMode(String mode)761     private static int modeToMode(String mode) {
762         int modeBits;
763         if ("r".equals(mode)) {
764             modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
765         } else if ("w".equals(mode) || "wt".equals(mode)) {
766             modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
767                     | ParcelFileDescriptor.MODE_CREATE
768                     | ParcelFileDescriptor.MODE_TRUNCATE;
769         } else if ("wa".equals(mode)) {
770             modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
771                     | ParcelFileDescriptor.MODE_CREATE
772                     | ParcelFileDescriptor.MODE_APPEND;
773         } else if ("rw".equals(mode)) {
774             modeBits = ParcelFileDescriptor.MODE_READ_WRITE
775                     | ParcelFileDescriptor.MODE_CREATE;
776         } else if ("rwt".equals(mode)) {
777             modeBits = ParcelFileDescriptor.MODE_READ_WRITE
778                     | ParcelFileDescriptor.MODE_CREATE
779                     | ParcelFileDescriptor.MODE_TRUNCATE;
780         } else {
781             throw new IllegalArgumentException("Invalid mode: " + mode);
782         }
783         return modeBits;
784     }
785 
buildPath(File base, String... segments)786     private static File buildPath(File base, String... segments) {
787         File cur = base;
788         for (String segment : segments) {
789             if (segment != null) {
790                 cur = new File(cur, segment);
791             }
792         }
793         return cur;
794     }
795 
copyOf(String[] original, int newLength)796     private static String[] copyOf(String[] original, int newLength) {
797         final String[] result = new String[newLength];
798         System.arraycopy(original, 0, result, 0, newLength);
799         return result;
800     }
801 
copyOf(Object[] original, int newLength)802     private static Object[] copyOf(Object[] original, int newLength) {
803         final Object[] result = new Object[newLength];
804         System.arraycopy(original, 0, result, 0, newLength);
805         return result;
806     }
807 }
808