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