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