use FileHelper.openOutputStreamSafe to resolve output streams
This commit is contained in:
@@ -299,7 +299,7 @@ public class FileHelper {
|
||||
try {
|
||||
ContentResolver resolver = context.getContentResolver();
|
||||
bis = new BufferedInputStream(FileHelper.openInputStreamSafe(resolver, fromUri));
|
||||
bos = new BufferedOutputStream(resolver.openOutputStream(toUri));
|
||||
bos = new BufferedOutputStream(FileHelper.openOutputStreamSafe(resolver, toUri));
|
||||
byte[] buf = new byte[1024];
|
||||
int len;
|
||||
while ( (len = bis.read(buf)) > 0) {
|
||||
@@ -388,4 +388,14 @@ public class FileHelper {
|
||||
}
|
||||
}
|
||||
|
||||
public static OutputStream openOutputStreamSafe(ContentResolver resolver, Uri uri)
|
||||
throws FileNotFoundException {
|
||||
|
||||
// Not supported on Android < 5
|
||||
if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
|
||||
return FileHelperLollipop.openOutputStreamSafe(resolver, uri);
|
||||
} else {
|
||||
return resolver.openOutputStream(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.res.AssetFileDescriptor;
|
||||
@@ -88,4 +89,35 @@ class FileHelperLollipop {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static OutputStream openOutputStreamSafe(ContentResolver resolver, Uri uri)
|
||||
throws FileNotFoundException {
|
||||
|
||||
String scheme = uri.getScheme();
|
||||
if (ContentResolver.SCHEME_FILE.equals(scheme)) {
|
||||
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
|
||||
new File(uri.getPath()), ParcelFileDescriptor.parseMode("w"));
|
||||
|
||||
try {
|
||||
final StructStat st = Os.fstat(pfd.getFileDescriptor());
|
||||
if (st.st_uid == android.os.Process.myUid()) {
|
||||
Timber.e("File is owned by the application itself, aborting!");
|
||||
throw new FileNotFoundException("Unable to create stream");
|
||||
}
|
||||
} catch (ErrnoException e) {
|
||||
Timber.e(e, "fstat() failed");
|
||||
throw new FileNotFoundException("fstat() failed");
|
||||
}
|
||||
|
||||
AssetFileDescriptor fd = new AssetFileDescriptor(pfd, 0, -1);
|
||||
try {
|
||||
return fd.createOutputStream();
|
||||
} catch (IOException e) {
|
||||
throw new FileNotFoundException("Unable to create stream");
|
||||
}
|
||||
} else {
|
||||
return resolver.openOutputStream(uri);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user