Sync FileProvider.java with android-7.0.0_r33

This commit is contained in:
Adrian Ulrich 2017-08-27 19:41:52 +02:00
parent a104b68201
commit d3b0436554

View File

@ -13,9 +13,12 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package android.support.v4.content; package android.support.v4.content;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
@ -31,12 +34,15 @@ import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns; import android.provider.OpenableColumns;
import android.text.TextUtils; import android.text.TextUtils;
import android.webkit.MimeTypeMap; import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserException;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing * FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file * of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
@ -133,9 +139,10 @@ import java.util.Map;
*</pre> *</pre>
* </dt> * </dt>
* <dd> * <dd>
* Represents files in the root of your app's external storage area. The path * Represents the root of the external storage. The root path of this subdirectory
* {@link Context#getExternalFilesDir(String) Context.getExternalFilesDir()} returns the * is the same that {@link
* <code>files/</code> subdirectory of this this root. * Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}
* returns.
* </dd> * </dd>
* <dt> * <dt>
* <pre> * <pre>
@ -290,24 +297,31 @@ import java.util.Map;
* <h3 id="">More Information</h3> * <h3 id="">More Information</h3>
* <p> * <p>
* To learn more about FileProvider, see the Android training class * To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-uri/index.html">Sharing Files Securely with URIs</a>. * <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p> * </p>
*/ */
public class FileProvider extends ContentProvider { public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = { private static final String[] COLUMNS = {
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };
private static final String private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS"; META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path"; private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path"; private static final String TAG_FILES_PATH = "files-path";
private static final String TAG_CACHE_PATH = "cache-path"; private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path"; private static final String TAG_EXTERNAL = "external-path";
private static final String ATTR_NAME = "name"; private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path"; private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/"); private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache") // @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>(); private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy; private PathStrategy mStrategy;
/** /**
* The default FileProvider implementation does not need to be initialized. If you want to * The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider. * override this method, you must provide your own subclass of FileProvider.
@ -316,6 +330,7 @@ public class FileProvider extends ContentProvider {
public boolean onCreate() { public boolean onCreate() {
return true; return true;
} }
/** /**
* After the FileProvider is instantiated, this method is called to provide the system with * After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider. * information about the provider.
@ -326,6 +341,7 @@ public class FileProvider extends ContentProvider {
@Override @Override
public void attachInfo(Context context, ProviderInfo info) { public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info); super.attachInfo(context, info);
// Sanity check our security // Sanity check our security
if (info.exported) { if (info.exported) {
throw new SecurityException("Provider must not be exported"); throw new SecurityException("Provider must not be exported");
@ -333,8 +349,10 @@ public class FileProvider extends ContentProvider {
if (!info.grantUriPermissions) { if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions"); throw new SecurityException("Provider must grant uri permissions");
} }
mStrategy = getPathStrategy(context, info.authority); mStrategy = getPathStrategy(context, info.authority);
} }
/** /**
* Return a content URI for a given {@link File}. Specific temporary * Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with * permissions for the content URI can be set with
@ -348,7 +366,7 @@ public class FileProvider extends ContentProvider {
* *
* @param context A {@link Context} for the current component. * @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a * @param authority The authority of a {@link FileProvider} defined in a
* {@code &lt;provider&gt;} element in your app's manifest. * {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a * @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}. * <code>content</code> {@link Uri}.
* @return A content URI for the file. * @return A content URI for the file.
@ -359,6 +377,7 @@ public class FileProvider extends ContentProvider {
final PathStrategy strategy = getPathStrategy(context, authority); final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file); return strategy.getUriForFile(file);
} }
/** /**
* Use a content URI returned by * Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
@ -392,9 +411,11 @@ public class FileProvider extends ContentProvider {
String sortOrder) { String sortOrder) {
// ContentProvider has already checked granted permissions // ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri); final File file = mStrategy.getFileForUri(uri);
if (projection == null) { if (projection == null) {
projection = COLUMNS; projection = COLUMNS;
} }
String[] cols = new String[projection.length]; String[] cols = new String[projection.length];
Object[] values = new Object[projection.length]; Object[] values = new Object[projection.length];
int i = 0; int i = 0;
@ -407,12 +428,15 @@ public class FileProvider extends ContentProvider {
values[i++] = file.length(); values[i++] = file.length();
} }
} }
cols = copyOf(cols, i); cols = copyOf(cols, i);
values = copyOf(values, i); values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1); final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values); cursor.addRow(values);
return cursor; return cursor;
} }
/** /**
* Returns the MIME type of a content URI returned by * Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}. * {@link #getUriForFile(Context, String, File) getUriForFile()}.
@ -426,6 +450,7 @@ public class FileProvider extends ContentProvider {
public String getType(Uri uri) { public String getType(Uri uri) {
// ContentProvider has already checked granted permissions // ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri); final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.'); final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) { if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1); final String extension = file.getName().substring(lastDot + 1);
@ -434,8 +459,10 @@ public class FileProvider extends ContentProvider {
return mime; return mime;
} }
} }
return "application/octet-stream"; return "application/octet-stream";
} }
/** /**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality. * subclass FileProvider if you want to provide different functionality.
@ -444,6 +471,7 @@ public class FileProvider extends ContentProvider {
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts"); throw new UnsupportedOperationException("No external inserts");
} }
/** /**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality. * subclass FileProvider if you want to provide different functionality.
@ -452,6 +480,7 @@ public class FileProvider extends ContentProvider {
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates"); throw new UnsupportedOperationException("No external updates");
} }
/** /**
* Deletes the file associated with the specified content URI, as * Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
@ -469,6 +498,7 @@ public class FileProvider extends ContentProvider {
final File file = mStrategy.getFileForUri(uri); final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0; return file.delete() ? 1 : 0;
} }
/** /**
* By default, FileProvider automatically returns the * By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code> * {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
@ -491,6 +521,7 @@ public class FileProvider extends ContentProvider {
final int fileMode = modeToMode(mode); final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode); return ParcelFileDescriptor.open(file, fileMode);
} }
/** /**
* Return {@link PathStrategy} for given authority, either by parsing or * Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache. * returning from cache.
@ -514,15 +545,17 @@ public class FileProvider extends ContentProvider {
} }
return strat; return strat;
} }
/** /**
* Parse and return {@link PathStrategy} for given authority as defined in * Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}. * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
* *
* @see #getPathStrategy(Context, String) * @see #getPathStrategy(Context, String)
*/ */
private static PathStrategy parsePathStrategy(Context context, String authority) private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException { throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority); final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager() final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA); .resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData( final XmlResourceParser in = info.loadXmlMetaData(
@ -531,12 +564,15 @@ public class FileProvider extends ContentProvider {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data"); "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
} }
int type; int type;
while ((type = in.next()) != END_DOCUMENT) { while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) { if (type == START_TAG) {
final String tag = in.getName(); final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME); final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH); String path = in.getAttributeValue(null, ATTR_PATH);
File target = null; File target = null;
if (TAG_ROOT_PATH.equals(tag)) { if (TAG_ROOT_PATH.equals(tag)) {
target = buildPath(DEVICE_ROOT, path); target = buildPath(DEVICE_ROOT, path);
@ -547,13 +583,16 @@ public class FileProvider extends ContentProvider {
} else if (TAG_EXTERNAL.equals(tag)) { } else if (TAG_EXTERNAL.equals(tag)) {
target = buildPath(Environment.getExternalStorageDirectory(), path); target = buildPath(Environment.getExternalStorageDirectory(), path);
} }
if (target != null) { if (target != null) {
strat.addRoot(name, target); strat.addRoot(name, target);
} }
} }
} }
return strat; return strat;
} }
/** /**
* Strategy for mapping between {@link File} and {@link Uri}. * Strategy for mapping between {@link File} and {@link Uri}.
* <p> * <p>
@ -572,11 +611,13 @@ public class FileProvider extends ContentProvider {
* Return a {@link Uri} that represents the given {@link File}. * Return a {@link Uri} that represents the given {@link File}.
*/ */
public Uri getUriForFile(File file); public Uri getUriForFile(File file);
/** /**
* Return a {@link File} that represents the given {@link Uri}. * Return a {@link File} that represents the given {@link Uri}.
*/ */
public File getFileForUri(Uri uri); public File getFileForUri(Uri uri);
} }
/** /**
* Strategy that provides access to files living under a narrow whitelist of * Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try * filesystem roots. It will throw {@link SecurityException} if callers try
@ -590,9 +631,11 @@ public class FileProvider extends ContentProvider {
static class SimplePathStrategy implements PathStrategy { static class SimplePathStrategy implements PathStrategy {
private final String mAuthority; private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>(); private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) { public SimplePathStrategy(String authority) {
mAuthority = authority; mAuthority = authority;
} }
/** /**
* Add a mapping from a name to a filesystem root. The provider only offers * Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots. * access to files that live under configured roots.
@ -601,6 +644,7 @@ public class FileProvider extends ContentProvider {
if (TextUtils.isEmpty(name)) { if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty"); throw new IllegalArgumentException("Name must not be empty");
} }
try { try {
// Resolve to canonical path to keep path checking fast // Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile(); root = root.getCanonicalFile();
@ -608,8 +652,10 @@ public class FileProvider extends ContentProvider {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e); "Failed to resolve canonical path for " + root, e);
} }
mRoots.put(name, root); mRoots.put(name, root);
} }
@Override @Override
public Uri getUriForFile(File file) { public Uri getUriForFile(File file) {
String path; String path;
@ -618,6 +664,7 @@ public class FileProvider extends ContentProvider {
} catch (IOException e) { } catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file); throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
} }
// Find the most-specific root path // Find the most-specific root path
Map.Entry<String, File> mostSpecific = null; Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) { for (Map.Entry<String, File> root : mRoots.entrySet()) {
@ -627,10 +674,12 @@ public class FileProvider extends ContentProvider {
mostSpecific = root; mostSpecific = root;
} }
} }
if (mostSpecific == null) { if (mostSpecific == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Failed to find configured root that contains " + path); "Failed to find configured root that contains " + path);
} }
// Start at first char of path under root // Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath(); final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) { if (rootPath.endsWith("/")) {
@ -638,33 +687,41 @@ public class FileProvider extends ContentProvider {
} else { } else {
path = path.substring(rootPath.length() + 1); path = path.substring(rootPath.length() + 1);
} }
// Encode the tag and path separately // Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/"); path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content") return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build(); .authority(mAuthority).encodedPath(path).build();
} }
@Override @Override
public File getFileForUri(Uri uri) { public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath(); String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1); final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex)); final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1)); path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag); final File root = mRoots.get(tag);
if (root == null) { if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri); throw new IllegalArgumentException("Unable to find configured root for " + uri);
} }
File file = new File(root, path); File file = new File(root, path);
try { try {
file = file.getCanonicalFile(); file = file.getCanonicalFile();
} catch (IOException e) { } catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file); throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
} }
if (!file.getPath().startsWith(root.getPath())) { if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root"); throw new SecurityException("Resolved path jumped beyond configured root");
} }
return file; return file;
} }
} }
/** /**
* Copied from ContentResolver.java * Copied from ContentResolver.java
*/ */
@ -692,6 +749,7 @@ public class FileProvider extends ContentProvider {
} }
return modeBits; return modeBits;
} }
private static File buildPath(File base, String... segments) { private static File buildPath(File base, String... segments) {
File cur = base; File cur = base;
for (String segment : segments) { for (String segment : segments) {
@ -701,11 +759,13 @@ public class FileProvider extends ContentProvider {
} }
return cur; return cur;
} }
private static String[] copyOf(String[] original, int newLength) { private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength]; final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength); System.arraycopy(original, 0, result, 0, newLength);
return result; return result;
} }
private static Object[] copyOf(Object[] original, int newLength) { private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength]; final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength); System.arraycopy(original, 0, result, 0, newLength);