use FileHelper.openOutputStreamSafe to resolve output streams

This commit is contained in:
Vincent Breitmoser
2024-01-29 10:48:53 +01:00
parent ba9c93d046
commit 4dd3391c9f
8 changed files with 70 additions and 30 deletions

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}