StorageManager.java revision c0d3f0ed524bad773f6d61082a07f062d53b27a0
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 static android.net.TrafficStats.MB_IN_BYTES; 20 21import android.annotation.NonNull; 22import android.annotation.Nullable; 23import android.annotation.SdkConstant; 24import android.app.ActivityThread; 25import android.content.ContentResolver; 26import android.content.Context; 27import android.content.pm.IPackageMoveObserver; 28import android.content.pm.PackageManager; 29import android.os.Binder; 30import android.os.Environment; 31import android.os.FileUtils; 32import android.os.Handler; 33import android.os.Looper; 34import android.os.Message; 35import android.os.ParcelFileDescriptor; 36import android.os.RemoteException; 37import android.os.ServiceManager; 38import android.os.SystemProperties; 39import android.os.UserHandle; 40import android.provider.Settings; 41import android.text.TextUtils; 42import android.util.Log; 43import android.util.Pair; 44import android.util.Slog; 45import android.util.SparseArray; 46 47import com.android.internal.os.SomeArgs; 48import com.android.internal.util.Preconditions; 49 50import java.io.BufferedReader; 51import java.io.File; 52import java.io.FileInputStream; 53import java.io.IOException; 54import java.io.InputStreamReader; 55import java.lang.ref.WeakReference; 56import java.util.ArrayList; 57import java.util.Arrays; 58import java.util.Collections; 59import java.util.Iterator; 60import java.util.List; 61import java.util.Objects; 62import java.util.concurrent.atomic.AtomicInteger; 63 64/** 65 * StorageManager is the interface to the systems storage service. The storage 66 * manager handles storage-related items such as Opaque Binary Blobs (OBBs). 67 * <p> 68 * OBBs contain a filesystem that maybe be encrypted on disk and mounted 69 * on-demand from an application. OBBs are a good way of providing large amounts 70 * of binary assets without packaging them into APKs as they may be multiple 71 * gigabytes in size. However, due to their size, they're most likely stored in 72 * a shared storage pool accessible from all programs. The system does not 73 * guarantee the security of the OBB file itself: if any program modifies the 74 * OBB, there is no guarantee that a read from that OBB will produce the 75 * expected output. 76 * <p> 77 * Get an instance of this class by calling 78 * {@link android.content.Context#getSystemService(java.lang.String)} with an 79 * argument of {@link android.content.Context#STORAGE_SERVICE}. 80 */ 81public class StorageManager { 82 private static final String TAG = "StorageManager"; 83 84 /** {@hide} */ 85 public static final String PROP_PRIMARY_PHYSICAL = "ro.vold.primary_physical"; 86 /** {@hide} */ 87 public static final String PROP_HAS_ADOPTABLE = "vold.has_adoptable"; 88 /** {@hide} */ 89 public static final String PROP_FORCE_ADOPTABLE = "persist.fw.force_adoptable"; 90 /** {@hide} */ 91 public static final String PROP_EMULATE_FBE = "persist.sys.emulate_fbe"; 92 /** {@hide} */ 93 public static final String PROP_SDCARDFS = "persist.sys.sdcardfs"; 94 95 /** {@hide} */ 96 public static final String UUID_PRIVATE_INTERNAL = null; 97 /** {@hide} */ 98 public static final String UUID_PRIMARY_PHYSICAL = "primary_physical"; 99 100 101 /** 102 * Activity Action: Allows the user to manage their storage. This activity provides the ability 103 * to free up space on the device by deleting data such as apps. 104 * <p> 105 * Input: Nothing. 106 * <p> 107 * Output: Nothing. 108 */ 109 @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION) 110 public static final String ACTION_MANAGE_STORAGE 111 = "android.os.storage.action.MANAGE_STORAGE"; 112 113 /** {@hide} */ 114 public static final int DEBUG_FORCE_ADOPTABLE = 1 << 0; 115 /** {@hide} */ 116 public static final int DEBUG_EMULATE_FBE = 1 << 1; 117 /** {@hide} */ 118 public static final int DEBUG_SDCARDFS_FORCE_ON = 1 << 2; 119 /** {@hide} */ 120 public static final int DEBUG_SDCARDFS_FORCE_OFF = 1 << 3; 121 122 // NOTE: keep in sync with installd 123 /** {@hide} */ 124 public static final int FLAG_STORAGE_DE = 1 << 0; 125 /** {@hide} */ 126 public static final int FLAG_STORAGE_CE = 1 << 1; 127 128 /** {@hide} */ 129 public static final int FLAG_FOR_WRITE = 1 << 8; 130 /** {@hide} */ 131 public static final int FLAG_REAL_STATE = 1 << 9; 132 /** {@hide} */ 133 public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10; 134 135 private static volatile IMountService sMountService = null; 136 137 // TODO: the location of the primary storage block varies from device to device, so we need to 138 // try the most likely candidates - a long-term solution would be a device-specific vold 139 // function that returns the calculated size. 140 private static final String[] INTERNAL_STORAGE_SIZE_PATHS = { 141 "/sys/block/mmcblk0/size", 142 "/sys/block/sda/size" 143 }; 144 private static final int INTERNAL_STORAGE_SECTOR_SIZE = 512; 145 146 private final Context mContext; 147 private final ContentResolver mResolver; 148 149 private final IMountService mMountService; 150 private final Looper mLooper; 151 private final AtomicInteger mNextNonce = new AtomicInteger(0); 152 153 private final ArrayList<StorageEventListenerDelegate> mDelegates = new ArrayList<>(); 154 155 private static class StorageEventListenerDelegate extends IMountServiceListener.Stub implements 156 Handler.Callback { 157 private static final int MSG_STORAGE_STATE_CHANGED = 1; 158 private static final int MSG_VOLUME_STATE_CHANGED = 2; 159 private static final int MSG_VOLUME_RECORD_CHANGED = 3; 160 private static final int MSG_VOLUME_FORGOTTEN = 4; 161 private static final int MSG_DISK_SCANNED = 5; 162 private static final int MSG_DISK_DESTROYED = 6; 163 164 final StorageEventListener mCallback; 165 final Handler mHandler; 166 167 public StorageEventListenerDelegate(StorageEventListener callback, Looper looper) { 168 mCallback = callback; 169 mHandler = new Handler(looper, this); 170 } 171 172 @Override 173 public boolean handleMessage(Message msg) { 174 final SomeArgs args = (SomeArgs) msg.obj; 175 switch (msg.what) { 176 case MSG_STORAGE_STATE_CHANGED: 177 mCallback.onStorageStateChanged((String) args.arg1, (String) args.arg2, 178 (String) args.arg3); 179 args.recycle(); 180 return true; 181 case MSG_VOLUME_STATE_CHANGED: 182 mCallback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3); 183 args.recycle(); 184 return true; 185 case MSG_VOLUME_RECORD_CHANGED: 186 mCallback.onVolumeRecordChanged((VolumeRecord) args.arg1); 187 args.recycle(); 188 return true; 189 case MSG_VOLUME_FORGOTTEN: 190 mCallback.onVolumeForgotten((String) args.arg1); 191 args.recycle(); 192 return true; 193 case MSG_DISK_SCANNED: 194 mCallback.onDiskScanned((DiskInfo) args.arg1, args.argi2); 195 args.recycle(); 196 return true; 197 case MSG_DISK_DESTROYED: 198 mCallback.onDiskDestroyed((DiskInfo) args.arg1); 199 args.recycle(); 200 return true; 201 } 202 args.recycle(); 203 return false; 204 } 205 206 @Override 207 public void onUsbMassStorageConnectionChanged(boolean connected) throws RemoteException { 208 // Ignored 209 } 210 211 @Override 212 public void onStorageStateChanged(String path, String oldState, String newState) { 213 final SomeArgs args = SomeArgs.obtain(); 214 args.arg1 = path; 215 args.arg2 = oldState; 216 args.arg3 = newState; 217 mHandler.obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget(); 218 } 219 220 @Override 221 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 222 final SomeArgs args = SomeArgs.obtain(); 223 args.arg1 = vol; 224 args.argi2 = oldState; 225 args.argi3 = newState; 226 mHandler.obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget(); 227 } 228 229 @Override 230 public void onVolumeRecordChanged(VolumeRecord rec) { 231 final SomeArgs args = SomeArgs.obtain(); 232 args.arg1 = rec; 233 mHandler.obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget(); 234 } 235 236 @Override 237 public void onVolumeForgotten(String fsUuid) { 238 final SomeArgs args = SomeArgs.obtain(); 239 args.arg1 = fsUuid; 240 mHandler.obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget(); 241 } 242 243 @Override 244 public void onDiskScanned(DiskInfo disk, int volumeCount) { 245 final SomeArgs args = SomeArgs.obtain(); 246 args.arg1 = disk; 247 args.argi2 = volumeCount; 248 mHandler.obtainMessage(MSG_DISK_SCANNED, args).sendToTarget(); 249 } 250 251 @Override 252 public void onDiskDestroyed(DiskInfo disk) throws RemoteException { 253 final SomeArgs args = SomeArgs.obtain(); 254 args.arg1 = disk; 255 mHandler.obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget(); 256 } 257 } 258 259 /** 260 * Binder listener for OBB action results. 261 */ 262 private final ObbActionListener mObbActionListener = new ObbActionListener(); 263 264 private class ObbActionListener extends IObbActionListener.Stub { 265 @SuppressWarnings("hiding") 266 private SparseArray<ObbListenerDelegate> mListeners = new SparseArray<ObbListenerDelegate>(); 267 268 @Override 269 public void onObbResult(String filename, int nonce, int status) { 270 final ObbListenerDelegate delegate; 271 synchronized (mListeners) { 272 delegate = mListeners.get(nonce); 273 if (delegate != null) { 274 mListeners.remove(nonce); 275 } 276 } 277 278 if (delegate != null) { 279 delegate.sendObbStateChanged(filename, status); 280 } 281 } 282 283 public int addListener(OnObbStateChangeListener listener) { 284 final ObbListenerDelegate delegate = new ObbListenerDelegate(listener); 285 286 synchronized (mListeners) { 287 mListeners.put(delegate.nonce, delegate); 288 } 289 290 return delegate.nonce; 291 } 292 } 293 294 private int getNextNonce() { 295 return mNextNonce.getAndIncrement(); 296 } 297 298 /** 299 * Private class containing sender and receiver code for StorageEvents. 300 */ 301 private class ObbListenerDelegate { 302 private final WeakReference<OnObbStateChangeListener> mObbEventListenerRef; 303 private final Handler mHandler; 304 305 private final int nonce; 306 307 ObbListenerDelegate(OnObbStateChangeListener listener) { 308 nonce = getNextNonce(); 309 mObbEventListenerRef = new WeakReference<OnObbStateChangeListener>(listener); 310 mHandler = new Handler(mLooper) { 311 @Override 312 public void handleMessage(Message msg) { 313 final OnObbStateChangeListener changeListener = getListener(); 314 if (changeListener == null) { 315 return; 316 } 317 318 changeListener.onObbStateChange((String) msg.obj, msg.arg1); 319 } 320 }; 321 } 322 323 OnObbStateChangeListener getListener() { 324 if (mObbEventListenerRef == null) { 325 return null; 326 } 327 return mObbEventListenerRef.get(); 328 } 329 330 void sendObbStateChanged(String path, int state) { 331 mHandler.obtainMessage(0, state, 0, path).sendToTarget(); 332 } 333 } 334 335 /** {@hide} */ 336 @Deprecated 337 public static StorageManager from(Context context) { 338 return context.getSystemService(StorageManager.class); 339 } 340 341 /** 342 * Constructs a StorageManager object through which an application can 343 * can communicate with the systems mount service. 344 * 345 * @param tgtLooper The {@link android.os.Looper} which events will be received on. 346 * 347 * <p>Applications can get instance of this class by calling 348 * {@link android.content.Context#getSystemService(java.lang.String)} with an argument 349 * of {@link android.content.Context#STORAGE_SERVICE}. 350 * 351 * @hide 352 */ 353 public StorageManager(Context context, Looper looper) { 354 mContext = context; 355 mResolver = context.getContentResolver(); 356 mLooper = looper; 357 mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount")); 358 if (mMountService == null) { 359 throw new IllegalStateException("Failed to find running mount service"); 360 } 361 } 362 363 /** 364 * Registers a {@link android.os.storage.StorageEventListener StorageEventListener}. 365 * 366 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object. 367 * 368 * @hide 369 */ 370 public void registerListener(StorageEventListener listener) { 371 synchronized (mDelegates) { 372 final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(listener, 373 mLooper); 374 try { 375 mMountService.registerListener(delegate); 376 } catch (RemoteException e) { 377 throw e.rethrowFromSystemServer(); 378 } 379 mDelegates.add(delegate); 380 } 381 } 382 383 /** 384 * Unregisters a {@link android.os.storage.StorageEventListener StorageEventListener}. 385 * 386 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object. 387 * 388 * @hide 389 */ 390 public void unregisterListener(StorageEventListener listener) { 391 synchronized (mDelegates) { 392 for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) { 393 final StorageEventListenerDelegate delegate = i.next(); 394 if (delegate.mCallback == listener) { 395 try { 396 mMountService.unregisterListener(delegate); 397 } catch (RemoteException e) { 398 throw e.rethrowFromSystemServer(); 399 } 400 i.remove(); 401 } 402 } 403 } 404 } 405 406 /** 407 * Enables USB Mass Storage (UMS) on the device. 408 * 409 * @hide 410 */ 411 @Deprecated 412 public void enableUsbMassStorage() { 413 } 414 415 /** 416 * Disables USB Mass Storage (UMS) on the device. 417 * 418 * @hide 419 */ 420 @Deprecated 421 public void disableUsbMassStorage() { 422 } 423 424 /** 425 * Query if a USB Mass Storage (UMS) host is connected. 426 * @return true if UMS host is connected. 427 * 428 * @hide 429 */ 430 @Deprecated 431 public boolean isUsbMassStorageConnected() { 432 return false; 433 } 434 435 /** 436 * Query if a USB Mass Storage (UMS) is enabled on the device. 437 * @return true if UMS host is enabled. 438 * 439 * @hide 440 */ 441 @Deprecated 442 public boolean isUsbMassStorageEnabled() { 443 return false; 444 } 445 446 /** 447 * Mount an Opaque Binary Blob (OBB) file. If a <code>key</code> is 448 * specified, it is supplied to the mounting process to be used in any 449 * encryption used in the OBB. 450 * <p> 451 * The OBB will remain mounted for as long as the StorageManager reference 452 * is held by the application. As soon as this reference is lost, the OBBs 453 * in use will be unmounted. The {@link OnObbStateChangeListener} registered 454 * with this call will receive the success or failure of this operation. 455 * <p> 456 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the 457 * file matches a package ID that is owned by the calling program's UID. 458 * That is, shared UID applications can attempt to mount any other 459 * application's OBB that shares its UID. 460 * 461 * @param rawPath the path to the OBB file 462 * @param key secret used to encrypt the OBB; may be <code>null</code> if no 463 * encryption was used on the OBB. 464 * @param listener will receive the success or failure of the operation 465 * @return whether the mount call was successfully queued or not 466 */ 467 public boolean mountObb(String rawPath, String key, OnObbStateChangeListener listener) { 468 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 469 Preconditions.checkNotNull(listener, "listener cannot be null"); 470 471 try { 472 final String canonicalPath = new File(rawPath).getCanonicalPath(); 473 final int nonce = mObbActionListener.addListener(listener); 474 mMountService.mountObb(rawPath, canonicalPath, key, mObbActionListener, nonce); 475 return true; 476 } catch (IOException e) { 477 throw new IllegalArgumentException("Failed to resolve path: " + rawPath, e); 478 } catch (RemoteException e) { 479 throw e.rethrowFromSystemServer(); 480 } 481 } 482 483 /** 484 * Unmount an Opaque Binary Blob (OBB) file asynchronously. If the 485 * <code>force</code> flag is true, it will kill any application needed to 486 * unmount the given OBB (even the calling application). 487 * <p> 488 * The {@link OnObbStateChangeListener} registered with this call will 489 * receive the success or failure of this operation. 490 * <p> 491 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the 492 * file matches a package ID that is owned by the calling program's UID. 493 * That is, shared UID applications can obtain access to any other 494 * application's OBB that shares its UID. 495 * <p> 496 * 497 * @param rawPath path to the OBB file 498 * @param force whether to kill any programs using this in order to unmount 499 * it 500 * @param listener will receive the success or failure of the operation 501 * @return whether the unmount call was successfully queued or not 502 */ 503 public boolean unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener) { 504 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 505 Preconditions.checkNotNull(listener, "listener cannot be null"); 506 507 try { 508 final int nonce = mObbActionListener.addListener(listener); 509 mMountService.unmountObb(rawPath, force, mObbActionListener, nonce); 510 return true; 511 } catch (RemoteException e) { 512 throw e.rethrowFromSystemServer(); 513 } 514 } 515 516 /** 517 * Check whether an Opaque Binary Blob (OBB) is mounted or not. 518 * 519 * @param rawPath path to OBB image 520 * @return true if OBB is mounted; false if not mounted or on error 521 */ 522 public boolean isObbMounted(String rawPath) { 523 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 524 525 try { 526 return mMountService.isObbMounted(rawPath); 527 } catch (RemoteException e) { 528 throw e.rethrowFromSystemServer(); 529 } 530 } 531 532 /** 533 * Check the mounted path of an Opaque Binary Blob (OBB) file. This will 534 * give you the path to where you can obtain access to the internals of the 535 * OBB. 536 * 537 * @param rawPath path to OBB image 538 * @return absolute path to mounted OBB image data or <code>null</code> if 539 * not mounted or exception encountered trying to read status 540 */ 541 public String getMountedObbPath(String rawPath) { 542 Preconditions.checkNotNull(rawPath, "rawPath cannot be null"); 543 544 try { 545 return mMountService.getMountedObbPath(rawPath); 546 } catch (RemoteException e) { 547 throw e.rethrowFromSystemServer(); 548 } 549 } 550 551 /** {@hide} */ 552 public @NonNull List<DiskInfo> getDisks() { 553 try { 554 return Arrays.asList(mMountService.getDisks()); 555 } catch (RemoteException e) { 556 throw e.rethrowFromSystemServer(); 557 } 558 } 559 560 /** {@hide} */ 561 public @Nullable DiskInfo findDiskById(String id) { 562 Preconditions.checkNotNull(id); 563 // TODO; go directly to service to make this faster 564 for (DiskInfo disk : getDisks()) { 565 if (Objects.equals(disk.id, id)) { 566 return disk; 567 } 568 } 569 return null; 570 } 571 572 /** {@hide} */ 573 public @Nullable VolumeInfo findVolumeById(String id) { 574 Preconditions.checkNotNull(id); 575 // TODO; go directly to service to make this faster 576 for (VolumeInfo vol : getVolumes()) { 577 if (Objects.equals(vol.id, id)) { 578 return vol; 579 } 580 } 581 return null; 582 } 583 584 /** {@hide} */ 585 public @Nullable VolumeInfo findVolumeByUuid(String fsUuid) { 586 Preconditions.checkNotNull(fsUuid); 587 // TODO; go directly to service to make this faster 588 for (VolumeInfo vol : getVolumes()) { 589 if (Objects.equals(vol.fsUuid, fsUuid)) { 590 return vol; 591 } 592 } 593 return null; 594 } 595 596 /** {@hide} */ 597 public @Nullable VolumeRecord findRecordByUuid(String fsUuid) { 598 Preconditions.checkNotNull(fsUuid); 599 // TODO; go directly to service to make this faster 600 for (VolumeRecord rec : getVolumeRecords()) { 601 if (Objects.equals(rec.fsUuid, fsUuid)) { 602 return rec; 603 } 604 } 605 return null; 606 } 607 608 /** {@hide} */ 609 public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) { 610 if (emulatedVol != null) { 611 return findVolumeById(emulatedVol.getId().replace("emulated", "private")); 612 } else { 613 return null; 614 } 615 } 616 617 /** {@hide} */ 618 public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) { 619 if (privateVol != null) { 620 return findVolumeById(privateVol.getId().replace("private", "emulated")); 621 } else { 622 return null; 623 } 624 } 625 626 /** {@hide} */ 627 public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) { 628 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 629 return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL); 630 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 631 return getPrimaryPhysicalVolume(); 632 } else { 633 return findVolumeByUuid(volumeUuid); 634 } 635 } 636 637 /** {@hide} */ 638 public @NonNull List<VolumeInfo> getVolumes() { 639 try { 640 return Arrays.asList(mMountService.getVolumes(0)); 641 } catch (RemoteException e) { 642 throw e.rethrowFromSystemServer(); 643 } 644 } 645 646 /** {@hide} */ 647 public @NonNull List<VolumeInfo> getWritablePrivateVolumes() { 648 try { 649 final ArrayList<VolumeInfo> res = new ArrayList<>(); 650 for (VolumeInfo vol : mMountService.getVolumes(0)) { 651 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 652 res.add(vol); 653 } 654 } 655 return res; 656 } catch (RemoteException e) { 657 throw e.rethrowFromSystemServer(); 658 } 659 } 660 661 /** {@hide} */ 662 public @NonNull List<VolumeRecord> getVolumeRecords() { 663 try { 664 return Arrays.asList(mMountService.getVolumeRecords(0)); 665 } catch (RemoteException e) { 666 throw e.rethrowFromSystemServer(); 667 } 668 } 669 670 /** {@hide} */ 671 public @Nullable String getBestVolumeDescription(VolumeInfo vol) { 672 if (vol == null) return null; 673 674 // Nickname always takes precedence when defined 675 if (!TextUtils.isEmpty(vol.fsUuid)) { 676 final VolumeRecord rec = findRecordByUuid(vol.fsUuid); 677 if (rec != null && !TextUtils.isEmpty(rec.nickname)) { 678 return rec.nickname; 679 } 680 } 681 682 if (!TextUtils.isEmpty(vol.getDescription())) { 683 return vol.getDescription(); 684 } 685 686 if (vol.disk != null) { 687 return vol.disk.getDescription(); 688 } 689 690 return null; 691 } 692 693 /** {@hide} */ 694 public @Nullable VolumeInfo getPrimaryPhysicalVolume() { 695 final List<VolumeInfo> vols = getVolumes(); 696 for (VolumeInfo vol : vols) { 697 if (vol.isPrimaryPhysical()) { 698 return vol; 699 } 700 } 701 return null; 702 } 703 704 /** {@hide} */ 705 public void mount(String volId) { 706 try { 707 mMountService.mount(volId); 708 } catch (RemoteException e) { 709 throw e.rethrowFromSystemServer(); 710 } 711 } 712 713 /** {@hide} */ 714 public void unmount(String volId) { 715 try { 716 mMountService.unmount(volId); 717 } catch (RemoteException e) { 718 throw e.rethrowFromSystemServer(); 719 } 720 } 721 722 /** {@hide} */ 723 public void format(String volId) { 724 try { 725 mMountService.format(volId); 726 } catch (RemoteException e) { 727 throw e.rethrowFromSystemServer(); 728 } 729 } 730 731 /** {@hide} */ 732 public long benchmark(String volId) { 733 try { 734 return mMountService.benchmark(volId); 735 } catch (RemoteException e) { 736 throw e.rethrowFromSystemServer(); 737 } 738 } 739 740 /** {@hide} */ 741 public void partitionPublic(String diskId) { 742 try { 743 mMountService.partitionPublic(diskId); 744 } catch (RemoteException e) { 745 throw e.rethrowFromSystemServer(); 746 } 747 } 748 749 /** {@hide} */ 750 public void partitionPrivate(String diskId) { 751 try { 752 mMountService.partitionPrivate(diskId); 753 } catch (RemoteException e) { 754 throw e.rethrowFromSystemServer(); 755 } 756 } 757 758 /** {@hide} */ 759 public void partitionMixed(String diskId, int ratio) { 760 try { 761 mMountService.partitionMixed(diskId, ratio); 762 } catch (RemoteException e) { 763 throw e.rethrowFromSystemServer(); 764 } 765 } 766 767 /** {@hide} */ 768 public void wipeAdoptableDisks() { 769 // We only wipe devices in "adoptable" locations, which are in a 770 // long-term stable slot/location on the device, where apps have a 771 // reasonable chance of storing sensitive data. (Apps need to go through 772 // SAF to write to transient volumes.) 773 final List<DiskInfo> disks = getDisks(); 774 for (DiskInfo disk : disks) { 775 final String diskId = disk.getId(); 776 if (disk.isAdoptable()) { 777 Slog.d(TAG, "Found adoptable " + diskId + "; wiping"); 778 try { 779 // TODO: switch to explicit wipe command when we have it, 780 // for now rely on the fact that vfat format does a wipe 781 mMountService.partitionPublic(diskId); 782 } catch (Exception e) { 783 Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e); 784 } 785 } else { 786 Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId()); 787 } 788 } 789 } 790 791 /** {@hide} */ 792 public void setVolumeNickname(String fsUuid, String nickname) { 793 try { 794 mMountService.setVolumeNickname(fsUuid, nickname); 795 } catch (RemoteException e) { 796 throw e.rethrowFromSystemServer(); 797 } 798 } 799 800 /** {@hide} */ 801 public void setVolumeInited(String fsUuid, boolean inited) { 802 try { 803 mMountService.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0, 804 VolumeRecord.USER_FLAG_INITED); 805 } catch (RemoteException e) { 806 throw e.rethrowFromSystemServer(); 807 } 808 } 809 810 /** {@hide} */ 811 public void setVolumeSnoozed(String fsUuid, boolean snoozed) { 812 try { 813 mMountService.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0, 814 VolumeRecord.USER_FLAG_SNOOZED); 815 } catch (RemoteException e) { 816 throw e.rethrowFromSystemServer(); 817 } 818 } 819 820 /** {@hide} */ 821 public void forgetVolume(String fsUuid) { 822 try { 823 mMountService.forgetVolume(fsUuid); 824 } catch (RemoteException e) { 825 throw e.rethrowFromSystemServer(); 826 } 827 } 828 829 /** 830 * This is not the API you're looking for. 831 * 832 * @see PackageManager#getPrimaryStorageCurrentVolume() 833 * @hide 834 */ 835 public String getPrimaryStorageUuid() { 836 try { 837 return mMountService.getPrimaryStorageUuid(); 838 } catch (RemoteException e) { 839 throw e.rethrowFromSystemServer(); 840 } 841 } 842 843 /** 844 * This is not the API you're looking for. 845 * 846 * @see PackageManager#movePrimaryStorage(VolumeInfo) 847 * @hide 848 */ 849 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) { 850 try { 851 mMountService.setPrimaryStorageUuid(volumeUuid, callback); 852 } catch (RemoteException e) { 853 throw e.rethrowFromSystemServer(); 854 } 855 } 856 857 /** 858 * Return the {@link StorageVolume} that contains the given file, or {@code null} if none. 859 */ 860 public @Nullable StorageVolume getStorageVolume(File file) { 861 return getStorageVolume(getVolumeList(), file); 862 } 863 864 /** {@hide} */ 865 public static @Nullable StorageVolume getStorageVolume(File file, int userId) { 866 return getStorageVolume(getVolumeList(userId, 0), file); 867 } 868 869 /** {@hide} */ 870 private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) { 871 if (file == null) { 872 return null; 873 } 874 try { 875 file = file.getCanonicalFile(); 876 } catch (IOException ignored) { 877 Slog.d(TAG, "Could not get canonical path for " + file); 878 return null; 879 } 880 for (StorageVolume volume : volumes) { 881 File volumeFile = volume.getPathFile(); 882 try { 883 volumeFile = volumeFile.getCanonicalFile(); 884 } catch (IOException ignored) { 885 continue; 886 } 887 if (FileUtils.contains(volumeFile, file)) { 888 return volume; 889 } 890 } 891 return null; 892 } 893 894 /** 895 * Gets the state of a volume via its mountpoint. 896 * @hide 897 */ 898 @Deprecated 899 public @NonNull String getVolumeState(String mountPoint) { 900 final StorageVolume vol = getStorageVolume(new File(mountPoint)); 901 if (vol != null) { 902 return vol.getState(); 903 } else { 904 return Environment.MEDIA_UNKNOWN; 905 } 906 } 907 908 /** 909 * Return the list of shared/external storage volumes available to the 910 * current user. This includes both the primary shared storage device and 911 * any attached external volumes including SD cards and USB drives. 912 * 913 * @see Environment#getExternalStorageDirectory() 914 * @see StorageVolume#createAccessIntent(String) 915 */ 916 public @NonNull List<StorageVolume> getStorageVolumes() { 917 final ArrayList<StorageVolume> res = new ArrayList<>(); 918 Collections.addAll(res, 919 getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)); 920 return res; 921 } 922 923 /** 924 * Return the primary shared/external storage volume available to the 925 * current user. This volume is the same storage device returned by 926 * {@link Environment#getExternalStorageDirectory()} and 927 * {@link Context#getExternalFilesDir(String)}. 928 */ 929 public @NonNull StorageVolume getPrimaryStorageVolume() { 930 return getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)[0]; 931 } 932 933 /** {@hide} */ 934 public static Pair<String, Long> getPrimaryStoragePathAndSize() { 935 for (String path : INTERNAL_STORAGE_SIZE_PATHS) { 936 final long numberBlocks = readLong(path); 937 if (numberBlocks > 0) { 938 return new Pair<>(path, Long.valueOf(numberBlocks * INTERNAL_STORAGE_SECTOR_SIZE)); 939 } 940 } 941 return null; 942 } 943 944 945 /** {@hide} */ 946 public long getPrimaryStorageSize() { 947 final Pair<String, Long> pair = getPrimaryStoragePathAndSize(); 948 return pair == null ? 0 : pair.second.longValue(); 949 } 950 951 private static long readLong(String path) { 952 try (final FileInputStream fis = new FileInputStream(path); 953 final BufferedReader reader = new BufferedReader(new InputStreamReader(fis));) { 954 return Long.parseLong(reader.readLine()); 955 } catch (Exception e) { 956 Slog.w(TAG, "readLong(): could not read " + path + ": " + e); 957 return 0; 958 } 959 } 960 961 /** @removed */ 962 public @NonNull StorageVolume[] getVolumeList() { 963 return getVolumeList(mContext.getUserId(), 0); 964 } 965 966 /** {@hide} */ 967 public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) { 968 final IMountService mountService = IMountService.Stub.asInterface( 969 ServiceManager.getService("mount")); 970 try { 971 String packageName = ActivityThread.currentOpPackageName(); 972 if (packageName == null) { 973 // Package name can be null if the activity thread is running but the app 974 // hasn't bound yet. In this case we fall back to the first package in the 975 // current UID. This works for runtime permissions as permission state is 976 // per UID and permission realted app ops are updated for all UID packages. 977 String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid( 978 android.os.Process.myUid()); 979 if (packageNames == null || packageNames.length <= 0) { 980 return new StorageVolume[0]; 981 } 982 packageName = packageNames[0]; 983 } 984 final int uid = ActivityThread.getPackageManager().getPackageUid(packageName, 985 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId); 986 if (uid <= 0) { 987 return new StorageVolume[0]; 988 } 989 return mountService.getVolumeList(uid, packageName, flags); 990 } catch (RemoteException e) { 991 throw e.rethrowFromSystemServer(); 992 } 993 } 994 995 /** 996 * Returns list of paths for all mountable volumes. 997 * @hide 998 */ 999 @Deprecated 1000 public @NonNull String[] getVolumePaths() { 1001 StorageVolume[] volumes = getVolumeList(); 1002 int count = volumes.length; 1003 String[] paths = new String[count]; 1004 for (int i = 0; i < count; i++) { 1005 paths[i] = volumes[i].getPath(); 1006 } 1007 return paths; 1008 } 1009 1010 /** @removed */ 1011 public @NonNull StorageVolume getPrimaryVolume() { 1012 return getPrimaryVolume(getVolumeList()); 1013 } 1014 1015 /** {@hide} */ 1016 public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) { 1017 for (StorageVolume volume : volumes) { 1018 if (volume.isPrimary()) { 1019 return volume; 1020 } 1021 } 1022 throw new IllegalStateException("Missing primary storage"); 1023 } 1024 1025 /** {@hide} */ 1026 private static final int DEFAULT_THRESHOLD_PERCENTAGE = 10; 1027 private static final long DEFAULT_THRESHOLD_MAX_BYTES = 500 * MB_IN_BYTES; 1028 private static final long DEFAULT_FULL_THRESHOLD_BYTES = MB_IN_BYTES; 1029 1030 /** 1031 * Return the number of available bytes until the given path is considered 1032 * running low on storage. 1033 * 1034 * @hide 1035 */ 1036 public long getStorageBytesUntilLow(File path) { 1037 return path.getUsableSpace() - getStorageFullBytes(path); 1038 } 1039 1040 /** 1041 * Return the number of available bytes at which the given path is 1042 * considered running low on storage. 1043 * 1044 * @hide 1045 */ 1046 public long getStorageLowBytes(File path) { 1047 final long lowPercent = Settings.Global.getInt(mResolver, 1048 Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE, DEFAULT_THRESHOLD_PERCENTAGE); 1049 final long lowBytes = (path.getTotalSpace() * lowPercent) / 100; 1050 1051 final long maxLowBytes = Settings.Global.getLong(mResolver, 1052 Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES); 1053 1054 return Math.min(lowBytes, maxLowBytes); 1055 } 1056 1057 /** 1058 * Return the number of available bytes at which the given path is 1059 * considered full. 1060 * 1061 * @hide 1062 */ 1063 public long getStorageFullBytes(File path) { 1064 return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES, 1065 DEFAULT_FULL_THRESHOLD_BYTES); 1066 } 1067 1068 /** {@hide} */ 1069 public void createUserKey(int userId, int serialNumber, boolean ephemeral) { 1070 try { 1071 mMountService.createUserKey(userId, serialNumber, ephemeral); 1072 } catch (RemoteException e) { 1073 throw e.rethrowFromSystemServer(); 1074 } 1075 } 1076 1077 /** {@hide} */ 1078 public void destroyUserKey(int userId) { 1079 try { 1080 mMountService.destroyUserKey(userId); 1081 } catch (RemoteException e) { 1082 throw e.rethrowFromSystemServer(); 1083 } 1084 } 1085 1086 /** {@hide} */ 1087 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) { 1088 try { 1089 mMountService.unlockUserKey(userId, serialNumber, token, secret); 1090 } catch (RemoteException e) { 1091 throw e.rethrowFromSystemServer(); 1092 } 1093 } 1094 1095 /** {@hide} */ 1096 public void lockUserKey(int userId) { 1097 try { 1098 mMountService.lockUserKey(userId); 1099 } catch (RemoteException e) { 1100 throw e.rethrowFromSystemServer(); 1101 } 1102 } 1103 1104 /** {@hide} */ 1105 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) { 1106 try { 1107 mMountService.prepareUserStorage(volumeUuid, userId, serialNumber, flags); 1108 } catch (RemoteException e) { 1109 throw e.rethrowFromSystemServer(); 1110 } 1111 } 1112 1113 /** {@hide} */ 1114 public void destroyUserStorage(String volumeUuid, int userId, int flags) { 1115 try { 1116 mMountService.destroyUserStorage(volumeUuid, userId, flags); 1117 } catch (RemoteException e) { 1118 throw e.rethrowFromSystemServer(); 1119 } 1120 } 1121 1122 /** {@hide} */ 1123 public static boolean isUserKeyUnlocked(int userId) { 1124 if (sMountService == null) { 1125 sMountService = IMountService.Stub 1126 .asInterface(ServiceManager.getService("mount")); 1127 } 1128 if (sMountService == null) { 1129 Slog.w(TAG, "Early during boot, assuming locked"); 1130 return false; 1131 } 1132 final long token = Binder.clearCallingIdentity(); 1133 try { 1134 return sMountService.isUserKeyUnlocked(userId); 1135 } catch (RemoteException e) { 1136 throw e.rethrowAsRuntimeException(); 1137 } finally { 1138 Binder.restoreCallingIdentity(token); 1139 } 1140 } 1141 1142 /** 1143 * Return if data stored at or under the given path will be encrypted while 1144 * at rest. This can help apps avoid the overhead of double-encrypting data. 1145 */ 1146 public boolean isEncrypted(File file) { 1147 if (FileUtils.contains(Environment.getDataDirectory(), file)) { 1148 return isEncrypted(); 1149 } else if (FileUtils.contains(Environment.getExpandDirectory(), file)) { 1150 return true; 1151 } 1152 // TODO: extend to support shared storage 1153 return false; 1154 } 1155 1156 /** {@hide} 1157 * Is this device encryptable or already encrypted? 1158 * @return true for encryptable or encrypted 1159 * false not encrypted and not encryptable 1160 */ 1161 public static boolean isEncryptable() { 1162 final String state = SystemProperties.get("ro.crypto.state", "unsupported"); 1163 return !"unsupported".equalsIgnoreCase(state); 1164 } 1165 1166 /** {@hide} 1167 * Is this device already encrypted? 1168 * @return true for encrypted. (Implies isEncryptable() == true) 1169 * false not encrypted 1170 */ 1171 public static boolean isEncrypted() { 1172 final String state = SystemProperties.get("ro.crypto.state", ""); 1173 return "encrypted".equalsIgnoreCase(state); 1174 } 1175 1176 /** {@hide} 1177 * Is this device file encrypted? 1178 * @return true for file encrypted. (Implies isEncrypted() == true) 1179 * false not encrypted or block encrypted 1180 */ 1181 public static boolean isFileEncryptedNativeOnly() { 1182 if (!isEncrypted()) { 1183 return false; 1184 } 1185 1186 final String status = SystemProperties.get("ro.crypto.type", ""); 1187 return "file".equalsIgnoreCase(status); 1188 } 1189 1190 /** {@hide} 1191 * Is this device block encrypted? 1192 * @return true for block encrypted. (Implies isEncrypted() == true) 1193 * false not encrypted or file encrypted 1194 */ 1195 public static boolean isBlockEncrypted() { 1196 if (!isEncrypted()) { 1197 return false; 1198 } 1199 final String status = SystemProperties.get("ro.crypto.type", ""); 1200 return "block".equalsIgnoreCase(status); 1201 } 1202 1203 /** {@hide} 1204 * Is this device block encrypted with credentials? 1205 * @return true for crediential block encrypted. 1206 * (Implies isBlockEncrypted() == true) 1207 * false not encrypted, file encrypted or default block encrypted 1208 */ 1209 public static boolean isNonDefaultBlockEncrypted() { 1210 if (!isBlockEncrypted()) { 1211 return false; 1212 } 1213 1214 try { 1215 IMountService mountService = IMountService.Stub.asInterface( 1216 ServiceManager.getService("mount")); 1217 return mountService.getPasswordType() != CRYPT_TYPE_DEFAULT; 1218 } catch (RemoteException e) { 1219 Log.e(TAG, "Error getting encryption type"); 1220 return false; 1221 } 1222 } 1223 1224 /** {@hide} 1225 * Is this device in the process of being block encrypted? 1226 * @return true for encrypting. 1227 * false otherwise 1228 * Whether device isEncrypted at this point is undefined 1229 * Note that only system services and CryptKeeper will ever see this return 1230 * true - no app will ever be launched in this state. 1231 * Also note that this state will not change without a teardown of the 1232 * framework, so no service needs to check for changes during their lifespan 1233 */ 1234 public static boolean isBlockEncrypting() { 1235 final String state = SystemProperties.get("vold.encrypt_progress", ""); 1236 return !"".equalsIgnoreCase(state); 1237 } 1238 1239 /** {@hide} 1240 * Is this device non default block encrypted and in the process of 1241 * prompting for credentials? 1242 * @return true for prompting for credentials. 1243 * (Implies isNonDefaultBlockEncrypted() == true) 1244 * false otherwise 1245 * Note that only system services and CryptKeeper will ever see this return 1246 * true - no app will ever be launched in this state. 1247 * Also note that this state will not change without a teardown of the 1248 * framework, so no service needs to check for changes during their lifespan 1249 */ 1250 public static boolean inCryptKeeperBounce() { 1251 final String status = SystemProperties.get("vold.decrypt"); 1252 return "trigger_restart_min_framework".equals(status); 1253 } 1254 1255 /** {@hide} */ 1256 public static boolean isFileEncryptedEmulatedOnly() { 1257 return SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false); 1258 } 1259 1260 /** {@hide} 1261 * Is this device running in a file encrypted mode, either native or emulated? 1262 * @return true for file encrypted, false otherwise 1263 */ 1264 public static boolean isFileEncryptedNativeOrEmulated() { 1265 return isFileEncryptedNativeOnly() 1266 || isFileEncryptedEmulatedOnly(); 1267 } 1268 1269 /** {@hide} */ 1270 public static File maybeTranslateEmulatedPathToInternal(File path) { 1271 final IMountService mountService = IMountService.Stub.asInterface( 1272 ServiceManager.getService("mount")); 1273 try { 1274 final VolumeInfo[] vols = mountService.getVolumes(0); 1275 for (VolumeInfo vol : vols) { 1276 if ((vol.getType() == VolumeInfo.TYPE_EMULATED 1277 || vol.getType() == VolumeInfo.TYPE_PUBLIC) && vol.isMountedReadable()) { 1278 final File internalPath = FileUtils.rewriteAfterRename(vol.getPath(), 1279 vol.getInternalPath(), path); 1280 if (internalPath != null && internalPath.exists()) { 1281 return internalPath; 1282 } 1283 } 1284 } 1285 } catch (RemoteException e) { 1286 throw e.rethrowFromSystemServer(); 1287 } 1288 return path; 1289 } 1290 1291 /** {@hide} */ 1292 public ParcelFileDescriptor mountAppFuse(String name) { 1293 try { 1294 return mMountService.mountAppFuse(name); 1295 } catch (RemoteException e) { 1296 throw e.rethrowFromSystemServer(); 1297 } 1298 } 1299 1300 /// Consts to match the password types in cryptfs.h 1301 /** @hide */ 1302 public static final int CRYPT_TYPE_PASSWORD = 0; 1303 /** @hide */ 1304 public static final int CRYPT_TYPE_DEFAULT = 1; 1305 /** @hide */ 1306 public static final int CRYPT_TYPE_PATTERN = 2; 1307 /** @hide */ 1308 public static final int CRYPT_TYPE_PIN = 3; 1309 1310 // Constants for the data available via MountService.getField. 1311 /** @hide */ 1312 public static final String SYSTEM_LOCALE_KEY = "SystemLocale"; 1313 /** @hide */ 1314 public static final String OWNER_INFO_KEY = "OwnerInfo"; 1315 /** @hide */ 1316 public static final String PATTERN_VISIBLE_KEY = "PatternVisible"; 1317 /** @hide */ 1318 public static final String PASSWORD_VISIBLE_KEY = "PasswordVisible"; 1319} 1320