Debian Codegraph @

core/java/android/os/FileUtils.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 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 android.os;
18
19 import static android.os.ParcelFileDescriptor.MODE_APPEND;
20 import static android.os.ParcelFileDescriptor.MODE_CREATE;
21 import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
22 import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
23 import static android.os.ParcelFileDescriptor.MODE_TRUNCATE;
24 import static android.os.ParcelFileDescriptor.MODE_WRITE_ONLY;
25 import static android.system.OsConstants.EINVAL;
26 import static android.system.OsConstants.ENOSYS;
27 import static android.system.OsConstants.F_OK;
28 import static android.system.OsConstants.O_ACCMODE;
29 import static android.system.OsConstants.O_APPEND;
30 import static android.system.OsConstants.O_CREAT;
31 import static android.system.OsConstants.O_RDONLY;
32 import static android.system.OsConstants.O_RDWR;
33 import static android.system.OsConstants.O_TRUNC;
34 import static android.system.OsConstants.O_WRONLY;
35 import static android.system.OsConstants.R_OK;
36 import static android.system.OsConstants.SPLICE_F_MORE;
37 import static android.system.OsConstants.SPLICE_F_MOVE;
38 import static android.system.OsConstants.S_ISFIFO;
39 import static android.system.OsConstants.S_ISREG;
40 import static android.system.OsConstants.W_OK;
41
42 import android.annotation.NonNull;
43 import android.annotation.Nullable;
44 import android.annotation.TestApi;
45 import android.app.AppGlobals;
46 import android.compat.annotation.UnsupportedAppUsage;
47 import android.content.ContentResolver;
48 import android.content.Context;
49 import android.content.pm.PackageManager;
50 import android.content.pm.ProviderInfo;
51 import android.provider.DocumentsContract.Document;
52 import android.provider.MediaStore;
53 import android.system.ErrnoException;
54 import android.system.Os;
55 import android.system.StructStat;
56 import android.text.TextUtils;
57 import android.util.DataUnit;
58 import android.util.Log;
59 import android.util.Slog;
60 import android.webkit.MimeTypeMap;
61
62 import com.android.internal.annotations.VisibleForTesting;
63 import com.android.internal.util.ArrayUtils;
64 import com.android.internal.util.SizedInputStream;
65
66 import libcore.io.IoUtils;
67 import libcore.util.EmptyArray;
68
69 import java.io.BufferedInputStream;
70 import java.io.ByteArrayOutputStream;
71 import java.io.File;
72 import java.io.FileDescriptor;
73 import java.io.FileInputStream;
74 import java.io.FileNotFoundException;
75 import java.io.FileOutputStream;
76 import java.io.FilenameFilter;
77 import java.io.IOException;
78 import java.io.InputStream;
79 import java.io.OutputStream;
80 import java.nio.charset.StandardCharsets;
81 import java.security.DigestInputStream;
82 import java.security.MessageDigest;
83 import java.security.NoSuchAlgorithmException;
84 import java.util.Arrays;
85 import java.util.Collection;
86 import java.util.Comparator;
87 import java.util.List;
88 import java.util.Objects;
89 import java.util.concurrent.Executor;
90 import java.util.concurrent.TimeUnit;
91 import java.util.regex.Pattern;
92 import java.util.zip.CRC32;
93 import java.util.zip.CheckedInputStream;
94
95 /**
96 * Utility methods useful for working with files.
97 */
98 public final class FileUtils {
99 private static final String TAG = "FileUtils";
100
101 /** {@hide} */ public static final int S_IRWXU = 00700;
102 /** {@hide} */ public static final int S_IRUSR = 00400;
103 /** {@hide} */ public static final int S_IWUSR = 00200;
104 /** {@hide} */ public static final int S_IXUSR = 00100;
105
106 /** {@hide} */ public static final int S_IRWXG = 00070;
107 /** {@hide} */ public static final int S_IRGRP = 00040;
108 /** {@hide} */ public static final int S_IWGRP = 00020;
109 /** {@hide} */ public static final int S_IXGRP = 00010;
110
111 /** {@hide} */ public static final int S_IRWXO = 00007;
112 /** {@hide} */ public static final int S_IROTH = 00004;
113 /** {@hide} */ public static final int S_IWOTH = 00002;
114 /** {@hide} */ public static final int S_IXOTH = 00001;
115
116 @UnsupportedAppUsage
117 private FileUtils() {
118 }
119
120 private static final String CAMERA_DIR_LOWER_CASE = "/storage/emulated/" + UserHandle.myUserId()
121 + "/dcim/camera";
122
123 /** Regular expression for safe filenames: no spaces or metacharacters.
124 *
125 * Use a preload holder so that FileUtils can be compile-time initialized.
126 */
127 private static class NoImagePreloadHolder {
128 public static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[\\w%+,./=_-]+");
129 }
130
131 // non-final so it can be toggled by Robolectric's ShadowFileUtils
132 private static boolean sEnableCopyOptimizations = true;
133 private static volatile int sMediaProviderAppId = -1;
134
135 private static final long COPY_CHECKPOINT_BYTES = 524288;
136
137 /**
138 * Listener that is called periodically as progress is made.
139 */
140 public interface ProgressListener {
141 public void onProgress(long progress);
142 }
143
144 /**
145 * Set owner and mode of of given {@link File}.
146 *
147 * @param mode to apply through {@code chmod}
148 * @param uid to apply through {@code chown}, or -1 to leave unchanged
149 * @param gid to apply through {@code chown}, or -1 to leave unchanged
150 * @return 0 on success, otherwise errno.
151 * @hide
152 */
153 @UnsupportedAppUsage
154 public static int setPermissions(File path, int mode, int uid, int gid) {
155 return setPermissions(path.getAbsolutePath(), mode, uid, gid);
156 }
157
158 /**
159 * Set owner and mode of of given path.
160 *
161 * @param mode to apply through {@code chmod}
162 * @param uid to apply through {@code chown}, or -1 to leave unchanged
163 * @param gid to apply through {@code chown}, or -1 to leave unchanged
164 * @return 0 on success, otherwise errno.
165 * @hide
166 */
167 @UnsupportedAppUsage
168 public static int setPermissions(String path, int mode, int uid, int gid) {
169 try {
170 Os.chmod(path, mode);
171 } catch (ErrnoException e) {
172 Slog.w(TAG, "Failed to chmod(" + path + "): " + e);
173 return e.errno;
174 }
175
176 if (uid >= 0 || gid >= 0) {
177 try {
178 Os.chown(path, uid, gid);
179 } catch (ErrnoException e) {
180 Slog.w(TAG, "Failed to chown(" + path + "): " + e);
181 return e.errno;
182 }
183 }
184
185 return 0;
186 }
187
188 /**
189 * Set owner and mode of of given {@link FileDescriptor}.
190 *
191 * @param mode to apply through {@code chmod}
192 * @param uid to apply through {@code chown}, or -1 to leave unchanged
193 * @param gid to apply through {@code chown}, or -1 to leave unchanged
194 * @return 0 on success, otherwise errno.
195 * @hide
196 */
197 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
198 public static int setPermissions(FileDescriptor fd, int mode, int uid, int gid) {
199 try {
200 Os.fchmod(fd, mode);
201 } catch (ErrnoException e) {
202 Slog.w(TAG, "Failed to fchmod(): " + e);
203 return e.errno;
204 }
205
206 if (uid >= 0 || gid >= 0) {
207 try {
208 Os.fchown(fd, uid, gid);
209 } catch (ErrnoException e) {
210 Slog.w(TAG, "Failed to fchown(): " + e);
211 return e.errno;
212 }
213 }
214
215 return 0;
216 }
217
218 /**
219 * Copy the owner UID, owner GID, and mode bits from one file to another.
220 *
221 * @param from File where attributes should be copied from.
222 * @param to File where attributes should be copied to.
223 * @hide
224 */
225 public static void copyPermissions(@NonNull File from, @NonNull File to) throws IOException {
226 try {
227 final StructStat stat = Os.stat(from.getAbsolutePath());
228 Os.chmod(to.getAbsolutePath(), stat.st_mode);
229 Os.chown(to.getAbsolutePath(), stat.st_uid, stat.st_gid);
230 } catch (ErrnoException e) {
231 throw e.rethrowAsIOException();
232 }
233 }
234
235 /**
236 * @deprecated use {@link Os#stat(String)} instead.
237 * @hide
238 */
239 @Deprecated
240 public static int getUid(String path) {
241 try {
242 return Os.stat(path).st_uid;
243 } catch (ErrnoException e) {
244 return -1;
245 }
246 }
247
248 /**
249 * Perform an fsync on the given FileOutputStream. The stream at this
250 * point must be flushed but not yet closed.
251 *
252 * @hide
253 */
254 @UnsupportedAppUsage
255 public static boolean sync(FileOutputStream stream) {
256 try {
257 if (stream != null) {
258 stream.getFD().sync();
259 }
260 return true;
261 } catch (IOException e) {
262 }
263 return false;
264 }
265
266 /**
267 * @deprecated use {@link #copy(File, File)} instead.
268 * @hide
269 */
270 @UnsupportedAppUsage
271 @Deprecated
272 public static boolean copyFile(File srcFile, File destFile) {
273 try {
274 copyFileOrThrow(srcFile, destFile);
275 return true;
276 } catch (IOException e) {
277 return false;
278 }
279 }
280
281 /**
282 * @deprecated use {@link #copy(File, File)} instead.
283 * @hide
284 */
285 @Deprecated
286 public static void copyFileOrThrow(File srcFile, File destFile) throws IOException {
287 try (InputStream in = new FileInputStream(srcFile)) {
288 copyToFileOrThrow(in, destFile);
289 }
290 }
291
292 /**
293 * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
294 * @hide
295 */
296 @UnsupportedAppUsage
297 @Deprecated
298 public static boolean copyToFile(InputStream inputStream, File destFile) {
299 try {
300 copyToFileOrThrow(inputStream, destFile);
301 return true;
302 } catch (IOException e) {
303 return false;
304 }
305 }
306
307 /**
308 * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
309 * @hide
310 */
311 @Deprecated
312 public static void copyToFileOrThrow(InputStream in, File destFile) throws IOException {
313 if (destFile.exists()) {
314 destFile.delete();
315 }
316 try (FileOutputStream out = new FileOutputStream(destFile)) {
317 copy(in, out);
318 try {
319 Os.fsync(out.getFD());
320 } catch (ErrnoException e) {
321 throw e.rethrowAsIOException();
322 }
323 }
324 }
325
326 /**
327 * Copy the contents of one file to another, replacing any existing content.
328 * <p>
329 * Attempts to use several optimization strategies to copy the data in the
330 * kernel before falling back to a userspace copy as a last resort.
331 *
332 * @return number of bytes copied.
333 * @hide
334 */
335 public static long copy(@NonNull File from, @NonNull File to) throws IOException {
336 return copy(from, to, null, null, null);
337 }
338
339 /**
340 * Copy the contents of one file to another, replacing any existing content.
341 * <p>
342 * Attempts to use several optimization strategies to copy the data in the
343 * kernel before falling back to a userspace copy as a last resort.
344 *
345 * @param signal to signal if the copy should be cancelled early.
346 * @param executor that listener events should be delivered via.
347 * @param listener to be periodically notified as the copy progresses.
348 * @return number of bytes copied.
349 * @hide
350 */
351 public static long copy(@NonNull File from, @NonNull File to,
352 @Nullable CancellationSignal signal, @Nullable Executor executor,
353 @Nullable ProgressListener listener) throws IOException {
354 try (FileInputStream in = new FileInputStream(from);
355 FileOutputStream out = new FileOutputStream(to)) {
356 return copy(in, out, signal, executor, listener);
357 }
358 }
359
360 /**
361 * Copy the contents of one stream to another.
362 * <p>
363 * Attempts to use several optimization strategies to copy the data in the
364 * kernel before falling back to a userspace copy as a last resort.
365 *
366 * @return number of bytes copied.
367 */
368 public static long copy(@NonNull InputStream in, @NonNull OutputStream out) throws IOException {
369 return copy(in, out, null, null, null);
370 }
371
372 /**
373 * Copy the contents of one stream to another.
374 * <p>
375 * Attempts to use several optimization strategies to copy the data in the
376 * kernel before falling back to a userspace copy as a last resort.
377 *
378 * @param signal to signal if the copy should be cancelled early.
379 * @param executor that listener events should be delivered via.
380 * @param listener to be periodically notified as the copy progresses.
381 * @return number of bytes copied.
382 */
383 public static long copy(@NonNull InputStream in, @NonNull OutputStream out,
384 @Nullable CancellationSignal signal, @Nullable Executor executor,
385 @Nullable ProgressListener listener) throws IOException {
386 if (sEnableCopyOptimizations) {
387 if (in instanceof FileInputStream && out instanceof FileOutputStream) {
388 return copy(((FileInputStream) in).getFD(), ((FileOutputStream) out).getFD(),
389 signal, executor, listener);
390 }
391 }
392
393 // Worse case fallback to userspace
394 return copyInternalUserspace(in, out, signal, executor, listener);
395 }
396
397 /**
398 * Copy the contents of one FD to another.
399 * <p>
400 * Attempts to use several optimization strategies to copy the data in the
401 * kernel before falling back to a userspace copy as a last resort.
402 *
403 * @return number of bytes copied.
404 */
405 public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out)
406 throws IOException {
407 return copy(in, out, null, null, null);
408 }
409
410 /**
411 * Copy the contents of one FD to another.
412 * <p>
413 * Attempts to use several optimization strategies to copy the data in the
414 * kernel before falling back to a userspace copy as a last resort.
415 *
416 * @param signal to signal if the copy should be cancelled early.
417 * @param executor that listener events should be delivered via.
418 * @param listener to be periodically notified as the copy progresses.
419 * @return number of bytes copied.
420 */
421 public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out,
422 @Nullable CancellationSignal signal, @Nullable Executor executor,
423 @Nullable ProgressListener listener) throws IOException {
424 return copy(in, out, Long.MAX_VALUE, signal, executor, listener);
425 }
426
427 /**
428 * Copy the contents of one FD to another.
429 * <p>
430 * Attempts to use several optimization strategies to copy the data in the
431 * kernel before falling back to a userspace copy as a last resort.
432 *
433 * @param count the number of bytes to copy.
434 * @param signal to signal if the copy should be cancelled early.
435 * @param executor that listener events should be delivered via.
436 * @param listener to be periodically notified as the copy progresses.
437 * @return number of bytes copied.
438 * @hide
439 */
440 public static long copy(@NonNull FileDescriptor in, @NonNull FileDescriptor out, long count,
441 @Nullable CancellationSignal signal, @Nullable Executor executor,
442 @Nullable ProgressListener listener) throws IOException {
443 if (sEnableCopyOptimizations) {
444 try {
445 final StructStat st_in = Os.fstat(in);
446 final StructStat st_out = Os.fstat(out);
447 if (S_ISREG(st_in.st_mode) && S_ISREG(st_out.st_mode)) {
448 try {
449 return copyInternalSendfile(in, out, count, signal, executor, listener);
450 } catch (ErrnoException e) {
451 if (e.errno == EINVAL || e.errno == ENOSYS) {
452 // sendfile(2) will fail in at least any of the following conditions:
453 // 1. |in| doesn't support mmap(2)
454 // 2. |out| was opened with O_APPEND
455 // We fallback to userspace copy if that fails
456 return copyInternalUserspace(in, out, count, signal, executor,
457 listener);
458 }
459 throw e;
460 }
461 } else if (S_ISFIFO(st_in.st_mode) || S_ISFIFO(st_out.st_mode)) {
462 return copyInternalSplice(in, out, count, signal, executor, listener);
463 }
464 } catch (ErrnoException e) {
465 throw e.rethrowAsIOException();
466 }
467 }
468
469 // Worse case fallback to userspace
470 return copyInternalUserspace(in, out, count, signal, executor, listener);
471 }
472
473 /**
474 * Requires one of input or output to be a pipe.
475 *
476 * @hide
477 */
478 @VisibleForTesting
479 public static long copyInternalSplice(FileDescriptor in, FileDescriptor out, long count,
480 CancellationSignal signal, Executor executor, ProgressListener listener)
481 throws ErrnoException {
482 long progress = 0;
483 long checkpoint = 0;
484
485 long t;
486 while ((t = Os.splice(in, null, out, null, Math.min(count, COPY_CHECKPOINT_BYTES),
487 SPLICE_F_MOVE | SPLICE_F_MORE)) != 0) {
488 progress += t;
489 checkpoint += t;
490 count -= t;
491
492 if (checkpoint >= COPY_CHECKPOINT_BYTES) {
493 if (signal != null) {
494 signal.throwIfCanceled();
495 }
496 if (executor != null && listener != null) {
497 final long progressSnapshot = progress;
498 executor.execute(() -> {
499 listener.onProgress(progressSnapshot);
500 });
501 }
502 checkpoint = 0;
503 }
504 }
505 if (executor != null && listener != null) {
506 final long progressSnapshot = progress;
507 executor.execute(() -> {
508 listener.onProgress(progressSnapshot);
509 });
510 }
511 return progress;
512 }
513
514 /**
515 * Requires both input and output to be a regular file.
516 *
517 * @hide
518 */
519 @VisibleForTesting
520 public static long copyInternalSendfile(FileDescriptor in, FileDescriptor out, long count,
521 CancellationSignal signal, Executor executor, ProgressListener listener)
522 throws ErrnoException {
523 long progress = 0;
524 long checkpoint = 0;
525
526 long t;
527 while ((t = Os.sendfile(out, in, null, Math.min(count, COPY_CHECKPOINT_BYTES))) != 0) {
528 progress += t;
529 checkpoint += t;
530 count -= t;
531
532 if (checkpoint >= COPY_CHECKPOINT_BYTES) {
533 if (signal != null) {
534 signal.throwIfCanceled();
535 }
536 if (executor != null && listener != null) {
537 final long progressSnapshot = progress;
538 executor.execute(() -> {
539 listener.onProgress(progressSnapshot);
540 });
541 }
542 checkpoint = 0;
543 }
544 }
545 if (executor != null && listener != null) {
546 final long progressSnapshot = progress;
547 executor.execute(() -> {
548 listener.onProgress(progressSnapshot);
549 });
550 }
551 return progress;
552 }
553
554 /** {@hide} */
555 @Deprecated
556 @VisibleForTesting
557 public static long copyInternalUserspace(FileDescriptor in, FileDescriptor out,
558 ProgressListener listener, CancellationSignal signal, long count)
559 throws IOException {
560 return copyInternalUserspace(in, out, count, signal, Runnable::run, listener);
561 }
562
563 /** {@hide} */
564 @VisibleForTesting
565 public static long copyInternalUserspace(FileDescriptor in, FileDescriptor out, long count,
566 CancellationSignal signal, Executor executor, ProgressListener listener)
567 throws IOException {
568 if (count != Long.MAX_VALUE) {
569 return copyInternalUserspace(new SizedInputStream(new FileInputStream(in), count),
570 new FileOutputStream(out), signal, executor, listener);
571 } else {
572 return copyInternalUserspace(new FileInputStream(in),
573 new FileOutputStream(out), signal, executor, listener);
574 }
575 }
576
577 /** {@hide} */
578 @VisibleForTesting
579 public static long copyInternalUserspace(InputStream in, OutputStream out,
580 CancellationSignal signal, Executor executor, ProgressListener listener)
581 throws IOException {
582 long progress = 0;
583 long checkpoint = 0;
584 byte[] buffer = new byte[8192];
585
586 int t;
587 while ((t = in.read(buffer)) != -1) {
588 out.write(buffer, 0, t);
589
590 progress += t;
591 checkpoint += t;
592
593 if (checkpoint >= COPY_CHECKPOINT_BYTES) {
594 if (signal != null) {
595 signal.throwIfCanceled();
596 }
597 if (executor != null && listener != null) {
598 final long progressSnapshot = progress;
599 executor.execute(() -> {
600 listener.onProgress(progressSnapshot);
601 });
602 }
603 checkpoint = 0;
604 }
605 }
606 if (executor != null && listener != null) {
607 final long progressSnapshot = progress;
608 executor.execute(() -> {
609 listener.onProgress(progressSnapshot);
610 });
611 }
612 return progress;
613 }
614
615 /**
616 * Check if a filename is "safe" (no metacharacters or spaces).
617 * @param file The file to check
618 * @hide
619 */
620 @UnsupportedAppUsage
621 public static boolean isFilenameSafe(File file) {
622 // Note, we check whether it matches what's known to be safe,
623 // rather than what's known to be unsafe. Non-ASCII, control
624 // characters, etc. are all unsafe by default.
625 return NoImagePreloadHolder.SAFE_FILENAME_PATTERN.matcher(file.getPath()).matches();
626 }
627
628 /**
629 * Read a text file into a String, optionally limiting the length.
630 * @param file to read (will not seek, so things like /proc files are OK)
631 * @param max length (positive for head, negative of tail, 0 for no limit)
632 * @param ellipsis to add of the file was truncated (can be null)
633 * @return the contents of the file, possibly truncated
634 * @throws IOException if something goes wrong reading the file
635 * @hide
636 */
637 @UnsupportedAppUsage
638 public static String readTextFile(File file, int max, String ellipsis) throws IOException {
639 InputStream input = new FileInputStream(file);
640 // wrapping a BufferedInputStream around it because when reading /proc with unbuffered
641 // input stream, bytes read not equal to buffer size is not necessarily the correct
642 // indication for EOF; but it is true for BufferedInputStream due to its implementation.
643 BufferedInputStream bis = new BufferedInputStream(input);
644 try {
645 long size = file.length();
646 if (max > 0 || (size > 0 && max == 0)) { // "head" mode: read the first N bytes
647 if (size > 0 && (max == 0 || size < max)) max = (int) size;
648 byte[] data = new byte[max + 1];
649 int length = bis.read(data);
650 if (length <= 0) return "";
651 if (length <= max) return new String(data, 0, length);
652 if (ellipsis == null) return new String(data, 0, max);
653 return new String(data, 0, max) + ellipsis;
654 } else if (max < 0) { // "tail" mode: keep the last N
655 int len;
656 boolean rolled = false;
657 byte[] last = null;
658 byte[] data = null;
659 do {
660 if (last != null) rolled = true;
661 byte[] tmp = last; last = data; data = tmp;
662 if (data == null) data = new byte[-max];
663 len = bis.read(data);
664 } while (len == data.length);
665
666 if (last == null && len <= 0) return "";
667 if (last == null) return new String(data, 0, len);
668 if (len > 0) {
669 rolled = true;
670 System.arraycopy(last, len, last, 0, last.length - len);
671 System.arraycopy(data, 0, last, last.length - len, len);
672 }
673 if (ellipsis == null || !rolled) return new String(last);
674 return ellipsis + new String(last);
675 } else { // "cat" mode: size unknown, read it all in streaming fashion
676 ByteArrayOutputStream contents = new ByteArrayOutputStream();
677 int len;
678 byte[] data = new byte[1024];
679 do {
680 len = bis.read(data);
681 if (len > 0) contents.write(data, 0, len);
682 } while (len == data.length);
683 return contents.toString();
684 }
685 } finally {
686 bis.close();
687 input.close();
688 }
689 }
690
691 /** {@hide} */
692 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
693 public static void stringToFile(File file, String string) throws IOException {
694 stringToFile(file.getAbsolutePath(), string);
695 }
696
697 /**
698 * Writes the bytes given in {@code content} to the file whose absolute path
699 * is {@code filename}.
700 *
701 * @hide
702 */
703 public static void bytesToFile(String filename, byte[] content) throws IOException {
704 if (filename.startsWith("/proc/")) {
705 final int oldMask = StrictMode.allowThreadDiskWritesMask();
706 try (FileOutputStream fos = new FileOutputStream(filename)) {
707 fos.write(content);
708 } finally {
709 StrictMode.setThreadPolicyMask(oldMask);
710 }
711 } else {
712 try (FileOutputStream fos = new FileOutputStream(filename)) {
713 fos.write(content);
714 }
715 }
716 }
717
718 /**
719 * Writes string to file. Basically same as "echo -n $string > $filename"
720 *
721 * @param filename
722 * @param string
723 * @throws IOException
724 * @hide
725 */
726 @UnsupportedAppUsage
727 public static void stringToFile(String filename, String string) throws IOException {
728 bytesToFile(filename, string.getBytes(StandardCharsets.UTF_8));
729 }
730
731 /**
732 * Computes the checksum of a file using the CRC32 checksum routine. The
733 * value of the checksum is returned.
734 *
735 * @param file the file to checksum, must not be null
736 * @return the checksum value or an exception is thrown.
737 * @deprecated this is a weak hashing algorithm, and should not be used due
738 * to its potential for collision.
739 * @hide
740 */
741 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
742 @Deprecated
743 public static long checksumCrc32(File file) throws FileNotFoundException, IOException {
744 CRC32 checkSummer = new CRC32();
745 CheckedInputStream cis = null;
746
747 try {
748 cis = new CheckedInputStream( new FileInputStream(file), checkSummer);
749 byte[] buf = new byte[128];
750 while(cis.read(buf) >= 0) {
751 // Just read for checksum to get calculated.
752 }
753 return checkSummer.getValue();
754 } finally {
755 if (cis != null) {
756 try {
757 cis.close();
758 } catch (IOException e) {
759 }
760 }
761 }
762 }
763
764 /**
765 * Compute the digest of the given file using the requested algorithm.
766 *
767 * @param algorithm Any valid algorithm accepted by
768 * {@link MessageDigest#getInstance(String)}.
769 * @hide
770 */
771 @TestApi
772 @NonNull
773 public static byte[] digest(@NonNull File file, @NonNull String algorithm)
774 throws IOException, NoSuchAlgorithmException {
775 try (FileInputStream in = new FileInputStream(file)) {
776 return digest(in, algorithm);
777 }
778 }
779
780 /**
781 * Compute the digest of the given file using the requested algorithm.
782 *
783 * @param algorithm Any valid algorithm accepted by
784 * {@link MessageDigest#getInstance(String)}.
785 * @hide
786 */
787 @TestApi
788 @NonNull
789 public static byte[] digest(@NonNull InputStream in, @NonNull String algorithm)
790 throws IOException, NoSuchAlgorithmException {
791 // TODO: implement kernel optimizations
792 return digestInternalUserspace(in, algorithm);
793 }
794
795 /**
796 * Compute the digest of the given file using the requested algorithm.
797 *
798 * @param algorithm Any valid algorithm accepted by
799 * {@link MessageDigest#getInstance(String)}.
800 * @hide
801 */
802 public static byte[] digest(FileDescriptor fd, String algorithm)
803 throws IOException, NoSuchAlgorithmException {
804 // TODO: implement kernel optimizations
805 return digestInternalUserspace(new FileInputStream(fd), algorithm);
806 }
807
808 private static byte[] digestInternalUserspace(InputStream in, String algorithm)
809 throws IOException, NoSuchAlgorithmException {
810 final MessageDigest digest = MessageDigest.getInstance(algorithm);
811 try (DigestInputStream digestStream = new DigestInputStream(in, digest)) {
812 final byte[] buffer = new byte[8192];
813 while (digestStream.read(buffer) != -1) {
814 }
815 }
816 return digest.digest();
817 }
818
819 /**
820 * Delete older files in a directory until only those matching the given
821 * constraints remain.
822 *
823 * @param minCount Always keep at least this many files.
824 * @param minAgeMs Always keep files younger than this age, in milliseconds.
825 * @return if any files were deleted.
826 * @hide
827 */
828 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
829 public static boolean deleteOlderFiles(File dir, int minCount, long minAgeMs) {
830 if (minCount < 0 || minAgeMs < 0) {
831 throw new IllegalArgumentException("Constraints must be positive or 0");
832 }
833
834 final File[] files = dir.listFiles();
835 if (files == null) return false;
836
837 // Sort with newest files first
838 Arrays.sort(files, new Comparator<File>() {
839 @Override
840 public int compare(File lhs, File rhs) {
841 return Long.compare(rhs.lastModified(), lhs.lastModified());
842 }
843 });
844
845 // Keep at least minCount files
846 boolean deleted = false;
847 for (int i = minCount; i < files.length; i++) {
848 final File file = files[i];
849
850 // Keep files newer than minAgeMs
851 final long age = System.currentTimeMillis() - file.lastModified();
852 if (age > minAgeMs) {
853 if (file.delete()) {
854 Log.d(TAG, "Deleted old file " + file);
855 deleted = true;
856 }
857 }
858 }
859 return deleted;
860 }
861
862 /**
863 * Test if a file lives under the given directory, either as a direct child
864 * or a distant grandchild.
865 * <p>
866 * Both files <em>must</em> have been resolved using
867 * {@link File#getCanonicalFile()} to avoid symlink or path traversal
868 * attacks.
869 *
870 * @hide
871 */
872 public static boolean contains(File[] dirs, File file) {
873 for (File dir : dirs) {
874 if (contains(dir, file)) {
875 return true;
876 }
877 }
878 return false;
879 }
880
881 /** {@hide} */
882 public static boolean contains(Collection<File> dirs, File file) {
883 for (File dir : dirs) {
884 if (contains(dir, file)) {
885 return true;
886 }
887 }
888 return false;
889 }
890
891 /**
892 * Test if a file lives under the given directory, either as a direct child
893 * or a distant grandchild.
894 * <p>
895 * Both files <em>must</em> have been resolved using
896 * {@link File#getCanonicalFile()} to avoid symlink or path traversal
897 * attacks.
898 *
899 * @hide
900 */
901 @TestApi
902 public static boolean contains(File dir, File file) {
903 if (dir == null || file == null) return false;
904 return contains(dir.getAbsolutePath(), file.getAbsolutePath());
905 }
906
907 /**
908 * Test if a file lives under the given directory, either as a direct child
909 * or a distant grandchild.
910 * <p>
911 * Both files <em>must</em> have been resolved using
912 * {@link File#getCanonicalFile()} to avoid symlink or path traversal
913 * attacks.
914 *
915 * @hide
916 */
917 public static boolean contains(String dirPath, String filePath) {
918 if (dirPath.equals(filePath)) {
919 return true;
920 }
921 if (!dirPath.endsWith("/")) {
922 dirPath += "/";
923 }
924 return filePath.startsWith(dirPath);
925 }
926
927 /** {@hide} */
928 public static boolean deleteContentsAndDir(File dir) {
929 if (deleteContents(dir)) {
930 return dir.delete();
931 } else {
932 return false;
933 }
934 }
935
936 /** {@hide} */
937 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
938 public static boolean deleteContents(File dir) {
939 File[] files = dir.listFiles();
940 boolean success = true;
941 if (files != null) {
942 for (File file : files) {
943 if (file.isDirectory()) {
944 success &= deleteContents(file);
945 }
946 if (!file.delete()) {
947 Log.w(TAG, "Failed to delete " + file);
948 success = false;
949 }
950 }
951 }
952 return success;
953 }
954
955 private static boolean isValidExtFilenameChar(char c) {
956 switch (c) {
957 case '\0':
958 case '/':
959 return false;
960 default:
961 return true;
962 }
963 }
964
965 /**
966 * Check if given filename is valid for an ext4 filesystem.
967 *
968 * @hide
969 */
970 public static boolean isValidExtFilename(String name) {
971 return (name != null) && name.equals(buildValidExtFilename(name));
972 }
973
974 /**
975 * Mutate the given filename to make it valid for an ext4 filesystem,
976 * replacing any invalid characters with "_".
977 *
978 * @hide
979 */
980 public static String buildValidExtFilename(String name) {
981 if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) {
982 return "(invalid)";
983 }
984 final StringBuilder res = new StringBuilder(name.length());
985 for (int i = 0; i < name.length(); i++) {
986 final char c = name.charAt(i);
987 if (isValidExtFilenameChar(c)) {
988 res.append(c);
989 } else {
990 res.append('_');
991 }
992 }
993 trimFilename(res, 255);
994 return res.toString();
995 }
996
997 private static boolean isValidFatFilenameChar(char c) {
998 if ((0x00 <= c && c <= 0x1f)) {
999 return false;
1000 }
1001 switch (c) {
1002 case '"':
1003 case '*':
1004 case '/':
1005 case ':':
1006 case '<':
1007 case '>':
1008 case '?':
1009 case '\\':
1010 case '|':
1011 case 0x7F:
1012 return false;
1013 default:
1014 return true;
1015 }
1016 }
1017
1018 /**
1019 * Check if given filename is valid for a FAT filesystem.
1020 *
1021 * @hide
1022 */
1023 public static boolean isValidFatFilename(String name) {
1024 return (name != null) && name.equals(buildValidFatFilename(name));
1025 }
1026
1027 /**
1028 * Mutate the given filename to make it valid for a FAT filesystem,
1029 * replacing any invalid characters with "_".
1030 *
1031 * @hide
1032 */
1033 public static String buildValidFatFilename(String name) {
1034 if (TextUtils.isEmpty(name) || ".".equals(name) || "..".equals(name)) {
1035 return "(invalid)";
1036 }
1037 final StringBuilder res = new StringBuilder(name.length());
1038 for (int i = 0; i < name.length(); i++) {
1039 final char c = name.charAt(i);
1040 if (isValidFatFilenameChar(c)) {
1041 res.append(c);
1042 } else {
1043 res.append('_');
1044 }
1045 }
1046 // Even though vfat allows 255 UCS-2 chars, we might eventually write to
1047 // ext4 through a FUSE layer, so use that limit.
1048 trimFilename(res, 255);
1049 return res.toString();
1050 }
1051
1052 /** {@hide} */
1053 @VisibleForTesting
1054 public static String trimFilename(String str, int maxBytes) {
1055 final StringBuilder res = new StringBuilder(str);
1056 trimFilename(res, maxBytes);
1057 return res.toString();
1058 }
1059
1060 /** {@hide} */
1061 private static void trimFilename(StringBuilder res, int maxBytes) {
1062 byte[] raw = res.toString().getBytes(StandardCharsets.UTF_8);
1063 if (raw.length > maxBytes) {
1064 maxBytes -= 3;
1065 while (raw.length > maxBytes) {
1066 res.deleteCharAt(res.length() / 2);
1067 raw = res.toString().getBytes(StandardCharsets.UTF_8);
1068 }
1069 res.insert(res.length() / 2, "...");
1070 }
1071 }
1072
1073 /** {@hide} */
1074 public static String rewriteAfterRename(File beforeDir, File afterDir, String path) {
1075 if (path == null) return null;
1076 final File result = rewriteAfterRename(beforeDir, afterDir, new File(path));
1077 return (result != null) ? result.getAbsolutePath() : null;
1078 }
1079
1080 /** {@hide} */
1081 public static String[] rewriteAfterRename(File beforeDir, File afterDir, String[] paths) {
1082 if (paths == null) return null;
1083 final String[] result = new String[paths.length];
1084 for (int i = 0; i < paths.length; i++) {
1085 result[i] = rewriteAfterRename(beforeDir, afterDir, paths[i]);
1086 }
1087 return result;
1088 }
1089
1090 /**
1091 * Given a path under the "before" directory, rewrite it to live under the
1092 * "after" directory. For example, {@code /before/foo/bar.txt} would become
1093 * {@code /after/foo/bar.txt}.
1094 *
1095 * @hide
1096 */
1097 public static File rewriteAfterRename(File beforeDir, File afterDir, File file) {
1098 if (file == null || beforeDir == null || afterDir == null) return null;
1099 if (contains(beforeDir, file)) {
1100 final String splice = file.getAbsolutePath().substring(
1101 beforeDir.getAbsolutePath().length());
1102 return new File(afterDir, splice);
1103 }
1104 return null;
1105 }
1106
1107 /** {@hide} */
1108 private static File buildUniqueFileWithExtension(File parent, String name, String ext)
1109 throws FileNotFoundException {
1110 File file = buildFile(parent, name, ext);
1111
1112 // If conflicting file, try adding counter suffix
1113 int n = 0;
1114 while (file.exists()) {
1115 if (n++ >= 32) {
1116 throw new FileNotFoundException("Failed to create unique file");
1117 }
1118 file = buildFile(parent, name + " (" + n + ")", ext);
1119 }
1120
1121 return file;
1122 }
1123
1124 /**
1125 * Generates a unique file name under the given parent directory. If the display name doesn't
1126 * have an extension that matches the requested MIME type, the default extension for that MIME
1127 * type is appended. If a file already exists, the name is appended with a numerical value to
1128 * make it unique.
1129 *
1130 * For example, the display name 'example' with 'text/plain' MIME might produce
1131 * 'example.txt' or 'example (1).txt', etc.
1132 *
1133 * @throws FileNotFoundException
1134 * @hide
1135 */
1136 public static File buildUniqueFile(File parent, String mimeType, String displayName)
1137 throws FileNotFoundException {
1138 final String[] parts = splitFileName(mimeType, displayName);
1139 return buildUniqueFileWithExtension(parent, parts[0], parts[1]);
1140 }
1141
1142 /** {@hide} */
1143 public static File buildNonUniqueFile(File parent, String mimeType, String displayName) {
1144 final String[] parts = splitFileName(mimeType, displayName);
1145 return buildFile(parent, parts[0], parts[1]);
1146 }
1147
1148 /**
1149 * Generates a unique file name under the given parent directory, keeping
1150 * any extension intact.
1151 *
1152 * @hide
1153 */
1154 public static File buildUniqueFile(File parent, String displayName)
1155 throws FileNotFoundException {
1156 final String name;
1157 final String ext;
1158
1159 // Extract requested extension from display name
1160 final int lastDot = displayName.lastIndexOf('.');
1161 if (lastDot >= 0) {
1162 name = displayName.substring(0, lastDot);
1163 ext = displayName.substring(lastDot + 1);
1164 } else {
1165 name = displayName;
1166 ext = null;
1167 }
1168
1169 return buildUniqueFileWithExtension(parent, name, ext);
1170 }
1171
1172 /**
1173 * Splits file name into base name and extension.
1174 * If the display name doesn't have an extension that matches the requested MIME type, the
1175 * extension is regarded as a part of filename and default extension for that MIME type is
1176 * appended.
1177 *
1178 * @hide
1179 */
1180 public static String[] splitFileName(String mimeType, String displayName) {
1181 String name;
1182 String ext;
1183
1184 if (Document.MIME_TYPE_DIR.equals(mimeType)) {
1185 name = displayName;
1186 ext = null;
1187 } else {
1188 String mimeTypeFromExt;
1189
1190 // Extract requested extension from display name
1191 final int lastDot = displayName.lastIndexOf('.');
1192 if (lastDot >= 0) {
1193 name = displayName.substring(0, lastDot);
1194 ext = displayName.substring(lastDot + 1);
1195 mimeTypeFromExt = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
1196 ext.toLowerCase());
1197 } else {
1198 name = displayName;
1199 ext = null;
1200 mimeTypeFromExt = null;
1201 }
1202
1203 if (mimeTypeFromExt == null) {
1204 mimeTypeFromExt = ContentResolver.MIME_TYPE_DEFAULT;
1205 }
1206
1207 final String extFromMimeType;
1208 if (ContentResolver.MIME_TYPE_DEFAULT.equals(mimeType)) {
1209 extFromMimeType = null;
1210 } else {
1211 extFromMimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
1212 }
1213
1214 if (Objects.equals(mimeType, mimeTypeFromExt) || Objects.equals(ext, extFromMimeType)) {
1215 // Extension maps back to requested MIME type; allow it
1216 } else {
1217 // No match; insist that create file matches requested MIME
1218 name = displayName;
1219 ext = extFromMimeType;
1220 }
1221 }
1222
1223 if (ext == null) {
1224 ext = "";
1225 }
1226
1227 return new String[] { name, ext };
1228 }
1229
1230 /** {@hide} */
1231 private static File buildFile(File parent, String name, String ext) {
1232 if (TextUtils.isEmpty(ext)) {
1233 return new File(parent, name);
1234 } else {
1235 return new File(parent, name + "." + ext);
1236 }
1237 }
1238
1239 /** {@hide} */
1240 public static @NonNull String[] listOrEmpty(@Nullable File dir) {
1241 return (dir != null) ? ArrayUtils.defeatNullable(dir.list())
1242 : EmptyArray.STRING;
1243 }
1244
1245 /** {@hide} */
1246 public static @NonNull File[] listFilesOrEmpty(@Nullable File dir) {
1247 return (dir != null) ? ArrayUtils.defeatNullable(dir.listFiles())
1248 : ArrayUtils.EMPTY_FILE;
1249 }
1250
1251 /** {@hide} */
1252 public static @NonNull File[] listFilesOrEmpty(@Nullable File dir, FilenameFilter filter) {
1253 return (dir != null) ? ArrayUtils.defeatNullable(dir.listFiles(filter))
1254 : ArrayUtils.EMPTY_FILE;
1255 }
1256
1257 /** {@hide} */
1258 public static @Nullable File newFileOrNull(@Nullable String path) {
1259 return (path != null) ? new File(path) : null;
1260 }
1261
1262 /**
1263 * Creates a directory with name {@code name} under an existing directory {@code baseDir} if it
1264 * doesn't exist already. Returns a {@code File} object representing the directory if it exists
1265 * and {@code null} if not.
1266 *
1267 * @hide
1268 */
1269 public static @Nullable File createDir(File baseDir, String name) {
1270 final File dir = new File(baseDir, name);
1271
1272 return createDir(dir) ? dir : null;
1273 }
1274
1275 /**
1276 * Ensure the given directory exists, creating it if needed. This method is threadsafe.
1277 *
1278 * @return false if the directory doesn't exist and couldn't be created
1279 *
1280 * @hide
1281 */
1282 public static boolean createDir(File dir) {
1283 if (dir.mkdir()) {
1284 return true;
1285 }
1286
1287 if (dir.exists()) {
1288 return dir.isDirectory();
1289 }
1290
1291 return false;
1292 }
1293
1294 /**
1295 * Round the given size of a storage device to a nice round power-of-two
1296 * value, such as 256MB or 32GB. This avoids showing weird values like
1297 * "29.5GB" in UI.
1298 *
1299 * @hide
1300 */
1301 public static long roundStorageSize(long size) {
1302 long val = 1;
1303 long pow = 1;
1304 while ((val * pow) < size) {
1305 val <<= 1;
1306 if (val > 512) {
1307 val = 1;
1308 pow *= 1000;
1309 }
1310 }
1311 return val * pow;
1312 }
1313
1314 private static long toBytes(long value, String unit) {
1315 unit = unit.toUpperCase();
1316
1317 if (List.of("B").contains(unit)) {
1318 return value;
1319 }
1320
1321 if (List.of("K", "KB").contains(unit)) {
1322 return DataUnit.KILOBYTES.toBytes(value);
1323 }
1324
1325 if (List.of("M", "MB").contains(unit)) {
1326 return DataUnit.MEGABYTES.toBytes(value);
1327 }
1328
1329 if (List.of("G", "GB").contains(unit)) {
1330 return DataUnit.GIGABYTES.toBytes(value);
1331 }
1332
1333 if (List.of("KI", "KIB").contains(unit)) {
1334 return DataUnit.KIBIBYTES.toBytes(value);
1335 }
1336
1337 if (List.of("MI", "MIB").contains(unit)) {
1338 return DataUnit.MEBIBYTES.toBytes(value);
1339 }
1340
1341 if (List.of("GI", "GIB").contains(unit)) {
1342 return DataUnit.GIBIBYTES.toBytes(value);
1343 }
1344
1345 return Long.MIN_VALUE;
1346 }
1347
1348 /**
1349 * @param fmtSize The string that contains the size to be parsed. The
1350 * expected format is:
1351 *
1352 * <p>"^((\\s*[-+]?[0-9]+)\\s*(B|K|KB|M|MB|G|GB|Ki|KiB|Mi|MiB|Gi|GiB)\\s*)$"
1353 *
1354 * <p>For example: 10Kb, 500GiB, 100mb. The unit is not case sensitive.
1355 *
1356 * @return the size in bytes. If {@code fmtSize} has invalid format, it
1357 * returns {@link Long#MIN_VALUE}.
1358 * @hide
1359 */
1360 public static long parseSize(@Nullable String fmtSize) {
1361 if (fmtSize == null || fmtSize.isBlank()) {
1362 return Long.MIN_VALUE;
1363 }
1364
1365 int sign = 1;
1366 fmtSize = fmtSize.trim();
1367 char first = fmtSize.charAt(0);
1368 if (first == '-' || first == '+') {
1369 if (first == '-') {
1370 sign = -1;
1371 }
1372
1373 fmtSize = fmtSize.replace(first + "", "");
1374 }
1375
1376 int index = 0;
1377 // Find the last index of the value in fmtSize.
1378 while (index < fmtSize.length() && Character.isDigit(fmtSize.charAt(index))) {
1379 index++;
1380 }
1381
1382 // Check if number and units are present.
1383 if (index == 0 || index == fmtSize.length()) {
1384 return Long.MIN_VALUE;
1385 }
1386
1387 long value = sign * Long.valueOf(fmtSize.substring(0, index));
1388 String unit = fmtSize.substring(index).trim();
1389
1390 return toBytes(value, unit);
1391 }
1392
1393 /**
1394 * Closes the given object quietly, ignoring any checked exceptions. Does
1395 * nothing if the given object is {@code null}.
1396 *
1397 * @deprecated This method may suppress potentially significant exceptions, particularly when
1398 * closing writable resources. With a writable resource, a failure thrown from {@code close()}
1399 * should be considered as significant as a failure thrown from a write method because it may
1400 * indicate a failure to flush bytes to the underlying resource.
1401 */
1402 @Deprecated
1403 public static void closeQuietly(@Nullable AutoCloseable closeable) {
1404 IoUtils.closeQuietly(closeable);
1405 }
1406
1407 /**
1408 * Closes the given object quietly, ignoring any checked exceptions. Does
1409 * nothing if the given object is {@code null}.
1410 *
1411 * @deprecated This method may suppress potentially significant exceptions, particularly when
1412 * closing writable resources. With a writable resource, a failure thrown from {@code close()}
1413 * should be considered as significant as a failure thrown from a write method because it may
1414 * indicate a failure to flush bytes to the underlying resource.
1415 */
1416 @Deprecated
1417 public static void closeQuietly(@Nullable FileDescriptor fd) {
1418 IoUtils.closeQuietly(fd);
1419 }
1420
1421 /** {@hide} */
1422 public static int translateModeStringToPosix(String mode) {
1423 // Quick check for invalid chars
1424 for (int i = 0; i < mode.length(); i++) {
1425 switch (mode.charAt(i)) {
1426 case 'r':
1427 case 'w':
1428 case 't':
1429 case 'a':
1430 break;
1431 default:
1432 throw new IllegalArgumentException("Bad mode: " + mode);
1433 }
1434 }
1435
1436 int res = 0;
1437 if (mode.startsWith("rw")) {
1438 res = O_RDWR | O_CREAT;
1439 } else if (mode.startsWith("w")) {
1440 res = O_WRONLY | O_CREAT;
1441 } else if (mode.startsWith("r")) {
1442 res = O_RDONLY;
1443 } else {
1444 throw new IllegalArgumentException("Bad mode: " + mode);
1445 }
1446 if (mode.indexOf('t') != -1) {
1447 res |= O_TRUNC;
1448 }
1449 if (mode.indexOf('a') != -1) {
1450 res |= O_APPEND;
1451 }
1452 return res;
1453 }
1454
1455 /** {@hide} */
1456 public static String translateModePosixToString(int mode) {
1457 String res = "";
1458 if ((mode & O_ACCMODE) == O_RDWR) {
1459 res = "rw";
1460 } else if ((mode & O_ACCMODE) == O_WRONLY) {
1461 res = "w";
1462 } else if ((mode & O_ACCMODE) == O_RDONLY) {
1463 res = "r";
1464 } else {
1465 throw new IllegalArgumentException("Bad mode: " + mode);
1466 }
1467 if ((mode & O_TRUNC) == O_TRUNC) {
1468 res += "t";
1469 }
1470 if ((mode & O_APPEND) == O_APPEND) {
1471 res += "a";
1472 }
1473 return res;
1474 }
1475
1476 /** {@hide} */
1477 public static int translateModePosixToPfd(int mode) {
1478 int res = 0;
1479 if ((mode & O_ACCMODE) == O_RDWR) {
1480 res = MODE_READ_WRITE;
1481 } else if ((mode & O_ACCMODE) == O_WRONLY) {
1482 res = MODE_WRITE_ONLY;
1483 } else if ((mode & O_ACCMODE) == O_RDONLY) {
1484 res = MODE_READ_ONLY;
1485 } else {
1486 throw new IllegalArgumentException("Bad mode: " + mode);
1487 }
1488 if ((mode & O_CREAT) == O_CREAT) {
1489 res |= MODE_CREATE;
1490 }
1491 if ((mode & O_TRUNC) == O_TRUNC) {
1492 res |= MODE_TRUNCATE;
1493 }
1494 if ((mode & O_APPEND) == O_APPEND) {
1495 res |= MODE_APPEND;
1496 }
1497 return res;
1498 }
1499
1500 /** {@hide} */
1501 public static int translateModePfdToPosix(int mode) {
1502 int res = 0;
1503 if ((mode & MODE_READ_WRITE) == MODE_READ_WRITE) {
1504 res = O_RDWR;
1505 } else if ((mode & MODE_WRITE_ONLY) == MODE_WRITE_ONLY) {
1506 res = O_WRONLY;
1507 } else if ((mode & MODE_READ_ONLY) == MODE_READ_ONLY) {
1508 res = O_RDONLY;
1509 } else {
1510 throw new IllegalArgumentException("Bad mode: " + mode);
1511 }
1512 if ((mode & MODE_CREATE) == MODE_CREATE) {
1513 res |= O_CREAT;
1514 }
1515 if ((mode & MODE_TRUNCATE) == MODE_TRUNCATE) {
1516 res |= O_TRUNC;
1517 }
1518 if ((mode & MODE_APPEND) == MODE_APPEND) {
1519 res |= O_APPEND;
1520 }
1521 return res;
1522 }
1523
1524 /** {@hide} */
1525 public static int translateModeAccessToPosix(int mode) {
1526 if (mode == F_OK) {
1527 // There's not an exact mapping, so we attempt a read-only open to
1528 // determine if a file exists
1529 return O_RDONLY;
1530 } else if ((mode & (R_OK | W_OK)) == (R_OK | W_OK)) {
1531 return O_RDWR;
1532 } else if ((mode & R_OK) == R_OK) {
1533 return O_RDONLY;
1534 } else if ((mode & W_OK) == W_OK) {
1535 return O_WRONLY;
1536 } else {
1537 throw new IllegalArgumentException("Bad mode: " + mode);
1538 }
1539 }
1540
1541 /** {@hide} */
1542 @VisibleForTesting
1543 public static ParcelFileDescriptor convertToModernFd(FileDescriptor fd) {
1544 Context context = AppGlobals.getInitialApplication();
1545 if (UserHandle.getAppId(Process.myUid()) == getMediaProviderAppId(context)) {
1546 // Never convert modern fd for MediaProvider, because this requires
1547 // MediaStore#scanFile and can cause infinite loops when MediaProvider scans
1548 return null;
1549 }
1550
1551 try (ParcelFileDescriptor dupFd = ParcelFileDescriptor.dup(fd)) {
1552 return MediaStore.getOriginalMediaFormatFileDescriptor(context, dupFd);
1553 } catch (Exception e) {
1554 // Ignore error
1555 return null;
1556 }
1557 }
1558
1559 private static int getMediaProviderAppId(Context context) {
1560 if (sMediaProviderAppId != -1) {
1561 return sMediaProviderAppId;
1562 }
1563
1564 PackageManager pm = context.getPackageManager();
1565 ProviderInfo provider = context.getPackageManager().resolveContentProvider(
1566 MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
1567 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
1568 | PackageManager.MATCH_SYSTEM_ONLY);
1569 if (provider == null) {
1570 return -1;
1571 }
1572
1573 sMediaProviderAppId = UserHandle.getAppId(provider.applicationInfo.uid);
1574 return sMediaProviderAppId;
1575 }
1576
1577 /** {@hide} */
1578 @VisibleForTesting
1579 public static class MemoryPipe extends Thread implements AutoCloseable {
1580 private final FileDescriptor[] pipe;
1581 private final byte[] data;
1582 private final boolean sink;
1583
1584 private MemoryPipe(byte[] data, boolean sink) throws IOException {
1585 try {
1586 this.pipe = Os.pipe();
1587 } catch (ErrnoException e) {
1588 throw e.rethrowAsIOException();
1589 }
1590 this.data = data;
1591 this.sink = sink;
1592 }
1593
1594 private MemoryPipe startInternal() {
1595 super.start();
1596 return this;
1597 }
1598
1599 public static MemoryPipe createSource(byte[] data) throws IOException {
1600 return new MemoryPipe(data, false).startInternal();
1601 }
1602
1603 public static MemoryPipe createSink(byte[] data) throws IOException {
1604 return new MemoryPipe(data, true).startInternal();
1605 }
1606
1607 public FileDescriptor getFD() {
1608 return sink ? pipe[1] : pipe[0];
1609 }
1610
1611 public FileDescriptor getInternalFD() {
1612 return sink ? pipe[0] : pipe[1];
1613 }
1614
1615 @Override
1616 public void run() {
1617 final FileDescriptor fd = getInternalFD();
1618 try {
1619 int i = 0;
1620 while (i < data.length) {
1621 if (sink) {
1622 i += Os.read(fd, data, i, data.length - i);
1623 } else {
1624 i += Os.write(fd, data, i, data.length - i);
1625 }
1626 }
1627 } catch (IOException | ErrnoException e) {
1628 // Ignored
1629 } finally {
1630 if (sink) {
1631 SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
1632 }
1633 IoUtils.closeQuietly(fd);
1634 }
1635 }
1636
1637 @Override
1638 public void close() throws Exception {
1639 IoUtils.closeQuietly(getFD());
1640 }
1641 }
1642 }