blob: 80dd48825ba7c02ec6f6426fb4f782c882ec5c83 [file] [log] [blame]
Aurimas Liutikas88c7ff12023-08-10 12:42:26 -07001/*
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.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.app.AppOpsManager.OP_LEGACY_STORAGE;
22import static android.app.AppOpsManager.OP_MANAGE_EXTERNAL_STORAGE;
23import static android.app.AppOpsManager.OP_READ_EXTERNAL_STORAGE;
24import static android.app.AppOpsManager.OP_READ_MEDIA_IMAGES;
25import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
26import static android.content.pm.PackageManager.PERMISSION_GRANTED;
27import static android.os.UserHandle.PER_USER_RANGE;
28
29import android.annotation.BytesLong;
30import android.annotation.CallbackExecutor;
31import android.annotation.IntDef;
32import android.annotation.NonNull;
33import android.annotation.Nullable;
34import android.annotation.RequiresPermission;
35import android.annotation.SdkConstant;
36import android.annotation.SuppressLint;
37import android.annotation.SystemApi;
38import android.annotation.SystemService;
39import android.annotation.TestApi;
40import android.annotation.WorkerThread;
41import android.app.Activity;
42import android.app.ActivityThread;
43import android.app.AppGlobals;
44import android.app.AppOpsManager;
45import android.app.PendingIntent;
46import android.compat.annotation.UnsupportedAppUsage;
47import android.content.ContentResolver;
48import android.content.Context;
49import android.content.Intent;
50import android.content.pm.ApplicationInfo;
51import android.content.pm.IPackageMoveObserver;
52import android.content.pm.PackageManager;
53import android.content.res.ObbInfo;
54import android.content.res.ObbScanner;
55import android.database.Cursor;
56import android.net.Uri;
57import android.os.Binder;
58import android.os.Build;
59import android.os.Environment;
60import android.os.FileUtils;
61import android.os.Handler;
62import android.os.IInstalld;
63import android.os.IVold;
64import android.os.IVoldTaskListener;
65import android.os.Looper;
66import android.os.Message;
67import android.os.ParcelFileDescriptor;
68import android.os.ParcelableException;
69import android.os.PersistableBundle;
70import android.os.ProxyFileDescriptorCallback;
71import android.os.RemoteException;
72import android.os.ServiceManager;
73import android.os.ServiceManager.ServiceNotFoundException;
74import android.os.SystemProperties;
75import android.os.UserHandle;
76import android.provider.DeviceConfig;
77import android.provider.MediaStore;
78import android.provider.Settings;
79import android.system.ErrnoException;
80import android.system.Os;
81import android.system.OsConstants;
82import android.text.TextUtils;
83import android.util.DataUnit;
84import android.util.Log;
85import android.util.Pair;
86import android.util.Slog;
87import android.util.SparseArray;
88
89import com.android.internal.annotations.GuardedBy;
90import com.android.internal.annotations.VisibleForTesting;
91import com.android.internal.logging.MetricsLogger;
92import com.android.internal.os.AppFuseMount;
93import com.android.internal.os.FuseAppLoop;
94import com.android.internal.os.FuseUnavailableMountException;
95import com.android.internal.os.RoSystemProperties;
96import com.android.internal.util.Preconditions;
97
98import dalvik.system.BlockGuard;
99
100import java.io.File;
101import java.io.FileDescriptor;
102import java.io.FileNotFoundException;
103import java.io.IOException;
104import java.lang.annotation.Retention;
105import java.lang.annotation.RetentionPolicy;
106import java.lang.ref.WeakReference;
107import java.nio.charset.StandardCharsets;
108import java.util.ArrayList;
109import java.util.Arrays;
110import java.util.Collections;
111import java.util.Iterator;
112import java.util.List;
113import java.util.Locale;
114import java.util.Objects;
115import java.util.UUID;
116import java.util.concurrent.CompletableFuture;
117import java.util.concurrent.Executor;
118import java.util.concurrent.ThreadFactory;
119import java.util.concurrent.TimeUnit;
120import java.util.concurrent.atomic.AtomicInteger;
121
122/**
123 * StorageManager is the interface to the systems storage service. The storage
124 * manager handles storage-related items such as Opaque Binary Blobs (OBBs).
125 * <p>
126 * OBBs contain a filesystem that maybe be encrypted on disk and mounted
127 * on-demand from an application. OBBs are a good way of providing large amounts
128 * of binary assets without packaging them into APKs as they may be multiple
129 * gigabytes in size. However, due to their size, they're most likely stored in
130 * a shared storage pool accessible from all programs. The system does not
131 * guarantee the security of the OBB file itself: if any program modifies the
132 * OBB, there is no guarantee that a read from that OBB will produce the
133 * expected output.
134 */
135@SystemService(Context.STORAGE_SERVICE)
136public class StorageManager {
137 private static final String TAG = "StorageManager";
138 private static final boolean LOCAL_LOGV = Log.isLoggable(TAG, Log.VERBOSE);
139
140 /** {@hide} */
141 public static final String PROP_PRIMARY_PHYSICAL = "ro.vold.primary_physical";
142 /** {@hide} */
143 public static final String PROP_HAS_ADOPTABLE = "vold.has_adoptable";
144 /** {@hide} */
145 public static final String PROP_HAS_RESERVED = "vold.has_reserved";
146 /** {@hide} */
147 public static final String PROP_ADOPTABLE = "persist.sys.adoptable";
148 /** {@hide} */
149 public static final String PROP_SDCARDFS = "persist.sys.sdcardfs";
150 /** {@hide} */
151 public static final String PROP_VIRTUAL_DISK = "persist.sys.virtual_disk";
152 /** {@hide} */
153 public static final String PROP_FORCED_SCOPED_STORAGE_WHITELIST =
154 "forced_scoped_storage_whitelist";
155
156 /** {@hide} */
157 public static final String UUID_PRIVATE_INTERNAL = null;
158 /** {@hide} */
159 public static final String UUID_PRIMARY_PHYSICAL = "primary_physical";
160 /** {@hide} */
161 public static final String UUID_SYSTEM = "system";
162
163 // NOTE: See comments around #convert for more details.
164 private static final String FAT_UUID_PREFIX = "fafafafa-fafa-5afa-8afa-fafa";
165
166 // NOTE: UUID constants below are namespaced
167 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad default
168 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad primary_physical
169 // uuid -v5 ad99aa3d-308e-4191-a200-ebcab371c0ad system
170
171 /**
172 * UUID representing the default internal storage of this device which
173 * provides {@link Environment#getDataDirectory()}.
174 * <p>
175 * This value is constant across all devices and it will never change, and
176 * thus it cannot be used to uniquely identify a particular physical device.
177 *
178 * @see #getUuidForPath(File)
179 * @see ApplicationInfo#storageUuid
180 */
181 public static final UUID UUID_DEFAULT = UUID
182 .fromString("41217664-9172-527a-b3d5-edabb50a7d69");
183
184 /** {@hide} */
185 public static final UUID UUID_PRIMARY_PHYSICAL_ = UUID
186 .fromString("0f95a519-dae7-5abf-9519-fbd6209e05fd");
187
188 /** {@hide} */
189 public static final UUID UUID_SYSTEM_ = UUID
190 .fromString("5d258386-e60d-59e3-826d-0089cdd42cc0");
191
192 /**
193 * Activity Action: Allows the user to manage their storage. This activity
194 * provides the ability to free up space on the device by deleting data such
195 * as apps.
196 * <p>
197 * If the sending application has a specific storage device or allocation
198 * size in mind, they can optionally define {@link #EXTRA_UUID} or
199 * {@link #EXTRA_REQUESTED_BYTES}, respectively.
200 * <p>
201 * This intent should be launched using
202 * {@link Activity#startActivityForResult(Intent, int)} so that the user
203 * knows which app is requesting the storage space. The returned result will
204 * be {@link Activity#RESULT_OK} if the requested space was made available,
205 * or {@link Activity#RESULT_CANCELED} otherwise.
206 */
207 @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
208 public static final String ACTION_MANAGE_STORAGE = "android.os.storage.action.MANAGE_STORAGE";
209
210 /**
211 * Activity Action: Allows the user to free up space by clearing app external cache directories.
212 * The intent doesn't automatically clear cache, but shows a dialog and lets the user decide.
213 * <p>
214 * This intent should be launched using
215 * {@link Activity#startActivityForResult(Intent, int)} so that the user
216 * knows which app is requesting to clear cache. The returned result will be:
217 * {@link Activity#RESULT_OK} if the activity was launched and all cache was cleared,
218 * {@link OsConstants#EIO} if an error occurred while clearing the cache or
219 * {@link Activity#RESULT_CANCELED} otherwise.
220 */
221 @RequiresPermission(android.Manifest.permission.MANAGE_EXTERNAL_STORAGE)
222 @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
223 public static final String ACTION_CLEAR_APP_CACHE = "android.os.storage.action.CLEAR_APP_CACHE";
224
225 /**
226 * Extra {@link UUID} used to indicate the storage volume where an
227 * application is interested in allocating or managing disk space.
228 *
229 * @see #ACTION_MANAGE_STORAGE
230 * @see #UUID_DEFAULT
231 * @see #getUuidForPath(File)
232 * @see Intent#putExtra(String, java.io.Serializable)
233 */
234 public static final String EXTRA_UUID = "android.os.storage.extra.UUID";
235
236 /**
237 * Extra used to indicate the total size (in bytes) that an application is
238 * interested in allocating.
239 * <p>
240 * When defined, the management UI will help guide the user to free up
241 * enough disk space to reach this requested value.
242 *
243 * @see #ACTION_MANAGE_STORAGE
244 */
245 public static final String EXTRA_REQUESTED_BYTES = "android.os.storage.extra.REQUESTED_BYTES";
246
247 /** {@hide} */
248 public static final int DEBUG_ADOPTABLE_FORCE_ON = 1 << 0;
249 /** {@hide} */
250 public static final int DEBUG_ADOPTABLE_FORCE_OFF = 1 << 1;
251 /** {@hide} */
252 public static final int DEBUG_SDCARDFS_FORCE_ON = 1 << 2;
253 /** {@hide} */
254 public static final int DEBUG_SDCARDFS_FORCE_OFF = 1 << 3;
255 /** {@hide} */
256 public static final int DEBUG_VIRTUAL_DISK = 1 << 4;
257
258 /** {@hide} */
259 public static final int FLAG_STORAGE_DE = IInstalld.FLAG_STORAGE_DE;
260 /** {@hide} */
261 public static final int FLAG_STORAGE_CE = IInstalld.FLAG_STORAGE_CE;
262 /** {@hide} */
263 public static final int FLAG_STORAGE_EXTERNAL = IInstalld.FLAG_STORAGE_EXTERNAL;
264 /** @hide */
265 public static final int FLAG_STORAGE_SDK = IInstalld.FLAG_STORAGE_SDK;
266
267 /** {@hide} */
268 @IntDef(prefix = "FLAG_STORAGE_", value = {
269 FLAG_STORAGE_DE,
270 FLAG_STORAGE_CE,
271 FLAG_STORAGE_EXTERNAL,
272 FLAG_STORAGE_SDK,
273 })
274 @Retention(RetentionPolicy.SOURCE)
275 public @interface StorageFlags {}
276
277 /** {@hide} */
278 public static final int FLAG_FOR_WRITE = 1 << 8;
279 /** {@hide} */
280 public static final int FLAG_REAL_STATE = 1 << 9;
281 /** {@hide} */
282 public static final int FLAG_INCLUDE_INVISIBLE = 1 << 10;
283 /** {@hide} */
284 public static final int FLAG_INCLUDE_RECENT = 1 << 11;
285 /** {@hide} */
286 public static final int FLAG_INCLUDE_SHARED_PROFILE = 1 << 12;
287
288 /** {@hide} */
289 public static final int FSTRIM_FLAG_DEEP = IVold.FSTRIM_FLAG_DEEP_TRIM;
290
291 /** @hide The volume is not encrypted. */
292 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
293 public static final int ENCRYPTION_STATE_NONE = 1;
294
295 private static volatile IStorageManager sStorageManager = null;
296
297 private final Context mContext;
298 private final ContentResolver mResolver;
299
300 private final IStorageManager mStorageManager;
301 private final AppOpsManager mAppOps;
302 private final Looper mLooper;
303 private final AtomicInteger mNextNonce = new AtomicInteger(0);
304
305 @GuardedBy("mDelegates")
306 private final ArrayList<StorageEventListenerDelegate> mDelegates = new ArrayList<>();
307
308 private class StorageEventListenerDelegate extends IStorageEventListener.Stub {
309 final Executor mExecutor;
310 final StorageEventListener mListener;
311 final StorageVolumeCallback mCallback;
312
313 public StorageEventListenerDelegate(@NonNull Executor executor,
314 @NonNull StorageEventListener listener, @NonNull StorageVolumeCallback callback) {
315 mExecutor = executor;
316 mListener = listener;
317 mCallback = callback;
318 }
319
320 @Override
321 public void onUsbMassStorageConnectionChanged(boolean connected) throws RemoteException {
322 mExecutor.execute(() -> {
323 mListener.onUsbMassStorageConnectionChanged(connected);
324 });
325 }
326
327 @Override
328 public void onStorageStateChanged(String path, String oldState, String newState) {
329 mExecutor.execute(() -> {
330 mListener.onStorageStateChanged(path, oldState, newState);
331
332 if (path != null) {
333 for (StorageVolume sv : getStorageVolumes()) {
334 if (Objects.equals(path, sv.getPath())) {
335 mCallback.onStateChanged(sv);
336 }
337 }
338 }
339 });
340 }
341
342 @Override
343 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
344 mExecutor.execute(() -> {
345 mListener.onVolumeStateChanged(vol, oldState, newState);
346
347 final File path = vol.getPathForUser(UserHandle.myUserId());
348 if (path != null) {
349 for (StorageVolume sv : getStorageVolumes()) {
350 if (Objects.equals(path.getAbsolutePath(), sv.getPath())) {
351 mCallback.onStateChanged(sv);
352 }
353 }
354 }
355 });
356 }
357
358 @Override
359 public void onVolumeRecordChanged(VolumeRecord rec) {
360 mExecutor.execute(() -> {
361 mListener.onVolumeRecordChanged(rec);
362 });
363 }
364
365 @Override
366 public void onVolumeForgotten(String fsUuid) {
367 mExecutor.execute(() -> {
368 mListener.onVolumeForgotten(fsUuid);
369 });
370 }
371
372 @Override
373 public void onDiskScanned(DiskInfo disk, int volumeCount) {
374 mExecutor.execute(() -> {
375 mListener.onDiskScanned(disk, volumeCount);
376 });
377 }
378
379 @Override
380 public void onDiskDestroyed(DiskInfo disk) throws RemoteException {
381 mExecutor.execute(() -> {
382 mListener.onDiskDestroyed(disk);
383 });
384 }
385 }
386
387 /**
388 * Binder listener for OBB action results.
389 */
390 private final ObbActionListener mObbActionListener = new ObbActionListener();
391
392 private class ObbActionListener extends IObbActionListener.Stub {
393 @SuppressWarnings("hiding")
394 private SparseArray<ObbListenerDelegate> mListeners = new SparseArray<ObbListenerDelegate>();
395
396 @Override
397 public void onObbResult(String filename, int nonce, int status) {
398 final ObbListenerDelegate delegate;
399 synchronized (mListeners) {
400 delegate = mListeners.get(nonce);
401 if (delegate != null) {
402 mListeners.remove(nonce);
403 }
404 }
405
406 if (delegate != null) {
407 delegate.sendObbStateChanged(filename, status);
408 }
409 }
410
411 public int addListener(OnObbStateChangeListener listener) {
412 final ObbListenerDelegate delegate = new ObbListenerDelegate(listener);
413
414 synchronized (mListeners) {
415 mListeners.put(delegate.nonce, delegate);
416 }
417
418 return delegate.nonce;
419 }
420 }
421
422 private int getNextNonce() {
423 return mNextNonce.getAndIncrement();
424 }
425
426 /**
427 * Private class containing sender and receiver code for StorageEvents.
428 */
429 private class ObbListenerDelegate {
430 private final WeakReference<OnObbStateChangeListener> mObbEventListenerRef;
431 private final Handler mHandler;
432
433 private final int nonce;
434
435 ObbListenerDelegate(OnObbStateChangeListener listener) {
436 nonce = getNextNonce();
437 mObbEventListenerRef = new WeakReference<OnObbStateChangeListener>(listener);
438 mHandler = new Handler(mLooper) {
439 @Override
440 public void handleMessage(Message msg) {
441 final OnObbStateChangeListener changeListener = getListener();
442 if (changeListener == null) {
443 return;
444 }
445
446 changeListener.onObbStateChange((String) msg.obj, msg.arg1);
447 }
448 };
449 }
450
451 OnObbStateChangeListener getListener() {
452 if (mObbEventListenerRef == null) {
453 return null;
454 }
455 return mObbEventListenerRef.get();
456 }
457
458 void sendObbStateChanged(String path, int state) {
459 mHandler.obtainMessage(0, state, 0, path).sendToTarget();
460 }
461 }
462
463 /** {@hide} */
464 @Deprecated
465 @UnsupportedAppUsage
466 public static StorageManager from(Context context) {
467 return context.getSystemService(StorageManager.class);
468 }
469
470 /**
471 * Constructs a StorageManager object through which an application can
472 * can communicate with the systems mount service.
473 *
474 * @param looper The {@link android.os.Looper} which events will be received on.
475 *
476 * <p>Applications can get instance of this class by calling
477 * {@link android.content.Context#getSystemService(java.lang.String)} with an argument
478 * of {@link android.content.Context#STORAGE_SERVICE}.
479 *
480 * @hide
481 */
482 @UnsupportedAppUsage
483 public StorageManager(Context context, Looper looper) throws ServiceNotFoundException {
484 mContext = context;
485 mResolver = context.getContentResolver();
486 mLooper = looper;
487 mStorageManager = IStorageManager.Stub.asInterface(ServiceManager.getServiceOrThrow("mount"));
488 mAppOps = mContext.getSystemService(AppOpsManager.class);
489 }
490
491 /**
492 * Registers a {@link android.os.storage.StorageEventListener StorageEventListener}.
493 *
494 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
495 *
496 * @hide
497 */
498 @UnsupportedAppUsage
499 public void registerListener(StorageEventListener listener) {
500 synchronized (mDelegates) {
501 final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(
502 mContext.getMainExecutor(), listener, new StorageVolumeCallback());
503 try {
504 mStorageManager.registerListener(delegate);
505 } catch (RemoteException e) {
506 throw e.rethrowFromSystemServer();
507 }
508 mDelegates.add(delegate);
509 }
510 }
511
512 /**
513 * Unregisters a {@link android.os.storage.StorageEventListener StorageEventListener}.
514 *
515 * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
516 *
517 * @hide
518 */
519 @UnsupportedAppUsage
520 public void unregisterListener(StorageEventListener listener) {
521 synchronized (mDelegates) {
522 for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) {
523 final StorageEventListenerDelegate delegate = i.next();
524 if (delegate.mListener == listener) {
525 try {
526 mStorageManager.unregisterListener(delegate);
527 } catch (RemoteException e) {
528 throw e.rethrowFromSystemServer();
529 }
530 i.remove();
531 }
532 }
533 }
534 }
535
536 /**
537 * Callback that delivers {@link StorageVolume} related events.
538 * <p>
539 * For example, this can be used to detect when a volume changes to the
540 * {@link Environment#MEDIA_MOUNTED} or {@link Environment#MEDIA_UNMOUNTED}
541 * states.
542 *
543 * @see StorageManager#registerStorageVolumeCallback
544 * @see StorageManager#unregisterStorageVolumeCallback
545 */
546 public static class StorageVolumeCallback {
547 /**
548 * Called when {@link StorageVolume#getState()} changes, such as
549 * changing to the {@link Environment#MEDIA_MOUNTED} or
550 * {@link Environment#MEDIA_UNMOUNTED} states.
551 * <p>
552 * The given argument is a snapshot in time and can be used to process
553 * events in the order they occurred, or you can call
554 * {@link StorageManager#getStorageVolumes()} to observe the latest
555 * value.
556 */
557 public void onStateChanged(@NonNull StorageVolume volume) { }
558 }
559
560 /**
561 * Registers the given callback to listen for {@link StorageVolume} changes.
562 * <p>
563 * For example, this can be used to detect when a volume changes to the
564 * {@link Environment#MEDIA_MOUNTED} or {@link Environment#MEDIA_UNMOUNTED}
565 * states.
566 *
567 * @see StorageManager#unregisterStorageVolumeCallback
568 */
569 public void registerStorageVolumeCallback(@CallbackExecutor @NonNull Executor executor,
570 @NonNull StorageVolumeCallback callback) {
571 synchronized (mDelegates) {
572 final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(
573 executor, new StorageEventListener(), callback);
574 try {
575 mStorageManager.registerListener(delegate);
576 } catch (RemoteException e) {
577 throw e.rethrowFromSystemServer();
578 }
579 mDelegates.add(delegate);
580 }
581 }
582
583 /**
584 * Unregisters the given callback from listening for {@link StorageVolume}
585 * changes.
586 *
587 * @see StorageManager#registerStorageVolumeCallback
588 */
589 public void unregisterStorageVolumeCallback(@NonNull StorageVolumeCallback callback) {
590 synchronized (mDelegates) {
591 for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) {
592 final StorageEventListenerDelegate delegate = i.next();
593 if (delegate.mCallback == callback) {
594 try {
595 mStorageManager.unregisterListener(delegate);
596 } catch (RemoteException e) {
597 throw e.rethrowFromSystemServer();
598 }
599 i.remove();
600 }
601 }
602 }
603 }
604
605 /**
606 * Enables USB Mass Storage (UMS) on the device.
607 *
608 * @hide
609 */
610 @Deprecated
611 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
612 public void enableUsbMassStorage() {
613 }
614
615 /**
616 * Disables USB Mass Storage (UMS) on the device.
617 *
618 * @hide
619 */
620 @Deprecated
621 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
622 public void disableUsbMassStorage() {
623 }
624
625 /**
626 * Query if a USB Mass Storage (UMS) host is connected.
627 * @return true if UMS host is connected.
628 *
629 * @hide
630 */
631 @Deprecated
632 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
633 public boolean isUsbMassStorageConnected() {
634 return false;
635 }
636
637 /**
638 * Query if a USB Mass Storage (UMS) is enabled on the device.
639 * @return true if UMS host is enabled.
640 *
641 * @hide
642 */
643 @Deprecated
644 @UnsupportedAppUsage
645 public boolean isUsbMassStorageEnabled() {
646 return false;
647 }
648
649 /**
650 * Mount an Opaque Binary Blob (OBB) file.
651 * <p>
652 * The OBB will remain mounted for as long as the StorageManager reference
653 * is held by the application. As soon as this reference is lost, the OBBs
654 * in use will be unmounted. The {@link OnObbStateChangeListener} registered
655 * with this call will receive the success or failure of this operation.
656 * <p>
657 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
658 * file matches a package ID that is owned by the calling program's UID.
659 * That is, shared UID applications can attempt to mount any other
660 * application's OBB that shares its UID.
661 *
662 * @param rawPath the path to the OBB file
663 * @param key must be <code>null</code>. Previously, some Android device
664 * implementations accepted a non-<code>null</code> key to mount
665 * an encrypted OBB file. However, this never worked reliably and
666 * is no longer supported.
667 * @param listener will receive the success or failure of the operation
668 * @return whether the mount call was successfully queued or not
669 */
670 public boolean mountObb(String rawPath, String key, OnObbStateChangeListener listener) {
671 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
672 Preconditions.checkArgument(key == null, "mounting encrypted OBBs is no longer supported");
673 Preconditions.checkNotNull(listener, "listener cannot be null");
674
675 try {
676 final String canonicalPath = new File(rawPath).getCanonicalPath();
677 final int nonce = mObbActionListener.addListener(listener);
678 mStorageManager.mountObb(rawPath, canonicalPath, mObbActionListener, nonce,
679 getObbInfo(canonicalPath));
680 return true;
681 } catch (IOException e) {
682 throw new IllegalArgumentException("Failed to resolve path: " + rawPath, e);
683 } catch (RemoteException e) {
684 throw e.rethrowFromSystemServer();
685 }
686 }
687
688 /**
689 * Returns a {@link PendingIntent} that can be used by Apps with
690 * {@link android.Manifest.permission#MANAGE_EXTERNAL_STORAGE} permission
691 * to launch the manageSpaceActivity for any App that implements it, irrespective of its
692 * exported status.
693 * <p>
694 * Caller has the responsibility of supplying a valid packageName which has
695 * manageSpaceActivity implemented.
696 *
697 * @param packageName package name for the App for which manageSpaceActivity is to be launched
698 * @param requestCode for launching the activity
699 * @return PendingIntent to launch the manageSpaceActivity if successful, null if the
700 * packageName doesn't have a manageSpaceActivity.
701 * @throws IllegalArgumentException an invalid packageName is supplied.
702 */
703 @RequiresPermission(android.Manifest.permission.MANAGE_EXTERNAL_STORAGE)
704 @Nullable
705 public PendingIntent getManageSpaceActivityIntent(
706 @NonNull String packageName, int requestCode) {
707 try {
708 return mStorageManager.getManageSpaceActivityIntent(packageName,
709 requestCode);
710 } catch (RemoteException e) {
711 throw e.rethrowFromSystemServer();
712 }
713 }
714
715 private ObbInfo getObbInfo(String canonicalPath) {
716 try {
717 final ObbInfo obbInfo = ObbScanner.getObbInfo(canonicalPath);
718 return obbInfo;
719 } catch (IOException e) {
720 throw new IllegalArgumentException("Couldn't get OBB info for " + canonicalPath, e);
721 }
722 }
723
724 /**
725 * Unmount an Opaque Binary Blob (OBB) file asynchronously. If the
726 * <code>force</code> flag is true, it will kill any application needed to
727 * unmount the given OBB (even the calling application).
728 * <p>
729 * The {@link OnObbStateChangeListener} registered with this call will
730 * receive the success or failure of this operation.
731 * <p>
732 * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
733 * file matches a package ID that is owned by the calling program's UID.
734 * That is, shared UID applications can obtain access to any other
735 * application's OBB that shares its UID.
736 * <p>
737 *
738 * @param rawPath path to the OBB file
739 * @param force whether to kill any programs using this in order to unmount
740 * it
741 * @param listener will receive the success or failure of the operation
742 * @return whether the unmount call was successfully queued or not
743 */
744 public boolean unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener) {
745 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
746 Preconditions.checkNotNull(listener, "listener cannot be null");
747
748 try {
749 final int nonce = mObbActionListener.addListener(listener);
750 mStorageManager.unmountObb(rawPath, force, mObbActionListener, nonce);
751 return true;
752 } catch (RemoteException e) {
753 throw e.rethrowFromSystemServer();
754 }
755 }
756
757 /**
758 * Check whether an Opaque Binary Blob (OBB) is mounted or not.
759 *
760 * @param rawPath path to OBB image
761 * @return true if OBB is mounted; false if not mounted or on error
762 */
763 public boolean isObbMounted(String rawPath) {
764 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
765
766 try {
767 return mStorageManager.isObbMounted(rawPath);
768 } catch (RemoteException e) {
769 throw e.rethrowFromSystemServer();
770 }
771 }
772
773 /**
774 * Check the mounted path of an Opaque Binary Blob (OBB) file. This will
775 * give you the path to where you can obtain access to the internals of the
776 * OBB.
777 *
778 * @param rawPath path to OBB image
779 * @return absolute path to mounted OBB image data or <code>null</code> if
780 * not mounted or exception encountered trying to read status
781 */
782 public String getMountedObbPath(String rawPath) {
783 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
784
785 try {
786 return mStorageManager.getMountedObbPath(rawPath);
787 } catch (RemoteException e) {
788 throw e.rethrowFromSystemServer();
789 }
790 }
791
792 /** {@hide} */
793 @UnsupportedAppUsage
794 public @NonNull List<DiskInfo> getDisks() {
795 try {
796 return Arrays.asList(mStorageManager.getDisks());
797 } catch (RemoteException e) {
798 throw e.rethrowFromSystemServer();
799 }
800 }
801
802 /** {@hide} */
803 @UnsupportedAppUsage
804 public @Nullable DiskInfo findDiskById(String id) {
805 Preconditions.checkNotNull(id);
806 // TODO; go directly to service to make this faster
807 for (DiskInfo disk : getDisks()) {
808 if (Objects.equals(disk.id, id)) {
809 return disk;
810 }
811 }
812 return null;
813 }
814
815 /** {@hide} */
816 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
817 public @Nullable VolumeInfo findVolumeById(String id) {
818 Preconditions.checkNotNull(id);
819 // TODO; go directly to service to make this faster
820 for (VolumeInfo vol : getVolumes()) {
821 if (Objects.equals(vol.id, id)) {
822 return vol;
823 }
824 }
825 return null;
826 }
827
828 /** {@hide} */
829 @UnsupportedAppUsage
830 public @Nullable VolumeInfo findVolumeByUuid(String fsUuid) {
831 Preconditions.checkNotNull(fsUuid);
832 // TODO; go directly to service to make this faster
833 for (VolumeInfo vol : getVolumes()) {
834 if (Objects.equals(vol.fsUuid, fsUuid)) {
835 return vol;
836 }
837 }
838 return null;
839 }
840
841 /** {@hide} */
842 public @Nullable VolumeRecord findRecordByUuid(String fsUuid) {
843 Preconditions.checkNotNull(fsUuid);
844 // TODO; go directly to service to make this faster
845 for (VolumeRecord rec : getVolumeRecords()) {
846 if (Objects.equals(rec.fsUuid, fsUuid)) {
847 return rec;
848 }
849 }
850 return null;
851 }
852
853 /** {@hide} */
854 public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) {
855 if (emulatedVol != null) {
856 String id = emulatedVol.getId();
857 int idx = id.indexOf(";");
858 if (idx != -1) {
859 id = id.substring(0, idx);
860 }
861 return findVolumeById(id.replace("emulated", "private"));
862 } else {
863 return null;
864 }
865 }
866
867 /** {@hide} */
868 @UnsupportedAppUsage
869 public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) {
870 if (privateVol != null) {
871 return findVolumeById(privateVol.getId().replace("private", "emulated") + ";"
872 + mContext.getUserId());
873 } else {
874 return null;
875 }
876 }
877
878 /** {@hide} */
879 public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) {
880 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
881 return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
882 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
883 return getPrimaryPhysicalVolume();
884 } else {
885 return findVolumeByUuid(volumeUuid);
886 }
887 }
888
889 /**
890 * Return a UUID identifying the storage volume that hosts the given
891 * filesystem path.
892 * <p>
893 * If this path is hosted by the default internal storage of the device at
894 * {@link Environment#getDataDirectory()}, the returned value will be
895 * {@link #UUID_DEFAULT}.
896 *
897 * @throws IOException when the storage device hosting the given path isn't
898 * present, or when it doesn't have a valid UUID.
899 */
900 public @NonNull UUID getUuidForPath(@NonNull File path) throws IOException {
901 Preconditions.checkNotNull(path);
902 final String pathString = path.getCanonicalPath();
903 if (FileUtils.contains(Environment.getDataDirectory().getAbsolutePath(), pathString)) {
904 return UUID_DEFAULT;
905 }
906 try {
907 for (VolumeInfo vol : mStorageManager.getVolumes(0)) {
908 if (vol.path != null && FileUtils.contains(vol.path, pathString)
909 && vol.type != VolumeInfo.TYPE_PUBLIC && vol.type != VolumeInfo.TYPE_STUB) {
910 // TODO: verify that emulated adopted devices have UUID of
911 // underlying volume
912 try {
913 return convert(vol.fsUuid);
914 } catch (IllegalArgumentException e) {
915 continue;
916 }
917 }
918 }
919 } catch (RemoteException e) {
920 throw e.rethrowFromSystemServer();
921 }
922 throw new FileNotFoundException("Failed to find a storage device for " + path);
923 }
924
925 /** {@hide} */
926 public @NonNull File findPathForUuid(String volumeUuid) throws FileNotFoundException {
927 final VolumeInfo vol = findVolumeByQualifiedUuid(volumeUuid);
928 if (vol != null) {
929 return vol.getPath();
930 }
931 throw new FileNotFoundException("Failed to find a storage device for " + volumeUuid);
932 }
933
934 /**
935 * Test if the given file descriptor supports allocation of disk space using
936 * {@link #allocateBytes(FileDescriptor, long)}.
937 */
938 public boolean isAllocationSupported(@NonNull FileDescriptor fd) {
939 try {
940 getUuidForPath(ParcelFileDescriptor.getFile(fd));
941 return true;
942 } catch (IOException e) {
943 return false;
944 }
945 }
946
947 /** {@hide} */
948 @UnsupportedAppUsage
949 public @NonNull List<VolumeInfo> getVolumes() {
950 try {
951 return Arrays.asList(mStorageManager.getVolumes(0));
952 } catch (RemoteException e) {
953 throw e.rethrowFromSystemServer();
954 }
955 }
956
957 /** {@hide} */
958 public @NonNull List<VolumeInfo> getWritablePrivateVolumes() {
959 try {
960 final ArrayList<VolumeInfo> res = new ArrayList<>();
961 for (VolumeInfo vol : mStorageManager.getVolumes(0)) {
962 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
963 res.add(vol);
964 }
965 }
966 return res;
967 } catch (RemoteException e) {
968 throw e.rethrowFromSystemServer();
969 }
970 }
971
972 /** {@hide} */
973 public @NonNull List<VolumeRecord> getVolumeRecords() {
974 try {
975 return Arrays.asList(mStorageManager.getVolumeRecords(0));
976 } catch (RemoteException e) {
977 throw e.rethrowFromSystemServer();
978 }
979 }
980
981 /** {@hide} */
982 @UnsupportedAppUsage
983 public @Nullable String getBestVolumeDescription(VolumeInfo vol) {
984 if (vol == null) return null;
985
986 // Nickname always takes precedence when defined
987 if (!TextUtils.isEmpty(vol.fsUuid)) {
988 final VolumeRecord rec = findRecordByUuid(vol.fsUuid);
989 if (rec != null && !TextUtils.isEmpty(rec.nickname)) {
990 return rec.nickname;
991 }
992 }
993
994 if (!TextUtils.isEmpty(vol.getDescription())) {
995 return vol.getDescription();
996 }
997
998 if (vol.disk != null) {
999 return vol.disk.getDescription();
1000 }
1001
1002 return null;
1003 }
1004
1005 /** {@hide} */
1006 @UnsupportedAppUsage
1007 public @Nullable VolumeInfo getPrimaryPhysicalVolume() {
1008 final List<VolumeInfo> vols = getVolumes();
1009 for (VolumeInfo vol : vols) {
1010 if (vol.isPrimaryPhysical()) {
1011 return vol;
1012 }
1013 }
1014 return null;
1015 }
1016
1017 /** {@hide} */
1018 public void mount(String volId) {
1019 try {
1020 mStorageManager.mount(volId);
1021 } catch (RemoteException e) {
1022 throw e.rethrowFromSystemServer();
1023 }
1024 }
1025
1026 /** {@hide} */
1027 @UnsupportedAppUsage
1028 public void unmount(String volId) {
1029 try {
1030 mStorageManager.unmount(volId);
1031 } catch (RemoteException e) {
1032 throw e.rethrowFromSystemServer();
1033 }
1034 }
1035
1036 /** {@hide} */
1037 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1038 public void format(String volId) {
1039 try {
1040 mStorageManager.format(volId);
1041 } catch (RemoteException e) {
1042 throw e.rethrowFromSystemServer();
1043 }
1044 }
1045
1046 /** {@hide} */
1047 @Deprecated
1048 public long benchmark(String volId) {
1049 final CompletableFuture<PersistableBundle> result = new CompletableFuture<>();
1050 benchmark(volId, new IVoldTaskListener.Stub() {
1051 @Override
1052 public void onStatus(int status, PersistableBundle extras) {
1053 // Ignored
1054 }
1055
1056 @Override
1057 public void onFinished(int status, PersistableBundle extras) {
1058 result.complete(extras);
1059 }
1060 });
1061 try {
1062 // Convert ms to ns
1063 return result.get(3, TimeUnit.MINUTES).getLong("run", Long.MAX_VALUE) * 1000000;
1064 } catch (Exception e) {
1065 return Long.MAX_VALUE;
1066 }
1067 }
1068
1069 /** {@hide} */
1070 public void benchmark(String volId, IVoldTaskListener listener) {
1071 try {
1072 mStorageManager.benchmark(volId, listener);
1073 } catch (RemoteException e) {
1074 throw e.rethrowFromSystemServer();
1075 }
1076 }
1077
1078 /** {@hide} */
1079 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1080 public void partitionPublic(String diskId) {
1081 try {
1082 mStorageManager.partitionPublic(diskId);
1083 } catch (RemoteException e) {
1084 throw e.rethrowFromSystemServer();
1085 }
1086 }
1087
1088 /** {@hide} */
1089 public void partitionPrivate(String diskId) {
1090 try {
1091 mStorageManager.partitionPrivate(diskId);
1092 } catch (RemoteException e) {
1093 throw e.rethrowFromSystemServer();
1094 }
1095 }
1096
1097 /** {@hide} */
1098 public void partitionMixed(String diskId, int ratio) {
1099 try {
1100 mStorageManager.partitionMixed(diskId, ratio);
1101 } catch (RemoteException e) {
1102 throw e.rethrowFromSystemServer();
1103 }
1104 }
1105
1106 /** {@hide} */
1107 public void wipeAdoptableDisks() {
1108 // We only wipe devices in "adoptable" locations, which are in a
1109 // long-term stable slot/location on the device, where apps have a
1110 // reasonable chance of storing sensitive data. (Apps need to go through
1111 // SAF to write to transient volumes.)
1112 final List<DiskInfo> disks = getDisks();
1113 for (DiskInfo disk : disks) {
1114 final String diskId = disk.getId();
1115 if (disk.isAdoptable()) {
1116 Slog.d(TAG, "Found adoptable " + diskId + "; wiping");
1117 try {
1118 // TODO: switch to explicit wipe command when we have it,
1119 // for now rely on the fact that vfat format does a wipe
1120 mStorageManager.partitionPublic(diskId);
1121 } catch (Exception e) {
1122 Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e);
1123 }
1124 } else {
1125 Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId());
1126 }
1127 }
1128 }
1129
1130 /** {@hide} */
1131 public void setVolumeNickname(String fsUuid, String nickname) {
1132 try {
1133 mStorageManager.setVolumeNickname(fsUuid, nickname);
1134 } catch (RemoteException e) {
1135 throw e.rethrowFromSystemServer();
1136 }
1137 }
1138
1139 /** {@hide} */
1140 public void setVolumeInited(String fsUuid, boolean inited) {
1141 try {
1142 mStorageManager.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0,
1143 VolumeRecord.USER_FLAG_INITED);
1144 } catch (RemoteException e) {
1145 throw e.rethrowFromSystemServer();
1146 }
1147 }
1148
1149 /** {@hide} */
1150 public void setVolumeSnoozed(String fsUuid, boolean snoozed) {
1151 try {
1152 mStorageManager.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0,
1153 VolumeRecord.USER_FLAG_SNOOZED);
1154 } catch (RemoteException e) {
1155 throw e.rethrowFromSystemServer();
1156 }
1157 }
1158
1159 /** {@hide} */
1160 public void forgetVolume(String fsUuid) {
1161 try {
1162 mStorageManager.forgetVolume(fsUuid);
1163 } catch (RemoteException e) {
1164 throw e.rethrowFromSystemServer();
1165 }
1166 }
1167
1168 /**
1169 * This is not the API you're looking for.
1170 *
1171 * @see PackageManager#getPrimaryStorageCurrentVolume()
1172 * @hide
1173 */
1174 public String getPrimaryStorageUuid() {
1175 try {
1176 return mStorageManager.getPrimaryStorageUuid();
1177 } catch (RemoteException e) {
1178 throw e.rethrowFromSystemServer();
1179 }
1180 }
1181
1182 /**
1183 * This is not the API you're looking for.
1184 *
1185 * @see PackageManager#movePrimaryStorage(VolumeInfo)
1186 * @hide
1187 */
1188 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
1189 try {
1190 mStorageManager.setPrimaryStorageUuid(volumeUuid, callback);
1191 } catch (RemoteException e) {
1192 throw e.rethrowFromSystemServer();
1193 }
1194 }
1195
1196 /**
1197 * Return the {@link StorageVolume} that contains the given file, or
1198 * {@code null} if none.
1199 */
1200 public @Nullable StorageVolume getStorageVolume(@NonNull File file) {
1201 return getStorageVolume(getVolumeList(), file);
1202 }
1203
1204 /**
1205 * Return the {@link StorageVolume} that contains the given
1206 * {@link MediaStore} item.
1207 */
1208 public @NonNull StorageVolume getStorageVolume(@NonNull Uri uri) {
1209 String volumeName = MediaStore.getVolumeName(uri);
1210
1211 // When Uri is pointing at a synthetic volume, we're willing to query to
1212 // resolve the actual volume name
1213 if (Objects.equals(volumeName, MediaStore.VOLUME_EXTERNAL)) {
1214 try (Cursor c = mContext.getContentResolver().query(uri,
1215 new String[] { MediaStore.MediaColumns.VOLUME_NAME }, null, null)) {
1216 if (c.moveToFirst()) {
1217 volumeName = c.getString(0);
1218 }
1219 }
1220 }
1221
1222 switch (volumeName) {
1223 case MediaStore.VOLUME_EXTERNAL_PRIMARY:
1224 return getPrimaryStorageVolume();
1225 default:
1226 for (StorageVolume vol : getStorageVolumes()) {
1227 if (Objects.equals(vol.getMediaStoreVolumeName(), volumeName)) {
1228 return vol;
1229 }
1230 }
1231 }
1232 throw new IllegalStateException("Unknown volume for " + uri);
1233 }
1234
1235 /** {@hide} */
1236 public static @Nullable StorageVolume getStorageVolume(File file, int userId) {
1237 return getStorageVolume(getVolumeList(userId, 0), file);
1238 }
1239
1240 /** {@hide} */
1241 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1242 private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) {
1243 if (file == null) {
1244 return null;
1245 }
1246 final String path = file.getAbsolutePath();
1247 if (path.startsWith(DEPRECATE_DATA_PREFIX)) {
1248 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
1249 return AppGlobals.getInitialApplication().getSystemService(StorageManager.class)
1250 .getStorageVolume(uri);
1251 }
1252 try {
1253 file = file.getCanonicalFile();
1254 } catch (IOException ignored) {
1255 Slog.d(TAG, "Could not get canonical path for " + file);
1256 return null;
1257 }
1258 for (StorageVolume volume : volumes) {
1259 File volumeFile = volume.getPathFile();
1260 try {
1261 volumeFile = volumeFile.getCanonicalFile();
1262 } catch (IOException ignored) {
1263 continue;
1264 }
1265 if (FileUtils.contains(volumeFile, file)) {
1266 return volume;
1267 }
1268 }
1269 return null;
1270 }
1271
1272 /**
1273 * Gets the state of a volume via its mountpoint.
1274 * @hide
1275 */
1276 @Deprecated
1277 @UnsupportedAppUsage
1278 public @NonNull String getVolumeState(String mountPoint) {
1279 final StorageVolume vol = getStorageVolume(new File(mountPoint));
1280 if (vol != null) {
1281 return vol.getState();
1282 } else {
1283 return Environment.MEDIA_UNKNOWN;
1284 }
1285 }
1286
1287 /**
1288 * Return the list of shared/external storage volumes currently available to
1289 * the calling user.
1290 * <p>
1291 * These storage volumes are actively attached to the device, but may be in
1292 * any mount state, as returned by {@link StorageVolume#getState()}. Returns
1293 * both the primary shared storage device and any attached external volumes,
1294 * including SD cards and USB drives.
1295 */
1296 public @NonNull List<StorageVolume> getStorageVolumes() {
1297 final ArrayList<StorageVolume> res = new ArrayList<>();
1298 Collections.addAll(res,
1299 getVolumeList(mContext.getUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE));
1300 return res;
1301 }
1302
1303 /**
1304 * Return the list of shared/external storage volumes currently available to
1305 * the calling user and the user it shares media with. Please refer to
1306 * <a href="https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support">
1307 * multi-user support</a> for more details.
1308 *
1309 * <p>
1310 * This is similar to {@link StorageManager#getStorageVolumes()} except that the result also
1311 * includes the volumes belonging to any user it shares media with
1312 */
1313 @RequiresPermission(android.Manifest.permission.MANAGE_EXTERNAL_STORAGE)
1314 public @NonNull List<StorageVolume> getStorageVolumesIncludingSharedProfiles() {
1315 final ArrayList<StorageVolume> res = new ArrayList<>();
1316 Collections.addAll(res,
1317 getVolumeList(mContext.getUserId(),
1318 FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE | FLAG_INCLUDE_SHARED_PROFILE));
1319 return res;
1320 }
1321
1322 /**
1323 * Return the list of shared/external storage volumes both currently and
1324 * recently available to the calling user.
1325 * <p>
1326 * Recently available storage volumes are likely to reappear in the future,
1327 * so apps are encouraged to preserve any indexed metadata related to these
1328 * volumes to optimize user experiences.
1329 */
1330 public @NonNull List<StorageVolume> getRecentStorageVolumes() {
1331 final ArrayList<StorageVolume> res = new ArrayList<>();
1332 Collections.addAll(res,
1333 getVolumeList(mContext.getUserId(),
1334 FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE | FLAG_INCLUDE_RECENT));
1335 return res;
1336 }
1337
1338 /**
1339 * Return the primary shared/external storage volume available to the
1340 * current user. This volume is the same storage device returned by
1341 * {@link Environment#getExternalStorageDirectory()} and
1342 * {@link Context#getExternalFilesDir(String)}.
1343 */
1344 public @NonNull StorageVolume getPrimaryStorageVolume() {
1345 return getVolumeList(mContext.getUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)[0];
1346 }
1347
1348 /** {@hide} */
1349 public static Pair<String, Long> getPrimaryStoragePathAndSize() {
1350 return Pair.create(null,
1351 FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace()
1352 + Environment.getRootDirectory().getTotalSpace()));
1353 }
1354
1355 /** {@hide} */
1356 public long getPrimaryStorageSize() {
1357 return FileUtils.roundStorageSize(Environment.getDataDirectory().getTotalSpace()
1358 + Environment.getRootDirectory().getTotalSpace());
1359 }
1360
1361 /** {@hide} */
1362 public void mkdirs(File file) {
1363 BlockGuard.getVmPolicy().onPathAccess(file.getAbsolutePath());
1364 try {
1365 mStorageManager.mkdirs(mContext.getOpPackageName(), file.getAbsolutePath());
1366 } catch (RemoteException e) {
1367 throw e.rethrowFromSystemServer();
1368 }
1369 }
1370
1371 /** @removed */
1372 public @NonNull StorageVolume[] getVolumeList() {
1373 return getVolumeList(mContext.getUserId(), 0);
1374 }
1375
1376 /** {@hide} */
1377 @UnsupportedAppUsage
1378 public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) {
1379 final IStorageManager storageManager = IStorageManager.Stub.asInterface(
1380 ServiceManager.getService("mount"));
1381 try {
1382 String packageName = ActivityThread.currentOpPackageName();
1383 if (packageName == null) {
1384 // Package name can be null if the activity thread is running but the app
1385 // hasn't bound yet. In this case we fall back to the first package in the
1386 // current UID. This works for runtime permissions as permission state is
1387 // per UID and permission realted app ops are updated for all UID packages.
1388 String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid(
1389 android.os.Process.myUid());
1390 if (packageNames == null || packageNames.length <= 0) {
1391 Log.w(TAG, "Missing package names; no storage volumes available");
1392 return new StorageVolume[0];
1393 }
1394 packageName = packageNames[0];
1395 }
1396 return storageManager.getVolumeList(userId, packageName, flags);
1397 } catch (RemoteException e) {
1398 throw e.rethrowFromSystemServer();
1399 }
1400 }
1401
1402 /**
1403 * Returns list of paths for all mountable volumes.
1404 * @hide
1405 */
1406 @Deprecated
1407 @UnsupportedAppUsage
1408 public @NonNull String[] getVolumePaths() {
1409 StorageVolume[] volumes = getVolumeList();
1410 int count = volumes.length;
1411 String[] paths = new String[count];
1412 for (int i = 0; i < count; i++) {
1413 paths[i] = volumes[i].getPath();
1414 }
1415 return paths;
1416 }
1417
1418 /** @removed */
1419 public @NonNull StorageVolume getPrimaryVolume() {
1420 return getPrimaryVolume(getVolumeList());
1421 }
1422
1423 /** {@hide} */
1424 public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) {
1425 for (StorageVolume volume : volumes) {
1426 if (volume.isPrimary()) {
1427 return volume;
1428 }
1429 }
1430 throw new IllegalStateException("Missing primary storage");
1431 }
1432
1433 /**
1434 * Devices having above STORAGE_THRESHOLD_PERCENT_HIGH of total space free are considered to be
1435 * in high free space category.
1436 *
1437 * @hide
1438 */
1439 public static final int DEFAULT_STORAGE_THRESHOLD_PERCENT_HIGH = 20;
1440 /** {@hide} */
1441 @TestApi
1442 public static final String
1443 STORAGE_THRESHOLD_PERCENT_HIGH_KEY = "storage_threshold_percent_high";
1444 /**
1445 * Devices having below STORAGE_THRESHOLD_PERCENT_LOW of total space free are considered to be
1446 * in low free space category and can be configured via
1447 * Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE.
1448 *
1449 * @hide
1450 */
1451 public static final int DEFAULT_STORAGE_THRESHOLD_PERCENT_LOW = 5;
1452 /**
1453 * For devices in high free space category, CACHE_RESERVE_PERCENT_HIGH percent of total space is
1454 * allocated for cache.
1455 *
1456 * @hide
1457 */
1458 public static final int DEFAULT_CACHE_RESERVE_PERCENT_HIGH = 10;
1459 /** {@hide} */
1460 @TestApi
1461 public static final String CACHE_RESERVE_PERCENT_HIGH_KEY = "cache_reserve_percent_high";
1462 /**
1463 * For devices in low free space category, CACHE_RESERVE_PERCENT_LOW percent of total space is
1464 * allocated for cache.
1465 *
1466 * @hide
1467 */
1468 public static final int DEFAULT_CACHE_RESERVE_PERCENT_LOW = 2;
1469 /** {@hide} */
1470 @TestApi
1471 public static final String CACHE_RESERVE_PERCENT_LOW_KEY = "cache_reserve_percent_low";
1472
1473 private static final long DEFAULT_THRESHOLD_MAX_BYTES = DataUnit.MEBIBYTES.toBytes(500);
1474
1475 private static final long DEFAULT_FULL_THRESHOLD_BYTES = DataUnit.MEBIBYTES.toBytes(1);
1476
1477 /**
1478 * Return the number of available bytes until the given path is considered
1479 * running low on storage.
1480 *
1481 * @hide
1482 */
1483 @UnsupportedAppUsage
1484 public long getStorageBytesUntilLow(File path) {
1485 return path.getUsableSpace() - getStorageFullBytes(path);
1486 }
1487
1488 /**
1489 * Return the number of available bytes at which the given path is
1490 * considered running low on storage.
1491 *
1492 * @hide
1493 */
1494 @UnsupportedAppUsage
1495 public long getStorageLowBytes(File path) {
1496 final long lowPercent = Settings.Global.getInt(mResolver,
1497 Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE,
1498 DEFAULT_STORAGE_THRESHOLD_PERCENT_LOW);
1499 final long lowBytes = (path.getTotalSpace() * lowPercent) / 100;
1500
1501 final long maxLowBytes = Settings.Global.getLong(mResolver,
1502 Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES);
1503
1504 return Math.min(lowBytes, maxLowBytes);
1505 }
1506
1507 /**
1508 * Compute the minimum number of bytes of storage on the device that could
1509 * be reserved for cached data depending on the device state which is then passed on
1510 * to getStorageCacheBytes.
1511 *
1512 * Input File path must point to a storage volume.
1513 *
1514 * @hide
1515 */
1516 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1517 @TestApi
1518 @SuppressLint("StreamFiles")
1519 public long computeStorageCacheBytes(@NonNull File path) {
1520 final int storageThresholdPercentHigh = DeviceConfig.getInt(
1521 DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
1522 STORAGE_THRESHOLD_PERCENT_HIGH_KEY, DEFAULT_STORAGE_THRESHOLD_PERCENT_HIGH);
1523 final int cacheReservePercentHigh = DeviceConfig.getInt(
1524 DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
1525 CACHE_RESERVE_PERCENT_HIGH_KEY, DEFAULT_CACHE_RESERVE_PERCENT_HIGH);
1526 final int cacheReservePercentLow = DeviceConfig.getInt(
1527 DeviceConfig.NAMESPACE_STORAGE_NATIVE_BOOT,
1528 CACHE_RESERVE_PERCENT_LOW_KEY, DEFAULT_CACHE_RESERVE_PERCENT_LOW);
1529 final long totalBytes = path.getTotalSpace();
1530 final long usableBytes = path.getUsableSpace();
1531 final long storageThresholdHighBytes = totalBytes * storageThresholdPercentHigh / 100;
1532 final long storageThresholdLowBytes = getStorageLowBytes(path);
1533 long result;
1534 if (usableBytes > storageThresholdHighBytes) {
1535 // If free space is >storageThresholdPercentHigh of total space,
1536 // reserve cacheReservePercentHigh of total space
1537 result = totalBytes * cacheReservePercentHigh / 100;
1538 } else if (usableBytes < storageThresholdLowBytes) {
1539 // If free space is <min(storageThresholdPercentLow of total space, 500MB),
1540 // reserve cacheReservePercentLow of total space
1541 result = totalBytes * cacheReservePercentLow / 100;
1542 } else {
1543 // Else, linearly interpolate the amount of space to reserve
1544 double slope = (cacheReservePercentHigh - cacheReservePercentLow) * totalBytes
1545 / (100.0 * (storageThresholdHighBytes - storageThresholdLowBytes));
1546 double intercept = totalBytes * cacheReservePercentLow / 100.0
1547 - storageThresholdLowBytes * slope;
1548 result = Math.round(slope * usableBytes + intercept);
1549 }
1550 return result;
1551 }
1552
1553 /**
1554 * Return the minimum number of bytes of storage on the device that should
1555 * be reserved for cached data.
1556 *
1557 * @hide
1558 */
1559 public long getStorageCacheBytes(@NonNull File path, @AllocateFlags int flags) {
1560 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
1561 return 0;
1562 } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED) != 0) {
1563 return 0;
1564 } else if ((flags & StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED) != 0) {
1565 return computeStorageCacheBytes(path) / 2;
1566 } else {
1567 return computeStorageCacheBytes(path);
1568 }
1569 }
1570
1571 /**
1572 * Return the number of available bytes at which the given path is
1573 * considered full.
1574 *
1575 * @hide
1576 */
1577 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1578 public long getStorageFullBytes(File path) {
1579 return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
1580 DEFAULT_FULL_THRESHOLD_BYTES);
1581 }
1582
1583 /** {@hide} */
1584 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
1585 try {
1586 mStorageManager.createUserKey(userId, serialNumber, ephemeral);
1587 } catch (RemoteException e) {
1588 throw e.rethrowFromSystemServer();
1589 }
1590 }
1591
1592 /** {@hide} */
1593 public void destroyUserKey(int userId) {
1594 try {
1595 mStorageManager.destroyUserKey(userId);
1596 } catch (RemoteException e) {
1597 throw e.rethrowFromSystemServer();
1598 }
1599 }
1600
1601 /** {@hide} */
1602 public void lockUserKey(int userId) {
1603 try {
1604 mStorageManager.lockUserKey(userId);
1605 } catch (RemoteException e) {
1606 throw e.rethrowFromSystemServer();
1607 }
1608 }
1609
1610 /** {@hide} */
1611 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
1612 try {
1613 mStorageManager.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
1614 } catch (RemoteException e) {
1615 throw e.rethrowFromSystemServer();
1616 }
1617 }
1618
1619 /** {@hide} */
1620 public void destroyUserStorage(String volumeUuid, int userId, int flags) {
1621 try {
1622 mStorageManager.destroyUserStorage(volumeUuid, userId, flags);
1623 } catch (RemoteException e) {
1624 throw e.rethrowFromSystemServer();
1625 }
1626 }
1627
1628 /** {@hide} */
1629 @TestApi
1630 public static boolean isUserKeyUnlocked(int userId) {
1631 if (sStorageManager == null) {
1632 sStorageManager = IStorageManager.Stub
1633 .asInterface(ServiceManager.getService("mount"));
1634 }
1635 if (sStorageManager == null) {
1636 Slog.w(TAG, "Early during boot, assuming locked");
1637 return false;
1638 }
1639 final long token = Binder.clearCallingIdentity();
1640 try {
1641 return sStorageManager.isUserKeyUnlocked(userId);
1642 } catch (RemoteException e) {
1643 throw e.rethrowAsRuntimeException();
1644 } finally {
1645 Binder.restoreCallingIdentity(token);
1646 }
1647 }
1648
1649 /**
1650 * Return if data stored at or under the given path will be encrypted while
1651 * at rest. This can help apps avoid the overhead of double-encrypting data.
1652 */
1653 public boolean isEncrypted(File file) {
1654 if (FileUtils.contains(Environment.getDataDirectory(), file)) {
1655 return isEncrypted();
1656 } else if (FileUtils.contains(Environment.getExpandDirectory(), file)) {
1657 return true;
1658 }
1659 // TODO: extend to support shared storage
1660 return false;
1661 }
1662
1663 /** {@hide}
1664 * Is this device encrypted?
1665 * <p>
1666 * Note: all devices launching with Android 10 (API level 29) or later are
1667 * required to be encrypted. This should only ever return false for
1668 * in-development devices on which encryption has not yet been configured.
1669 *
1670 * @return true if encrypted, false if not encrypted
1671 */
1672 public static boolean isEncrypted() {
1673 return RoSystemProperties.CRYPTO_ENCRYPTED;
1674 }
1675
1676 /** {@hide}
1677 * Does this device have file-based encryption (FBE) enabled?
1678 * @return true if the device has file-based encryption enabled.
1679 */
1680 public static boolean isFileEncrypted() {
1681 if (!isEncrypted()) {
1682 return false;
1683 }
1684 return RoSystemProperties.CRYPTO_FILE_ENCRYPTED;
1685 }
1686
1687 /** {@hide}
1688 * @deprecated Use {@link #isFileEncrypted} instead, since emulated FBE is no longer supported.
1689 */
1690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1691 @Deprecated
1692 public static boolean isFileEncryptedNativeOnly() {
1693 return isFileEncrypted();
1694 }
1695
1696 /** {@hide}
1697 * @deprecated Use {@link #isFileEncrypted} instead, since emulated FBE is no longer supported.
1698 */
1699 @Deprecated
1700 public static boolean isFileEncryptedNativeOrEmulated() {
1701 return isFileEncrypted();
1702 }
1703
1704 /** {@hide} */
1705 public static boolean hasAdoptable() {
1706 switch (SystemProperties.get(PROP_ADOPTABLE)) {
1707 case "force_on":
1708 return true;
1709 case "force_off":
1710 return false;
1711 default:
1712 return SystemProperties.getBoolean(PROP_HAS_ADOPTABLE, false);
1713 }
1714 }
1715
1716 /**
1717 * Return if the currently booted device has the "isolated storage" feature
1718 * flag enabled.
1719 *
1720 * @hide
1721 */
1722 @SystemApi
1723 public static boolean hasIsolatedStorage() {
1724 return false;
1725 }
1726
1727 /**
1728 * @deprecated disabled now that FUSE has been replaced by sdcardfs
1729 * @hide
1730 */
1731 @Deprecated
1732 public static File maybeTranslateEmulatedPathToInternal(File path) {
1733 // Disabled now that FUSE has been replaced by sdcardfs
1734 return path;
1735 }
1736
1737 /**
1738 * Translate given shared storage path from a path in an app sandbox
1739 * namespace to a path in the system namespace.
1740 *
1741 * @hide
1742 */
1743 public File translateAppToSystem(File file, int pid, int uid) {
1744 return file;
1745 }
1746
1747 /**
1748 * Translate given shared storage path from a path in the system namespace
1749 * to a path in an app sandbox namespace.
1750 *
1751 * @hide
1752 */
1753 public File translateSystemToApp(File file, int pid, int uid) {
1754 return file;
1755 }
1756
1757 /**
1758 * Check that given app holds both permission and appop.
1759 * @hide
1760 */
1761 public static boolean checkPermissionAndAppOp(Context context, boolean enforce, int pid,
1762 int uid, String packageName, @NonNull String featureId, String permission, int op) {
1763 return checkPermissionAndAppOp(context, enforce, pid, uid, packageName, featureId,
1764 permission, op, true);
1765 }
1766
1767 /**
1768 * Check that given app holds both permission and appop but do not noteOp.
1769 * @hide
1770 */
1771 public static boolean checkPermissionAndCheckOp(Context context, boolean enforce,
1772 int pid, int uid, String packageName, String permission, int op) {
1773 return checkPermissionAndAppOp(context, enforce, pid, uid, packageName,
1774 null /* featureId is not needed when not noting */, permission, op, false);
1775 }
1776
1777 /**
1778 * Check that given app holds both permission and appop.
1779 * @hide
1780 */
1781 private static boolean checkPermissionAndAppOp(Context context, boolean enforce, int pid,
1782 int uid, String packageName, @Nullable String featureId, String permission, int op,
1783 boolean note) {
1784 if (context.checkPermission(permission, pid, uid) != PERMISSION_GRANTED) {
1785 if (enforce) {
1786 throw new SecurityException(
1787 "Permission " + permission + " denied for package " + packageName);
1788 } else {
1789 return false;
1790 }
1791 }
1792
1793 AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
1794 final int mode;
1795 if (note) {
1796 mode = appOps.noteOpNoThrow(op, uid, packageName, featureId, null);
1797 } else {
1798 try {
1799 appOps.checkPackage(uid, packageName);
1800 } catch (SecurityException e) {
1801 if (enforce) {
1802 throw e;
1803 } else {
1804 return false;
1805 }
1806 }
1807 mode = appOps.checkOpNoThrow(op, uid, packageName);
1808 }
1809 switch (mode) {
1810 case AppOpsManager.MODE_ALLOWED:
1811 return true;
1812 case AppOpsManager.MODE_DEFAULT:
1813 case AppOpsManager.MODE_IGNORED:
1814 case AppOpsManager.MODE_ERRORED:
1815 if (enforce) {
1816 throw new SecurityException("Op " + AppOpsManager.opToName(op) + " "
1817 + AppOpsManager.modeToName(mode) + " for package " + packageName);
1818 } else {
1819 return false;
1820 }
1821 default:
1822 throw new IllegalStateException(
1823 AppOpsManager.opToName(op) + " has unknown mode "
1824 + AppOpsManager.modeToName(mode));
1825 }
1826 }
1827
1828 private boolean checkPermissionAndAppOp(boolean enforce, int pid, int uid, String packageName,
1829 @Nullable String featureId, String permission, int op) {
1830 return checkPermissionAndAppOp(mContext, enforce, pid, uid, packageName, featureId,
1831 permission, op);
1832 }
1833
1834 private boolean noteAppOpAllowingLegacy(boolean enforce,
1835 int pid, int uid, String packageName, @Nullable String featureId, int op) {
1836 final int mode = mAppOps.noteOpNoThrow(op, uid, packageName, featureId, null);
1837 switch (mode) {
1838 case AppOpsManager.MODE_ALLOWED:
1839 return true;
1840 case AppOpsManager.MODE_DEFAULT:
1841 case AppOpsManager.MODE_IGNORED:
1842 case AppOpsManager.MODE_ERRORED:
1843 // Legacy apps technically have the access granted by this op,
1844 // even when the op is denied
1845 if ((mAppOps.checkOpNoThrow(OP_LEGACY_STORAGE, uid,
1846 packageName) == AppOpsManager.MODE_ALLOWED)) return true;
1847
1848 if (enforce) {
1849 throw new SecurityException("Op " + AppOpsManager.opToName(op) + " "
1850 + AppOpsManager.modeToName(mode) + " for package " + packageName);
1851 } else {
1852 return false;
1853 }
1854 default:
1855 throw new IllegalStateException(
1856 AppOpsManager.opToName(op) + " has unknown mode "
1857 + AppOpsManager.modeToName(mode));
1858 }
1859 }
1860
1861 // Callers must hold both the old and new permissions, so that we can
1862 // handle obscure cases like when an app targets Q but was installed on
1863 // a device that was originally running on P before being upgraded to Q.
1864
1865 /**
1866 * @deprecated This method should not be used since it check slegacy permissions,
1867 * no longer valid. Clients should check the appropriate permissions directly
1868 * instead (e.g. READ_MEDIA_IMAGES).
1869 *
1870 * {@hide}
1871 */
1872 @Deprecated
1873 public boolean checkPermissionReadImages(boolean enforce,
1874 int pid, int uid, String packageName, @Nullable String featureId) {
1875 if (!checkExternalStoragePermissionAndAppOp(enforce, pid, uid, packageName, featureId,
1876 READ_EXTERNAL_STORAGE, OP_READ_EXTERNAL_STORAGE)) {
1877 return false;
1878 }
1879 return noteAppOpAllowingLegacy(enforce, pid, uid, packageName, featureId,
1880 OP_READ_MEDIA_IMAGES);
1881 }
1882
1883 private boolean checkExternalStoragePermissionAndAppOp(boolean enforce,
1884 int pid, int uid, String packageName, @Nullable String featureId, String permission,
1885 int op) {
1886 // First check if app has MANAGE_EXTERNAL_STORAGE.
1887 final int mode = mAppOps.noteOpNoThrow(OP_MANAGE_EXTERNAL_STORAGE, uid, packageName,
1888 featureId, null);
1889 if (mode == AppOpsManager.MODE_ALLOWED) {
1890 return true;
1891 }
1892 if (mode == AppOpsManager.MODE_DEFAULT && mContext.checkPermission(
1893 MANAGE_EXTERNAL_STORAGE, pid, uid) == PERMISSION_GRANTED) {
1894 return true;
1895 }
1896 // If app doesn't have MANAGE_EXTERNAL_STORAGE, then check if it has requested granular
1897 // permission.
1898 return checkPermissionAndAppOp(enforce, pid, uid, packageName, featureId, permission, op);
1899 }
1900
1901 /** {@hide} */
1902 @VisibleForTesting
1903 public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1904 int mode, ProxyFileDescriptorCallback callback, Handler handler, ThreadFactory factory)
1905 throws IOException {
1906 Preconditions.checkNotNull(callback);
1907 MetricsLogger.count(mContext, "storage_open_proxy_file_descriptor", 1);
1908 // Retry is needed because the mount point mFuseAppLoop is using may be unmounted before
1909 // invoking StorageManagerService#openProxyFileDescriptor. In this case, we need to re-mount
1910 // the bridge by calling mountProxyFileDescriptorBridge.
1911 while (true) {
1912 try {
1913 synchronized (mFuseAppLoopLock) {
1914 boolean newlyCreated = false;
1915 if (mFuseAppLoop == null) {
1916 final AppFuseMount mount = mStorageManager.mountProxyFileDescriptorBridge();
1917 if (mount == null) {
1918 throw new IOException("Failed to mount proxy bridge");
1919 }
1920 mFuseAppLoop = new FuseAppLoop(mount.mountPointId, mount.fd, factory);
1921 newlyCreated = true;
1922 }
1923 if (handler == null) {
1924 handler = new Handler(Looper.getMainLooper());
1925 }
1926 try {
1927 final int fileId = mFuseAppLoop.registerCallback(callback, handler);
1928 final ParcelFileDescriptor pfd = mStorageManager.openProxyFileDescriptor(
1929 mFuseAppLoop.getMountPointId(), fileId, mode);
1930 if (pfd == null) {
1931 mFuseAppLoop.unregisterCallback(fileId);
1932 throw new FuseUnavailableMountException(
1933 mFuseAppLoop.getMountPointId());
1934 }
1935 return pfd;
1936 } catch (FuseUnavailableMountException exception) {
1937 // The bridge is being unmounted. Tried to recreate it unless the bridge was
1938 // just created.
1939 if (newlyCreated) {
1940 throw new IOException(exception);
1941 }
1942 mFuseAppLoop = null;
1943 continue;
1944 }
1945 }
1946 } catch (RemoteException e) {
1947 // Cannot recover from remote exception.
1948 throw new IOException(e);
1949 }
1950 }
1951 }
1952
1953 /** {@hide} */
1954 public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1955 int mode, ProxyFileDescriptorCallback callback)
1956 throws IOException {
1957 return openProxyFileDescriptor(mode, callback, null, null);
1958 }
1959
1960 /**
1961 * Opens a seekable {@link ParcelFileDescriptor} that proxies all low-level
1962 * I/O requests back to the given {@link ProxyFileDescriptorCallback}.
1963 * <p>
1964 * This can be useful when you want to provide quick access to a large file
1965 * that isn't backed by a real file on disk, such as a file on a network
1966 * share, cloud storage service, etc. As an example, you could respond to a
1967 * {@link ContentResolver#openFileDescriptor(android.net.Uri, String)}
1968 * request by returning a {@link ParcelFileDescriptor} created with this
1969 * method, and then stream the content on-demand as requested.
1970 * <p>
1971 * Another useful example might be where you have an encrypted file that
1972 * you're willing to decrypt on-demand, but where you want to avoid
1973 * persisting the cleartext version.
1974 *
1975 * @param mode The desired access mode, must be one of
1976 * {@link ParcelFileDescriptor#MODE_READ_ONLY},
1977 * {@link ParcelFileDescriptor#MODE_WRITE_ONLY}, or
1978 * {@link ParcelFileDescriptor#MODE_READ_WRITE}
1979 * @param callback Callback to process file operation requests issued on
1980 * returned file descriptor.
1981 * @param handler Handler that invokes callback methods.
1982 * @return Seekable ParcelFileDescriptor.
1983 * @throws IOException
1984 */
1985 public @NonNull ParcelFileDescriptor openProxyFileDescriptor(
1986 int mode, ProxyFileDescriptorCallback callback, Handler handler)
1987 throws IOException {
1988 Preconditions.checkNotNull(handler);
1989 return openProxyFileDescriptor(mode, callback, handler, null);
1990 }
1991
1992 /** {@hide} */
1993 @VisibleForTesting
1994 public int getProxyFileDescriptorMountPointId() {
1995 synchronized (mFuseAppLoopLock) {
1996 return mFuseAppLoop != null ? mFuseAppLoop.getMountPointId() : -1;
1997 }
1998 }
1999
2000 /**
2001 * Return quota size in bytes for all cached data belonging to the calling
2002 * app on the given storage volume.
2003 * <p>
2004 * If your app goes above this quota, your cached files will be some of the
2005 * first to be deleted when additional disk space is needed. Conversely, if
2006 * your app stays under this quota, your cached files will be some of the
2007 * last to be deleted when additional disk space is needed.
2008 * <p>
2009 * This quota will change over time depending on how frequently the user
2010 * interacts with your app, and depending on how much system-wide disk space
2011 * is used.
2012 * <p class="note">
2013 * Note: if your app uses the {@code android:sharedUserId} manifest feature,
2014 * then cached data for all packages in your shared UID is tracked together
2015 * as a single unit.
2016 * </p>
2017 *
2018 * @param storageUuid the UUID of the storage volume that you're interested
2019 * in. The UUID for a specific path can be obtained using
2020 * {@link #getUuidForPath(File)}.
2021 * @throws IOException when the storage device isn't present, or when it
2022 * doesn't support cache quotas.
2023 * @see #getCacheSizeBytes(UUID)
2024 */
2025 @WorkerThread
2026 public @BytesLong long getCacheQuotaBytes(@NonNull UUID storageUuid) throws IOException {
2027 try {
2028 final ApplicationInfo app = mContext.getApplicationInfo();
2029 return mStorageManager.getCacheQuotaBytes(convert(storageUuid), app.uid);
2030 } catch (ParcelableException e) {
2031 e.maybeRethrow(IOException.class);
2032 throw new RuntimeException(e);
2033 } catch (RemoteException e) {
2034 throw e.rethrowFromSystemServer();
2035 }
2036 }
2037
2038 /**
2039 * Return total size in bytes of all cached data belonging to the calling
2040 * app on the given storage volume.
2041 * <p>
2042 * Cached data tracked by this method always includes
2043 * {@link Context#getCacheDir()} and {@link Context#getCodeCacheDir()}, and
2044 * it also includes {@link Context#getExternalCacheDir()} if the primary
2045 * shared/external storage is hosted on the same storage device as your
2046 * private data.
2047 * <p class="note">
2048 * Note: if your app uses the {@code android:sharedUserId} manifest feature,
2049 * then cached data for all packages in your shared UID is tracked together
2050 * as a single unit.
2051 * </p>
2052 *
2053 * @param storageUuid the UUID of the storage volume that you're interested
2054 * in. The UUID for a specific path can be obtained using
2055 * {@link #getUuidForPath(File)}.
2056 * @throws IOException when the storage device isn't present, or when it
2057 * doesn't support cache quotas.
2058 * @see #getCacheQuotaBytes(UUID)
2059 */
2060 @WorkerThread
2061 public @BytesLong long getCacheSizeBytes(@NonNull UUID storageUuid) throws IOException {
2062 try {
2063 final ApplicationInfo app = mContext.getApplicationInfo();
2064 return mStorageManager.getCacheSizeBytes(convert(storageUuid), app.uid);
2065 } catch (ParcelableException e) {
2066 e.maybeRethrow(IOException.class);
2067 throw new RuntimeException(e);
2068 } catch (RemoteException e) {
2069 throw e.rethrowFromSystemServer();
2070 }
2071 }
2072
2073
2074 /** @hide */
2075 @IntDef(prefix = { "MOUNT_MODE_" }, value = {
2076 MOUNT_MODE_EXTERNAL_NONE,
2077 MOUNT_MODE_EXTERNAL_DEFAULT,
2078 MOUNT_MODE_EXTERNAL_INSTALLER,
2079 MOUNT_MODE_EXTERNAL_PASS_THROUGH,
2080 MOUNT_MODE_EXTERNAL_ANDROID_WRITABLE
2081 })
2082 /** @hide */
2083 public @interface MountMode {}
2084
2085 /**
2086 * No external storage should be mounted.
2087 * @hide
2088 */
2089 @SystemApi
2090 public static final int MOUNT_MODE_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
2091 /**
2092 * Default external storage should be mounted.
2093 * @hide
2094 */
2095 @SystemApi
2096 public static final int MOUNT_MODE_EXTERNAL_DEFAULT = IVold.REMOUNT_MODE_DEFAULT;
2097 /**
2098 * Mount mode for package installers which should give them access to
2099 * all obb dirs in addition to their package sandboxes
2100 * @hide
2101 */
2102 @SystemApi
2103 public static final int MOUNT_MODE_EXTERNAL_INSTALLER = IVold.REMOUNT_MODE_INSTALLER;
2104 /**
2105 * The lower file system should be bind mounted directly on external storage
2106 * @hide
2107 */
2108 @SystemApi
2109 public static final int MOUNT_MODE_EXTERNAL_PASS_THROUGH = IVold.REMOUNT_MODE_PASS_THROUGH;
2110
2111 /**
2112 * Use the regular scoped storage filesystem, but Android/ should be writable.
2113 * Used to support the applications hosting DownloadManager and the MTP server.
2114 * @hide
2115 */
2116 @SystemApi
2117 public static final int MOUNT_MODE_EXTERNAL_ANDROID_WRITABLE =
2118 IVold.REMOUNT_MODE_ANDROID_WRITABLE;
2119 /**
2120 * Flag indicating that a disk space allocation request should operate in an
2121 * aggressive mode. This flag should only be rarely used in situations that
2122 * are critical to system health or security.
2123 * <p>
2124 * When set, the system is more aggressive about the data that it considers
2125 * for possible deletion when allocating disk space.
2126 * <p class="note">
2127 * Note: your app must hold the
2128 * {@link android.Manifest.permission#ALLOCATE_AGGRESSIVE} permission for
2129 * this flag to take effect.
2130 * </p>
2131 *
2132 * @see #getAllocatableBytes(UUID, int)
2133 * @see #allocateBytes(UUID, long, int)
2134 * @see #allocateBytes(FileDescriptor, long, int)
2135 * @hide
2136 */
2137 @RequiresPermission(android.Manifest.permission.ALLOCATE_AGGRESSIVE)
2138 @SystemApi
2139 public static final int FLAG_ALLOCATE_AGGRESSIVE = 1 << 0;
2140
2141 /**
2142 * Flag indicating that a disk space allocation request should be allowed to
2143 * clear up to all reserved disk space.
2144 *
2145 * @hide
2146 */
2147 public static final int FLAG_ALLOCATE_DEFY_ALL_RESERVED = 1 << 1;
2148
2149 /**
2150 * Flag indicating that a disk space allocation request should be allowed to
2151 * clear up to half of all reserved disk space.
2152 *
2153 * @hide
2154 */
2155 public static final int FLAG_ALLOCATE_DEFY_HALF_RESERVED = 1 << 2;
2156
2157 /**
2158 * Flag indicating that a disk space check should not take into account
2159 * freeable cached space when determining allocatable space.
2160 *
2161 * Intended for use with {@link #getAllocatableBytes()}.
2162 * @hide
2163 */
2164 public static final int FLAG_ALLOCATE_NON_CACHE_ONLY = 1 << 3;
2165
2166 /**
2167 * Flag indicating that a disk space check should only return freeable
2168 * cached space when determining allocatable space.
2169 *
2170 * Intended for use with {@link #getAllocatableBytes()}.
2171 * @hide
2172 */
2173 public static final int FLAG_ALLOCATE_CACHE_ONLY = 1 << 4;
2174
2175 /** @hide */
2176 @IntDef(flag = true, prefix = { "FLAG_ALLOCATE_" }, value = {
2177 FLAG_ALLOCATE_AGGRESSIVE,
2178 FLAG_ALLOCATE_DEFY_ALL_RESERVED,
2179 FLAG_ALLOCATE_DEFY_HALF_RESERVED,
2180 FLAG_ALLOCATE_NON_CACHE_ONLY,
2181 FLAG_ALLOCATE_CACHE_ONLY,
2182 })
2183 @Retention(RetentionPolicy.SOURCE)
2184 public @interface AllocateFlags {}
2185
2186 /**
2187 * Return the maximum number of new bytes that your app can allocate for
2188 * itself on the given storage volume. This value is typically larger than
2189 * {@link File#getUsableSpace()}, since the system may be willing to delete
2190 * cached files to satisfy an allocation request. You can then allocate
2191 * space for yourself using {@link #allocateBytes(UUID, long)} or
2192 * {@link #allocateBytes(FileDescriptor, long)}.
2193 * <p>
2194 * This method is best used as a pre-flight check, such as deciding if there
2195 * is enough space to store an entire music album before you allocate space
2196 * for each audio file in the album. Attempts to allocate disk space beyond
2197 * the returned value will fail.
2198 * <p>
2199 * If the returned value is not large enough for the data you'd like to
2200 * persist, you can launch {@link #ACTION_MANAGE_STORAGE} with the
2201 * {@link #EXTRA_UUID} and {@link #EXTRA_REQUESTED_BYTES} options to help
2202 * involve the user in freeing up disk space.
2203 * <p>
2204 * If you're progressively allocating an unbounded amount of storage space
2205 * (such as when recording a video) you should avoid calling this method
2206 * more than once every 30 seconds.
2207 * <p class="note">
2208 * Note: if your app uses the {@code android:sharedUserId} manifest feature,
2209 * then allocatable space for all packages in your shared UID is tracked
2210 * together as a single unit.
2211 * </p>
2212 *
2213 * @param storageUuid the UUID of the storage volume where you're
2214 * considering allocating disk space, since allocatable space can
2215 * vary widely depending on the underlying storage device. The
2216 * UUID for a specific path can be obtained using
2217 * {@link #getUuidForPath(File)}.
2218 * @return the maximum number of new bytes that the calling app can allocate
2219 * using {@link #allocateBytes(UUID, long)} or
2220 * {@link #allocateBytes(FileDescriptor, long)}.
2221 * @throws IOException when the storage device isn't present, or when it
2222 * doesn't support allocating space.
2223 */
2224 @WorkerThread
2225 public @BytesLong long getAllocatableBytes(@NonNull UUID storageUuid)
2226 throws IOException {
2227 return getAllocatableBytes(storageUuid, 0);
2228 }
2229
2230 /** @hide */
2231 @SystemApi
2232 @WorkerThread
2233 @SuppressLint("RequiresPermission")
2234 public long getAllocatableBytes(@NonNull UUID storageUuid,
2235 @RequiresPermission @AllocateFlags int flags) throws IOException {
2236 try {
2237 return mStorageManager.getAllocatableBytes(convert(storageUuid), flags,
2238 mContext.getOpPackageName());
2239 } catch (ParcelableException e) {
2240 e.maybeRethrow(IOException.class);
2241 throw new RuntimeException(e);
2242 } catch (RemoteException e) {
2243 throw e.rethrowFromSystemServer();
2244 }
2245 }
2246
2247 /**
2248 * Allocate the requested number of bytes for your application to use on the
2249 * given storage volume. This will cause the system to delete any cached
2250 * files necessary to satisfy your request.
2251 * <p>
2252 * Attempts to allocate disk space beyond the value returned by
2253 * {@link #getAllocatableBytes(UUID)} will fail.
2254 * <p>
2255 * Since multiple apps can be running simultaneously, this method may be
2256 * subject to race conditions. If possible, consider using
2257 * {@link #allocateBytes(FileDescriptor, long)} which will guarantee
2258 * that bytes are allocated to an opened file.
2259 * <p>
2260 * If you're progressively allocating an unbounded amount of storage space
2261 * (such as when recording a video) you should avoid calling this method
2262 * more than once every 60 seconds.
2263 *
2264 * @param storageUuid the UUID of the storage volume where you'd like to
2265 * allocate disk space. The UUID for a specific path can be
2266 * obtained using {@link #getUuidForPath(File)}.
2267 * @param bytes the number of bytes to allocate.
2268 * @throws IOException when the storage device isn't present, or when it
2269 * doesn't support allocating space, or if the device had
2270 * trouble allocating the requested space.
2271 * @see #getAllocatableBytes(UUID)
2272 */
2273 @WorkerThread
2274 public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes)
2275 throws IOException {
2276 allocateBytes(storageUuid, bytes, 0);
2277 }
2278
2279 /** @hide */
2280 @SystemApi
2281 @WorkerThread
2282 @SuppressLint("RequiresPermission")
2283 public void allocateBytes(@NonNull UUID storageUuid, @BytesLong long bytes,
2284 @RequiresPermission @AllocateFlags int flags) throws IOException {
2285 try {
2286 mStorageManager.allocateBytes(convert(storageUuid), bytes, flags,
2287 mContext.getOpPackageName());
2288 } catch (ParcelableException e) {
2289 e.maybeRethrow(IOException.class);
2290 } catch (RemoteException e) {
2291 throw e.rethrowFromSystemServer();
2292 }
2293 }
2294
2295 /**
2296 * Returns the External Storage mount mode corresponding to the given uid and packageName.
2297 * These mount modes specify different views and access levels for
2298 * different apps on external storage.
2299 *
2300 * @params uid UID of the application
2301 * @params packageName name of the package
2302 * @return {@code MountMode} for the given uid and packageName.
2303 *
2304 * @hide
2305 */
2306 @RequiresPermission(android.Manifest.permission.WRITE_MEDIA_STORAGE)
2307 @SystemApi
2308 @MountMode
2309 public int getExternalStorageMountMode(int uid, @NonNull String packageName) {
2310 try {
2311 return mStorageManager.getExternalStorageMountMode(uid, packageName);
2312 } catch (RemoteException e) {
2313 throw e.rethrowFromSystemServer();
2314 }
2315 }
2316
2317 /**
2318 * Allocate the requested number of bytes for your application to use in the
2319 * given open file. This will cause the system to delete any cached files
2320 * necessary to satisfy your request.
2321 * <p>
2322 * Attempts to allocate disk space beyond the value returned by
2323 * {@link #getAllocatableBytes(UUID)} will fail.
2324 * <p>
2325 * This method guarantees that bytes have been allocated to the opened file,
2326 * otherwise it will throw if fast allocation is not possible. Fast
2327 * allocation is typically only supported in private app data directories,
2328 * and on shared/external storage devices which are emulated.
2329 * <p>
2330 * If you're progressively allocating an unbounded amount of storage space
2331 * (such as when recording a video) you should avoid calling this method
2332 * more than once every 60 seconds.
2333 *
2334 * @param fd the open file that you'd like to allocate disk space for.
2335 * @param bytes the number of bytes to allocate. This is the desired final
2336 * size of the open file. If the open file is smaller than this
2337 * requested size, it will be extended without modifying any
2338 * existing contents. If the open file is larger than this
2339 * requested size, it will be truncated.
2340 * @throws IOException when the storage device isn't present, or when it
2341 * doesn't support allocating space, or if the device had
2342 * trouble allocating the requested space.
2343 * @see #isAllocationSupported(FileDescriptor)
2344 * @see Environment#isExternalStorageEmulated(File)
2345 */
2346 @WorkerThread
2347 public void allocateBytes(FileDescriptor fd, @BytesLong long bytes) throws IOException {
2348 allocateBytes(fd, bytes, 0);
2349 }
2350
2351 /** @hide */
2352 @SystemApi
2353 @WorkerThread
2354 @SuppressLint("RequiresPermission")
2355 public void allocateBytes(FileDescriptor fd, @BytesLong long bytes,
2356 @RequiresPermission @AllocateFlags int flags) throws IOException {
2357 final File file = ParcelFileDescriptor.getFile(fd);
2358 final UUID uuid = getUuidForPath(file);
2359 for (int i = 0; i < 3; i++) {
2360 try {
2361 final long haveBytes = Os.fstat(fd).st_blocks * 512;
2362 final long needBytes = bytes - haveBytes;
2363
2364 if (needBytes > 0) {
2365 allocateBytes(uuid, needBytes, flags);
2366 }
2367
2368 try {
2369 Os.posix_fallocate(fd, 0, bytes);
2370 return;
2371 } catch (ErrnoException e) {
2372 if (e.errno == OsConstants.ENOSYS || e.errno == OsConstants.ENOTSUP) {
2373 Log.w(TAG, "fallocate() not supported; falling back to ftruncate()");
2374 Os.ftruncate(fd, bytes);
2375 return;
2376 } else {
2377 throw e;
2378 }
2379 }
2380 } catch (ErrnoException e) {
2381 if (e.errno == OsConstants.ENOSPC) {
2382 Log.w(TAG, "Odd, not enough space; let's try again?");
2383 continue;
2384 }
2385 throw e.rethrowAsIOException();
2386 }
2387 }
2388 throw new IOException(
2389 "Well this is embarassing; we can't allocate " + bytes + " for " + file);
2390 }
2391
2392 private static final String XATTR_CACHE_GROUP = "user.cache_group";
2393 private static final String XATTR_CACHE_TOMBSTONE = "user.cache_tombstone";
2394
2395
2396 // Project IDs below must match android_projectid_config.h
2397 /**
2398 * Default project ID for files on external storage
2399 *
2400 * {@hide}
2401 */
2402 public static final int PROJECT_ID_EXT_DEFAULT = 1000;
2403
2404 /**
2405 * project ID for audio files on external storage
2406 *
2407 * {@hide}
2408 */
2409 public static final int PROJECT_ID_EXT_MEDIA_AUDIO = 1001;
2410
2411 /**
2412 * project ID for video files on external storage
2413 *
2414 * {@hide}
2415 */
2416 public static final int PROJECT_ID_EXT_MEDIA_VIDEO = 1002;
2417
2418 /**
2419 * project ID for image files on external storage
2420 *
2421 * {@hide}
2422 */
2423 public static final int PROJECT_ID_EXT_MEDIA_IMAGE = 1003;
2424
2425 /**
2426 * Constant for use with
2427 * {@link #updateExternalStorageFileQuotaType(String, int)} (String, int)}, to indicate the file
2428 * is not a media file.
2429 *
2430 * @hide
2431 */
2432 @SystemApi
2433 public static final int QUOTA_TYPE_MEDIA_NONE = 0;
2434
2435 /**
2436 * Constant for use with
2437 * {@link #updateExternalStorageFileQuotaType(String, int)} (String, int)}, to indicate the file
2438 * is an image file.
2439 *
2440 * @hide
2441 */
2442 @SystemApi
2443 public static final int QUOTA_TYPE_MEDIA_IMAGE = 1;
2444
2445 /**
2446 * Constant for use with
2447 * {@link #updateExternalStorageFileQuotaType(String, int)} (String, int)}, to indicate the file
2448 * is an audio file.
2449 *
2450 * @hide
2451 */
2452 @SystemApi
2453 public static final int QUOTA_TYPE_MEDIA_AUDIO = 2;
2454
2455 /**
2456 * Constant for use with
2457 * {@link #updateExternalStorageFileQuotaType(String, int)} (String, int)}, to indicate the file
2458 * is a video file.
2459 *
2460 * @hide
2461 */
2462 @SystemApi
2463 public static final int QUOTA_TYPE_MEDIA_VIDEO = 3;
2464
2465 /** @hide */
2466 @Retention(RetentionPolicy.SOURCE)
2467 @IntDef(prefix = { "QUOTA_TYPE_" }, value = {
2468 QUOTA_TYPE_MEDIA_NONE,
2469 QUOTA_TYPE_MEDIA_AUDIO,
2470 QUOTA_TYPE_MEDIA_VIDEO,
2471 QUOTA_TYPE_MEDIA_IMAGE,
2472 })
2473 public @interface QuotaType {}
2474
2475 private static native boolean setQuotaProjectId(String path, long projectId);
2476
2477 private static long getProjectIdForUser(int userId, int projectId) {
2478 // Much like UserHandle.getUid(), store the user ID in the upper bits
2479 return userId * PER_USER_RANGE + projectId;
2480 }
2481
2482 /**
2483 * Let StorageManager know that the quota type for a file on external storage should
2484 * be updated. Android tracks quotas for various media types. Consequently, this should be
2485 * called on first creation of a new file on external storage, and whenever the
2486 * media type of the file is updated later.
2487 *
2488 * This API doesn't require any special permissions, though typical implementations
2489 * will require being called from an SELinux domain that allows setting file attributes
2490 * related to quota (eg the GID or project ID).
2491 * If the calling user has MANAGE_EXTERNAL_STORAGE permissions, quota for shared profile's
2492 * volumes is also updated.
2493 *
2494 * The default platform user of this API is the MediaProvider process, which is
2495 * responsible for managing all of external storage.
2496 *
2497 * @param path the path to the file for which we should update the quota type
2498 * @param quotaType the quota type of the file; this is based on the
2499 * {@code QuotaType} constants, eg
2500 * {@code StorageManager.QUOTA_TYPE_MEDIA_AUDIO}
2501 *
2502 * @throws IllegalArgumentException if {@code quotaType} does not correspond to a valid
2503 * quota type.
2504 * @throws IOException if the quota type could not be updated.
2505 *
2506 * @hide
2507 */
2508 @SystemApi
2509 public void updateExternalStorageFileQuotaType(@NonNull File path,
2510 @QuotaType int quotaType) throws IOException {
2511 long projectId;
2512 final String filePath = path.getCanonicalPath();
2513 int volFlags = FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE;
2514 // If caller has MANAGE_EXTERNAL_STORAGE permission, results from User Profile(s) are also
2515 // returned by enabling FLAG_INCLUDE_SHARED_PROFILE.
2516 if (mContext.checkSelfPermission(MANAGE_EXTERNAL_STORAGE) == PERMISSION_GRANTED) {
2517 volFlags |= FLAG_INCLUDE_SHARED_PROFILE;
2518 }
2519 final StorageVolume[] availableVolumes = getVolumeList(mContext.getUserId(), volFlags);
2520 final StorageVolume volume = getStorageVolume(availableVolumes, path);
2521 if (volume == null) {
2522 Log.w(TAG, "Failed to update quota type for " + filePath);
2523 return;
2524 }
2525 if (!volume.isEmulated()) {
2526 // We only support quota tracking on emulated filesystems
2527 return;
2528 }
2529
2530 final int userId = volume.getOwner().getIdentifier();
2531 if (userId < 0) {
2532 throw new IllegalStateException("Failed to update quota type for " + filePath);
2533 }
2534 switch (quotaType) {
2535 case QUOTA_TYPE_MEDIA_NONE:
2536 projectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2537 break;
2538 case QUOTA_TYPE_MEDIA_AUDIO:
2539 projectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2540 break;
2541 case QUOTA_TYPE_MEDIA_VIDEO:
2542 projectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2543 break;
2544 case QUOTA_TYPE_MEDIA_IMAGE:
2545 projectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2546 break;
2547 default:
2548 throw new IllegalArgumentException("Invalid quota type: " + quotaType);
2549 }
2550 if (!setQuotaProjectId(filePath, projectId)) {
2551 throw new IOException("Failed to update quota type for " + filePath);
2552 }
2553 }
2554
2555 /**
2556 * Asks StorageManager to fixup the permissions of an application-private directory.
2557 *
2558 * On devices without sdcardfs, filesystem permissions aren't magically fixed up. This
2559 * is problematic mostly in application-private directories, which are owned by the
2560 * application itself; if another process with elevated permissions creates a file
2561 * in these directories, the UID will be wrong, and the owning package won't be able
2562 * to access the files.
2563 *
2564 * This API can be used to recursively fix up the permissions on the passed in path.
2565 * The default platform user of this API is the DownloadProvider, which can download
2566 * things in application-private directories on their behalf.
2567 *
2568 * This API doesn't require any special permissions, because it merely changes the
2569 * permissions of a directory to what they should anyway be.
2570 *
2571 * @param path the path for which we should fix up the permissions
2572 *
2573 * @hide
2574 */
2575 public void fixupAppDir(@NonNull File path) {
2576 try {
2577 mStorageManager.fixupAppDir(path.getCanonicalPath());
2578 } catch (IOException e) {
2579 Log.e(TAG, "Failed to get canonical path for " + path.getPath(), e);
2580 } catch (RemoteException e) {
2581 throw e.rethrowFromSystemServer();
2582 }
2583 }
2584
2585 /** {@hide} */
2586 private static void setCacheBehavior(File path, String name, boolean enabled)
2587 throws IOException {
2588 if (!path.isDirectory()) {
2589 throw new IOException("Cache behavior can only be set on directories");
2590 }
2591 if (enabled) {
2592 try {
2593 Os.setxattr(path.getAbsolutePath(), name,
2594 "1".getBytes(StandardCharsets.UTF_8), 0);
2595 } catch (ErrnoException e) {
2596 throw e.rethrowAsIOException();
2597 }
2598 } else {
2599 try {
2600 Os.removexattr(path.getAbsolutePath(), name);
2601 } catch (ErrnoException e) {
2602 if (e.errno != OsConstants.ENODATA) {
2603 throw e.rethrowAsIOException();
2604 }
2605 }
2606 }
2607 }
2608
2609 /** {@hide} */
2610 private static boolean isCacheBehavior(File path, String name) throws IOException {
2611 try {
2612 Os.getxattr(path.getAbsolutePath(), name);
2613 return true;
2614 } catch (ErrnoException e) {
2615 if (e.errno != OsConstants.ENODATA) {
2616 throw e.rethrowAsIOException();
2617 } else {
2618 return false;
2619 }
2620 }
2621 }
2622
2623 /**
2624 * Enable or disable special cache behavior that treats this directory and
2625 * its contents as an entire group.
2626 * <p>
2627 * When enabled and this directory is considered for automatic deletion by
2628 * the OS, all contained files will either be deleted together, or not at
2629 * all. This is useful when you have a directory that contains several
2630 * related metadata files that depend on each other, such as movie file and
2631 * a subtitle file.
2632 * <p>
2633 * When enabled, the <em>newest</em> {@link File#lastModified()} value of
2634 * any contained files is considered the modified time of the entire
2635 * directory.
2636 * <p>
2637 * This behavior can only be set on a directory, and it applies recursively
2638 * to all contained files and directories.
2639 */
2640 public void setCacheBehaviorGroup(File path, boolean group) throws IOException {
2641 setCacheBehavior(path, XATTR_CACHE_GROUP, group);
2642 }
2643
2644 /**
2645 * Read the current value set by
2646 * {@link #setCacheBehaviorGroup(File, boolean)}.
2647 */
2648 public boolean isCacheBehaviorGroup(File path) throws IOException {
2649 return isCacheBehavior(path, XATTR_CACHE_GROUP);
2650 }
2651
2652 /**
2653 * Enable or disable special cache behavior that leaves deleted cache files
2654 * intact as tombstones.
2655 * <p>
2656 * When enabled and a file contained in this directory is automatically
2657 * deleted by the OS, the file will be truncated to have a length of 0 bytes
2658 * instead of being fully deleted. This is useful if you need to distinguish
2659 * between a file that was deleted versus one that never existed.
2660 * <p>
2661 * This behavior can only be set on a directory, and it applies recursively
2662 * to all contained files and directories.
2663 * <p class="note">
2664 * Note: this behavior is ignored completely if the user explicitly requests
2665 * that all cached data be cleared.
2666 * </p>
2667 */
2668 public void setCacheBehaviorTombstone(File path, boolean tombstone) throws IOException {
2669 setCacheBehavior(path, XATTR_CACHE_TOMBSTONE, tombstone);
2670 }
2671
2672 /**
2673 * Read the current value set by
2674 * {@link #setCacheBehaviorTombstone(File, boolean)}.
2675 */
2676 public boolean isCacheBehaviorTombstone(File path) throws IOException {
2677 return isCacheBehavior(path, XATTR_CACHE_TOMBSTONE);
2678 }
2679
2680 /**
2681 * Returns true if {@code uuid} is a FAT volume identifier. FAT Volume identifiers
2682 * are 32 randomly generated bits that are represented in string form as AAAA-AAAA.
2683 */
2684 private static boolean isFatVolumeIdentifier(String uuid) {
2685 return uuid.length() == 9 && uuid.charAt(4) == '-';
2686 }
2687
2688 /** {@hide} */
2689 @TestApi
2690 public static @NonNull UUID convert(@Nullable String uuid) {
2691 // UUID_PRIVATE_INTERNAL is null, so this accepts nullable input
2692 if (Objects.equals(uuid, UUID_PRIVATE_INTERNAL)) {
2693 return UUID_DEFAULT;
2694 } else if (Objects.equals(uuid, UUID_PRIMARY_PHYSICAL)) {
2695 return UUID_PRIMARY_PHYSICAL_;
2696 } else if (Objects.equals(uuid, UUID_SYSTEM)) {
2697 return UUID_SYSTEM_;
2698 } else if (isFatVolumeIdentifier(uuid)) {
2699 // FAT volume identifiers are not UUIDs but we need to coerce them into
2700 // UUIDs in order to satisfy apis that take java.util.UUID arguments.
2701 //
2702 // We coerce a 32 bit fat volume identifier of the form XXXX-YYYY into
2703 // a UUID of form "fafafafa-fafa-5afa-8afa-fafaXXXXYYYY". This is an
2704 // RFC-422 UUID with Version 5, which is a namespaced UUID. The UUIDs we
2705 // coerce into are not true namespace UUIDs; although FAT storage volume
2706 // identifiers are unique names within a fixed namespace, this UUID is not
2707 // based on an SHA-1 hash of the name. We avoid the SHA-1 hash because
2708 // (a) we need this transform to be reversible (b) it's pointless to generate
2709 // a 128 bit hash from a 32 bit value.
2710 return UUID.fromString(FAT_UUID_PREFIX + uuid.replace("-", ""));
2711 } else {
2712 return UUID.fromString(uuid);
2713 }
2714 }
2715
2716 /** {@hide} */
2717 @TestApi
2718 public static @NonNull String convert(@NonNull UUID storageUuid) {
2719 if (UUID_DEFAULT.equals(storageUuid)) {
2720 return UUID_PRIVATE_INTERNAL;
2721 } else if (UUID_PRIMARY_PHYSICAL_.equals(storageUuid)) {
2722 return UUID_PRIMARY_PHYSICAL;
2723 } else if (UUID_SYSTEM_.equals(storageUuid)) {
2724 return UUID_SYSTEM;
2725 } else {
2726 String uuidString = storageUuid.toString();
2727 // This prefix match will exclude fsUuids from private volumes because
2728 // (a) linux fsUuids are generally Version 4 (random) UUIDs so the prefix
2729 // will contain 4xxx instead of 5xxx and (b) we've already matched against
2730 // known namespace (Version 5) UUIDs above.
2731 if (uuidString.startsWith(FAT_UUID_PREFIX)) {
2732 String fatStr = uuidString.substring(FAT_UUID_PREFIX.length())
2733 .toUpperCase(Locale.US);
2734 return fatStr.substring(0, 4) + "-" + fatStr.substring(4);
2735 }
2736
2737 return storageUuid.toString();
2738 }
2739 }
2740
2741 /**
2742 * Check whether the device supports filesystem checkpoint.
2743 *
2744 * @return true if the device supports filesystem checkpoint, false otherwise.
2745 */
2746 public boolean isCheckpointSupported() {
2747 try {
2748 return mStorageManager.supportsCheckpoint();
2749 } catch (RemoteException e) {
2750 throw e.rethrowFromSystemServer();
2751 }
2752 }
2753
2754 /**
2755 * Reason to provide if app IO is blocked/resumed for unknown reasons
2756 *
2757 * @hide
2758 */
2759 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2760 public static final int APP_IO_BLOCKED_REASON_UNKNOWN = 0;
2761
2762 /**
2763 * Reason to provide if app IO is blocked/resumed because of transcoding
2764 *
2765 * @hide
2766 */
2767 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2768 public static final int APP_IO_BLOCKED_REASON_TRANSCODING = 1;
2769
2770 /**
2771 * Constants for use with
2772 * {@link #notifyAppIoBlocked} and {@link notifyAppIoResumed}, to specify the reason an app's
2773 * IO is blocked/resumed.
2774 *
2775 * @hide
2776 */
2777 @Retention(RetentionPolicy.SOURCE)
2778 @IntDef(prefix = { "APP_IO_BLOCKED_REASON_" }, value = {
2779 APP_IO_BLOCKED_REASON_TRANSCODING,
2780 APP_IO_BLOCKED_REASON_UNKNOWN,
2781 })
2782 public @interface AppIoBlockedReason {}
2783
2784 /**
2785 * Notify the system that an app with {@code uid} and {@code tid} is blocked on an IO request on
2786 * {@code volumeUuid} for {@code reason}.
2787 *
2788 * This blocked state can be used to modify the ANR behavior for the app while it's blocked.
2789 * For example during transcoding.
2790 *
2791 * This can only be called by the {@link ExternalStorageService} holding the
2792 * {@link android.Manifest.permission#WRITE_MEDIA_STORAGE} permission.
2793 *
2794 * @param volumeUuid the UUID of the storage volume that the app IO is blocked on
2795 * @param uid the UID of the app blocked on IO
2796 * @param tid the tid of the app blocked on IO
2797 * @param reason the reason the app is blocked on IO
2798 *
2799 * @hide
2800 */
2801 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2802 public void notifyAppIoBlocked(@NonNull UUID volumeUuid, int uid, int tid,
2803 @AppIoBlockedReason int reason) {
2804 Objects.requireNonNull(volumeUuid);
2805 try {
2806 mStorageManager.notifyAppIoBlocked(convert(volumeUuid), uid, tid, reason);
2807 } catch (RemoteException e) {
2808 throw e.rethrowFromSystemServer();
2809 }
2810 }
2811
2812 /**
2813 * Notify the system that an app with {@code uid} and {@code tid} has resmued a previously
2814 * blocked IO request on {@code volumeUuid} for {@code reason}.
2815 *
2816 * All app IO will be automatically marked as unblocked if {@code volumeUuid} is unmounted.
2817 *
2818 * This can only be called by the {@link ExternalStorageService} holding the
2819 * {@link android.Manifest.permission#WRITE_MEDIA_STORAGE} permission.
2820 *
2821 * @param volumeUuid the UUID of the storage volume that the app IO is resumed on
2822 * @param uid the UID of the app resuming IO
2823 * @param tid the tid of the app resuming IO
2824 * @param reason the reason the app is resuming IO
2825 *
2826 * @hide
2827 */
2828 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2829 public void notifyAppIoResumed(@NonNull UUID volumeUuid, int uid, int tid,
2830 @AppIoBlockedReason int reason) {
2831 Objects.requireNonNull(volumeUuid);
2832 try {
2833 mStorageManager.notifyAppIoResumed(convert(volumeUuid), uid, tid, reason);
2834 } catch (RemoteException e) {
2835 throw e.rethrowFromSystemServer();
2836 }
2837 }
2838
2839 /**
2840 * Check if {@code uid} with {@code tid} is blocked on IO for {@code reason}.
2841 *
2842 * This requires {@link ExternalStorageService} the
2843 * {@link android.Manifest.permission#WRITE_MEDIA_STORAGE} permission.
2844 *
2845 * @param volumeUuid the UUID of the storage volume to check IO blocked status
2846 * @param uid the UID of the app to check IO blocked status
2847 * @param tid the tid of the app to check IO blocked status
2848 * @param reason the reason to check IO blocked status for
2849 *
2850 * @hide
2851 */
2852 @TestApi
2853 public boolean isAppIoBlocked(@NonNull UUID volumeUuid, int uid, int tid,
2854 @AppIoBlockedReason int reason) {
2855 Objects.requireNonNull(volumeUuid);
2856 try {
2857 return mStorageManager.isAppIoBlocked(convert(volumeUuid), uid, tid, reason);
2858 } catch (RemoteException e) {
2859 throw e.rethrowFromSystemServer();
2860 }
2861 }
2862
2863 /**
2864 * Notify the system of the current cloud media provider.
2865 *
2866 * This can only be called by the {@link android.service.storage.ExternalStorageService}
2867 * holding the {@link android.Manifest.permission#WRITE_MEDIA_STORAGE} permission.
2868 *
2869 * @param authority the authority of the content provider
2870 * @hide
2871 */
2872 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2873 public void setCloudMediaProvider(@Nullable String authority) {
2874 try {
2875 mStorageManager.setCloudMediaProvider(authority);
2876 } catch (RemoteException e) {
2877 throw e.rethrowFromSystemServer();
2878 }
2879 }
2880
2881 /**
2882 * Returns the authority of the current cloud media provider that was set by the
2883 * {@link android.service.storage.ExternalStorageService} holding the
2884 * {@link android.Manifest.permission#WRITE_MEDIA_STORAGE} permission via
2885 * {@link #setCloudMediaProvider(String)}.
2886 *
2887 * @hide
2888 */
2889 @Nullable
2890 @TestApi
2891 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2892 public String getCloudMediaProvider() {
2893 try {
2894 return mStorageManager.getCloudMediaProvider();
2895 } catch (RemoteException e) {
2896 throw e.rethrowFromSystemServer();
2897 }
2898 }
2899
2900 private final Object mFuseAppLoopLock = new Object();
2901
2902 @GuardedBy("mFuseAppLoopLock")
2903 private @Nullable FuseAppLoop mFuseAppLoop = null;
2904
2905 /** @hide */
2906 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2907 public static final int CRYPT_TYPE_PASSWORD = 0;
2908 /** @hide */
2909 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2910 public static final int CRYPT_TYPE_DEFAULT = 1;
2911}