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