StorageManager.java revision fcf1e55821b694df3b8434f40aa3b6d3c3e7ea50
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    /**
828     * Return the {@link StorageVolume} that contains the given file, or {@code null} if none.
829     */
830    public @Nullable StorageVolume getStorageVolume(File file) {
831        return getStorageVolume(getVolumeList(), file);
832    }
833
834    /** {@hide} */
835    public static @Nullable StorageVolume getStorageVolume(File file, int userId) {
836        return getStorageVolume(getVolumeList(userId, 0), file);
837    }
838
839    /** {@hide} */
840    private static @Nullable StorageVolume getStorageVolume(StorageVolume[] volumes, File file) {
841        if (file == null) {
842            return null;
843        }
844        try {
845            file = file.getCanonicalFile();
846        } catch (IOException ignored) {
847            Slog.d(TAG, "Could not get canonical path for " + file);
848            return null;
849        }
850        for (StorageVolume volume : volumes) {
851            File volumeFile = volume.getPathFile();
852            try {
853                volumeFile = volumeFile.getCanonicalFile();
854            } catch (IOException ignored) {
855                continue;
856            }
857            if (FileUtils.contains(volumeFile, file)) {
858                return volume;
859            }
860        }
861        return null;
862    }
863
864    /**
865     * Gets the state of a volume via its mountpoint.
866     * @hide
867     */
868    @Deprecated
869    public @NonNull String getVolumeState(String mountPoint) {
870        final StorageVolume vol = getStorageVolume(new File(mountPoint));
871        if (vol != null) {
872            return vol.getState();
873        } else {
874            return Environment.MEDIA_UNKNOWN;
875        }
876    }
877
878    /**
879     * Return the list of shared/external storage volumes available to the
880     * current user. This includes both the primary shared storage device and
881     * any attached external volumes including SD cards and USB drives.
882     *
883     * @see Environment#getExternalStorageDirectory()
884     * @see StorageVolume#createAccessIntent(String)
885     */
886    public @NonNull List<StorageVolume> getStorageVolumes() {
887        final ArrayList<StorageVolume> res = new ArrayList<>();
888        Collections.addAll(res,
889                getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE));
890        return res;
891    }
892
893    /**
894     * Return the primary shared/external storage volume available to the
895     * current user. This volume is the same storage device returned by
896     * {@link Environment#getExternalStorageDirectory()} and
897     * {@link Context#getExternalFilesDir(String)}.
898     */
899    public @NonNull StorageVolume getPrimaryStorageVolume() {
900        return getVolumeList(UserHandle.myUserId(), FLAG_REAL_STATE | FLAG_INCLUDE_INVISIBLE)[0];
901    }
902
903    /** @removed */
904    public @NonNull StorageVolume[] getVolumeList() {
905        return getVolumeList(mContext.getUserId(), 0);
906    }
907
908    /** {@hide} */
909    public static @NonNull StorageVolume[] getVolumeList(int userId, int flags) {
910        final IMountService mountService = IMountService.Stub.asInterface(
911                ServiceManager.getService("mount"));
912        try {
913            String packageName = ActivityThread.currentOpPackageName();
914            if (packageName == null) {
915                // Package name can be null if the activity thread is running but the app
916                // hasn't bound yet. In this case we fall back to the first package in the
917                // current UID. This works for runtime permissions as permission state is
918                // per UID and permission realted app ops are updated for all UID packages.
919                String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid(
920                        android.os.Process.myUid());
921                if (packageNames == null || packageNames.length <= 0) {
922                    return new StorageVolume[0];
923                }
924                packageName = packageNames[0];
925            }
926            final int uid = ActivityThread.getPackageManager().getPackageUid(packageName,
927                    PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
928            if (uid <= 0) {
929                return new StorageVolume[0];
930            }
931            return mountService.getVolumeList(uid, packageName, flags);
932        } catch (RemoteException e) {
933            throw e.rethrowFromSystemServer();
934        }
935    }
936
937    /**
938     * Returns list of paths for all mountable volumes.
939     * @hide
940     */
941    @Deprecated
942    public @NonNull String[] getVolumePaths() {
943        StorageVolume[] volumes = getVolumeList();
944        int count = volumes.length;
945        String[] paths = new String[count];
946        for (int i = 0; i < count; i++) {
947            paths[i] = volumes[i].getPath();
948        }
949        return paths;
950    }
951
952    /** @removed */
953    public @NonNull StorageVolume getPrimaryVolume() {
954        return getPrimaryVolume(getVolumeList());
955    }
956
957    /** {@hide} */
958    public static @NonNull StorageVolume getPrimaryVolume(StorageVolume[] volumes) {
959        for (StorageVolume volume : volumes) {
960            if (volume.isPrimary()) {
961                return volume;
962            }
963        }
964        throw new IllegalStateException("Missing primary storage");
965    }
966
967    /** {@hide} */
968    private static final int DEFAULT_THRESHOLD_PERCENTAGE = 10;
969    private static final long DEFAULT_THRESHOLD_MAX_BYTES = 500 * MB_IN_BYTES;
970    private static final long DEFAULT_FULL_THRESHOLD_BYTES = MB_IN_BYTES;
971
972    /**
973     * Return the number of available bytes until the given path is considered
974     * running low on storage.
975     *
976     * @hide
977     */
978    public long getStorageBytesUntilLow(File path) {
979        return path.getUsableSpace() - getStorageFullBytes(path);
980    }
981
982    /**
983     * Return the number of available bytes at which the given path is
984     * considered running low on storage.
985     *
986     * @hide
987     */
988    public long getStorageLowBytes(File path) {
989        final long lowPercent = Settings.Global.getInt(mResolver,
990                Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE, DEFAULT_THRESHOLD_PERCENTAGE);
991        final long lowBytes = (path.getTotalSpace() * lowPercent) / 100;
992
993        final long maxLowBytes = Settings.Global.getLong(mResolver,
994                Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES, DEFAULT_THRESHOLD_MAX_BYTES);
995
996        return Math.min(lowBytes, maxLowBytes);
997    }
998
999    /**
1000     * Return the number of available bytes at which the given path is
1001     * considered full.
1002     *
1003     * @hide
1004     */
1005    public long getStorageFullBytes(File path) {
1006        return Settings.Global.getLong(mResolver, Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
1007                DEFAULT_FULL_THRESHOLD_BYTES);
1008    }
1009
1010    /** {@hide} */
1011    public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
1012        try {
1013            mMountService.createUserKey(userId, serialNumber, ephemeral);
1014        } catch (RemoteException e) {
1015            throw e.rethrowFromSystemServer();
1016        }
1017    }
1018
1019    /** {@hide} */
1020    public void destroyUserKey(int userId) {
1021        try {
1022            mMountService.destroyUserKey(userId);
1023        } catch (RemoteException e) {
1024            throw e.rethrowFromSystemServer();
1025        }
1026    }
1027
1028    /** {@hide} */
1029    public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
1030        try {
1031            mMountService.unlockUserKey(userId, serialNumber, token, secret);
1032        } catch (RemoteException e) {
1033            throw e.rethrowFromSystemServer();
1034        }
1035    }
1036
1037    /** {@hide} */
1038    public void lockUserKey(int userId) {
1039        try {
1040            mMountService.lockUserKey(userId);
1041        } catch (RemoteException e) {
1042            throw e.rethrowFromSystemServer();
1043        }
1044    }
1045
1046    /** {@hide} */
1047    public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
1048        try {
1049            mMountService.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
1050        } catch (RemoteException e) {
1051            throw e.rethrowFromSystemServer();
1052        }
1053    }
1054
1055    /** {@hide} */
1056    public void destroyUserStorage(String volumeUuid, int userId, int flags) {
1057        try {
1058            mMountService.destroyUserStorage(volumeUuid, userId, flags);
1059        } catch (RemoteException e) {
1060            throw e.rethrowFromSystemServer();
1061        }
1062    }
1063
1064    /** {@hide} */
1065    public boolean isUserKeyUnlocked(int userId) {
1066        try {
1067            return mMountService.isUserKeyUnlocked(userId);
1068        } catch (RemoteException e) {
1069            throw e.rethrowFromSystemServer();
1070        }
1071    }
1072
1073    /**
1074     * Return if data stored at or under the given path will be encrypted while
1075     * at rest. This can help apps avoid the overhead of double-encrypting data.
1076     */
1077    public boolean isEncrypted(File file) {
1078        if (FileUtils.contains(Environment.getDataDirectory(), file)) {
1079            return isEncrypted();
1080        } else if (FileUtils.contains(Environment.getExpandDirectory(), file)) {
1081            return true;
1082        }
1083        // TODO: extend to support shared storage
1084        return false;
1085    }
1086
1087    /** {@hide}
1088     * Is this device encryptable or already encrypted?
1089     * @return true for encryptable or encrypted
1090     *         false not encrypted and not encryptable
1091     */
1092    public static boolean isEncryptable() {
1093        final String state = SystemProperties.get("ro.crypto.state", "unsupported");
1094        return !"unsupported".equalsIgnoreCase(state);
1095    }
1096
1097    /** {@hide}
1098     * Is this device already encrypted?
1099     * @return true for encrypted. (Implies isEncryptable() == true)
1100     *         false not encrypted
1101     */
1102    public static boolean isEncrypted() {
1103        final String state = SystemProperties.get("ro.crypto.state", "");
1104        return "encrypted".equalsIgnoreCase(state);
1105    }
1106
1107    /** {@hide}
1108     * Is this device file encrypted?
1109     * @return true for file encrypted. (Implies isEncrypted() == true)
1110     *         false not encrypted or block encrypted
1111     */
1112    public static boolean isFileEncryptedNativeOnly() {
1113        if (!isEncrypted()) {
1114            return false;
1115        }
1116
1117        final String status = SystemProperties.get("ro.crypto.type", "");
1118        return "file".equalsIgnoreCase(status);
1119    }
1120
1121    /** {@hide}
1122     * Is this device block encrypted?
1123     * @return true for block encrypted. (Implies isEncrypted() == true)
1124     *         false not encrypted or file encrypted
1125     */
1126    public static boolean isBlockEncrypted() {
1127        if (!isEncrypted()) {
1128            return false;
1129        }
1130        final String status = SystemProperties.get("ro.crypto.type", "");
1131        return "block".equalsIgnoreCase(status);
1132    }
1133
1134    /** {@hide}
1135     * Is this device block encrypted with credentials?
1136     * @return true for crediential block encrypted.
1137     *         (Implies isBlockEncrypted() == true)
1138     *         false not encrypted, file encrypted or default block encrypted
1139     */
1140    public static boolean isNonDefaultBlockEncrypted() {
1141        if (!isBlockEncrypted()) {
1142            return false;
1143        }
1144
1145        try {
1146            IMountService mountService = IMountService.Stub.asInterface(
1147                    ServiceManager.getService("mount"));
1148            return mountService.getPasswordType() != CRYPT_TYPE_DEFAULT;
1149        } catch (RemoteException e) {
1150            Log.e(TAG, "Error getting encryption type");
1151            return false;
1152        }
1153    }
1154
1155    /** {@hide}
1156     * Is this device in the process of being block encrypted?
1157     * @return true for encrypting.
1158     *         false otherwise
1159     * Whether device isEncrypted at this point is undefined
1160     * Note that only system services and CryptKeeper will ever see this return
1161     * true - no app will ever be launched in this state.
1162     * Also note that this state will not change without a teardown of the
1163     * framework, so no service needs to check for changes during their lifespan
1164     */
1165    public static boolean isBlockEncrypting() {
1166        final String state = SystemProperties.get("vold.encrypt_progress", "");
1167        return !"".equalsIgnoreCase(state);
1168    }
1169
1170    /** {@hide}
1171     * Is this device non default block encrypted and in the process of
1172     * prompting for credentials?
1173     * @return true for prompting for credentials.
1174     *         (Implies isNonDefaultBlockEncrypted() == true)
1175     *         false otherwise
1176     * Note that only system services and CryptKeeper will ever see this return
1177     * true - no app will ever be launched in this state.
1178     * Also note that this state will not change without a teardown of the
1179     * framework, so no service needs to check for changes during their lifespan
1180     */
1181    public static boolean inCryptKeeperBounce() {
1182        final String status = SystemProperties.get("vold.decrypt");
1183        return "trigger_restart_min_framework".equals(status);
1184    }
1185
1186    /** {@hide} */
1187    public static boolean isFileEncryptedEmulatedOnly() {
1188        return SystemProperties.getBoolean(StorageManager.PROP_EMULATE_FBE, false);
1189    }
1190
1191    /** {@hide}
1192     * Is this device running in a file encrypted mode, either native or emulated?
1193     * @return true for file encrypted, false otherwise
1194     */
1195    public static boolean isFileEncryptedNativeOrEmulated() {
1196        return isFileEncryptedNativeOnly()
1197               || isFileEncryptedEmulatedOnly();
1198    }
1199
1200    /** {@hide} */
1201    public static File maybeTranslateEmulatedPathToInternal(File path) {
1202        final IMountService mountService = IMountService.Stub.asInterface(
1203                ServiceManager.getService("mount"));
1204        try {
1205            final VolumeInfo[] vols = mountService.getVolumes(0);
1206            for (VolumeInfo vol : vols) {
1207                if ((vol.getType() == VolumeInfo.TYPE_EMULATED
1208                        || vol.getType() == VolumeInfo.TYPE_PUBLIC) && vol.isMountedReadable()) {
1209                    final File internalPath = FileUtils.rewriteAfterRename(vol.getPath(),
1210                            vol.getInternalPath(), path);
1211                    if (internalPath != null && internalPath.exists()) {
1212                        return internalPath;
1213                    }
1214                }
1215            }
1216        } catch (RemoteException e) {
1217            throw e.rethrowFromSystemServer();
1218        }
1219        return path;
1220    }
1221
1222    /** {@hide} */
1223    public ParcelFileDescriptor mountAppFuse(String name) {
1224        try {
1225            return mMountService.mountAppFuse(name);
1226        } catch (RemoteException e) {
1227            throw e.rethrowFromSystemServer();
1228        }
1229    }
1230
1231    /// Consts to match the password types in cryptfs.h
1232    /** @hide */
1233    public static final int CRYPT_TYPE_PASSWORD = 0;
1234    /** @hide */
1235    public static final int CRYPT_TYPE_DEFAULT = 1;
1236    /** @hide */
1237    public static final int CRYPT_TYPE_PATTERN = 2;
1238    /** @hide */
1239    public static final int CRYPT_TYPE_PIN = 3;
1240
1241    // Constants for the data available via MountService.getField.
1242    /** @hide */
1243    public static final String SYSTEM_LOCALE_KEY = "SystemLocale";
1244    /** @hide */
1245    public static final String OWNER_INFO_KEY = "OwnerInfo";
1246    /** @hide */
1247    public static final String PATTERN_VISIBLE_KEY = "PatternVisible";
1248    /** @hide */
1249    public static final String PASSWORD_VISIBLE_KEY = "PasswordVisible";
1250}
1251