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