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