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