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