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