1 /* 2 * Copyright (C) 2008 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.storage; 18 19 import android.annotation.BytesLong; 20 import android.annotation.IntDef; 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.annotation.RequiresPermission; 24 import android.annotation.SdkConstant; 25 import android.annotation.SuppressLint; 26 import android.annotation.SystemApi; 27 import android.annotation.SystemService; 28 import android.annotation.WorkerThread; 29 import android.app.Activity; 30 import android.app.ActivityThread; 31 import android.content.ContentResolver; 32 import android.content.Context; 33 import android.content.Intent; 34 import android.content.pm.ApplicationInfo; 35 import android.content.pm.IPackageMoveObserver; 36 import android.content.pm.PackageManager; 37 import android.os.Binder; 38 import android.os.Environment; 39 import android.os.FileUtils; 40 import android.os.Handler; 41 import android.os.IVold; 42 import android.os.IVoldTaskListener; 43 import android.os.Looper; 44 import android.os.Message; 45 import android.os.ParcelFileDescriptor; 46 import android.os.ParcelableException; 47 import android.os.PersistableBundle; 48 import android.os.ProxyFileDescriptorCallback; 49 import android.os.RemoteException; 50 import android.os.ServiceManager; 51 import android.os.ServiceManager.ServiceNotFoundException; 52 import android.os.SystemProperties; 53 import android.provider.Settings; 54 import android.system.ErrnoException; 55 import android.system.Os; 56 import android.system.OsConstants; 57 import android.text.TextUtils; 58 import android.util.DataUnit; 59 import android.util.Log; 60 import android.util.Pair; 61 import android.util.Slog; 62 import android.util.SparseArray; 63 64 import com.android.internal.annotations.GuardedBy; 65 import com.android.internal.annotations.VisibleForTesting; 66 import com.android.internal.logging.MetricsLogger; 67 import com.android.internal.os.AppFuseMount; 68 import com.android.internal.os.FuseAppLoop; 69 import com.android.internal.os.FuseUnavailableMountException; 70 import com.android.internal.os.RoSystemProperties; 71 import com.android.internal.os.SomeArgs; 72 import com.android.internal.util.Preconditions; 73 74 import java.io.File; 75 import java.io.FileDescriptor; 76 import java.io.FileNotFoundException; 77 import java.io.IOException; 78 import java.lang.annotation.Retention; 79 import java.lang.annotation.RetentionPolicy; 80 import java.lang.ref.WeakReference; 81 import java.nio.charset.StandardCharsets; 82 import java.util.ArrayList; 83 import java.util.Arrays; 84 import java.util.Collections; 85 import java.util.Iterator; 86 import java.util.List; 87 import java.util.Objects; 88 import java.util.UUID; 89 import java.util.concurrent.CompletableFuture; 90 import java.util.concurrent.ThreadFactory; 91 import java.util.concurrent.TimeUnit; 92 import java.util.concurrent.atomic.AtomicInteger; 93 94 /** 95 * StorageManager is the interface to the systems storage service. The storage 96 * manager handles storage-related items such as Opaque Binary Blobs (OBBs). 97 * <p> 98 * OBBs contain a filesystem that maybe be encrypted on disk and mounted 99 * on-demand from an application. OBBs are a good way of providing large amounts 100 * of binary assets without packaging them into APKs as they may be multiple 101 * gigabytes in size. However, due to their size, they're most likely stored in 102 * a shared storage pool accessible from all programs. The system does not 103 * guarantee the security of the OBB file itself: if any program modifies the 104 * OBB, there is no guarantee that a read from that OBB will produce the 105 * expected output. 106 */ 107 @SystemService(Context.STORAGE_SERVICE) 108 public class StorageManager { 109 private static final String TAG = "StorageManager"; 110 111 /** {@hide} */ 112 public static final String PROP_PRIMARY_PHYSICAL = "ro.vold.primary_physical"; 113 /** {@hide} */ 114 public static final String PROP_HAS_ADOPTABLE = "vold.has_adoptable"; 115 /** {@hide} */ 116 public static final String PROP_HAS_RESERVED = "vold.has_reserved"; 117 /** {@hide} */ 118 public static final String PROP_ADOPTABLE = "persist.sys.adoptable"; 119 /** {@hide} */ 120 public static final String PROP_EMULATE_FBE = "persist.sys.emulate_fbe"; 121 /** {@hide} */ 122 public static final String PROP_SDCARDFS = "persist.sys.sdcardfs"; 123 /** {@hide} */ 124 public static final String PROP_VIRTUAL_DISK = "persist.sys.virtual_disk"; 125 126 /** {@hide} */ 127 public static final String UUID_PRIVATE_INTERNAL = null; 128 /** {@hide} */ 129 public static final String UUID_PRIMARY_PHYSICAL = "primary_physical"; 130 /** {@hide} */ 131 public static final String UUID_SYSTEM = "system"; 132 133 // NOTE: UUID constants below are namespaced 134 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad default 135 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad primary_physical 136 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad system 137 138 /** 139 * UUID representing the default internal storage of this device which 140 * provides {@link Environment#getDataDirectory()}. 141 * <p> 142 * This value is constant across all devices and it will never change, and 143 * thus it cannot be used to uniquely identify a particular physical device. 144 * 145 * @see #getUuidForPath(File) 146 * @see ApplicationInfo#storageUuid 147 */ 148 public static final UUID UUID_DEFAULT = UUID 149 .fromString("41217664-9172-527a-b3d5-edabb50a7d69"); 150 151 /** {@hide} */ 152 public static final UUID UUID_PRIMARY_PHYSICAL_ = UUID 153 .fromString("0f95a519-dae7-5abf-9519-fbd6209e05fd"); 154 155 /** {@hide} */ 156 public static final UUID UUID_SYSTEM_ = UUID 157 .fromString("5d258386-e60d-59e3-826d-0089cdd42cc0"); 158 159 /** 160 * Activity Action: Allows the user to manage their storage. This activity 161 * provides the ability to free up space on the device by deleting data such 162 * as apps. 163 * <p> 164 * If the sending application has a specific storage device or allocation 165 * size in mind, they can optionally define {@link #EXTRA_UUID} or 166 * {@link #EXTRA_REQUESTED_BYTES}, respectively. 167 * <p> 168 * This intent should be launched using 169 * {@link Activity#startActivityForResult(Intent, int)} so that the user 170 * knows which app is requesting the storage space. The returned result will 171 * be {@link Activity#RESULT_OK} if the requested space was made available, 172 * or {@link Activity#RESULT_CANCELED} otherwise. 173 */ 174 @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION) 175 public static final String ACTION_MANAGE_STORAGE = "android.os.storage.action.MANAGE_STORAGE"; 176 177 /** 178 * Extra {@link UUID} used to indicate the storage volume where an 179 * application is interested in allocating or managing disk space. 180 * 181 * @see #ACTION_MANAGE_STORAGE 182 * @see #UUID_DEFAULT 183 * @see #getUuidForPath(File) 184 * @see Intent#putExtra(String, java.io.Serializable) 185 */ 186 public static final String EXTRA_UUID = "android.os.storage.extra.UUID"; 187 188 /** 189 * Extra used to indicate the total size (in bytes) that an application is 190 * interested in allocating. 191 * <p> 192 * When defined, the management UI will help guide the user to free up 193 * enough disk space to reach this requested value. 194 * 195 * @see #ACTION_MANAGE_STORAGE 196 */ 197 public static final String EXTRA_REQUESTED_BYTES = "android.os.storage.extra.REQUESTED_BYTES"; 198 199 /** {@hide} */ 200 public static final int DEBUG_ADOPTABLE_FORCE_ON = 1 << 0; 201 /** {@hide} */ 202 public static final int DEBUG_ADOPTABLE_FORCE_OFF = 1 << 1; 203 /** {@hide} */ 204 public static final int DEBUG_EMULATE_FBE = 1 << 2; 205 /** {@hide} */ 206 public static final int DEBUG_SDCARDFS_FORCE_ON = 1 << 3; 207 /** {@hide} */ 208 public static final int DEBUG_SDCARDFS_FORCE_OFF = 1 << 4; 209 /** {@hide} */ 210 public static final int DEBUG_VIRTUAL_DISK = 1 << 5; 211 212 // NOTE: keep in sync with installd 213 /** {@hide} */ 214 public static final int FLAG_STORAGE_DE = 1 << 0; 215 /** {@hide} */ 216 public static final int FLAG_STORAGE_CE = 1 << 1; 217 218 /** {@hide} */ 219 public static final int FLAG_FOR_WRITE = 1 << 8; 220 /** {@hide} */ 221 public static final int FLAG_REAL_STATE = 1 << 9; 222 /** {@hide} */ 223 public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10; 224 225 /** {@hide} */ 226 public static final int FSTRIM_FLAG_DEEP = IVold.FSTRIM_FLAG_DEEP_TRIM; 227 228 /** @hide The volume is not encrypted. */ 229 public static final int ENCRYPTION_STATE_NONE = 230 IVold.ENCRYPTION_STATE_NONE; 231 232 /** @hide The volume has been encrypted succesfully. */ 233 public static final int ENCRYPTION_STATE_OK = 234 IVold.ENCRYPTION_STATE_OK; 235 236 /** @hide The volume is in a bad state. */ 237 public static final int ENCRYPTION_STATE_ERROR_UNKNOWN = 238 IVold.ENCRYPTION_STATE_ERROR_UNKNOWN; 239 240 /** @hide Encryption is incomplete */ 241 public static final int ENCRYPTION_STATE_ERROR_INCOMPLETE = 242 IVold.ENCRYPTION_STATE_ERROR_INCOMPLETE; 243 244 /** @hide Encryption is incomplete and irrecoverable */ 245 public static final int ENCRYPTION_STATE_ERROR_INCONSISTENT = 246 IVold.ENCRYPTION_STATE_ERROR_INCONSISTENT; 247 248 /** @hide Underlying data is corrupt */ 249 public static final int ENCRYPTION_STATE_ERROR_CORRUPT = 250 IVold.ENCRYPTION_STATE_ERROR_CORRUPT; 251 252 private static volatile IStorageManager sStorageManager = null; 253 254 private final Context mContext; 255 private final ContentResolver mResolver; 256 257 private final IStorageManager mStorageManager; 258 private final Looper mLooper; 259 private final AtomicInteger mNextNonce = new AtomicInteger(0); 260 261 private final ArrayList<StorageEventListenerDelegate> mDelegates = new ArrayList<>(); 262 263 private static class StorageEventListenerDelegate extends IStorageEventListener.Stub implements 264 Handler.Callback { 265 private static final int MSG_STORAGE_STATE_CHANGED = 1; 266 private static final int MSG_VOLUME_STATE_CHANGED = 2; 267 private static final int MSG_VOLUME_RECORD_CHANGED = 3; 268 private static final int MSG_VOLUME_FORGOTTEN = 4; 269 private static final int MSG_DISK_SCANNED = 5; 270 private static final int MSG_DISK_DESTROYED = 6; 271 272 final StorageEventListener mCallback; 273 final Handler mHandler; 274 StorageEventListenerDelegate(StorageEventListener callback, Looper looper)275 public StorageEventListenerDelegate(StorageEventListener callback, Looper looper) { 276 mCallback = callback; 277 mHandler = new Handler(looper, this); 278 } 279 280 @Override handleMessage(Message msg)281 public boolean handleMessage(Message msg) { 282 final SomeArgs args = (SomeArgs) msg.obj; 283 switch (msg.what) { 284 case MSG_STORAGE_STATE_CHANGED: 285 mCallback.onStorageStateChanged((String) args.arg1, (String) args.arg2, 286 (String) args.arg3); 287 args.recycle(); 288 return true; 289 case MSG_VOLUME_STATE_CHANGED: 290 mCallback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3); 291 args.recycle(); 292 return true; 293 case MSG_VOLUME_RECORD_CHANGED: 294 mCallback.onVolumeRecordChanged((VolumeRecord) args.arg1); 295 args.recycle(); 296 return true; 297 case MSG_VOLUME_FORGOTTEN: 298 mCallback.onVolumeForgotten((String) args.arg1); 299 args.recycle(); 300 return true; 301 case MSG_DISK_SCANNED: 302 mCallback.onDiskScanned((DiskInfo) args.arg1, args.argi2); 303 args.recycle(); 304 return true; 305 case MSG_DISK_DESTROYED: 306 mCallback.onDiskDestroyed((DiskInfo) args.arg1); 307 args.recycle(); 308 return true; 309 } 310 args.recycle(); 311 return false; 312 } 313 314 @Override onUsbMassStorageConnectionChanged(boolean connected)315 public void onUsbMassStorageConnectionChanged(boolean connected) throws RemoteException { 316 // Ignored 317 } 318 319 @Override onStorageStateChanged(String path, String oldState, String newState)320 public void onStorageStateChanged(String path, String oldState, String newState) { 321 final SomeArgs args = SomeArgs.obtain(); 322 args.arg1 = path; 323 args.arg2 = oldState; 324 args.arg3 = newState; 325 mHandler.obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget(); 326 } 327 328 @Override onVolumeStateChanged(VolumeInfo vol, int oldState, int newState)329 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 330 final SomeArgs args = SomeArgs.obtain(); 331 args.arg1 = vol; 332 args.argi2 = oldState; 333 args.argi3 = newState; 334 mHandler.obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget(); 335 } 336 337 @Override onVolumeRecordChanged(VolumeRecord rec)338 public void onVolumeRecordChanged(VolumeRecord rec) { 339 final SomeArgs args = SomeArgs.obtain(); 340 args.arg1 = rec; 341 mHandler.obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget(); 342 } 343 344 @Override onVolumeForgotten(String fsUuid)345 public void onVolumeForgotten(String fsUuid) { 346 final SomeArgs args = SomeArgs.obtain(); 347 args.arg1 = fsUuid; 348 mHandler.obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget(); 349 } 350 351 @Override onDiskScanned(DiskInfo disk, int volumeCount)352 public void onDiskScanned(DiskInfo disk, int volumeCount) { 353 final SomeArgs args = SomeArgs.obtain(); 354 args.arg1 = disk; 355 args.argi2 = volumeCount; 356 mHandler.obtainMessage(MSG_DISK_SCANNED, args).sendToTarget(); 357 } 358 359 @Override onDiskDestroyed(DiskInfo disk)360 public void onDiskDestroyed(DiskInfo disk) throws RemoteException { 361 final SomeArgs args = SomeArgs.obtain(); 362 args.arg1 = disk; 363 mHandler.obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget(); 364 } 365 } 366 367 /** 368 * Binder listener for OBB action results. 369 */ 370 private final ObbActionListener mObbActionListener = new ObbActionListener(); 371 372 private class ObbActionListener extends IObbActionListener.Stub { 373 @SuppressWarnings("hiding") 374 private SparseArray<ObbListenerDelegate> mListeners = new SparseArray<ObbListenerDelegate>(); 375 376 @Override onObbResult(String filename, int nonce, int status)377 public void onObbResult(String filename, int nonce, int status) { 378 final ObbListenerDelegate delegate; 379 synchronized (mListeners) { 380 delegate = mListeners.get(nonce); 381 if (delegate != null) { 382 mListeners.remove(nonce); 383 } 384 } 385 386 if (delegate != null) { 387 delegate.sendObbStateChanged(filename, status); 388 } 389 } 390 addListener(OnObbStateChangeListener listener)391 public int addListener(OnObbStateChangeListener listener) { 392 final ObbListenerDelegate delegate = new ObbListenerDelegate(listener); 393 394 synchronized (mListeners) { 395 mListeners.put(delegate.nonce, delegate); 396 } 397 398 return delegate.nonce; 399 } 400 } 401 getNextNonce()402 private int getNextNonce() { 403 return mNextNonce.getAndIncrement(); 404 } 405 406 /** 407 * Private class containing sender and receiver code for StorageEvents. 408 */ 409 private class ObbListenerDelegate { 410 private final WeakReference<OnObbStateChangeListener> mObbEventListenerRef; 411 private final Handler mHandler; 412 413 private final int nonce; 414 ObbListenerDelegate(OnObbStateChangeListener listener)415 ObbListenerDelegate(OnObbStateChangeListener listener) { 416 nonce = getNextNonce(); 417 mObbEventListenerRef = new WeakReference<OnObbStateChangeListener>(listener); 418 mHandler = new Handler(mLooper) { 419 @Override 420 public void handleMessage(Message msg) { 421 final OnObbStateChangeListener changeListener = getListener(); 422 if (changeListener == null) { 423 return; 424 } 425 426 changeListener.onObbStateChange((String) msg.obj, msg.arg1); 427 } 428 }; 429 } 430 getListener()431 OnObbStateChangeListener getListener() { 432 if (mObbEventListenerRef == null) { 433 return null; 434 } 435 return mObbEventListenerRef.get(); 436 } 437 sendObbStateChanged(String path, int state)438 void sendObbStateChanged(String path, int state) { 439 mHandler.obtainMessage(0, state, 0, path).sendToTarget(); 440 } 441 } 442 443 /** {@hide} */ 444 @Deprecated from(Context context)445 public static StorageManager from(Context context) { 446 return context.getSystemService(StorageManager.class); 447 } 448 449 /** 450 * Constructs a StorageManager object through which an application can 451 * can communicate with the systems mount service. 452 * 453 * @param looper The {@link android.os.Looper} which events will be received on. 454 * 455 * <p>Applications can get instance of this class by calling 456 * {@link android.content.Context#getSystemService(java.lang.String)} with an argument 457 * of {@link android.content.Context#STORAGE_SERVICE}. 458 * 459 * @hide 460 */ StorageManager(Context context, Looper looper)461 public StorageManager(Context context, Looper looper) throws ServiceNotFoundException { 462 mContext = context; 463 mResolver = context.getContentResolver(); 464 mLooper = looper; 465 mStorageManager = IStorageManager.Stub.asInterface(ServiceManager.getServiceOrThrow("mount")); 466 } 467 468 /** 469 * Registers a {@link android.os.storage.StorageEventListener StorageEventListener}. 470 * 471 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object. 472 * 473 * @hide 474 */ registerListener(StorageEventListener listener)475 public void registerListener(StorageEventListener listener) { 476 synchronized (mDelegates) { 477 final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(listener, 478 mLooper); 479 try { 480 mStorageManager.registerListener(delegate); 481 } catch (RemoteException e) { 482 throw e.rethrowFromSystemServer(); 483 } 484 mDelegates.add(delegate); 485 } 486 } 487 488 /** 489 * Unregisters a {@link android.os.storage.StorageEventListener StorageEventListener}. 490 * 491 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object. 492 * 493 * @hide 494 */ unregisterListener(StorageEventListener listener)495 public void unregisterListener(StorageEventListener listener) { 496 synchronized (mDelegates) { 497 for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) { 498 final StorageEventListenerDelegate delegate = i.next(); 499 if (delegate.mCallback == listener) { 500 try { 501 mStorageManager.unregisterListener(delegate); 502 } catch (RemoteException e) { 503 throw e.rethrowFromSystemServer(); 504 } 505 i.remove(); 506 } 507 } 508 } 509 } 510 511 /** 512 * Enables USB Mass Storage (UMS) on the device. 513 * 514 * @hide 515 */ 516 @Deprecated enableUsbMassStorage()517 public void enableUsbMassStorage() { 518 } 519 520 /** 521 * Disables USB Mass Storage (UMS) on the device. 522 * 523 * @hide 524 */ 525 @Deprecated disableUsbMassStorage()526 public void disableUsbMassStorage() { 527 } 528 529 /** 530 * Query if a USB Mass Storage (UMS) host is connected. 531 * @return true if UMS host is connected. 532 * 533 * @hide 534 */ 535 @Deprecated isUsbMassStorageConnected()536 public boolean isUsbMassStorageConnected() { 537 return false; 538 } 539 540 /** 541 * Query if a USB Mass Storage (UMS) is enabled on the device. 542 * @return true if UMS host is enabled. 543 * 544 * @hide 545 */ 546 @Deprecated isUsbMassStorageEnabled()547 public boolean isUsbMassStorageEnabled() { 548 return false; 549 } 550 551 /** 552 * Mount an Opaque Binary Blob (OBB) file. If a <code>key</code> is 553 * specified, it is supplied to the mounting process to be used in any 554 * encryption used in the OBB. 555 * <p> 556 * The OBB will remain mounted for as long as the StorageManager reference 557 * is held by the application. As soon as this reference is lost, the OBBs 558 * in use will be unmounted. The {@link OnObbStateChangeListener} registered 559 * with this call will receive the success or failure of this operation. 560 * <p> 561 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the 562 * file matches a package ID that is owned by the calling program's UID. 563 * That is, shared UID applications can attempt to mount any other 564 * application's OBB that shares its UID. 565 * 566 * @param rawPath the path to the OBB file 567 * @param key secret used to encrypt the OBB; may be <code>null</code> if no 568 * encryption was used on the OBB. 569 * @param listener will receive the success or failure of the operation 570 * @return whether the mount call was successfully queued or not 571 */ mountObb(String rawPath, String key, OnObbStateChangeListener listener)572 public boolean mountObb(String rawPath, String key, OnObbStateChangeListener listener) { 573 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 574 Preconditions.checkNotNull(listener, "listener cannot be null"); 575 576 try { 577 final String canonicalPath = new File(rawPath).getCanonicalPath(); 578 final int nonce = mObbActionListener.addListener(listener); 579 mStorageManager.mountObb(rawPath, canonicalPath, key, mObbActionListener, nonce); 580 return true; 581 } catch (IOException e) { 582 throw new IllegalArgumentException("Failed to resolve path: " + rawPath, e); 583 } catch (RemoteException e) { 584 throw e.rethrowFromSystemServer(); 585 } 586 } 587 588 /** 589 * Unmount an Opaque Binary Blob (OBB) file asynchronously. If the 590 * <code>force</code> flag is true, it will kill any application needed to 591 * unmount the given OBB (even the calling application). 592 * <p> 593 * The {@link OnObbStateChangeListener} registered with this call will 594 * receive the success or failure of this operation. 595 * <p> 596 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the 597 * file matches a package ID that is owned by the calling program's UID. 598 * That is, shared UID applications can obtain access to any other 599 * application's OBB that shares its UID. 600 * <p> 601 * 602 * @param rawPath path to the OBB file 603 * @param force whether to kill any programs using this in order to unmount 604 * it 605 * @param listener will receive the success or failure of the operation 606 * @return whether the unmount call was successfully queued or not 607 */ unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener)608 public boolean unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener) { 609 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 610 Preconditions.checkNotNull(listener, "listener cannot be null"); 611 612 try { 613 final int nonce = mObbActionListener.addListener(listener); 614 mStorageManager.unmountObb(rawPath, force, mObbActionListener, nonce); 615 return true; 616 } catch (RemoteException e) { 617 throw e.rethrowFromSystemServer(); 618 } 619 } 620 621 /** 622 * Check whether an Opaque Binary Blob (OBB) is mounted or not. 623 * 624 * @param rawPath path to OBB image 625 * @return true if OBB is mounted; false if not mounted or on error 626 */ isObbMounted(String rawPath)627 public boolean isObbMounted(String rawPath) { 628 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 629 630 try { 631 return mStorageManager.isObbMounted(rawPath); 632 } catch (RemoteException e) { 633 throw e.rethrowFromSystemServer(); 634 } 635 } 636 637 /** 638 * Check the mounted path of an Opaque Binary Blob (OBB) file. This will 639 * give you the path to where you can obtain access to the internals of the 640 * OBB. 641 * 642 * @param rawPath path to OBB image 643 * @return absolute path to mounted OBB image data or <code>null</code> if 644 * not mounted or exception encountered trying to read status 645 */ getMountedObbPath(String rawPath)646 public String getMountedObbPath(String rawPath) { 647 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 648 649 try { 650 return mStorageManager.getMountedObbPath(rawPath); 651 } catch (RemoteException e) { 652 throw e.rethrowFromSystemServer(); 653 } 654 } 655 656 /** {@hide} */ getDisks()657 public @NonNull List<DiskInfo> getDisks() { 658 try { 659 return Arrays.asList(mStorageManager.getDisks()); 660 } catch (RemoteException e) { 661 throw e.rethrowFromSystemServer(); 662 } 663 } 664 665 /** {@hide} */ findDiskById(String id)666 public @Nullable DiskInfo findDiskById(String id) { 667 Preconditions.checkNotNull(id); 668 // TODO; go directly to service to make this faster 669 for (DiskInfo disk : getDisks()) { 670 if (Objects.equals(disk.id, id)) { 671 return disk; 672 } 673 } 674 return null; 675 } 676 677 /** {@hide} */ findVolumeById(String id)678 public @Nullable VolumeInfo findVolumeById(String id) { 679 Preconditions.checkNotNull(id); 680 // TODO; go directly to service to make this faster 681 for (VolumeInfo vol : getVolumes()) { 682 if (Objects.equals(vol.id, id)) { 683 return vol; 684 } 685 } 686 return null; 687 } 688 689 /** {@hide} */ findVolumeByUuid(String fsUuid)690 public @Nullable VolumeInfo findVolumeByUuid(String fsUuid) { 691 Preconditions.checkNotNull(fsUuid); 692 // TODO; go directly to service to make this faster 693 for (VolumeInfo vol : getVolumes()) { 694 if (Objects.equals(vol.fsUuid, fsUuid)) { 695 return vol; 696 } 697 } 698 return null; 699 } 700 701 /** {@hide} */ findRecordByUuid(String fsUuid)702 public @Nullable VolumeRecord findRecordByUuid(String fsUuid) { 703 Preconditions.checkNotNull(fsUuid); 704 // TODO; go directly to service to make this faster 705 for (VolumeRecord rec : getVolumeRecords()) { 706 if (Objects.equals(rec.fsUuid, fsUuid)) { 707 return rec; 708 } 709 } 710 return null; 711 } 712 713 /** {@hide} */ findPrivateForEmulated(VolumeInfo emulatedVol)714 public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) { 715 if (emulatedVol != null) { 716 return findVolumeById(emulatedVol.getId().replace("emulated", "private")); 717 } else { 718 return null; 719 } 720 } 721 722 /** {@hide} */ findEmulatedForPrivate(VolumeInfo privateVol)723 public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) { 724 if (privateVol != null) { 725 return findVolumeById(privateVol.getId().replace("private", "emulated")); 726 } else { 727 return null; 728 } 729 } 730 731 /** {@hide} */ findVolumeByQualifiedUuid(String volumeUuid)732 public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) { 733 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 734 return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL); 735 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 736 return getPrimaryPhysicalVolume(); 737 } else { 738 return findVolumeByUuid(volumeUuid); 739 } 740 } 741 742 /** 743 * Return a UUID identifying the storage volume that hosts the given 744 * filesystem path. 745 * <p> 746 * If this path is hosted by the default internal storage of the device at 747 * {@link Environment#getDataDirectory()}, the returned value will be 748 * {@link #UUID_DEFAULT}. 749 * 750 * @throws IOException when the storage device hosting the given path isn't 751 * present, or when it doesn't have a valid UUID. 752 */ getUuidForPath(@onNull File path)753 public @NonNull UUID getUuidForPath(@NonNull File path) throws IOException { 754 Preconditions.checkNotNull(path); 755 final String pathString = path.getCanonicalPath(); 756 if (FileUtils.contains(Environment.getDataDirectory().getAbsolutePath(), pathString)) { 757 return UUID_DEFAULT; 758 } 759 try { 760 for (VolumeInfo vol : mStorageManager.getVolumes(0)) { 761 if (vol.path != null && FileUtils.contains(vol.path, pathString) 762 && vol.type != VolumeInfo.TYPE_PUBLIC) { 763 // TODO: verify that emulated adopted devices have UUID of 764 // underlying volume 765 try { 766 return convert(vol.fsUuid); 767 } catch (IllegalArgumentException e) { 768 continue; 769 } 770 } 771 } 772 } catch (RemoteException e) { 773 throw e.rethrowFromSystemServer(); 774 } 775 throw new FileNotFoundException("Failed to find a storage device for " + path); 776 } 777 778 /** {@hide} */ findPathForUuid(String volumeUuid)779 public @NonNull File findPathForUuid(String volumeUuid) throws FileNotFoundException { 780 final VolumeInfo vol = findVolumeByQualifiedUuid(volumeUuid); 781 if (vol != null) { 782 return vol.getPath(); 783 } 784 throw new FileNotFoundException("Failed to find a storage device for " + volumeUuid); 785 } 786 787 /** 788 * Test if the given file descriptor supports allocation of disk space using 789 * {@link #allocateBytes(FileDescriptor, long)}. 790 */ isAllocationSupported(@onNull FileDescriptor fd)791 public boolean isAllocationSupported(@NonNull FileDescriptor fd) { 792 try { 793 getUuidForPath(ParcelFileDescriptor.getFile(fd)); 794 return true; 795 } catch (IOException e) { 796 return false; 797 } 798 } 799 800 /** {@hide} */ getVolumes()801 public @NonNull List<VolumeInfo> getVolumes() { 802 try { 803 return Arrays.asList(mStorageManager.getVolumes(0)); 804 } catch (RemoteException e) { 805 throw e.rethrowFromSystemServer(); 806 } 807 } 808 809 /** {@hide} */ getWritablePrivateVolumes()810 public @NonNull List<VolumeInfo> getWritablePrivateVolumes() { 811 try { 812 final ArrayList<VolumeInfo> res = new ArrayList<>(); 813 for (VolumeInfo vol : mStorageManager.getVolumes(0)) { 814 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 815 res.add(vol); 816 } 817 } 818 return res; 819 } catch (RemoteException e) { 820 throw e.rethrowFromSystemServer(); 821 } 822 } 823 824 /** {@hide} */ getVolumeRecords()825 public @NonNull List<VolumeRecord> getVolumeRecords() { 826 try { 827 return Arrays.asList(mStorageManager.getVolumeRecords(0)); 828 } catch (RemoteException e) { 829 throw e.rethrowFromSystemServer(); 830 } 831 } 832 833 /** {@hide} */ getBestVolumeDescription(VolumeInfo vol)834 public @Nullable String getBestVolumeDescription(VolumeInfo vol) { 835 if (vol == null) return null; 836 837 // Nickname always takes precedence when defined 838 if (!TextUtils.isEmpty(vol.fsUuid)) { 839 final VolumeRecord rec = findRecordByUuid(vol.fsUuid); 840 if (rec != null && !TextUtils.isEmpty(rec.nickname)) { 841 return rec.nickname; 842 } 843 } 844 845 if (!TextUtils.isEmpty(vol.getDescription())) { 846 return vol.getDescription(); 847 } 848 849 if (vol.disk != null) { 850 return vol.disk.getDescription(); 851 } 852 853 return null; 854 } 855 856 /** {@hide} */ getPrimaryPhysicalVolume()857 public @Nullable VolumeInfo getPrimaryPhysicalVolume() { 858 final List<VolumeInfo> vols = getVolumes(); 859 for (VolumeInfo vol : vols) { 860 if (vol.isPrimaryPhysical()) { 861 return vol; 862 } 863 } 864 return null; 865 } 866 867 /** {@hide} */ mount(String volId)868 public void mount(String volId) { 869 try { 870 mStorageManager.mount(volId); 871 } catch (RemoteException e) { 872 throw e.rethrowFromSystemServer(); 873 } 874 } 875 876 /** {@hide} */ unmount(String volId)877 public void unmount(String volId) { 878 try { 879 mStorageManager.unmount(volId); 880 } catch (RemoteException e) { 881 throw e.rethrowFromSystemServer(); 882 } 883 } 884 885 /** {@hide} */ format(String volId)886 public void format(String volId) { 887 try { 888 mStorageManager.format(volId); 889 } catch (RemoteException e) { 890 throw e.rethrowFromSystemServer(); 891 } 892 } 893 894 /** {@hide} */ 895 @Deprecated benchmark(String volId)896 public long benchmark(String volId) { 897 final CompletableFuture<PersistableBundle> result = new CompletableFuture<>(); 898 benchmark(volId, new IVoldTaskListener.Stub() { 899 @Override 900 public void onStatus(int status, PersistableBundle extras) { 901 // Ignored 902 } 903 904 @Override 905 public void onFinished(int status, PersistableBundle extras) { 906 result.complete(extras); 907 } 908 }); 909 try { 910 // Convert ms to ns 911 return result.get(3, TimeUnit.MINUTES).getLong("run", Long.MAX_VALUE) * 1000000; 912 } catch (Exception e) { 913 return Long.MAX_VALUE; 914 } 915 } 916 917 /** {@hide} */ benchmark(String volId, IVoldTaskListener listener)918 public void benchmark(String volId, IVoldTaskListener listener) { 919 try { 920 mStorageManager.benchmark(volId, listener); 921 } catch (RemoteException e) { 922 throw e.rethrowFromSystemServer(); 923 } 924 } 925 926 /** {@hide} */ partitionPublic(String diskId)927 public void partitionPublic(String diskId) { 928 try { 929 mStorageManager.partitionPublic(diskId); 930 } catch (RemoteException e) { 931 throw e.rethrowFromSystemServer(); 932 } 933 } 934 935 /** {@hide} */ partitionPrivate(String diskId)936 public void partitionPrivate(String diskId) { 937 try { 938 mStorageManager.partitionPrivate(diskId); 939 } catch (RemoteException e) { 940 throw e.rethrowFromSystemServer(); 941 } 942 } 943 944 /** {@hide} */ partitionMixed(String diskId, int ratio)945 public void partitionMixed(String diskId, int ratio) { 946 try { 947 mStorageManager.partitionMixed(diskId, ratio); 948 } catch (RemoteException e) { 949 throw e.rethrowFromSystemServer(); 950 } 951 } 952 953 /** {@hide} */ wipeAdoptableDisks()954 public void wipeAdoptableDisks() { 955 // We only wipe devices in "adoptable" locations, which are in a 956 // long-term stable slot/location on the device, where apps have a 957 // reasonable chance of storing sensitive data. (Apps need to go through 958 // SAF to write to transient volumes.) 959 final List<DiskInfo> disks = getDisks(); 960 for (DiskInfo disk : disks) { 961 final String diskId = disk.getId(); 962 if (disk.isAdoptable()) { 963 Slog.d(TAG, "Found adoptable " + diskId + "; wiping"); 964 try { 965 // TODO: switch to explicit wipe command when we have it, 966 // for now rely on the fact that vfat format does a wipe 967 mStorageManager.partitionPublic(diskId); 968 } catch (Exception e) { 969 Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e); 970 } 971 } else { 972 Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId()); 973 } 974 } 975 } 976 977 /** {@hide} */ setVolumeNickname(String fsUuid, String nickname)978 public void setVolumeNickname(String fsUuid, String nickname) { 979 try { 980 mStorageManager.setVolumeNickname(fsUuid, nickname); 981 } catch (RemoteException e) { 982 throw e.rethrowFromSystemServer(); 983 } 984 } 985 986 /** {@hide} */ setVolumeInited(String fsUuid, boolean inited)987 public void setVolumeInited(String fsUuid, boolean inited) { 988 try { 989 mStorageManager.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0, 990 VolumeRecord.USER_FLAG_INITED); 991 } catch (RemoteException e) { 992 throw e.rethrowFromSystemServer(); 993 } 994 } 995 996 /** {@hide} */ setVolumeSnoozed(String fsUuid, boolean snoozed)997 public void setVolumeSnoozed(String fsUuid, boolean snoozed) { 998 try { 999 mStorageManager.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0, 1000 VolumeRecord.USER_FLAG_SNOOZED); 1001 } catch (RemoteException e) { 1002 throw e.rethrowFromSystemServer(); 1003 } 1004 } 1005 1006 /** {@hide} */ forgetVolume(String fsUuid)1007 public void forgetVolume(String fsUuid) { 1008 try { 1009 mStorageManager.forgetVolume(fsUuid); 1010 } catch (RemoteException e) { 1011 throw e.rethrowFromSystemServer(); 1012 } 1013 } 1014 1015 /** 1016 * This is not the API you're looking for. 1017 * 1018 * @see PackageManager#getPrimaryStorageCurrentVolume() 1019 * @hide 1020 */ getPrimaryStorageUuid()1021 public String getPrimaryStorageUuid() { 1022 try { 1023 return mStorageManager.getPrimaryStorageUuid(); 1024 } catch (RemoteException e) { 1025 throw e.rethrowFromSystemServer(); 1026 } 1027 } 1028 1029 /** 1030 * This is not the API you're looking for. 1031 * 1032 * @see PackageManager#movePrimaryStorage(VolumeInfo) 1033 * @hide 1034 */ setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback)1035 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) { 1036 try { 1037 mStorageManager.setPrimaryStorageUuid(volumeUuid, callback); 1038 } catch (RemoteException e) { 1039 throw e.rethrowFromSystemServer(); 1040 } 1041 } 1042 1043 /** 1044 * Return the {@link StorageVolume} that contains the given file, or {@code null} if none. 1045 */ getStorageVolume(File file)1046 public @Nullable StorageVolume getStorageVolume(File file) { 1047 return getStorageVolume(getVolumeList(), file); 1048 } 1049 1050 /** {@hide} */ getStorageVolume(File file, int userId)1051 public static @Nullable StorageVolume getStorageVolume(File file, int userId) { 1052 return getStorageVolume(getVolumeList(userId, 0), file); 1053 } 1054 1055 /** {@hide} */ getStorageVolume(StorageVolume[] volumes, File file)1056 private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) { 1057 if (file == null) { 1058 return null; 1059 } 1060 try { 1061 file = file.getCanonicalFile(); 1062 } catch (IOException ignored) { 1063 Slog.d(TAG, "Could not get canonical path for " + file); 1064 return null; 1065 } 1066 for (StorageVolume volume : volumes) { 1067 File volumeFile = volume.getPathFile(); 1068 try { 1069 volumeFile = volumeFile.getCanonicalFile(); 1070 } catch (IOException ignored) { 1071 continue; 1072 } 1073 if (FileUtils.contains(volumeFile, file)) { 1074 return volume; 1075 } 1076 } 1077 return null; 1078 } 1079 1080 /** 1081 * Gets the state of a volume via its mountpoint. 1082 * @hide 1083 */ 1084 @Deprecated getVolumeState(String mountPoint)1085 public @NonNull String getVolumeState(String mountPoint) { 1086 final StorageVolume vol = getStorageVolume(new File(mountPoint)); 1087 if (vol != null) { 1088 return vol.getState(); 1089 } else { 1090 return Environment.MEDIA_UNKNOWN; 1091 } 1092 } 1093 1094 /** 1095 * Return the list of shared/external storage volumes available to the 1096 * current user. This includes both the primary shared storage device and 1097 * any attached external volumes including SD cards and USB drives. 1098 * 1099 * @see Environment#getExternalStorageDirectory() 1100 * @see StorageVolume#createAccessIntent(String) 1101 */ getStorageVolumes()1102 public @NonNull List<StorageVolume> getStorageVolumes() { 1103 final ArrayList<StorageVolume> res = new ArrayList<>(); 1104 Collections.addAll(res, 1105 getVolumeList(mContext.getUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)); 1106 return res; 1107 } 1108 1109 /** 1110 * Return the primary shared/external storage volume available to the 1111 * current user. This volume is the same storage device returned by 1112 * {@link Environment#getExternalStorageDirectory()} and 1113 * {@link Context#getExternalFilesDir(String)}. 1114 */ getPrimaryStorageVolume()1115 public @NonNull StorageVolume getPrimaryStorageVolume() { 1116 return getVolumeList(mContext.getUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)[0]; 1117 } 1118 1119 /** {@hide} */ getPrimaryStoragePathAndSize()1120 public static Pair<String, Long> getPrimaryStoragePathAndSize() { 1121 return Pair.create(null, 1122 FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace() 1123 + Environment.getRootDirectory().getTotalSpace())); 1124 } 1125 1126 /** {@hide} */ getPrimaryStorageSize()1127 public long getPrimaryStorageSize() { 1128 return FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace() 1129 + Environment.getRootDirectory().getTotalSpace()); 1130 } 1131 1132 /** {@hide} */ mkdirs(File file)1133 public void mkdirs(File file) { 1134 try { 1135 mStorageManager.mkdirs(mContext.getOpPackageName(), file.getAbsolutePath()); 1136 } catch (RemoteException e) { 1137 throw e.rethrowFromSystemServer(); 1138 } 1139 } 1140 1141 /** @removed */ getVolumeList()1142 public @NonNull StorageVolume[] getVolumeList() { 1143 return getVolumeList(mContext.getUserId(), 0); 1144 } 1145 1146 /** {@hide} */ getVolumeList(int userId, int flags)1147 public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) { 1148 final IStorageManager storageManager = IStorageManager.Stub.asInterface( 1149 ServiceManager.getService("mount")); 1150 try { 1151 String packageName = ActivityThread.currentOpPackageName(); 1152 if (packageName == null) { 1153 // Package name can be null if the activity thread is running but the app 1154 // hasn't bound yet. In this case we fall back to the first package in the 1155 // current UID. This works for runtime permissions as permission state is 1156 // per UID and permission realted app ops are updated for all UID packages. 1157 String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid( 1158 android.os.Process.myUid()); 1159 if (packageNames == null || packageNames.length <= 0) { 1160 return new StorageVolume[0]; 1161 } 1162 packageName = packageNames[0]; 1163 } 1164 final int uid = ActivityThread.getPackageManager().getPackageUid(packageName, 1165 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId); 1166 if (uid <= 0) { 1167 return new StorageVolume[0]; 1168 } 1169 return storageManager.getVolumeList(uid, packageName, flags); 1170 } catch (RemoteException e) { 1171 throw e.rethrowFromSystemServer(); 1172 } 1173 } 1174 1175 /** 1176 * Returns list of paths for all mountable volumes. 1177 * @hide 1178 */ 1179 @Deprecated getVolumePaths()1180 public @NonNull String[] getVolumePaths() { 1181 StorageVolume[] volumes = getVolumeList(); 1182 int count = volumes.length; 1183 String[] paths = new String[count]; 1184 for (int i = 0; i < count; i++) { 1185 paths[i] = volumes[i].getPath(); 1186 } 1187 return paths; 1188 } 1189 1190 /** @removed */ getPrimaryVolume()1191 public @NonNull StorageVolume getPrimaryVolume() { 1192 return getPrimaryVolume(getVolumeList()); 1193 } 1194 1195 /** {@hide} */ getPrimaryVolume(StorageVolume[] volumes)1196 public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) { 1197 for (StorageVolume volume : volumes) { 1198 if (volume.isPrimary()) { 1199 return volume; 1200 } 1201 } 1202 throw new IllegalStateException("Missing primary storage"); 1203 } 1204 1205 private static final int DEFAULT_THRESHOLD_PERCENTAGE = 5; 1206 private static final long DEFAULT_THRESHOLD_MAX_BYTES = DataUnit.MEBIBYTES.toBytes(500); 1207 1208 private static final int DEFAULT_CACHE_PERCENTAGE = 10; 1209 private static final long DEFAULT_CACHE_MAX_BYTES = DataUnit.GIBIBYTES.toBytes(5); 1210 1211 private static final long DEFAULT_FULL_THRESHOLD_BYTES = DataUnit.MEBIBYTES.toBytes(1); 1212 1213 /** 1214 * Return the number of available bytes until the given path is considered 1215 * running low on storage. 1216 * 1217 * @hide 1218 */ getStorageBytesUntilLow(File path)1219 public long getStorageBytesUntilLow(File path) { 1220 return path.getUsableSpace() - getStorageFullBytes(path); 1221 } 1222 1223 /** 1224 * Return the number of available bytes at which the given path is 1225 * considered running low on storage. 1226 * 1227 * @hide 1228 */ getStorageLowBytes(File path)1229 public long getStorageLowBytes(File path) { 1230 final long lowPercent = Settings.Global.getInt(mResolver, 1231 Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE, DEFAULT_THRESHOLD_PERCENTAGE); 1232 final long lowBytes = (path.getTotalSpace() * lowPercent) / 100; 1233 1234 final long maxLowBytes = Settings.Global.getLong(mResolver, 1235 Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES); 1236 1237 return Math.min(lowBytes, maxLowBytes); 1238 } 1239 1240 /** 1241 * Return the minimum number of bytes of storage on the device that should 1242 * be reserved for cached data. 1243 * 1244 * @hide 1245 */ getStorageCacheBytes(File path, @AllocateFlags int flags)1246 public long getStorageCacheBytes(File path, @AllocateFlags int flags) { 1247 final long cachePercent = Settings.Global.getInt(mResolver, 1248 Settings.Global.SYS_STORAGE_CACHE_PERCENTAGE, DEFAULT_CACHE_PERCENTAGE); 1249 final long cacheBytes = (path.getTotalSpace() * cachePercent) / 100; 1250 1251 final long maxCacheBytes = Settings.Global.getLong(mResolver, 1252 Settings.Global.SYS_STORAGE_CACHE_MAX_BYTES, DEFAULT_CACHE_MAX_BYTES); 1253 1254 final long result = Math.min(cacheBytes, maxCacheBytes); 1255 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) { 1256 return 0; 1257 } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED) != 0) { 1258 return 0; 1259 } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED) != 0) { 1260 return result / 2; 1261 } else { 1262 return result; 1263 } 1264 } 1265 1266 /** 1267 * Return the number of available bytes at which the given path is 1268 * considered full. 1269 * 1270 * @hide 1271 */ getStorageFullBytes(File path)1272 public long getStorageFullBytes(File path) { 1273 return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES, 1274 DEFAULT_FULL_THRESHOLD_BYTES); 1275 } 1276 1277 /** {@hide} */ createUserKey(int userId, int serialNumber, boolean ephemeral)1278 public void createUserKey(int userId, int serialNumber, boolean ephemeral) { 1279 try { 1280 mStorageManager.createUserKey(userId, serialNumber, ephemeral); 1281 } catch (RemoteException e) { 1282 throw e.rethrowFromSystemServer(); 1283 } 1284 } 1285 1286 /** {@hide} */ destroyUserKey(int userId)1287 public void destroyUserKey(int userId) { 1288 try { 1289 mStorageManager.destroyUserKey(userId); 1290 } catch (RemoteException e) { 1291 throw e.rethrowFromSystemServer(); 1292 } 1293 } 1294 1295 /** {@hide} */ unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret)1296 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) { 1297 try { 1298 mStorageManager.unlockUserKey(userId, serialNumber, token, secret); 1299 } catch (RemoteException e) { 1300 throw e.rethrowFromSystemServer(); 1301 } 1302 } 1303 1304 /** {@hide} */ lockUserKey(int userId)1305 public void lockUserKey(int userId) { 1306 try { 1307 mStorageManager.lockUserKey(userId); 1308 } catch (RemoteException e) { 1309 throw e.rethrowFromSystemServer(); 1310 } 1311 } 1312 1313 /** {@hide} */ prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags)1314 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) { 1315 try { 1316 mStorageManager.prepareUserStorage(volumeUuid, userId, serialNumber, flags); 1317 } catch (RemoteException e) { 1318 throw e.rethrowFromSystemServer(); 1319 } 1320 } 1321 1322 /** {@hide} */ destroyUserStorage(String volumeUuid, int userId, int flags)1323 public void destroyUserStorage(String volumeUuid, int userId, int flags) { 1324 try { 1325 mStorageManager.destroyUserStorage(volumeUuid, userId, flags); 1326 } catch (RemoteException e) { 1327 throw e.rethrowFromSystemServer(); 1328 } 1329 } 1330 1331 /** {@hide} */ isUserKeyUnlocked(int userId)1332 public static boolean isUserKeyUnlocked(int userId) { 1333 if (sStorageManager == null) { 1334 sStorageManager = IStorageManager.Stub 1335 .asInterface(ServiceManager.getService("mount")); 1336 } 1337 if (sStorageManager == null) { 1338 Slog.w(TAG, "Early during boot, assuming locked"); 1339 return false; 1340 } 1341 final long token = Binder.clearCallingIdentity(); 1342 try { 1343 return sStorageManager.isUserKeyUnlocked(userId); 1344 } catch (RemoteException e) { 1345 throw e.rethrowAsRuntimeException(); 1346 } finally { 1347 Binder.restoreCallingIdentity(token); 1348 } 1349 } 1350 1351 /** 1352 * Return if data stored at or under the given path will be encrypted while 1353 * at rest. This can help apps avoid the overhead of double-encrypting data. 1354 */ isEncrypted(File file)1355 public boolean isEncrypted(File file) { 1356 if (FileUtils.contains(Environment.getDataDirectory(), file)) { 1357 return isEncrypted(); 1358 } else if (FileUtils.contains(Environment.getExpandDirectory(), file)) { 1359 return true; 1360 } 1361 // TODO: extend to support shared storage 1362 return false; 1363 } 1364 1365 /** {@hide} 1366 * Is this device encryptable or already encrypted? 1367 * @return true for encryptable or encrypted 1368 * false not encrypted and not encryptable 1369 */ isEncryptable()1370 public static boolean isEncryptable() { 1371 return RoSystemProperties.CRYPTO_ENCRYPTABLE; 1372 } 1373 1374 /** {@hide} 1375 * Is this device already encrypted? 1376 * @return true for encrypted. (Implies isEncryptable() == true) 1377 * false not encrypted 1378 */ isEncrypted()1379 public static boolean isEncrypted() { 1380 return RoSystemProperties.CRYPTO_ENCRYPTED; 1381 } 1382 1383 /** {@hide} 1384 * Is this device file encrypted? 1385 * @return true for file encrypted. (Implies isEncrypted() == true) 1386 * false not encrypted or block encrypted 1387 */ isFileEncryptedNativeOnly()1388 public static boolean isFileEncryptedNativeOnly() { 1389 if (!isEncrypted()) { 1390 return false; 1391 } 1392 return RoSystemProperties.CRYPTO_FILE_ENCRYPTED; 1393 } 1394 1395 /** {@hide} 1396 * Is this device block encrypted? 1397 * @return true for block encrypted. (Implies isEncrypted() == true) 1398 * false not encrypted or file encrypted 1399 */ isBlockEncrypted()1400 public static boolean isBlockEncrypted() { 1401 if (!isEncrypted()) { 1402 return false; 1403 } 1404 return RoSystemProperties.CRYPTO_BLOCK_ENCRYPTED; 1405 } 1406 1407 /** {@hide} 1408 * Is this device block encrypted with credentials? 1409 * @return true for crediential block encrypted. 1410 * (Implies isBlockEncrypted() == true) 1411 * false not encrypted, file encrypted or default block encrypted 1412 */ isNonDefaultBlockEncrypted()1413 public static boolean isNonDefaultBlockEncrypted() { 1414 if (!isBlockEncrypted()) { 1415 return false; 1416 } 1417 1418 try { 1419 IStorageManager storageManager = IStorageManager.Stub.asInterface( 1420 ServiceManager.getService("mount")); 1421 return storageManager.getPasswordType() != CRYPT_TYPE_DEFAULT; 1422 } catch (RemoteException e) { 1423 Log.e(TAG, "Error getting encryption type"); 1424 return false; 1425 } 1426 } 1427 1428 /** {@hide} 1429 * Is this device in the process of being block encrypted? 1430 * @return true for encrypting. 1431 * false otherwise 1432 * Whether device isEncrypted at this point is undefined 1433 * Note that only system services and CryptKeeper will ever see this return 1434 * true - no app will ever be launched in this state. 1435 * Also note that this state will not change without a teardown of the 1436 * framework, so no service needs to check for changes during their lifespan 1437 */ isBlockEncrypting()1438 public static boolean isBlockEncrypting() { 1439 final String state = SystemProperties.get("vold.encrypt_progress", ""); 1440 return !"".equalsIgnoreCase(state); 1441 } 1442 1443 /** {@hide} 1444 * Is this device non default block encrypted and in the process of 1445 * prompting for credentials? 1446 * @return true for prompting for credentials. 1447 * (Implies isNonDefaultBlockEncrypted() == true) 1448 * false otherwise 1449 * Note that only system services and CryptKeeper will ever see this return 1450 * true - no app will ever be launched in this state. 1451 * Also note that this state will not change without a teardown of the 1452 * framework, so no service needs to check for changes during their lifespan 1453 */ inCryptKeeperBounce()1454 public static boolean inCryptKeeperBounce() { 1455 final String status = SystemProperties.get("vold.decrypt"); 1456 return "trigger_restart_min_framework".equals(status); 1457 } 1458 1459 /** {@hide} */ isFileEncryptedEmulatedOnly()1460 public static boolean isFileEncryptedEmulatedOnly() { 1461 return SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false); 1462 } 1463 1464 /** {@hide} 1465 * Is this device running in a file encrypted mode, either native or emulated? 1466 * @return true for file encrypted, false otherwise 1467 */ isFileEncryptedNativeOrEmulated()1468 public static boolean isFileEncryptedNativeOrEmulated() { 1469 return isFileEncryptedNativeOnly() 1470 || isFileEncryptedEmulatedOnly(); 1471 } 1472 1473 /** {@hide} */ hasAdoptable()1474 public static boolean hasAdoptable() { 1475 return SystemProperties.getBoolean(PROP_HAS_ADOPTABLE, false); 1476 } 1477 1478 /** {@hide} */ maybeTranslateEmulatedPathToInternal(File path)1479 public static File maybeTranslateEmulatedPathToInternal(File path) { 1480 // Disabled now that FUSE has been replaced by sdcardfs 1481 return path; 1482 } 1483 1484 /** {@hide} */ 1485 @VisibleForTesting openProxyFileDescriptor( int mode, ProxyFileDescriptorCallback callback, Handler handler, ThreadFactory factory)1486 public @NonNull ParcelFileDescriptor openProxyFileDescriptor( 1487 int mode, ProxyFileDescriptorCallback callback, Handler handler, ThreadFactory factory) 1488 throws IOException { 1489 Preconditions.checkNotNull(callback); 1490 MetricsLogger.count(mContext, "storage_open_proxy_file_descriptor", 1); 1491 // Retry is needed because the mount point mFuseAppLoop is using may be unmounted before 1492 // invoking StorageManagerService#openProxyFileDescriptor. In this case, we need to re-mount 1493 // the bridge by calling mountProxyFileDescriptorBridge. 1494 while (true) { 1495 try { 1496 synchronized (mFuseAppLoopLock) { 1497 boolean newlyCreated = false; 1498 if (mFuseAppLoop == null) { 1499 final AppFuseMount mount = mStorageManager.mountProxyFileDescriptorBridge(); 1500 if (mount == null) { 1501 throw new IOException("Failed to mount proxy bridge"); 1502 } 1503 mFuseAppLoop = new FuseAppLoop(mount.mountPointId, mount.fd, factory); 1504 newlyCreated = true; 1505 } 1506 if (handler == null) { 1507 handler = new Handler(Looper.getMainLooper()); 1508 } 1509 try { 1510 final int fileId = mFuseAppLoop.registerCallback(callback, handler); 1511 final ParcelFileDescriptor pfd = mStorageManager.openProxyFileDescriptor( 1512 mFuseAppLoop.getMountPointId(), fileId, mode); 1513 if (pfd == null) { 1514 mFuseAppLoop.unregisterCallback(fileId); 1515 throw new FuseUnavailableMountException( 1516 mFuseAppLoop.getMountPointId()); 1517 } 1518 return pfd; 1519 } catch (FuseUnavailableMountException exception) { 1520 // The bridge is being unmounted. Tried to recreate it unless the bridge was 1521 // just created. 1522 if (newlyCreated) { 1523 throw new IOException(exception); 1524 } 1525 mFuseAppLoop = null; 1526 continue; 1527 } 1528 } 1529 } catch (RemoteException e) { 1530 // Cannot recover from remote exception. 1531 throw new IOException(e); 1532 } 1533 } 1534 } 1535 1536 /** {@hide} */ openProxyFileDescriptor( int mode, ProxyFileDescriptorCallback callback)1537 public @NonNull ParcelFileDescriptor openProxyFileDescriptor( 1538 int mode, ProxyFileDescriptorCallback callback) 1539 throws IOException { 1540 return openProxyFileDescriptor(mode, callback, null, null); 1541 } 1542 1543 /** 1544 * Opens a seekable {@link ParcelFileDescriptor} that proxies all low-level 1545 * I/O requests back to the given {@link ProxyFileDescriptorCallback}. 1546 * <p> 1547 * This can be useful when you want to provide quick access to a large file 1548 * that isn't backed by a real file on disk, such as a file on a network 1549 * share, cloud storage service, etc. As an example, you could respond to a 1550 * {@link ContentResolver#openFileDescriptor(android.net.Uri, String)} 1551 * request by returning a {@link ParcelFileDescriptor} created with this 1552 * method, and then stream the content on-demand as requested. 1553 * <p> 1554 * Another useful example might be where you have an encrypted file that 1555 * you're willing to decrypt on-demand, but where you want to avoid 1556 * persisting the cleartext version. 1557 * 1558 * @param mode The desired access mode, must be one of 1559 * {@link ParcelFileDescriptor#MODE_READ_ONLY}, 1560 * {@link ParcelFileDescriptor#MODE_WRITE_ONLY}, or 1561 * {@link ParcelFileDescriptor#MODE_READ_WRITE} 1562 * @param callback Callback to process file operation requests issued on 1563 * returned file descriptor. 1564 * @param handler Handler that invokes callback methods. 1565 * @return Seekable ParcelFileDescriptor. 1566 * @throws IOException 1567 */ openProxyFileDescriptor( int mode, ProxyFileDescriptorCallback callback, Handler handler)1568 public @NonNull ParcelFileDescriptor openProxyFileDescriptor( 1569 int mode, ProxyFileDescriptorCallback callback, Handler handler) 1570 throws IOException { 1571 Preconditions.checkNotNull(handler); 1572 return openProxyFileDescriptor(mode, callback, handler, null); 1573 } 1574 1575 /** {@hide} */ 1576 @VisibleForTesting getProxyFileDescriptorMountPointId()1577 public int getProxyFileDescriptorMountPointId() { 1578 synchronized (mFuseAppLoopLock) { 1579 return mFuseAppLoop != null ? mFuseAppLoop.getMountPointId() : -1; 1580 } 1581 } 1582 1583 /** 1584 * Return quota size in bytes for all cached data belonging to the calling 1585 * app on the given storage volume. 1586 * <p> 1587 * If your app goes above this quota, your cached files will be some of the 1588 * first to be deleted when additional disk space is needed. Conversely, if 1589 * your app stays under this quota, your cached files will be some of the 1590 * last to be deleted when additional disk space is needed. 1591 * <p> 1592 * This quota will change over time depending on how frequently the user 1593 * interacts with your app, and depending on how much system-wide disk space 1594 * is used. 1595 * <p class="note"> 1596 * Note: if your app uses the {@code android:sharedUserId} manifest feature, 1597 * then cached data for all packages in your shared UID is tracked together 1598 * as a single unit. 1599 * </p> 1600 * 1601 * @param storageUuid the UUID of the storage volume that you're interested 1602 * in. The UUID for a specific path can be obtained using 1603 * {@link #getUuidForPath(File)}. 1604 * @throws IOException when the storage device isn't present, or when it 1605 * doesn't support cache quotas. 1606 * @see #getCacheSizeBytes(UUID) 1607 */ 1608 @WorkerThread getCacheQuotaBytes(@onNull UUID storageUuid)1609 public @BytesLong long getCacheQuotaBytes(@NonNull UUID storageUuid) throws IOException { 1610 try { 1611 final ApplicationInfo app = mContext.getApplicationInfo(); 1612 return mStorageManager.getCacheQuotaBytes(convert(storageUuid), app.uid); 1613 } catch (ParcelableException e) { 1614 e.maybeRethrow(IOException.class); 1615 throw new RuntimeException(e); 1616 } catch (RemoteException e) { 1617 throw e.rethrowFromSystemServer(); 1618 } 1619 } 1620 1621 /** 1622 * Return total size in bytes of all cached data belonging to the calling 1623 * app on the given storage volume. 1624 * <p> 1625 * Cached data tracked by this method always includes 1626 * {@link Context#getCacheDir()} and {@link Context#getCodeCacheDir()}, and 1627 * it also includes {@link Context#getExternalCacheDir()} if the primary 1628 * shared/external storage is hosted on the same storage device as your 1629 * private data. 1630 * <p class="note"> 1631 * Note: if your app uses the {@code android:sharedUserId} manifest feature, 1632 * then cached data for all packages in your shared UID is tracked together 1633 * as a single unit. 1634 * </p> 1635 * 1636 * @param storageUuid the UUID of the storage volume that you're interested 1637 * in. The UUID for a specific path can be obtained using 1638 * {@link #getUuidForPath(File)}. 1639 * @throws IOException when the storage device isn't present, or when it 1640 * doesn't support cache quotas. 1641 * @see #getCacheQuotaBytes(UUID) 1642 */ 1643 @WorkerThread getCacheSizeBytes(@onNull UUID storageUuid)1644 public @BytesLong long getCacheSizeBytes(@NonNull UUID storageUuid) throws IOException { 1645 try { 1646 final ApplicationInfo app = mContext.getApplicationInfo(); 1647 return mStorageManager.getCacheSizeBytes(convert(storageUuid), app.uid); 1648 } catch (ParcelableException e) { 1649 e.maybeRethrow(IOException.class); 1650 throw new RuntimeException(e); 1651 } catch (RemoteException e) { 1652 throw e.rethrowFromSystemServer(); 1653 } 1654 } 1655 1656 /** 1657 * Flag indicating that a disk space allocation request should operate in an 1658 * aggressive mode. This flag should only be rarely used in situations that 1659 * are critical to system health or security. 1660 * <p> 1661 * When set, the system is more aggressive about the data that it considers 1662 * for possible deletion when allocating disk space. 1663 * <p class="note"> 1664 * Note: your app must hold the 1665 * {@link android.Manifest.permission#ALLOCATE_AGGRESSIVE} permission for 1666 * this flag to take effect. 1667 * </p> 1668 * 1669 * @see #getAllocatableBytes(UUID, int) 1670 * @see #allocateBytes(UUID, long, int) 1671 * @see #allocateBytes(FileDescriptor, long, int) 1672 * @hide 1673 */ 1674 @RequiresPermission(android.Manifest.permission.ALLOCATE_AGGRESSIVE) 1675 @SystemApi 1676 public static final int FLAG_ALLOCATE_AGGRESSIVE = 1 << 0; 1677 1678 /** 1679 * Flag indicating that a disk space allocation request should be allowed to 1680 * clear up to all reserved disk space. 1681 * 1682 * @hide 1683 */ 1684 public static final int FLAG_ALLOCATE_DEFY_ALL_RESERVED = 1 << 1; 1685 1686 /** 1687 * Flag indicating that a disk space allocation request should be allowed to 1688 * clear up to half of all reserved disk space. 1689 * 1690 * @hide 1691 */ 1692 public static final int FLAG_ALLOCATE_DEFY_HALF_RESERVED = 1 << 2; 1693 1694 /** @hide */ 1695 @IntDef(flag = true, prefix = { "FLAG_ALLOCATE_" }, value = { 1696 FLAG_ALLOCATE_AGGRESSIVE, 1697 FLAG_ALLOCATE_DEFY_ALL_RESERVED, 1698 FLAG_ALLOCATE_DEFY_HALF_RESERVED, 1699 }) 1700 @Retention(RetentionPolicy.SOURCE) 1701 public @interface AllocateFlags {} 1702 1703 /** 1704 * Return the maximum number of new bytes that your app can allocate for 1705 * itself on the given storage volume. This value is typically larger than 1706 * {@link File#getUsableSpace()}, since the system may be willing to delete 1707 * cached files to satisfy an allocation request. You can then allocate 1708 * space for yourself using {@link #allocateBytes(UUID, long)} or 1709 * {@link #allocateBytes(FileDescriptor, long)}. 1710 * <p> 1711 * This method is best used as a pre-flight check, such as deciding if there 1712 * is enough space to store an entire music album before you allocate space 1713 * for each audio file in the album. Attempts to allocate disk space beyond 1714 * the returned value will fail. 1715 * <p> 1716 * If the returned value is not large enough for the data you'd like to 1717 * persist, you can launch {@link #ACTION_MANAGE_STORAGE} with the 1718 * {@link #EXTRA_UUID} and {@link #EXTRA_REQUESTED_BYTES} options to help 1719 * involve the user in freeing up disk space. 1720 * <p> 1721 * If you're progressively allocating an unbounded amount of storage space 1722 * (such as when recording a video) you should avoid calling this method 1723 * more than once every 30 seconds. 1724 * <p class="note"> 1725 * Note: if your app uses the {@code android:sharedUserId} manifest feature, 1726 * then allocatable space for all packages in your shared UID is tracked 1727 * together as a single unit. 1728 * </p> 1729 * 1730 * @param storageUuid the UUID of the storage volume where you're 1731 * considering allocating disk space, since allocatable space can 1732 * vary widely depending on the underlying storage device. The 1733 * UUID for a specific path can be obtained using 1734 * {@link #getUuidForPath(File)}. 1735 * @return the maximum number of new bytes that the calling app can allocate 1736 * using {@link #allocateBytes(UUID, long)} or 1737 * {@link #allocateBytes(FileDescriptor, long)}. 1738 * @throws IOException when the storage device isn't present, or when it 1739 * doesn't support allocating space. 1740 */ 1741 @WorkerThread getAllocatableBytes(@onNull UUID storageUuid)1742 public @BytesLong long getAllocatableBytes(@NonNull UUID storageUuid) 1743 throws IOException { 1744 return getAllocatableBytes(storageUuid, 0); 1745 } 1746 1747 /** @hide */ 1748 @SystemApi 1749 @WorkerThread 1750 @SuppressLint("Doclava125") getAllocatableBytes(@onNull UUID storageUuid, @RequiresPermission @AllocateFlags int flags)1751 public long getAllocatableBytes(@NonNull UUID storageUuid, 1752 @RequiresPermission @AllocateFlags int flags) throws IOException { 1753 try { 1754 return mStorageManager.getAllocatableBytes(convert(storageUuid), flags, 1755 mContext.getOpPackageName()); 1756 } catch (ParcelableException e) { 1757 e.maybeRethrow(IOException.class); 1758 throw new RuntimeException(e); 1759 } catch (RemoteException e) { 1760 throw e.rethrowFromSystemServer(); 1761 } 1762 } 1763 1764 /** 1765 * Allocate the requested number of bytes for your application to use on the 1766 * given storage volume. This will cause the system to delete any cached 1767 * files necessary to satisfy your request. 1768 * <p> 1769 * Attempts to allocate disk space beyond the value returned by 1770 * {@link #getAllocatableBytes(UUID)} will fail. 1771 * <p> 1772 * Since multiple apps can be running simultaneously, this method may be 1773 * subject to race conditions. If possible, consider using 1774 * {@link #allocateBytes(FileDescriptor, long)} which will guarantee 1775 * that bytes are allocated to an opened file. 1776 * <p> 1777 * If you're progressively allocating an unbounded amount of storage space 1778 * (such as when recording a video) you should avoid calling this method 1779 * more than once every 60 seconds. 1780 * 1781 * @param storageUuid the UUID of the storage volume where you'd like to 1782 * allocate disk space. The UUID for a specific path can be 1783 * obtained using {@link #getUuidForPath(File)}. 1784 * @param bytes the number of bytes to allocate. 1785 * @throws IOException when the storage device isn't present, or when it 1786 * doesn't support allocating space, or if the device had 1787 * trouble allocating the requested space. 1788 * @see #getAllocatableBytes(UUID) 1789 */ 1790 @WorkerThread allocateBytes(@onNull UUID storageUuid, @BytesLong long bytes)1791 public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes) 1792 throws IOException { 1793 allocateBytes(storageUuid, bytes, 0); 1794 } 1795 1796 /** @hide */ 1797 @SystemApi 1798 @WorkerThread 1799 @SuppressLint("Doclava125") allocateBytes(@onNull UUID storageUuid, @BytesLong long bytes, @RequiresPermission @AllocateFlags int flags)1800 public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes, 1801 @RequiresPermission @AllocateFlags int flags) throws IOException { 1802 try { 1803 mStorageManager.allocateBytes(convert(storageUuid), bytes, flags, 1804 mContext.getOpPackageName()); 1805 } catch (ParcelableException e) { 1806 e.maybeRethrow(IOException.class); 1807 } catch (RemoteException e) { 1808 throw e.rethrowFromSystemServer(); 1809 } 1810 } 1811 1812 /** 1813 * Allocate the requested number of bytes for your application to use in the 1814 * given open file. This will cause the system to delete any cached files 1815 * necessary to satisfy your request. 1816 * <p> 1817 * Attempts to allocate disk space beyond the value returned by 1818 * {@link #getAllocatableBytes(UUID)} will fail. 1819 * <p> 1820 * This method guarantees that bytes have been allocated to the opened file, 1821 * otherwise it will throw if fast allocation is not possible. Fast 1822 * allocation is typically only supported in private app data directories, 1823 * and on shared/external storage devices which are emulated. 1824 * <p> 1825 * If you're progressively allocating an unbounded amount of storage space 1826 * (such as when recording a video) you should avoid calling this method 1827 * more than once every 60 seconds. 1828 * 1829 * @param fd the open file that you'd like to allocate disk space for. 1830 * @param bytes the number of bytes to allocate. This is the desired final 1831 * size of the open file. If the open file is smaller than this 1832 * requested size, it will be extended without modifying any 1833 * existing contents. If the open file is larger than this 1834 * requested size, it will be truncated. 1835 * @throws IOException when the storage device isn't present, or when it 1836 * doesn't support allocating space, or if the device had 1837 * trouble allocating the requested space. 1838 * @see #getAllocatableBytes(UUID, int) 1839 * @see #isAllocationSupported(FileDescriptor) 1840 * @see Environment#isExternalStorageEmulated(File) 1841 */ 1842 @WorkerThread allocateBytes(FileDescriptor fd, @BytesLong long bytes)1843 public void allocateBytes(FileDescriptor fd, @BytesLong long bytes) throws IOException { 1844 allocateBytes(fd, bytes, 0); 1845 } 1846 1847 /** @hide */ 1848 @SystemApi 1849 @WorkerThread 1850 @SuppressLint("Doclava125") allocateBytes(FileDescriptor fd, @BytesLong long bytes, @RequiresPermission @AllocateFlags int flags)1851 public void allocateBytes(FileDescriptor fd, @BytesLong long bytes, 1852 @RequiresPermission @AllocateFlags int flags) throws IOException { 1853 final File file = ParcelFileDescriptor.getFile(fd); 1854 final UUID uuid = getUuidForPath(file); 1855 for (int i = 0; i < 3; i++) { 1856 try { 1857 final long haveBytes = Os.fstat(fd).st_blocks * 512; 1858 final long needBytes = bytes - haveBytes; 1859 1860 if (needBytes > 0) { 1861 allocateBytes(uuid, needBytes, flags); 1862 } 1863 1864 try { 1865 Os.posix_fallocate(fd, 0, bytes); 1866 return; 1867 } catch (ErrnoException e) { 1868 if (e.errno == OsConstants.ENOSYS || e.errno == OsConstants.ENOTSUP) { 1869 Log.w(TAG, "fallocate() not supported; falling back to ftruncate()"); 1870 Os.ftruncate(fd, bytes); 1871 return; 1872 } else { 1873 throw e; 1874 } 1875 } 1876 } catch (ErrnoException e) { 1877 if (e.errno == OsConstants.ENOSPC) { 1878 Log.w(TAG, "Odd, not enough space; let's try again?"); 1879 continue; 1880 } 1881 throw e.rethrowAsIOException(); 1882 } 1883 } 1884 throw new IOException( 1885 "Well this is embarassing; we can't allocate " + bytes + " for " + file); 1886 } 1887 1888 private static final String XATTR_CACHE_GROUP = "user.cache_group"; 1889 private static final String XATTR_CACHE_TOMBSTONE = "user.cache_tombstone"; 1890 1891 /** {@hide} */ setCacheBehavior(File path, String name, boolean enabled)1892 private static void setCacheBehavior(File path, String name, boolean enabled) 1893 throws IOException { 1894 if (!path.isDirectory()) { 1895 throw new IOException("Cache behavior can only be set on directories"); 1896 } 1897 if (enabled) { 1898 try { 1899 Os.setxattr(path.getAbsolutePath(), name, 1900 "1".getBytes(StandardCharsets.UTF_8), 0); 1901 } catch (ErrnoException e) { 1902 throw e.rethrowAsIOException(); 1903 } 1904 } else { 1905 try { 1906 Os.removexattr(path.getAbsolutePath(), name); 1907 } catch (ErrnoException e) { 1908 if (e.errno != OsConstants.ENODATA) { 1909 throw e.rethrowAsIOException(); 1910 } 1911 } 1912 } 1913 } 1914 1915 /** {@hide} */ isCacheBehavior(File path, String name)1916 private static boolean isCacheBehavior(File path, String name) throws IOException { 1917 try { 1918 Os.getxattr(path.getAbsolutePath(), name); 1919 return true; 1920 } catch (ErrnoException e) { 1921 if (e.errno != OsConstants.ENODATA) { 1922 throw e.rethrowAsIOException(); 1923 } else { 1924 return false; 1925 } 1926 } 1927 } 1928 1929 /** 1930 * Enable or disable special cache behavior that treats this directory and 1931 * its contents as an entire group. 1932 * <p> 1933 * When enabled and this directory is considered for automatic deletion by 1934 * the OS, all contained files will either be deleted together, or not at 1935 * all. This is useful when you have a directory that contains several 1936 * related metadata files that depend on each other, such as movie file and 1937 * a subtitle file. 1938 * <p> 1939 * When enabled, the <em>newest</em> {@link File#lastModified()} value of 1940 * any contained files is considered the modified time of the entire 1941 * directory. 1942 * <p> 1943 * This behavior can only be set on a directory, and it applies recursively 1944 * to all contained files and directories. 1945 */ setCacheBehaviorGroup(File path, boolean group)1946 public void setCacheBehaviorGroup(File path, boolean group) throws IOException { 1947 setCacheBehavior(path, XATTR_CACHE_GROUP, group); 1948 } 1949 1950 /** 1951 * Read the current value set by 1952 * {@link #setCacheBehaviorGroup(File, boolean)}. 1953 */ isCacheBehaviorGroup(File path)1954 public boolean isCacheBehaviorGroup(File path) throws IOException { 1955 return isCacheBehavior(path, XATTR_CACHE_GROUP); 1956 } 1957 1958 /** 1959 * Enable or disable special cache behavior that leaves deleted cache files 1960 * intact as tombstones. 1961 * <p> 1962 * When enabled and a file contained in this directory is automatically 1963 * deleted by the OS, the file will be truncated to have a length of 0 bytes 1964 * instead of being fully deleted. This is useful if you need to distinguish 1965 * between a file that was deleted versus one that never existed. 1966 * <p> 1967 * This behavior can only be set on a directory, and it applies recursively 1968 * to all contained files and directories. 1969 * <p class="note"> 1970 * Note: this behavior is ignored completely if the user explicitly requests 1971 * that all cached data be cleared. 1972 * </p> 1973 */ setCacheBehaviorTombstone(File path, boolean tombstone)1974 public void setCacheBehaviorTombstone(File path, boolean tombstone) throws IOException { 1975 setCacheBehavior(path, XATTR_CACHE_TOMBSTONE, tombstone); 1976 } 1977 1978 /** 1979 * Read the current value set by 1980 * {@link #setCacheBehaviorTombstone(File, boolean)}. 1981 */ isCacheBehaviorTombstone(File path)1982 public boolean isCacheBehaviorTombstone(File path) throws IOException { 1983 return isCacheBehavior(path, XATTR_CACHE_TOMBSTONE); 1984 } 1985 1986 /** {@hide} */ convert(String uuid)1987 public static UUID convert(String uuid) { 1988 if (Objects.equals(uuid, UUID_PRIVATE_INTERNAL)) { 1989 return UUID_DEFAULT; 1990 } else if (Objects.equals(uuid, UUID_PRIMARY_PHYSICAL)) { 1991 return UUID_PRIMARY_PHYSICAL_; 1992 } else if (Objects.equals(uuid, UUID_SYSTEM)) { 1993 return UUID_SYSTEM_; 1994 } else { 1995 return UUID.fromString(uuid); 1996 } 1997 } 1998 1999 /** {@hide} */ convert(UUID storageUuid)2000 public static String convert(UUID storageUuid) { 2001 if (UUID_DEFAULT.equals(storageUuid)) { 2002 return UUID_PRIVATE_INTERNAL; 2003 } else if (UUID_PRIMARY_PHYSICAL_.equals(storageUuid)) { 2004 return UUID_PRIMARY_PHYSICAL; 2005 } else if (UUID_SYSTEM_.equals(storageUuid)) { 2006 return UUID_SYSTEM; 2007 } else { 2008 return storageUuid.toString(); 2009 } 2010 } 2011 2012 private final Object mFuseAppLoopLock = new Object(); 2013 2014 @GuardedBy("mFuseAppLoopLock") 2015 private @Nullable FuseAppLoop mFuseAppLoop = null; 2016 2017 /// Consts to match the password types in cryptfs.h 2018 /** @hide */ 2019 public static final int CRYPT_TYPE_PASSWORD = IVold.PASSWORD_TYPE_PASSWORD; 2020 /** @hide */ 2021 public static final int CRYPT_TYPE_DEFAULT = IVold.PASSWORD_TYPE_DEFAULT; 2022 /** @hide */ 2023 public static final int CRYPT_TYPE_PATTERN = IVold.PASSWORD_TYPE_PATTERN; 2024 /** @hide */ 2025 public static final int CRYPT_TYPE_PIN = IVold.PASSWORD_TYPE_PIN; 2026 2027 // Constants for the data available via StorageManagerService.getField. 2028 /** @hide */ 2029 public static final String SYSTEM_LOCALE_KEY = "SystemLocale"; 2030 /** @hide */ 2031 public static final String OWNER_INFO_KEY = "OwnerInfo"; 2032 /** @hide */ 2033 public static final String PATTERN_VISIBLE_KEY = "PatternVisible"; 2034 /** @hide */ 2035 public static final String PASSWORD_VISIBLE_KEY = "PasswordVisible"; 2036 } 2037