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