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