StorageManager.java revision 9e8d9e250b4e3fe8e57072072ed84b5dea0a19d3
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os.storage;
18
19import static android.net.TrafficStats.MB_IN_BYTES;
20
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.app.ActivityThread;
24import android.content.ContentResolver;
25import android.content.Context;
26import android.content.pm.IPackageMoveObserver;
27import android.content.pm.PackageManager;
28import android.os.Environment;
29import android.os.FileUtils;
30import android.os.Handler;
31import android.os.Looper;
32import android.os.Message;
33import android.os.ParcelFileDescriptor;
34import android.os.RemoteException;
35import android.os.ServiceManager;
36import android.provider.Settings;
37import android.text.TextUtils;
38import android.util.Log;
39import android.util.Slog;
40import android.util.SparseArray;
41
42import com.android.internal.os.SomeArgs;
43import com.android.internal.util.Preconditions;
44
45import java.io.File;
46import java.io.IOException;
47import java.lang.ref.WeakReference;
48import java.util.ArrayList;
49import java.util.Arrays;
50import java.util.Iterator;
51import java.util.List;
52import java.util.Objects;
53import java.util.concurrent.atomic.AtomicInteger;
54
55/**
56 * StorageManager is the interface to the systems storage service. The storage
57 * manager handles storage-related items such as Opaque Binary Blobs (OBBs).
58 * <p>
59 * OBBs contain a filesystem that maybe be encrypted on disk and mounted
60 * on-demand from an application. OBBs are a good way of providing large amounts
61 * of binary assets without packaging them into APKs as they may be multiple
62 * gigabytes in size. However, due to their size, they're most likely stored in
63 * a shared storage pool accessible from all programs. The system does not
64 * guarantee the security of the OBB file itself: if any program modifies the
65 * OBB, there is no guarantee that a read from that OBB will produce the
66 * expected output.
67 * <p>
68 * Get an instance of this class by calling
69 * {@link android.content.Context#getSystemService(java.lang.String)} with an
70 * argument of {@link android.content.Context#STORAGE_SERVICE}.
71 */
72public class StorageManager {
73    private static final String TAG = "StorageManager";
74
75    /** {@hide} */
76    public static final String PROP_PRIMARY_PHYSICAL = "ro.vold.primary_physical";
77    /** {@hide} */
78    public static final String PROP_HAS_ADOPTABLE = "vold.has_adoptable";
79    /** {@hide} */
80    public static final String PROP_HAS_FBE = "vold.has_fbe";
81    /** {@hide} */
82    public static final String PROP_FORCE_ADOPTABLE = "persist.fw.force_adoptable";
83    /** {@hide} */
84    public static final String PROP_EMULATE_FBE = "vold.emulate_fbe";
85
86    /** {@hide} */
87    public static final String UUID_PRIVATE_INTERNAL = null;
88    /** {@hide} */
89    public static final String UUID_PRIMARY_PHYSICAL = "primary_physical";
90
91    /** {@hide} */
92    public static final int DEBUG_FORCE_ADOPTABLE = 1 << 0;
93    /** {@hide} */
94    public static final int DEBUG_EMULATE_FBE = 1 << 1;
95
96    /** {@hide} */
97    public static final int FLAG_FOR_WRITE = 1 << 0;
98
99    private final Context mContext;
100    private final ContentResolver mResolver;
101
102    private final IMountService mMountService;
103    private final Looper mLooper;
104    private final AtomicInteger mNextNonce = new AtomicInteger(0);
105
106    private final ArrayList<StorageEventListenerDelegate> mDelegates = new ArrayList<>();
107
108    private static class StorageEventListenerDelegate extends IMountServiceListener.Stub implements
109            Handler.Callback {
110        private static final int MSG_STORAGE_STATE_CHANGED = 1;
111        private static final int MSG_VOLUME_STATE_CHANGED = 2;
112        private static final int MSG_VOLUME_RECORD_CHANGED = 3;
113        private static final int MSG_VOLUME_FORGOTTEN = 4;
114        private static final int MSG_DISK_SCANNED = 5;
115        private static final int MSG_DISK_DESTROYED = 6;
116
117        final StorageEventListener mCallback;
118        final Handler mHandler;
119
120        public StorageEventListenerDelegate(StorageEventListener callback, Looper looper) {
121            mCallback = callback;
122            mHandler = new Handler(looper, this);
123        }
124
125        @Override
126        public boolean handleMessage(Message msg) {
127            final SomeArgs args = (SomeArgs) msg.obj;
128            switch (msg.what) {
129                case MSG_STORAGE_STATE_CHANGED:
130                    mCallback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
131                            (String) args.arg3);
132                    args.recycle();
133                    return true;
134                case MSG_VOLUME_STATE_CHANGED:
135                    mCallback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
136                    args.recycle();
137                    return true;
138                case MSG_VOLUME_RECORD_CHANGED:
139                    mCallback.onVolumeRecordChanged((VolumeRecord) args.arg1);
140                    args.recycle();
141                    return true;
142                case MSG_VOLUME_FORGOTTEN:
143                    mCallback.onVolumeForgotten((String) args.arg1);
144                    args.recycle();
145                    return true;
146                case MSG_DISK_SCANNED:
147                    mCallback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
148                    args.recycle();
149                    return true;
150                case MSG_DISK_DESTROYED:
151                    mCallback.onDiskDestroyed((DiskInfo) args.arg1);
152                    args.recycle();
153                    return true;
154            }
155            args.recycle();
156            return false;
157        }
158
159        @Override
160        public void onUsbMassStorageConnectionChanged(boolean connected) throws RemoteException {
161            // Ignored
162        }
163
164        @Override
165        public void onStorageStateChanged(String path, String oldState, String newState) {
166            final SomeArgs args = SomeArgs.obtain();
167            args.arg1 = path;
168            args.arg2 = oldState;
169            args.arg3 = newState;
170            mHandler.obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
171        }
172
173        @Override
174        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
175            final SomeArgs args = SomeArgs.obtain();
176            args.arg1 = vol;
177            args.argi2 = oldState;
178            args.argi3 = newState;
179            mHandler.obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
180        }
181
182        @Override
183        public void onVolumeRecordChanged(VolumeRecord rec) {
184            final SomeArgs args = SomeArgs.obtain();
185            args.arg1 = rec;
186            mHandler.obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
187        }
188
189        @Override
190        public void onVolumeForgotten(String fsUuid) {
191            final SomeArgs args = SomeArgs.obtain();
192            args.arg1 = fsUuid;
193            mHandler.obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
194        }
195
196        @Override
197        public void onDiskScanned(DiskInfo disk, int volumeCount) {
198            final SomeArgs args = SomeArgs.obtain();
199            args.arg1 = disk;
200            args.argi2 = volumeCount;
201            mHandler.obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
202        }
203
204        @Override
205        public void onDiskDestroyed(DiskInfo disk) throws RemoteException {
206            final SomeArgs args = SomeArgs.obtain();
207            args.arg1 = disk;
208            mHandler.obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
209        }
210    }
211
212    /**
213     * Binder listener for OBB action results.
214     */
215    private final ObbActionListener mObbActionListener = new ObbActionListener();
216
217    private class ObbActionListener extends IObbActionListener.Stub {
218        @SuppressWarnings("hiding")
219        private SparseArray<ObbListenerDelegate> mListeners = new SparseArray<ObbListenerDelegate>();
220
221        @Override
222        public void onObbResult(String filename, int nonce, int status) {
223            final ObbListenerDelegate delegate;
224            synchronized (mListeners) {
225                delegate = mListeners.get(nonce);
226                if (delegate != null) {
227                    mListeners.remove(nonce);
228                }
229            }
230
231            if (delegate != null) {
232                delegate.sendObbStateChanged(filename, status);
233            }
234        }
235
236        public int addListener(OnObbStateChangeListener listener) {
237            final ObbListenerDelegate delegate = new ObbListenerDelegate(listener);
238
239            synchronized (mListeners) {
240                mListeners.put(delegate.nonce, delegate);
241            }
242
243            return delegate.nonce;
244        }
245    }
246
247    private int getNextNonce() {
248        return mNextNonce.getAndIncrement();
249    }
250
251    /**
252     * Private class containing sender and receiver code for StorageEvents.
253     */
254    private class ObbListenerDelegate {
255        private final WeakReference<OnObbStateChangeListener> mObbEventListenerRef;
256        private final Handler mHandler;
257
258        private final int nonce;
259
260        ObbListenerDelegate(OnObbStateChangeListener listener) {
261            nonce = getNextNonce();
262            mObbEventListenerRef = new WeakReference<OnObbStateChangeListener>(listener);
263            mHandler = new Handler(mLooper) {
264                @Override
265                public void handleMessage(Message msg) {
266                    final OnObbStateChangeListener changeListener = getListener();
267                    if (changeListener == null) {
268                        return;
269                    }
270
271                    changeListener.onObbStateChange((String) msg.obj, msg.arg1);
272                }
273            };
274        }
275
276        OnObbStateChangeListener getListener() {
277            if (mObbEventListenerRef == null) {
278                return null;
279            }
280            return mObbEventListenerRef.get();
281        }
282
283        void sendObbStateChanged(String path, int state) {
284            mHandler.obtainMessage(0, state, 0, path).sendToTarget();
285        }
286    }
287
288    /** {@hide} */
289    @Deprecated
290    public static StorageManager from(Context context) {
291        return context.getSystemService(StorageManager.class);
292    }
293
294    /**
295     * Constructs a StorageManager object through which an application can
296     * can communicate with the systems mount service.
297     *
298     * @param tgtLooper The {@link android.os.Looper} which events will be received on.
299     *
300     * <p>Applications can get instance of this class by calling
301     * {@link android.content.Context#getSystemService(java.lang.String)} with an argument
302     * of {@link android.content.Context#STORAGE_SERVICE}.
303     *
304     * @hide
305     */
306    public StorageManager(Context context, Looper looper) {
307        mContext = context;
308        mResolver = context.getContentResolver();
309        mLooper = looper;
310        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
311        if (mMountService == null) {
312            throw new IllegalStateException("Failed to find running mount service");
313        }
314    }
315
316    /**
317     * Registers a {@link android.os.storage.StorageEventListener StorageEventListener}.
318     *
319     * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
320     *
321     * @hide
322     */
323    public void registerListener(StorageEventListener listener) {
324        synchronized (mDelegates) {
325            final StorageEventListenerDelegate delegate = new StorageEventListenerDelegate(listener,
326                    mLooper);
327            try {
328                mMountService.registerListener(delegate);
329            } catch (RemoteException e) {
330                throw e.rethrowAsRuntimeException();
331            }
332            mDelegates.add(delegate);
333        }
334    }
335
336    /**
337     * Unregisters a {@link android.os.storage.StorageEventListener StorageEventListener}.
338     *
339     * @param listener A {@link android.os.storage.StorageEventListener StorageEventListener} object.
340     *
341     * @hide
342     */
343    public void unregisterListener(StorageEventListener listener) {
344        synchronized (mDelegates) {
345            for (Iterator<StorageEventListenerDelegate> i = mDelegates.iterator(); i.hasNext();) {
346                final StorageEventListenerDelegate delegate = i.next();
347                if (delegate.mCallback == listener) {
348                    try {
349                        mMountService.unregisterListener(delegate);
350                    } catch (RemoteException e) {
351                        throw e.rethrowAsRuntimeException();
352                    }
353                    i.remove();
354                }
355            }
356        }
357    }
358
359    /**
360     * Enables USB Mass Storage (UMS) on the device.
361     *
362     * @hide
363     */
364    @Deprecated
365    public void enableUsbMassStorage() {
366    }
367
368    /**
369     * Disables USB Mass Storage (UMS) on the device.
370     *
371     * @hide
372     */
373    @Deprecated
374    public void disableUsbMassStorage() {
375    }
376
377    /**
378     * Query if a USB Mass Storage (UMS) host is connected.
379     * @return true if UMS host is connected.
380     *
381     * @hide
382     */
383    @Deprecated
384    public boolean isUsbMassStorageConnected() {
385        return false;
386    }
387
388    /**
389     * Query if a USB Mass Storage (UMS) is enabled on the device.
390     * @return true if UMS host is enabled.
391     *
392     * @hide
393     */
394    @Deprecated
395    public boolean isUsbMassStorageEnabled() {
396        return false;
397    }
398
399    /**
400     * Mount an Opaque Binary Blob (OBB) file. If a <code>key</code> is
401     * specified, it is supplied to the mounting process to be used in any
402     * encryption used in the OBB.
403     * <p>
404     * The OBB will remain mounted for as long as the StorageManager reference
405     * is held by the application. As soon as this reference is lost, the OBBs
406     * in use will be unmounted. The {@link OnObbStateChangeListener} registered
407     * with this call will receive the success or failure of this operation.
408     * <p>
409     * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
410     * file matches a package ID that is owned by the calling program's UID.
411     * That is, shared UID applications can attempt to mount any other
412     * application's OBB that shares its UID.
413     *
414     * @param rawPath the path to the OBB file
415     * @param key secret used to encrypt the OBB; may be <code>null</code> if no
416     *            encryption was used on the OBB.
417     * @param listener will receive the success or failure of the operation
418     * @return whether the mount call was successfully queued or not
419     */
420    public boolean mountObb(String rawPath, String key, OnObbStateChangeListener listener) {
421        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
422        Preconditions.checkNotNull(listener, "listener cannot be null");
423
424        try {
425            final String canonicalPath = new File(rawPath).getCanonicalPath();
426            final int nonce = mObbActionListener.addListener(listener);
427            mMountService.mountObb(rawPath, canonicalPath, key, mObbActionListener, nonce);
428            return true;
429        } catch (IOException e) {
430            throw new IllegalArgumentException("Failed to resolve path: " + rawPath, e);
431        } catch (RemoteException e) {
432            Log.e(TAG, "Failed to mount OBB", e);
433        }
434
435        return false;
436    }
437
438    /**
439     * Unmount an Opaque Binary Blob (OBB) file asynchronously. If the
440     * <code>force</code> flag is true, it will kill any application needed to
441     * unmount the given OBB (even the calling application).
442     * <p>
443     * The {@link OnObbStateChangeListener} registered with this call will
444     * receive the success or failure of this operation.
445     * <p>
446     * <em>Note:</em> you can only mount OBB files for which the OBB tag on the
447     * file matches a package ID that is owned by the calling program's UID.
448     * That is, shared UID applications can obtain access to any other
449     * application's OBB that shares its UID.
450     * <p>
451     *
452     * @param rawPath path to the OBB file
453     * @param force whether to kill any programs using this in order to unmount
454     *            it
455     * @param listener will receive the success or failure of the operation
456     * @return whether the unmount call was successfully queued or not
457     */
458    public boolean unmountObb(String rawPath, boolean force, OnObbStateChangeListener listener) {
459        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
460        Preconditions.checkNotNull(listener, "listener cannot be null");
461
462        try {
463            final int nonce = mObbActionListener.addListener(listener);
464            mMountService.unmountObb(rawPath, force, mObbActionListener, nonce);
465            return true;
466        } catch (RemoteException e) {
467            Log.e(TAG, "Failed to mount OBB", e);
468        }
469
470        return false;
471    }
472
473    /**
474     * Check whether an Opaque Binary Blob (OBB) is mounted or not.
475     *
476     * @param rawPath path to OBB image
477     * @return true if OBB is mounted; false if not mounted or on error
478     */
479    public boolean isObbMounted(String rawPath) {
480        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
481
482        try {
483            return mMountService.isObbMounted(rawPath);
484        } catch (RemoteException e) {
485            Log.e(TAG, "Failed to check if OBB is mounted", e);
486        }
487
488        return false;
489    }
490
491    /**
492     * Check the mounted path of an Opaque Binary Blob (OBB) file. This will
493     * give you the path to where you can obtain access to the internals of the
494     * OBB.
495     *
496     * @param rawPath path to OBB image
497     * @return absolute path to mounted OBB image data or <code>null</code> if
498     *         not mounted or exception encountered trying to read status
499     */
500    public String getMountedObbPath(String rawPath) {
501        Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
502
503        try {
504            return mMountService.getMountedObbPath(rawPath);
505        } catch (RemoteException e) {
506            Log.e(TAG, "Failed to find mounted path for OBB", e);
507        }
508
509        return null;
510    }
511
512    /** {@hide} */
513    public @NonNull List<DiskInfo> getDisks() {
514        try {
515            return Arrays.asList(mMountService.getDisks());
516        } catch (RemoteException e) {
517            throw e.rethrowAsRuntimeException();
518        }
519    }
520
521    /** {@hide} */
522    public @Nullable DiskInfo findDiskById(String id) {
523        Preconditions.checkNotNull(id);
524        // TODO; go directly to service to make this faster
525        for (DiskInfo disk : getDisks()) {
526            if (Objects.equals(disk.id, id)) {
527                return disk;
528            }
529        }
530        return null;
531    }
532
533    /** {@hide} */
534    public @Nullable VolumeInfo findVolumeById(String id) {
535        Preconditions.checkNotNull(id);
536        // TODO; go directly to service to make this faster
537        for (VolumeInfo vol : getVolumes()) {
538            if (Objects.equals(vol.id, id)) {
539                return vol;
540            }
541        }
542        return null;
543    }
544
545    /** {@hide} */
546    public @Nullable VolumeInfo findVolumeByUuid(String fsUuid) {
547        Preconditions.checkNotNull(fsUuid);
548        // TODO; go directly to service to make this faster
549        for (VolumeInfo vol : getVolumes()) {
550            if (Objects.equals(vol.fsUuid, fsUuid)) {
551                return vol;
552            }
553        }
554        return null;
555    }
556
557    /** {@hide} */
558    public @Nullable VolumeRecord findRecordByUuid(String fsUuid) {
559        Preconditions.checkNotNull(fsUuid);
560        // TODO; go directly to service to make this faster
561        for (VolumeRecord rec : getVolumeRecords()) {
562            if (Objects.equals(rec.fsUuid, fsUuid)) {
563                return rec;
564            }
565        }
566        return null;
567    }
568
569    /** {@hide} */
570    public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) {
571        if (emulatedVol != null) {
572            return findVolumeById(emulatedVol.getId().replace("emulated", "private"));
573        } else {
574            return null;
575        }
576    }
577
578    /** {@hide} */
579    public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) {
580        if (privateVol != null) {
581            return findVolumeById(privateVol.getId().replace("private", "emulated"));
582        } else {
583            return null;
584        }
585    }
586
587    /** {@hide} */
588    public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) {
589        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
590            return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
591        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
592            return getPrimaryPhysicalVolume();
593        } else {
594            return findVolumeByUuid(volumeUuid);
595        }
596    }
597
598    /** {@hide} */
599    public @NonNull List<VolumeInfo> getVolumes() {
600        try {
601            return Arrays.asList(mMountService.getVolumes(0));
602        } catch (RemoteException e) {
603            throw e.rethrowAsRuntimeException();
604        }
605    }
606
607    /** {@hide} */
608    public @NonNull List<VolumeInfo> getWritablePrivateVolumes() {
609        try {
610            final ArrayList<VolumeInfo> res = new ArrayList<>();
611            for (VolumeInfo vol : mMountService.getVolumes(0)) {
612                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
613                    res.add(vol);
614                }
615            }
616            return res;
617        } catch (RemoteException e) {
618            throw e.rethrowAsRuntimeException();
619        }
620    }
621
622    /** {@hide} */
623    public @NonNull List<VolumeRecord> getVolumeRecords() {
624        try {
625            return Arrays.asList(mMountService.getVolumeRecords(0));
626        } catch (RemoteException e) {
627            throw e.rethrowAsRuntimeException();
628        }
629    }
630
631    /** {@hide} */
632    public @Nullable String getBestVolumeDescription(VolumeInfo vol) {
633        if (vol == null) return null;
634
635        // Nickname always takes precedence when defined
636        if (!TextUtils.isEmpty(vol.fsUuid)) {
637            final VolumeRecord rec = findRecordByUuid(vol.fsUuid);
638            if (rec != null && !TextUtils.isEmpty(rec.nickname)) {
639                return rec.nickname;
640            }
641        }
642
643        if (!TextUtils.isEmpty(vol.getDescription())) {
644            return vol.getDescription();
645        }
646
647        if (vol.disk != null) {
648            return vol.disk.getDescription();
649        }
650
651        return null;
652    }
653
654    /** {@hide} */
655    public @Nullable VolumeInfo getPrimaryPhysicalVolume() {
656        final List<VolumeInfo> vols = getVolumes();
657        for (VolumeInfo vol : vols) {
658            if (vol.isPrimaryPhysical()) {
659                return vol;
660            }
661        }
662        return null;
663    }
664
665    /** {@hide} */
666    public void mount(String volId) {
667        try {
668            mMountService.mount(volId);
669        } catch (RemoteException e) {
670            throw e.rethrowAsRuntimeException();
671        }
672    }
673
674    /** {@hide} */
675    public void unmount(String volId) {
676        try {
677            mMountService.unmount(volId);
678        } catch (RemoteException e) {
679            throw e.rethrowAsRuntimeException();
680        }
681    }
682
683    /** {@hide} */
684    public void format(String volId) {
685        try {
686            mMountService.format(volId);
687        } catch (RemoteException e) {
688            throw e.rethrowAsRuntimeException();
689        }
690    }
691
692    /** {@hide} */
693    public long benchmark(String volId) {
694        try {
695            return mMountService.benchmark(volId);
696        } catch (RemoteException e) {
697            throw e.rethrowAsRuntimeException();
698        }
699    }
700
701    /** {@hide} */
702    public void partitionPublic(String diskId) {
703        try {
704            mMountService.partitionPublic(diskId);
705        } catch (RemoteException e) {
706            throw e.rethrowAsRuntimeException();
707        }
708    }
709
710    /** {@hide} */
711    public void partitionPrivate(String diskId) {
712        try {
713            mMountService.partitionPrivate(diskId);
714        } catch (RemoteException e) {
715            throw e.rethrowAsRuntimeException();
716        }
717    }
718
719    /** {@hide} */
720    public void partitionMixed(String diskId, int ratio) {
721        try {
722            mMountService.partitionMixed(diskId, ratio);
723        } catch (RemoteException e) {
724            throw e.rethrowAsRuntimeException();
725        }
726    }
727
728    /** {@hide} */
729    public void wipeAdoptableDisks() {
730        // We only wipe devices in "adoptable" locations, which are in a
731        // long-term stable slot/location on the device, where apps have a
732        // reasonable chance of storing sensitive data. (Apps need to go through
733        // SAF to write to transient volumes.)
734        final List<DiskInfo> disks = getDisks();
735        for (DiskInfo disk : disks) {
736            final String diskId = disk.getId();
737            if (disk.isAdoptable()) {
738                Slog.d(TAG, "Found adoptable " + diskId + "; wiping");
739                try {
740                    // TODO: switch to explicit wipe command when we have it,
741                    // for now rely on the fact that vfat format does a wipe
742                    mMountService.partitionPublic(diskId);
743                } catch (Exception e) {
744                    Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e);
745                }
746            } else {
747                Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId());
748            }
749        }
750    }
751
752    /** {@hide} */
753    public void setVolumeNickname(String fsUuid, String nickname) {
754        try {
755            mMountService.setVolumeNickname(fsUuid, nickname);
756        } catch (RemoteException e) {
757            throw e.rethrowAsRuntimeException();
758        }
759    }
760
761    /** {@hide} */
762    public void setVolumeInited(String fsUuid, boolean inited) {
763        try {
764            mMountService.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0,
765                    VolumeRecord.USER_FLAG_INITED);
766        } catch (RemoteException e) {
767            throw e.rethrowAsRuntimeException();
768        }
769    }
770
771    /** {@hide} */
772    public void setVolumeSnoozed(String fsUuid, boolean snoozed) {
773        try {
774            mMountService.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0,
775                    VolumeRecord.USER_FLAG_SNOOZED);
776        } catch (RemoteException e) {
777            throw e.rethrowAsRuntimeException();
778        }
779    }
780
781    /** {@hide} */
782    public void forgetVolume(String fsUuid) {
783        try {
784            mMountService.forgetVolume(fsUuid);
785        } catch (RemoteException e) {
786            throw e.rethrowAsRuntimeException();
787        }
788    }
789
790    /**
791     * This is not the API you're looking for.
792     *
793     * @see PackageManager#getPrimaryStorageCurrentVolume()
794     * @hide
795     */
796    public String getPrimaryStorageUuid() {
797        try {
798            return mMountService.getPrimaryStorageUuid();
799        } catch (RemoteException e) {
800            throw e.rethrowAsRuntimeException();
801        }
802    }
803
804    /**
805     * This is not the API you're looking for.
806     *
807     * @see PackageManager#movePrimaryStorage(VolumeInfo)
808     * @hide
809     */
810    public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
811        try {
812            mMountService.setPrimaryStorageUuid(volumeUuid, callback);
813        } catch (RemoteException e) {
814            throw e.rethrowAsRuntimeException();
815        }
816    }
817
818    /** {@hide} */
819    public @Nullable StorageVolume getStorageVolume(File file) {
820        return getStorageVolume(getVolumeList(), file);
821    }
822
823    /** {@hide} */
824    public static @Nullable StorageVolume getStorageVolume(File file, int userId) {
825        return getStorageVolume(getVolumeList(userId, 0), file);
826    }
827
828    /** {@hide} */
829    private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) {
830        try {
831            file = file.getCanonicalFile();
832        } catch (IOException ignored) {
833            return null;
834        }
835        for (StorageVolume volume : volumes) {
836            File volumeFile = volume.getPathFile();
837            try {
838                volumeFile = volumeFile.getCanonicalFile();
839            } catch (IOException ignored) {
840                continue;
841            }
842            if (FileUtils.contains(volumeFile, file)) {
843                return volume;
844            }
845        }
846        return null;
847    }
848
849    /**
850     * Gets the state of a volume via its mountpoint.
851     * @hide
852     */
853    @Deprecated
854    public @NonNull String getVolumeState(String mountPoint) {
855        final StorageVolume vol = getStorageVolume(new File(mountPoint));
856        if (vol != null) {
857            return vol.getState();
858        } else {
859            return Environment.MEDIA_UNKNOWN;
860        }
861    }
862
863    /** {@hide} */
864    public @NonNull StorageVolume[] getVolumeList() {
865        return getVolumeList(mContext.getUserId(), 0);
866    }
867
868    /** {@hide} */
869    public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) {
870        final IMountService mountService = IMountService.Stub.asInterface(
871                ServiceManager.getService("mount"));
872        try {
873            String packageName = ActivityThread.currentOpPackageName();
874            if (packageName == null) {
875                // Package name can be null if the activity thread is running but the app
876                // hasn't bound yet. In this case we fall back to the first package in the
877                // current UID. This works for runtime permissions as permission state is
878                // per UID and permission realted app ops are updated for all UID packages.
879                String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid(
880                        android.os.Process.myUid());
881                if (packageNames == null || packageNames.length <= 0) {
882                    return new StorageVolume[0];
883                }
884                packageName = packageNames[0];
885            }
886            final int uid = ActivityThread.getPackageManager().getPackageUid(packageName, userId);
887            if (uid <= 0) {
888                return new StorageVolume[0];
889            }
890            return mountService.getVolumeList(uid, packageName, flags);
891        } catch (RemoteException e) {
892            throw e.rethrowAsRuntimeException();
893        }
894    }
895
896    /**
897     * Returns list of paths for all mountable volumes.
898     * @hide
899     */
900    @Deprecated
901    public @NonNull String[] getVolumePaths() {
902        StorageVolume[] volumes = getVolumeList();
903        int count = volumes.length;
904        String[] paths = new String[count];
905        for (int i = 0; i < count; i++) {
906            paths[i] = volumes[i].getPath();
907        }
908        return paths;
909    }
910
911    /** {@hide} */
912    public @NonNull StorageVolume getPrimaryVolume() {
913        return getPrimaryVolume(getVolumeList());
914    }
915
916    /** {@hide} */
917    public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) {
918        for (StorageVolume volume : volumes) {
919            if (volume.isPrimary()) {
920                return volume;
921            }
922        }
923        throw new IllegalStateException("Missing primary storage");
924    }
925
926    /** {@hide} */
927    private static final int DEFAULT_THRESHOLD_PERCENTAGE = 10;
928    private static final long DEFAULT_THRESHOLD_MAX_BYTES = 500 * MB_IN_BYTES;
929    private static final long DEFAULT_FULL_THRESHOLD_BYTES = MB_IN_BYTES;
930
931    /**
932     * Return the number of available bytes until the given path is considered
933     * running low on storage.
934     *
935     * @hide
936     */
937    public long getStorageBytesUntilLow(File path) {
938        return path.getUsableSpace() - getStorageFullBytes(path);
939    }
940
941    /**
942     * Return the number of available bytes at which the given path is
943     * considered running low on storage.
944     *
945     * @hide
946     */
947    public long getStorageLowBytes(File path) {
948        final long lowPercent = Settings.Global.getInt(mResolver,
949                Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE, DEFAULT_THRESHOLD_PERCENTAGE);
950        final long lowBytes = (path.getTotalSpace() * lowPercent) / 100;
951
952        final long maxLowBytes = Settings.Global.getLong(mResolver,
953                Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES);
954
955        return Math.min(lowBytes, maxLowBytes);
956    }
957
958    /**
959     * Return the number of available bytes at which the given path is
960     * considered full.
961     *
962     * @hide
963     */
964    public long getStorageFullBytes(File path) {
965        return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
966                DEFAULT_FULL_THRESHOLD_BYTES);
967    }
968
969    /** {@hide} */
970    public void createUserKey(int userId, int serialNumber) {
971        try {
972            mMountService.createUserKey(userId, serialNumber);
973        } catch (RemoteException e) {
974            throw e.rethrowAsRuntimeException();
975        }
976    }
977
978    /** {@hide} */
979    public void destroyUserKey(int userId) {
980        try {
981            mMountService.destroyUserKey(userId);
982        } catch (RemoteException e) {
983            throw e.rethrowAsRuntimeException();
984        }
985    }
986
987    /** {@hide} */
988    public void unlockUserKey(int userId, int serialNumber, byte[] token) {
989        try {
990            mMountService.unlockUserKey(userId, serialNumber, token);
991        } catch (RemoteException e) {
992            throw e.rethrowAsRuntimeException();
993        }
994    }
995
996    /** {@hide} */
997    public void lockUserKey(int userId) {
998        try {
999            mMountService.lockUserKey(userId);
1000        } catch (RemoteException e) {
1001            throw e.rethrowAsRuntimeException();
1002        }
1003    }
1004
1005    /** {@hide} */
1006    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber) {
1007        try {
1008            mMountService.prepareUserStorage(volumeUuid, userId, serialNumber);
1009        } catch (RemoteException e) {
1010            throw e.rethrowAsRuntimeException();
1011        }
1012    }
1013
1014    /** {@hide} */
1015    public boolean isUserKeyUnlocked(int userId) {
1016        try {
1017            return mMountService.isUserKeyUnlocked(userId);
1018        } catch (RemoteException e) {
1019            throw e.rethrowAsRuntimeException();
1020        }
1021    }
1022
1023    /** {@hide} */
1024    public boolean isPerUserEncryptionEnabled() {
1025        try {
1026            return mMountService.isPerUserEncryptionEnabled();
1027        } catch (RemoteException e) {
1028            throw e.rethrowAsRuntimeException();
1029        }
1030    }
1031
1032    /** {@hide} */
1033    public static File maybeTranslateEmulatedPathToInternal(File path) {
1034        final IMountService mountService = IMountService.Stub.asInterface(
1035                ServiceManager.getService("mount"));
1036        try {
1037            final VolumeInfo[] vols = mountService.getVolumes(0);
1038            for (VolumeInfo vol : vols) {
1039                if ((vol.getType() == VolumeInfo.TYPE_EMULATED
1040                        || vol.getType() == VolumeInfo.TYPE_PUBLIC) && vol.isMountedReadable()) {
1041                    final File internalPath = FileUtils.rewriteAfterRename(vol.getPath(),
1042                            vol.getInternalPath(), path);
1043                    if (internalPath != null && internalPath.exists()) {
1044                        return internalPath;
1045                    }
1046                }
1047            }
1048        } catch (RemoteException ignored) {
1049        }
1050        return path;
1051    }
1052
1053    /** {@hide} */
1054    public ParcelFileDescriptor mountAppFuse(String name) {
1055        try {
1056            return mMountService.mountAppFuse(name);
1057        } catch (RemoteException e) {
1058            throw e.rethrowAsRuntimeException();
1059        }
1060    }
1061
1062    /// Consts to match the password types in cryptfs.h
1063    /** @hide */
1064    public static final int CRYPT_TYPE_PASSWORD = 0;
1065    /** @hide */
1066    public static final int CRYPT_TYPE_DEFAULT = 1;
1067    /** @hide */
1068    public static final int CRYPT_TYPE_PATTERN = 2;
1069    /** @hide */
1070    public static final int CRYPT_TYPE_PIN = 3;
1071
1072    // Constants for the data available via MountService.getField.
1073    /** @hide */
1074    public static final String SYSTEM_LOCALE_KEY = "SystemLocale";
1075    /** @hide */
1076    public static final String OWNER_INFO_KEY = "OwnerInfo";
1077    /** @hide */
1078    public static final String PATTERN_VISIBLE_KEY = "PatternVisible";
1079    /** @hide */
1080    public static final String PASSWORD_VISIBLE_KEY = "PasswordVisible";
1081}
1082