MountService.java revision 9b10ef5fe85e9d29721ff0cd15161f960d38a8db
1/*
2 * Copyright (C) 2007 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 com.android.server;
18
19import com.android.server.am.ActivityManagerService;
20
21import android.content.BroadcastReceiver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.content.pm.PackageManager;
26import android.net.Uri;
27import android.os.storage.IMountService;
28import android.os.storage.IMountServiceListener;
29import android.os.storage.StorageResultCode;
30import android.os.Handler;
31import android.os.Message;
32import android.os.RemoteException;
33import android.os.IBinder;
34import android.os.Environment;
35import android.os.ServiceManager;
36import android.os.SystemClock;
37import android.os.SystemProperties;
38import android.util.Log;
39import java.util.ArrayList;
40import java.util.HashSet;
41
42/**
43 * MountService implements back-end services for platform storage
44 * management.
45 * @hide - Applications should use android.os.storage.StorageManager
46 * to access the MountService.
47 */
48class MountService extends IMountService.Stub
49        implements INativeDaemonConnectorCallbacks {
50    private static final boolean LOCAL_LOGD = false;
51
52    private static final String TAG = "MountService";
53
54    /*
55     * Internal vold volume state constants
56     */
57    class VolumeState {
58        public static final int Init       = -1;
59        public static final int NoMedia    = 0;
60        public static final int Idle       = 1;
61        public static final int Pending    = 2;
62        public static final int Checking   = 3;
63        public static final int Mounted    = 4;
64        public static final int Unmounting = 5;
65        public static final int Formatting = 6;
66        public static final int Shared     = 7;
67        public static final int SharedMnt  = 8;
68    }
69
70    /*
71     * Internal vold response code constants
72     */
73    class VoldResponseCode {
74        /*
75         * 100 series - Requestion action was initiated; expect another reply
76         *              before proceeding with a new command.
77         */
78        public static final int VolumeListResult               = 110;
79        public static final int AsecListResult                 = 111;
80        public static final int StorageUsersListResult         = 112;
81
82        /*
83         * 200 series - Requestion action has been successfully completed.
84         */
85        public static final int ShareStatusResult              = 210;
86        public static final int AsecPathResult                 = 211;
87        public static final int ShareEnabledResult             = 212;
88
89        /*
90         * 400 series - Command was accepted, but the requested action
91         *              did not take place.
92         */
93        public static final int OpFailedNoMedia                = 401;
94        public static final int OpFailedMediaBlank             = 402;
95        public static final int OpFailedMediaCorrupt           = 403;
96        public static final int OpFailedVolNotMounted          = 404;
97        public static final int OpFailedStorageBusy            = 405;
98
99        /*
100         * 600 series - Unsolicited broadcasts.
101         */
102        public static final int VolumeStateChange              = 605;
103        public static final int ShareAvailabilityChange        = 620;
104        public static final int VolumeDiskInserted             = 630;
105        public static final int VolumeDiskRemoved              = 631;
106        public static final int VolumeBadRemoval               = 632;
107    }
108
109    private Context                               mContext;
110    private NativeDaemonConnector                 mConnector;
111    private String                                mLegacyState = Environment.MEDIA_REMOVED;
112    private PackageManagerService                 mPms;
113    private boolean                               mUmsEnabling;
114    // Used as a lock for methods that register/unregister listeners.
115    final private ArrayList<MountServiceBinderListener> mListeners =
116            new ArrayList<MountServiceBinderListener>();
117    private boolean                               mBooted = false;
118    private boolean                               mReady = false;
119    private boolean                               mSendUmsConnectedOnBoot = false;
120
121    /**
122     * Private hash of currently mounted secure containers.
123     * Used as a lock in methods to manipulate secure containers.
124     */
125    final private HashSet<String> mAsecMountSet = new HashSet<String>();
126
127    private static final int H_UNMOUNT_PM_UPDATE = 1;
128    private static final int H_UNMOUNT_PM_DONE = 2;
129    private static final int H_UNMOUNT_MS = 3;
130    private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
131    private static final int MAX_UNMOUNT_RETRIES = 4;
132
133    private IntentFilter mPmFilter = new IntentFilter(
134            Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
135    private BroadcastReceiver mPmReceiver = new BroadcastReceiver() {
136        public void onReceive(Context context, Intent intent) {
137            String action = intent.getAction();
138            if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
139                mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
140            }
141        }
142    };
143
144    class UnmountCallBack {
145        String path;
146        int retries;
147        boolean force;
148
149        UnmountCallBack(String path, boolean force) {
150            retries = 0;
151            this.path = path;
152            this.force = force;
153        }
154
155        void handleFinished() {
156            doUnmountVolume(path, true);
157        }
158    }
159
160    class UmsEnableCallBack extends UnmountCallBack {
161        String method;
162
163        UmsEnableCallBack(String path, String method, boolean force) {
164            super(path, force);
165            this.method = method;
166        }
167
168        @Override
169        void handleFinished() {
170            super.handleFinished();
171            doShareUnshareVolume(path, method, true);
172        }
173    }
174
175    final private Handler mHandler = new Handler() {
176        ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
177
178        public void handleMessage(Message msg) {
179            switch (msg.what) {
180                case H_UNMOUNT_PM_UPDATE: {
181                    UnmountCallBack ucb = (UnmountCallBack) msg.obj;
182                    mForceUnmounts.add(ucb);
183                    mContext.registerReceiver(mPmReceiver, mPmFilter);
184                    boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
185                    if (!hasExtPkgs) {
186                        // Unregister right away
187                        mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
188                    }
189                    break;
190                }
191                case H_UNMOUNT_PM_DONE: {
192                    // Unregister receiver
193                    mContext.unregisterReceiver(mPmReceiver);
194                    UnmountCallBack ucb = mForceUnmounts.get(0);
195                    if (ucb == null || ucb.path == null) {
196                        // Just ignore
197                        return;
198                    }
199                    String path = ucb.path;
200                    boolean done = false;
201                    if (!ucb.force) {
202                        done = true;
203                    } else {
204                        int pids[] = getStorageUsers(path);
205                        if (pids == null || pids.length == 0) {
206                            done = true;
207                        } else {
208                            // Kill processes holding references first
209                            ActivityManagerService ams = (ActivityManagerService)
210                            ServiceManager.getService("activity");
211                            // Eliminate system process here?
212                            boolean ret = ams.killPidsForMemory(pids);
213                            if (ret) {
214                                // Confirm if file references have been freed.
215                                pids = getStorageUsers(path);
216                                if (pids == null || pids.length == 0) {
217                                    done = true;
218                                }
219                            }
220                        }
221                    }
222                    if (done) {
223                        mForceUnmounts.remove(0);
224                        mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
225                                ucb));
226                    } else {
227                        if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
228                            Log.i(TAG, "Cannot unmount inspite of " +
229                                    MAX_UNMOUNT_RETRIES + " to unmount media");
230                            // Send final broadcast indicating failure to unmount.
231                        } else {
232                            mHandler.sendMessageDelayed(
233                                    mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
234                                            ucb.retries++),
235                                    RETRY_UNMOUNT_DELAY);
236                        }
237                    }
238                    break;
239                }
240                case H_UNMOUNT_MS : {
241                    UnmountCallBack ucb = (UnmountCallBack) msg.obj;
242                    ucb.handleFinished();
243                    break;
244                }
245            }
246        }
247    };
248
249    private void waitForReady() {
250        while (mReady == false) {
251            for (int retries = 5; retries > 0; retries--) {
252                if (mReady) {
253                    return;
254                }
255                SystemClock.sleep(1000);
256            }
257            Log.w(TAG, "Waiting too long for mReady!");
258        }
259    }
260
261    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
262        public void onReceive(Context context, Intent intent) {
263            String action = intent.getAction();
264
265            if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
266                mBooted = true;
267
268                /*
269                 * In the simulator, we need to broadcast a volume mounted event
270                 * to make the media scanner run.
271                 */
272                if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
273                    notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
274                    return;
275                }
276                new Thread() {
277                    public void run() {
278                        try {
279                            String path = Environment.getExternalStorageDirectory().getPath();
280                            if (getVolumeState(
281                                    Environment.getExternalStorageDirectory().getPath()).equals(
282                                            Environment.MEDIA_UNMOUNTED)) {
283                                int rc = doMountVolume(path);
284                                if (rc != StorageResultCode.OperationSucceeded) {
285                                    Log.e(TAG, String.format("Boot-time mount failed (%d)", rc));
286                                }
287                            }
288                            /*
289                             * If UMS is connected in boot, send the connected event
290                             * now that we're up.
291                             */
292                            if (mSendUmsConnectedOnBoot) {
293                                sendUmsIntent(true);
294                                mSendUmsConnectedOnBoot = false;
295                            }
296                        } catch (Exception ex) {
297                            Log.e(TAG, "Boot-time mount exception", ex);
298                        }
299                    }
300                }.start();
301            }
302        }
303    };
304
305    private final class MountServiceBinderListener implements IBinder.DeathRecipient {
306        final IMountServiceListener mListener;
307
308        MountServiceBinderListener(IMountServiceListener listener) {
309            mListener = listener;
310
311        }
312
313        public void binderDied() {
314            if (LOCAL_LOGD) Log.d(TAG, "An IMountServiceListener has died!");
315            synchronized(mListeners) {
316                mListeners.remove(this);
317                mListener.asBinder().unlinkToDeath(this, 0);
318            }
319        }
320    }
321
322    private void doShareUnshareVolume(String path, String method, boolean enable) {
323        // TODO: Add support for multiple share methods
324        if (!method.equals("ums")) {
325            throw new IllegalArgumentException(String.format("Method %s not supported", method));
326        }
327
328        try {
329            mConnector.doCommand(String.format(
330                    "volume %sshare %s %s", (enable ? "" : "un"), path, method));
331        } catch (NativeDaemonConnectorException e) {
332            Log.e(TAG, "Failed to share/unshare", e);
333        }
334    }
335
336    private void updatePublicVolumeState(String path, String state) {
337        if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
338            Log.w(TAG, "Multiple volumes not currently supported");
339            return;
340        }
341
342        if (mLegacyState.equals(state)) {
343            Log.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
344            return;
345        }
346
347        String oldState = mLegacyState;
348        mLegacyState = state;
349
350        synchronized (mListeners) {
351            for (int i = mListeners.size() -1; i >= 0; i--) {
352                MountServiceBinderListener bl = mListeners.get(i);
353                try {
354                    bl.mListener.onStorageStateChanged(path, oldState, state);
355                } catch (RemoteException rex) {
356                    Log.e(TAG, "Listener dead");
357                    mListeners.remove(i);
358                } catch (Exception ex) {
359                    Log.e(TAG, "Listener failed", ex);
360                }
361            }
362        }
363    }
364
365    /**
366     *
367     * Callback from NativeDaemonConnector
368     */
369    public void onDaemonConnected() {
370        /*
371         * Since we'll be calling back into the NativeDaemonConnector,
372         * we need to do our work in a new thread.
373         */
374        new Thread() {
375            public void run() {
376                /**
377                 * Determine media state and UMS detection status
378                 */
379                String path = Environment.getExternalStorageDirectory().getPath();
380                String state = Environment.MEDIA_REMOVED;
381
382                try {
383                    String[] vols = mConnector.doListCommand(
384                        "volume list", VoldResponseCode.VolumeListResult);
385                    for (String volstr : vols) {
386                        String[] tok = volstr.split(" ");
387                        // FMT: <label> <mountpoint> <state>
388                        if (!tok[1].equals(path)) {
389                            Log.w(TAG, String.format(
390                                    "Skipping unknown volume '%s'",tok[1]));
391                            continue;
392                        }
393                        int st = Integer.parseInt(tok[2]);
394                        if (st == VolumeState.NoMedia) {
395                            state = Environment.MEDIA_REMOVED;
396                        } else if (st == VolumeState.Idle) {
397                            state = Environment.MEDIA_UNMOUNTED;
398                        } else if (st == VolumeState.Mounted) {
399                            state = Environment.MEDIA_MOUNTED;
400                            Log.i(TAG, "Media already mounted on daemon connection");
401                        } else if (st == VolumeState.Shared) {
402                            state = Environment.MEDIA_SHARED;
403                            Log.i(TAG, "Media shared on daemon connection");
404                        } else {
405                            throw new Exception(String.format("Unexpected state %d", st));
406                        }
407                    }
408                    if (state != null) {
409                        updatePublicVolumeState(path, state);
410                    }
411                } catch (Exception e) {
412                    Log.e(TAG, "Error processing initial volume state", e);
413                    updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
414                }
415
416                try {
417                    boolean avail = doGetShareMethodAvailable("ums");
418                    notifyShareAvailabilityChange("ums", avail);
419                } catch (Exception ex) {
420                    Log.w(TAG, "Failed to get share availability");
421                }
422                /*
423                 * Now that we've done our initialization, release
424                 * the hounds!
425                 */
426                mReady = true;
427            }
428        }.start();
429    }
430
431    /**
432     * Callback from NativeDaemonConnector
433     */
434    public boolean onEvent(int code, String raw, String[] cooked) {
435        Intent in = null;
436
437        if (code == VoldResponseCode.VolumeStateChange) {
438            /*
439             * One of the volumes we're managing has changed state.
440             * Format: "NNN Volume <label> <path> state changed
441             * from <old_#> (<old_str>) to <new_#> (<new_str>)"
442             */
443            notifyVolumeStateChange(
444                    cooked[2], cooked[3], Integer.parseInt(cooked[7]),
445                            Integer.parseInt(cooked[10]));
446        } else if (code == VoldResponseCode.ShareAvailabilityChange) {
447            // FMT: NNN Share method <method> now <available|unavailable>
448            boolean avail = false;
449            if (cooked[5].equals("available")) {
450                avail = true;
451            }
452            notifyShareAvailabilityChange(cooked[3], avail);
453        } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
454                   (code == VoldResponseCode.VolumeDiskRemoved) ||
455                   (code == VoldResponseCode.VolumeBadRemoval)) {
456            // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
457            // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
458            // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
459            final String label = cooked[2];
460            final String path = cooked[3];
461            int major = -1;
462            int minor = -1;
463
464            try {
465                String devComp = cooked[6].substring(1, cooked[6].length() -1);
466                String[] devTok = devComp.split(":");
467                major = Integer.parseInt(devTok[0]);
468                minor = Integer.parseInt(devTok[1]);
469            } catch (Exception ex) {
470                Log.e(TAG, "Failed to parse major/minor", ex);
471            }
472
473            if (code == VoldResponseCode.VolumeDiskInserted) {
474                new Thread() {
475                    public void run() {
476                        try {
477                            int rc;
478                            if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
479                                Log.w(TAG, String.format("Insertion mount failed (%d)", rc));
480                            }
481                        } catch (Exception ex) {
482                            Log.w(TAG, "Failed to mount media on insertion", ex);
483                        }
484                    }
485                }.start();
486            } else if (code == VoldResponseCode.VolumeDiskRemoved) {
487                /*
488                 * This event gets trumped if we're already in BAD_REMOVAL state
489                 */
490                if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
491                    return true;
492                }
493                /* Send the media unmounted event first */
494                updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
495                in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
496                mContext.sendBroadcast(in);
497
498                updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
499                in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
500            } else if (code == VoldResponseCode.VolumeBadRemoval) {
501                /* Send the media unmounted event first */
502                updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
503                in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
504                mContext.sendBroadcast(in);
505
506                updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
507                in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
508            } else {
509                Log.e(TAG, String.format("Unknown code {%d}", code));
510            }
511        } else {
512            return false;
513        }
514
515        if (in != null) {
516            mContext.sendBroadcast(in);
517	}
518       return true;
519    }
520
521    private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
522        String vs = getVolumeState(path);
523
524        Intent in = null;
525
526        if (oldState == VolumeState.Shared && newState != oldState) {
527            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
528                                                Uri.parse("file://" + path)));
529        }
530
531        if (newState == VolumeState.Init) {
532        } else if (newState == VolumeState.NoMedia) {
533            // NoMedia is handled via Disk Remove events
534        } else if (newState == VolumeState.Idle) {
535            /*
536             * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
537             * if we're in the process of enabling UMS
538             */
539            if (!vs.equals(
540                    Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
541                            Environment.MEDIA_NOFS) && !vs.equals(
542                                    Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
543                updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
544                in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
545            }
546        } else if (newState == VolumeState.Pending) {
547        } else if (newState == VolumeState.Checking) {
548            updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
549            in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
550        } else if (newState == VolumeState.Mounted) {
551            updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
552            // Update media status on PackageManagerService to mount packages on sdcard
553            mPms.updateExternalMediaStatus(true);
554            in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
555            in.putExtra("read-only", false);
556        } else if (newState == VolumeState.Unmounting) {
557            mPms.updateExternalMediaStatus(false);
558            in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
559        } else if (newState == VolumeState.Formatting) {
560        } else if (newState == VolumeState.Shared) {
561            /* Send the media unmounted event first */
562            updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
563            in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
564            mContext.sendBroadcast(in);
565
566            updatePublicVolumeState(path, Environment.MEDIA_SHARED);
567            in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
568        } else if (newState == VolumeState.SharedMnt) {
569            Log.e(TAG, "Live shared mounts not supported yet!");
570            return;
571        } else {
572            Log.e(TAG, "Unhandled VolumeState {" + newState + "}");
573        }
574
575        if (in != null) {
576            mContext.sendBroadcast(in);
577        }
578    }
579
580    private boolean doGetShareMethodAvailable(String method) {
581        ArrayList<String> rsp = mConnector.doCommand("share status " + method);
582
583        for (String line : rsp) {
584            String []tok = line.split(" ");
585            int code;
586            try {
587                code = Integer.parseInt(tok[0]);
588            } catch (NumberFormatException nfe) {
589                Log.e(TAG, String.format("Error parsing code %s", tok[0]));
590                return false;
591            }
592            if (code == VoldResponseCode.ShareStatusResult) {
593                if (tok[2].equals("available"))
594                    return true;
595                return false;
596            } else {
597                Log.e(TAG, String.format("Unexpected response code %d", code));
598                return false;
599            }
600        }
601        Log.e(TAG, "Got an empty response");
602        return false;
603    }
604
605    private int doMountVolume(String path) {
606        int rc = StorageResultCode.OperationSucceeded;
607
608        try {
609            mConnector.doCommand(String.format("volume mount %s", path));
610        } catch (NativeDaemonConnectorException e) {
611            /*
612             * Mount failed for some reason
613             */
614            Intent in = null;
615            int code = e.getCode();
616            if (code == VoldResponseCode.OpFailedNoMedia) {
617                /*
618                 * Attempt to mount but no media inserted
619                 */
620                rc = StorageResultCode.OperationFailedNoMedia;
621            } else if (code == VoldResponseCode.OpFailedMediaBlank) {
622                /*
623                 * Media is blank or does not contain a supported filesystem
624                 */
625                updatePublicVolumeState(path, Environment.MEDIA_NOFS);
626                in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
627                rc = StorageResultCode.OperationFailedMediaBlank;
628            } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
629                /*
630                 * Volume consistency check failed
631                 */
632                updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
633                in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
634                rc = StorageResultCode.OperationFailedMediaCorrupt;
635            } else {
636                rc = StorageResultCode.OperationFailedInternalError;
637            }
638
639            /*
640             * Send broadcast intent (if required for the failure)
641             */
642            if (in != null) {
643                mContext.sendBroadcast(in);
644            }
645        }
646
647        return rc;
648    }
649
650    /*
651     * If force is not set, we do not unmount if there are
652     * processes holding references to the volume about to be unmounted.
653     * If force is set, all the processes holding references need to be
654     * killed via the ActivityManager before actually unmounting the volume.
655     * This might even take a while and might be retried after timed delays
656     * to make sure we dont end up in an instable state and kill some core
657     * processes.
658     */
659    private int doUnmountVolume(String path, boolean force) {
660        if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
661            return VoldResponseCode.OpFailedVolNotMounted;
662        }
663
664        // We unmounted the volume. No of the asec containers are available now.
665        synchronized (mAsecMountSet) {
666            mAsecMountSet.clear();
667        }
668        // Notify PackageManager of potential media removal and deal with
669        // return code later on. The caller of this api should be aware or have been
670        // notified that the applications installed on the media will be killed.
671        // Redundant probably. But no harm in updating state again.
672        mPms.updateExternalMediaStatus(false);
673        try {
674            mConnector.doCommand(String.format(
675                    "volume unmount %s%s", path, (force ? " force" : "")));
676            return StorageResultCode.OperationSucceeded;
677        } catch (NativeDaemonConnectorException e) {
678            // Don't worry about mismatch in PackageManager since the
679            // call back will handle the status changes any way.
680            int code = e.getCode();
681            if (code == VoldResponseCode.OpFailedVolNotMounted) {
682                return StorageResultCode.OperationFailedStorageNotMounted;
683            } else if (code == VoldResponseCode.OpFailedStorageBusy) {
684                return StorageResultCode.OperationFailedStorageBusy;
685            } else {
686                return StorageResultCode.OperationFailedInternalError;
687            }
688        }
689    }
690
691    private int doFormatVolume(String path) {
692        try {
693            String cmd = String.format("volume format %s", path);
694            mConnector.doCommand(cmd);
695            return StorageResultCode.OperationSucceeded;
696        } catch (NativeDaemonConnectorException e) {
697            int code = e.getCode();
698            if (code == VoldResponseCode.OpFailedNoMedia) {
699                return StorageResultCode.OperationFailedNoMedia;
700            } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
701                return StorageResultCode.OperationFailedMediaCorrupt;
702            } else {
703                return StorageResultCode.OperationFailedInternalError;
704            }
705        }
706    }
707
708    private boolean doGetVolumeShared(String path, String method) {
709        String cmd = String.format("volume shared %s %s", path, method);
710        ArrayList<String> rsp = mConnector.doCommand(cmd);
711
712        for (String line : rsp) {
713            String []tok = line.split(" ");
714            int code;
715            try {
716                code = Integer.parseInt(tok[0]);
717            } catch (NumberFormatException nfe) {
718                Log.e(TAG, String.format("Error parsing code %s", tok[0]));
719                return false;
720            }
721            if (code == VoldResponseCode.ShareEnabledResult) {
722                if (tok[2].equals("enabled"))
723                    return true;
724                return false;
725            } else {
726                Log.e(TAG, String.format("Unexpected response code %d", code));
727                return false;
728            }
729        }
730        Log.e(TAG, "Got an empty response");
731        return false;
732    }
733
734    private void notifyShareAvailabilityChange(String method, final boolean avail) {
735        if (!method.equals("ums")) {
736           Log.w(TAG, "Ignoring unsupported share method {" + method + "}");
737           return;
738        }
739
740        synchronized (mListeners) {
741            for (int i = mListeners.size() -1; i >= 0; i--) {
742                MountServiceBinderListener bl = mListeners.get(i);
743                try {
744                    bl.mListener.onUsbMassStorageConnectionChanged(avail);
745                } catch (RemoteException rex) {
746                    Log.e(TAG, "Listener dead");
747                    mListeners.remove(i);
748                } catch (Exception ex) {
749                    Log.e(TAG, "Listener failed", ex);
750                }
751            }
752        }
753
754        if (mBooted == true) {
755            sendUmsIntent(avail);
756        } else {
757            mSendUmsConnectedOnBoot = avail;
758        }
759    }
760
761    private void sendUmsIntent(boolean c) {
762        mContext.sendBroadcast(
763                new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
764    }
765
766    private void validatePermission(String perm) {
767        if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
768            throw new SecurityException(String.format("Requires %s permission", perm));
769        }
770    }
771
772    /**
773     * Constructs a new MountService instance
774     *
775     * @param context  Binder context for this service
776     */
777    public MountService(Context context) {
778        mContext = context;
779
780        // XXX: This will go away soon in favor of IMountServiceObserver
781        mPms = (PackageManagerService) ServiceManager.getService("package");
782
783        mContext.registerReceiver(mBroadcastReceiver,
784                new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
785
786        /*
787         * Vold does not run in the simulator, so pretend the connector thread
788         * ran and did its thing.
789         */
790        if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
791            mReady = true;
792            mUmsEnabling = true;
793            return;
794        }
795
796        mConnector = new NativeDaemonConnector(this, "vold", 10, "VoldConnector");
797        mReady = false;
798        Thread thread = new Thread(mConnector, NativeDaemonConnector.class.getName());
799        thread.start();
800    }
801
802    /**
803     * Exposed API calls below here
804     */
805
806    public void registerListener(IMountServiceListener listener) {
807        synchronized (mListeners) {
808            MountServiceBinderListener bl = new MountServiceBinderListener(listener);
809            try {
810                listener.asBinder().linkToDeath(bl, 0);
811                mListeners.add(bl);
812            } catch (RemoteException rex) {
813                Log.e(TAG, "Failed to link to listener death");
814            }
815        }
816    }
817
818    public void unregisterListener(IMountServiceListener listener) {
819        synchronized (mListeners) {
820            for(MountServiceBinderListener bl : mListeners) {
821                if (bl.mListener == listener) {
822                    mListeners.remove(mListeners.indexOf(bl));
823                    return;
824                }
825            }
826        }
827    }
828
829    public void shutdown() {
830        validatePermission(android.Manifest.permission.SHUTDOWN);
831
832        Log.i(TAG, "Shutting down");
833
834        String path = Environment.getExternalStorageDirectory().getPath();
835        String state = getVolumeState(path);
836
837        if (state.equals(Environment.MEDIA_SHARED)) {
838            /*
839             * If the media is currently shared, unshare it.
840             * XXX: This is still dangerous!. We should not
841             * be rebooting at *all* if UMS is enabled, since
842             * the UMS host could have dirty FAT cache entries
843             * yet to flush.
844             */
845            setUsbMassStorageEnabled(false);
846        } else if (state.equals(Environment.MEDIA_CHECKING)) {
847            /*
848             * If the media is being checked, then we need to wait for
849             * it to complete before being able to proceed.
850             */
851            // XXX: @hackbod - Should we disable the ANR timer here?
852            int retries = 30;
853            while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
854                try {
855                    Thread.sleep(1000);
856                } catch (InterruptedException iex) {
857                    Log.e(TAG, "Interrupted while waiting for media", iex);
858                    break;
859                }
860                state = Environment.getExternalStorageState();
861            }
862            if (retries == 0) {
863                Log.e(TAG, "Timed out waiting for media to check");
864            }
865        }
866
867        if (state.equals(Environment.MEDIA_MOUNTED)) {
868            /*
869             * If the media is mounted, then gracefully unmount it.
870             */
871            if (doUnmountVolume(path, true) != StorageResultCode.OperationSucceeded) {
872                Log.e(TAG, "Failed to unmount media for shutdown");
873            }
874        }
875    }
876
877    private boolean getUmsEnabling() {
878        synchronized (mListeners) {
879            return mUmsEnabling;
880        }
881    }
882
883    private void setUmsEnabling(boolean enable) {
884        synchronized (mListeners) {
885            mUmsEnabling = true;
886        }
887    }
888
889    public boolean isUsbMassStorageConnected() {
890        waitForReady();
891
892        if (getUmsEnabling()) {
893            return true;
894        }
895        return doGetShareMethodAvailable("ums");
896    }
897
898    public void setUsbMassStorageEnabled(boolean enable) {
899        waitForReady();
900        validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
901
902        // TODO: Add support for multiple share methods
903
904        /*
905         * If the volume is mounted and we're enabling then unmount it
906         */
907        String path = Environment.getExternalStorageDirectory().getPath();
908        String vs = getVolumeState(path);
909        String method = "ums";
910        if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
911            // Override for isUsbMassStorageEnabled()
912            setUmsEnabling(enable);
913            UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
914            mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
915            // Clear override
916            setUmsEnabling(false);
917        }
918        /*
919         * If we disabled UMS then mount the volume
920         */
921        if (!enable) {
922            doShareUnshareVolume(path, method, enable);
923            if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
924                Log.e(TAG, "Failed to remount " + path +
925                        " after disabling share method " + method);
926                /*
927                 * Even though the mount failed, the unshare didn't so don't indicate an error.
928                 * The mountVolume() call will have set the storage state and sent the necessary
929                 * broadcasts.
930                 */
931            }
932        }
933    }
934
935    public boolean isUsbMassStorageEnabled() {
936        waitForReady();
937        return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
938    }
939
940    /**
941     * @return state of the volume at the specified mount point
942     */
943    public String getVolumeState(String mountPoint) {
944        /*
945         * XXX: Until we have multiple volume discovery, just hardwire
946         * this to /sdcard
947         */
948        if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
949            Log.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
950            throw new IllegalArgumentException();
951        }
952
953        return mLegacyState;
954    }
955
956    public int mountVolume(String path) {
957        validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
958
959        waitForReady();
960        return doMountVolume(path);
961    }
962
963    public void unmountVolume(String path, boolean force) {
964        validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
965        waitForReady();
966
967        UnmountCallBack ucb = new UnmountCallBack(path, force);
968        mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
969    }
970
971    public int formatVolume(String path) {
972        validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
973        waitForReady();
974
975        return doFormatVolume(path);
976    }
977
978    public int []getStorageUsers(String path) {
979        validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
980        waitForReady();
981        try {
982            String[] r = mConnector.doListCommand(
983                    String.format("storage users %s", path),
984                            VoldResponseCode.StorageUsersListResult);
985            // FMT: <pid> <process name>
986            int[] data = new int[r.length];
987            for (int i = 0; i < r.length; i++) {
988                String []tok = r[i].split(" ");
989                try {
990                    data[i] = Integer.parseInt(tok[0]);
991                } catch (NumberFormatException nfe) {
992                    Log.e(TAG, String.format("Error parsing pid %s", tok[0]));
993                    return new int[0];
994                }
995            }
996            return data;
997        } catch (NativeDaemonConnectorException e) {
998            Log.e(TAG, "Failed to retrieve storage users list", e);
999            return new int[0];
1000        }
1001    }
1002
1003    private void warnOnNotMounted() {
1004        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
1005            Log.w(TAG, "getSecureContainerList() called when storage not mounted");
1006        }
1007    }
1008
1009    public String[] getSecureContainerList() {
1010        validatePermission(android.Manifest.permission.ASEC_ACCESS);
1011        waitForReady();
1012        warnOnNotMounted();
1013
1014        try {
1015            return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1016        } catch (NativeDaemonConnectorException e) {
1017            return new String[0];
1018        }
1019    }
1020
1021    public int createSecureContainer(String id, int sizeMb, String fstype,
1022                                    String key, int ownerUid) {
1023        validatePermission(android.Manifest.permission.ASEC_CREATE);
1024        waitForReady();
1025        warnOnNotMounted();
1026
1027        int rc = StorageResultCode.OperationSucceeded;
1028        String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1029        try {
1030            mConnector.doCommand(cmd);
1031        } catch (NativeDaemonConnectorException e) {
1032            rc = StorageResultCode.OperationFailedInternalError;
1033        }
1034
1035        if (rc == StorageResultCode.OperationSucceeded) {
1036            synchronized (mAsecMountSet) {
1037                mAsecMountSet.add(id);
1038            }
1039        }
1040        return rc;
1041    }
1042
1043    public int finalizeSecureContainer(String id) {
1044        validatePermission(android.Manifest.permission.ASEC_CREATE);
1045        warnOnNotMounted();
1046
1047        int rc = StorageResultCode.OperationSucceeded;
1048        try {
1049            mConnector.doCommand(String.format("asec finalize %s", id));
1050            /*
1051             * Finalization does a remount, so no need
1052             * to update mAsecMountSet
1053             */
1054        } catch (NativeDaemonConnectorException e) {
1055            rc = StorageResultCode.OperationFailedInternalError;
1056        }
1057        return rc;
1058    }
1059
1060    public int destroySecureContainer(String id, boolean force) {
1061        validatePermission(android.Manifest.permission.ASEC_DESTROY);
1062        waitForReady();
1063        warnOnNotMounted();
1064
1065        int rc = StorageResultCode.OperationSucceeded;
1066        try {
1067            mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
1068        } catch (NativeDaemonConnectorException e) {
1069            int code = e.getCode();
1070            if (code == VoldResponseCode.OpFailedStorageBusy) {
1071                rc = StorageResultCode.OperationFailedStorageBusy;
1072            } else {
1073                rc = StorageResultCode.OperationFailedInternalError;
1074            }
1075        }
1076
1077        if (rc == StorageResultCode.OperationSucceeded) {
1078            synchronized (mAsecMountSet) {
1079                if (mAsecMountSet.contains(id)) {
1080                    mAsecMountSet.remove(id);
1081                }
1082            }
1083        }
1084
1085        return rc;
1086    }
1087
1088    public int mountSecureContainer(String id, String key, int ownerUid) {
1089        validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
1090        waitForReady();
1091        warnOnNotMounted();
1092
1093        synchronized (mAsecMountSet) {
1094            if (mAsecMountSet.contains(id)) {
1095                return StorageResultCode.OperationFailedStorageMounted;
1096            }
1097        }
1098
1099        int rc = StorageResultCode.OperationSucceeded;
1100        String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1101        try {
1102            mConnector.doCommand(cmd);
1103        } catch (NativeDaemonConnectorException e) {
1104            rc = StorageResultCode.OperationFailedInternalError;
1105        }
1106
1107        if (rc == StorageResultCode.OperationSucceeded) {
1108            synchronized (mAsecMountSet) {
1109                mAsecMountSet.add(id);
1110            }
1111        }
1112        return rc;
1113    }
1114
1115    public int unmountSecureContainer(String id, boolean force) {
1116        validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
1117        waitForReady();
1118        warnOnNotMounted();
1119
1120        synchronized (mAsecMountSet) {
1121            if (!mAsecMountSet.contains(id)) {
1122                return StorageResultCode.OperationFailedStorageNotMounted;
1123            }
1124         }
1125
1126        int rc = StorageResultCode.OperationSucceeded;
1127        String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
1128        try {
1129            mConnector.doCommand(cmd);
1130        } catch (NativeDaemonConnectorException e) {
1131            int code = e.getCode();
1132            if (code == VoldResponseCode.OpFailedStorageBusy) {
1133                rc = StorageResultCode.OperationFailedStorageBusy;
1134            } else {
1135                rc = StorageResultCode.OperationFailedInternalError;
1136            }
1137        }
1138
1139        if (rc == StorageResultCode.OperationSucceeded) {
1140            synchronized (mAsecMountSet) {
1141                mAsecMountSet.remove(id);
1142            }
1143        }
1144        return rc;
1145    }
1146
1147    public boolean isSecureContainerMounted(String id) {
1148        validatePermission(android.Manifest.permission.ASEC_ACCESS);
1149        waitForReady();
1150        warnOnNotMounted();
1151
1152        synchronized (mAsecMountSet) {
1153            return mAsecMountSet.contains(id);
1154        }
1155    }
1156
1157    public int renameSecureContainer(String oldId, String newId) {
1158        validatePermission(android.Manifest.permission.ASEC_RENAME);
1159        waitForReady();
1160        warnOnNotMounted();
1161
1162        synchronized (mAsecMountSet) {
1163            /*
1164             * Because a mounted container has active internal state which cannot be
1165             * changed while active, we must ensure both ids are not currently mounted.
1166             */
1167            if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
1168                return StorageResultCode.OperationFailedStorageMounted;
1169            }
1170        }
1171
1172        int rc = StorageResultCode.OperationSucceeded;
1173        String cmd = String.format("asec rename %s %s", oldId, newId);
1174        try {
1175            mConnector.doCommand(cmd);
1176        } catch (NativeDaemonConnectorException e) {
1177            rc = StorageResultCode.OperationFailedInternalError;
1178        }
1179
1180        return rc;
1181    }
1182
1183    public String getSecureContainerPath(String id) {
1184        validatePermission(android.Manifest.permission.ASEC_ACCESS);
1185        waitForReady();
1186        warnOnNotMounted();
1187
1188        ArrayList<String> rsp = mConnector.doCommand("asec path " + id);
1189
1190        for (String line : rsp) {
1191            String []tok = line.split(" ");
1192            int code = Integer.parseInt(tok[0]);
1193            if (code == VoldResponseCode.AsecPathResult) {
1194                return tok[1];
1195            } else {
1196                Log.e(TAG, String.format("Unexpected response code %d", code));
1197                return "";
1198            }
1199        }
1200
1201        Log.e(TAG, "Got an empty response");
1202        return "";
1203    }
1204}
1205
1206