blob: 10920fabf140142dcc649fb0292bbe7d390650f9 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080019import com.android.server.am.ActivityManagerService;
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.BroadcastReceiver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.net.Uri;
San Mehatb1043402010-02-05 08:26:50 -080027import android.os.storage.IMountService;
28import android.os.storage.IMountServiceListener;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080029import android.os.storage.IMountShutdownObserver;
San Mehatb1043402010-02-05 08:26:50 -080030import android.os.storage.StorageResultCode;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080031import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040032import android.os.HandlerThread;
33import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080035import android.os.RemoteException;
36import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Environment;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080038import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080039import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.util.Log;
San Mehat22dd86e2010-01-12 12:21:18 -080042import java.util.ArrayList;
San Mehat6cdd9c02010-02-09 14:45:20 -080043import java.util.HashSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045/**
San Mehatb1043402010-02-05 08:26:50 -080046 * MountService implements back-end services for platform storage
47 * management.
48 * @hide - Applications should use android.os.storage.StorageManager
49 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 */
San Mehat22dd86e2010-01-12 12:21:18 -080051class MountService extends IMountService.Stub
52 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080053 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080054 private static final boolean DEBUG_UNMOUNT = false;
55 private static final boolean DEBUG_EVENTS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57 private static final String TAG = "MountService";
58
San Mehat4270e1e2010-01-29 05:32:19 -080059 /*
60 * Internal vold volume state constants
61 */
San Mehat7fd0fee2009-12-17 07:12:23 -080062 class VolumeState {
63 public static final int Init = -1;
64 public static final int NoMedia = 0;
65 public static final int Idle = 1;
66 public static final int Pending = 2;
67 public static final int Checking = 3;
68 public static final int Mounted = 4;
69 public static final int Unmounting = 5;
70 public static final int Formatting = 6;
71 public static final int Shared = 7;
72 public static final int SharedMnt = 8;
73 }
74
San Mehat4270e1e2010-01-29 05:32:19 -080075 /*
76 * Internal vold response code constants
77 */
San Mehat22dd86e2010-01-12 12:21:18 -080078 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -080079 /*
80 * 100 series - Requestion action was initiated; expect another reply
81 * before proceeding with a new command.
82 */
San Mehat22dd86e2010-01-12 12:21:18 -080083 public static final int VolumeListResult = 110;
84 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -080085 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -080086
San Mehat4270e1e2010-01-29 05:32:19 -080087 /*
88 * 200 series - Requestion action has been successfully completed.
89 */
90 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -080091 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -080092 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -080093
San Mehat4270e1e2010-01-29 05:32:19 -080094 /*
95 * 400 series - Command was accepted, but the requested action
96 * did not take place.
97 */
98 public static final int OpFailedNoMedia = 401;
99 public static final int OpFailedMediaBlank = 402;
100 public static final int OpFailedMediaCorrupt = 403;
101 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800102 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700103 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800104
105 /*
106 * 600 series - Unsolicited broadcasts.
107 */
San Mehat22dd86e2010-01-12 12:21:18 -0800108 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800109 public static final int ShareAvailabilityChange = 620;
110 public static final int VolumeDiskInserted = 630;
111 public static final int VolumeDiskRemoved = 631;
112 public static final int VolumeBadRemoval = 632;
113 }
114
San Mehat4270e1e2010-01-29 05:32:19 -0800115 private Context mContext;
116 private NativeDaemonConnector mConnector;
117 private String mLegacyState = Environment.MEDIA_REMOVED;
118 private PackageManagerService mPms;
119 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800120 // Used as a lock for methods that register/unregister listeners.
121 final private ArrayList<MountServiceBinderListener> mListeners =
122 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800123 private boolean mBooted = false;
124 private boolean mReady = false;
125 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800126
San Mehat6cdd9c02010-02-09 14:45:20 -0800127 /**
128 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800129 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800130 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800131 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800132
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800133 private static final int H_UNMOUNT_PM_UPDATE = 1;
134 private static final int H_UNMOUNT_PM_DONE = 2;
135 private static final int H_UNMOUNT_MS = 3;
136 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
137 private static final int MAX_UNMOUNT_RETRIES = 4;
138
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800139 class UnmountCallBack {
140 String path;
141 int retries;
142 boolean force;
143
144 UnmountCallBack(String path, boolean force) {
145 retries = 0;
146 this.path = path;
147 this.force = force;
148 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800149
150 void handleFinished() {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800151 if (DEBUG_UNMOUNT) Log.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800152 doUnmountVolume(path, true);
153 }
154 }
155
156 class UmsEnableCallBack extends UnmountCallBack {
157 String method;
158
159 UmsEnableCallBack(String path, String method, boolean force) {
160 super(path, force);
161 this.method = method;
162 }
163
164 @Override
165 void handleFinished() {
166 super.handleFinished();
167 doShareUnshareVolume(path, method, true);
168 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800169 }
170
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800171 class ShutdownCallBack extends UnmountCallBack {
172 IMountShutdownObserver observer;
173 ShutdownCallBack(String path, IMountShutdownObserver observer) {
174 super(path, true);
175 this.observer = observer;
176 }
177
178 @Override
179 void handleFinished() {
180 int ret = doUnmountVolume(path, true);
181 if (observer != null) {
182 try {
183 observer.onShutDownComplete(ret);
184 } catch (RemoteException e) {
185 Log.w(TAG, "RemoteException when shutting down");
186 }
187 }
188 }
189 }
190
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400191 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800192 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700193 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800194
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400195 MountServiceHandler(Looper l) {
196 super(l);
197 }
198
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800199 public void handleMessage(Message msg) {
200 switch (msg.what) {
201 case H_UNMOUNT_PM_UPDATE: {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800202 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800203 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
204 mForceUnmounts.add(ucb);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700205 if (DEBUG_UNMOUNT) Log.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800206 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700207 if (!mUpdatingStatus) {
208 if (DEBUG_UNMOUNT) Log.i(TAG, "Updating external media status on PackageManager");
209 mUpdatingStatus = true;
210 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800211 }
212 break;
213 }
214 case H_UNMOUNT_PM_DONE: {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800215 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_PM_DONE");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700216 if (!mUpdatingStatus) {
217 // Does not correspond to unmount's status update.
218 return;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800219 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700220 if (DEBUG_UNMOUNT) Log.i(TAG, "Updated status. Processing requests");
221 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800222 int size = mForceUnmounts.size();
223 int sizeArr[] = new int[size];
224 int sizeArrN = 0;
225 for (int i = 0; i < size; i++) {
226 UnmountCallBack ucb = mForceUnmounts.get(i);
227 String path = ucb.path;
228 boolean done = false;
229 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800230 done = true;
231 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800232 int pids[] = getStorageUsers(path);
233 if (pids == null || pids.length == 0) {
234 done = true;
235 } else {
236 // Kill processes holding references first
237 ActivityManagerService ams = (ActivityManagerService)
238 ServiceManager.getService("activity");
239 // Eliminate system process here?
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700240 boolean ret = ams.killPids(pids, "Unmount media");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800241 if (ret) {
242 // Confirm if file references have been freed.
243 pids = getStorageUsers(path);
244 if (pids == null || pids.length == 0) {
245 done = true;
246 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800247 }
248 }
249 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800250 if (done) {
251 sizeArr[sizeArrN++] = i;
252 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
253 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800254 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800255 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700256 Log.i(TAG, "Cannot unmount media inspite of " +
257 MAX_UNMOUNT_RETRIES + " retries");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800258 // Send final broadcast indicating failure to unmount.
259 } else {
260 mHandler.sendMessageDelayed(
261 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
262 ucb.retries++),
263 RETRY_UNMOUNT_DELAY);
264 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800265 }
266 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800267 // Remove already processed elements from list.
268 for (int i = (sizeArrN-1); i >= 0; i--) {
269 mForceUnmounts.remove(sizeArr[i]);
270 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800271 break;
272 }
273 case H_UNMOUNT_MS : {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800274 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800275 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800276 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800277 break;
278 }
279 }
280 }
281 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400282 final private HandlerThread mHandlerThread;
283 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800284
San Mehat207e5382010-02-04 20:46:54 -0800285 private void waitForReady() {
286 while (mReady == false) {
287 for (int retries = 5; retries > 0; retries--) {
288 if (mReady) {
289 return;
290 }
291 SystemClock.sleep(1000);
292 }
293 Log.w(TAG, "Waiting too long for mReady!");
294 }
San Mehat1f6301e2010-01-07 22:40:27 -0800295 }
296
San Mehat207e5382010-02-04 20:46:54 -0800297 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800299 String action = intent.getAction();
300
301 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800302 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800303
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800304 /*
305 * In the simulator, we need to broadcast a volume mounted event
306 * to make the media scanner run.
307 */
308 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
309 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
310 return;
311 }
San Mehatfafb0412010-02-18 19:40:04 -0800312 new Thread() {
313 public void run() {
314 try {
315 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700316 String state = getVolumeState(path);
317
318 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800319 int rc = doMountVolume(path);
320 if (rc != StorageResultCode.OperationSucceeded) {
321 Log.e(TAG, String.format("Boot-time mount failed (%d)", rc));
322 }
San Mehat6a254402010-03-22 10:21:00 -0700323 } else if (state.equals(Environment.MEDIA_SHARED)) {
324 /*
325 * Bootstrap UMS enabled state since vold indicates
326 * the volume is shared (runtime restart while ums enabled)
327 */
328 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800329 }
San Mehat6a254402010-03-22 10:21:00 -0700330
San Mehat6a965af22010-02-24 17:47:30 -0800331 /*
San Mehat6a254402010-03-22 10:21:00 -0700332 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800333 * now that we're up.
334 */
335 if (mSendUmsConnectedOnBoot) {
336 sendUmsIntent(true);
337 mSendUmsConnectedOnBoot = false;
338 }
San Mehatfafb0412010-02-18 19:40:04 -0800339 } catch (Exception ex) {
340 Log.e(TAG, "Boot-time mount exception", ex);
341 }
San Mehat207e5382010-02-04 20:46:54 -0800342 }
San Mehatfafb0412010-02-18 19:40:04 -0800343 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345 }
346 };
347
San Mehat4270e1e2010-01-29 05:32:19 -0800348 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
349 final IMountServiceListener mListener;
350
351 MountServiceBinderListener(IMountServiceListener listener) {
352 mListener = listener;
353
San Mehat91c77612010-01-07 10:39:41 -0800354 }
355
San Mehat4270e1e2010-01-29 05:32:19 -0800356 public void binderDied() {
San Mehatb1043402010-02-05 08:26:50 -0800357 if (LOCAL_LOGD) Log.d(TAG, "An IMountServiceListener has died!");
San Mehat4270e1e2010-01-29 05:32:19 -0800358 synchronized(mListeners) {
359 mListeners.remove(this);
360 mListener.asBinder().unlinkToDeath(this, 0);
361 }
362 }
363 }
364
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800365 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800366 // TODO: Add support for multiple share methods
367 if (!method.equals("ums")) {
368 throw new IllegalArgumentException(String.format("Method %s not supported", method));
369 }
370
San Mehat4270e1e2010-01-29 05:32:19 -0800371 try {
372 mConnector.doCommand(String.format(
373 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
374 } catch (NativeDaemonConnectorException e) {
375 Log.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800376 }
San Mehat4270e1e2010-01-29 05:32:19 -0800377 }
378
San Mehat207e5382010-02-04 20:46:54 -0800379 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800380 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
381 Log.w(TAG, "Multiple volumes not currently supported");
382 return;
383 }
San Mehatb1043402010-02-05 08:26:50 -0800384
385 if (mLegacyState.equals(state)) {
386 Log.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
387 return;
388 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800389 // Update state on PackageManager
390 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700391 mPms.updateExternalMediaStatus(false, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800392 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700393 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800394 }
San Mehat4270e1e2010-01-29 05:32:19 -0800395 String oldState = mLegacyState;
396 mLegacyState = state;
397
398 synchronized (mListeners) {
399 for (int i = mListeners.size() -1; i >= 0; i--) {
400 MountServiceBinderListener bl = mListeners.get(i);
401 try {
San Mehatb1043402010-02-05 08:26:50 -0800402 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800403 } catch (RemoteException rex) {
404 Log.e(TAG, "Listener dead");
405 mListeners.remove(i);
406 } catch (Exception ex) {
407 Log.e(TAG, "Listener failed", ex);
408 }
409 }
410 }
411 }
412
413 /**
414 *
415 * Callback from NativeDaemonConnector
416 */
417 public void onDaemonConnected() {
418 /*
419 * Since we'll be calling back into the NativeDaemonConnector,
420 * we need to do our work in a new thread.
421 */
422 new Thread() {
423 public void run() {
424 /**
425 * Determine media state and UMS detection status
426 */
427 String path = Environment.getExternalStorageDirectory().getPath();
428 String state = Environment.MEDIA_REMOVED;
429
430 try {
431 String[] vols = mConnector.doListCommand(
432 "volume list", VoldResponseCode.VolumeListResult);
433 for (String volstr : vols) {
434 String[] tok = volstr.split(" ");
435 // FMT: <label> <mountpoint> <state>
436 if (!tok[1].equals(path)) {
437 Log.w(TAG, String.format(
438 "Skipping unknown volume '%s'",tok[1]));
439 continue;
440 }
441 int st = Integer.parseInt(tok[2]);
442 if (st == VolumeState.NoMedia) {
443 state = Environment.MEDIA_REMOVED;
444 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800445 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800446 } else if (st == VolumeState.Mounted) {
447 state = Environment.MEDIA_MOUNTED;
448 Log.i(TAG, "Media already mounted on daemon connection");
449 } else if (st == VolumeState.Shared) {
450 state = Environment.MEDIA_SHARED;
451 Log.i(TAG, "Media shared on daemon connection");
452 } else {
453 throw new Exception(String.format("Unexpected state %d", st));
454 }
455 }
456 if (state != null) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800457 if (DEBUG_EVENTS) Log.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800458 updatePublicVolumeState(path, state);
459 }
460 } catch (Exception e) {
461 Log.e(TAG, "Error processing initial volume state", e);
462 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
463 }
464
465 try {
San Mehat207e5382010-02-04 20:46:54 -0800466 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800467 notifyShareAvailabilityChange("ums", avail);
468 } catch (Exception ex) {
469 Log.w(TAG, "Failed to get share availability");
470 }
San Mehat207e5382010-02-04 20:46:54 -0800471 /*
472 * Now that we've done our initialization, release
473 * the hounds!
474 */
475 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800476 }
477 }.start();
478 }
479
480 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800481 * Callback from NativeDaemonConnector
482 */
483 public boolean onEvent(int code, String raw, String[] cooked) {
484 Intent in = null;
485
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800486 if (DEBUG_EVENTS) {
487 StringBuilder builder = new StringBuilder();
488 builder.append("onEvent::");
489 builder.append(" raw= " + raw);
490 if (cooked != null) {
491 builder.append(" cooked = " );
492 for (String str : cooked) {
493 builder.append(" " + str);
494 }
495 }
496 Log.i(TAG, builder.toString());
497 }
San Mehat4270e1e2010-01-29 05:32:19 -0800498 if (code == VoldResponseCode.VolumeStateChange) {
499 /*
500 * One of the volumes we're managing has changed state.
501 * Format: "NNN Volume <label> <path> state changed
502 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
503 */
504 notifyVolumeStateChange(
505 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
506 Integer.parseInt(cooked[10]));
507 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
508 // FMT: NNN Share method <method> now <available|unavailable>
509 boolean avail = false;
510 if (cooked[5].equals("available")) {
511 avail = true;
512 }
513 notifyShareAvailabilityChange(cooked[3], avail);
514 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
515 (code == VoldResponseCode.VolumeDiskRemoved) ||
516 (code == VoldResponseCode.VolumeBadRemoval)) {
517 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
518 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
519 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
520 final String label = cooked[2];
521 final String path = cooked[3];
522 int major = -1;
523 int minor = -1;
524
525 try {
526 String devComp = cooked[6].substring(1, cooked[6].length() -1);
527 String[] devTok = devComp.split(":");
528 major = Integer.parseInt(devTok[0]);
529 minor = Integer.parseInt(devTok[1]);
530 } catch (Exception ex) {
531 Log.e(TAG, "Failed to parse major/minor", ex);
532 }
533
San Mehat4270e1e2010-01-29 05:32:19 -0800534 if (code == VoldResponseCode.VolumeDiskInserted) {
535 new Thread() {
536 public void run() {
537 try {
538 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800539 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehat4270e1e2010-01-29 05:32:19 -0800540 Log.w(TAG, String.format("Insertion mount failed (%d)", rc));
541 }
542 } catch (Exception ex) {
543 Log.w(TAG, "Failed to mount media on insertion", ex);
544 }
545 }
546 }.start();
547 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
548 /*
549 * This event gets trumped if we're already in BAD_REMOVAL state
550 */
551 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
552 return true;
553 }
554 /* Send the media unmounted event first */
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800555 if (DEBUG_EVENTS) Log.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800556 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
557 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
558 mContext.sendBroadcast(in);
559
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800560 if (DEBUG_EVENTS) Log.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800561 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
562 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
563 } else if (code == VoldResponseCode.VolumeBadRemoval) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800564 if (DEBUG_EVENTS) Log.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800565 /* Send the media unmounted event first */
566 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
567 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
568 mContext.sendBroadcast(in);
569
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800570 if (DEBUG_EVENTS) Log.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800571 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
572 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
573 } else {
574 Log.e(TAG, String.format("Unknown code {%d}", code));
575 }
576 } else {
577 return false;
578 }
579
580 if (in != null) {
581 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400582 }
583 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800584 }
585
San Mehat207e5382010-02-04 20:46:54 -0800586 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800587 String vs = getVolumeState(path);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800588 if (DEBUG_EVENTS) Log.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800589
590 Intent in = null;
591
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500592 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehat2fe718a2010-03-11 12:01:49 -0800593 if (LOCAL_LOGD) Log.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500594 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
595 Uri.parse("file://" + path)));
596 }
597
San Mehat4270e1e2010-01-29 05:32:19 -0800598 if (newState == VolumeState.Init) {
599 } else if (newState == VolumeState.NoMedia) {
600 // NoMedia is handled via Disk Remove events
601 } else if (newState == VolumeState.Idle) {
602 /*
603 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
604 * if we're in the process of enabling UMS
605 */
606 if (!vs.equals(
607 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
608 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800609 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800610 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800611 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
612 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
613 }
614 } else if (newState == VolumeState.Pending) {
615 } else if (newState == VolumeState.Checking) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800616 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800617 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
618 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
619 } else if (newState == VolumeState.Mounted) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800620 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800621 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800622 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
623 in.putExtra("read-only", false);
624 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800625 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
626 } else if (newState == VolumeState.Formatting) {
627 } else if (newState == VolumeState.Shared) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800628 if (DEBUG_EVENTS) Log.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800629 /* Send the media unmounted event first */
630 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
631 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
632 mContext.sendBroadcast(in);
633
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800634 if (DEBUG_EVENTS) Log.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800635 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
636 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehat2fe718a2010-03-11 12:01:49 -0800637 if (LOCAL_LOGD) Log.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800638 } else if (newState == VolumeState.SharedMnt) {
639 Log.e(TAG, "Live shared mounts not supported yet!");
640 return;
641 } else {
642 Log.e(TAG, "Unhandled VolumeState {" + newState + "}");
643 }
644
645 if (in != null) {
646 mContext.sendBroadcast(in);
647 }
648 }
649
San Mehat207e5382010-02-04 20:46:54 -0800650 private boolean doGetShareMethodAvailable(String method) {
651 ArrayList<String> rsp = mConnector.doCommand("share status " + method);
652
653 for (String line : rsp) {
654 String []tok = line.split(" ");
655 int code;
656 try {
657 code = Integer.parseInt(tok[0]);
658 } catch (NumberFormatException nfe) {
659 Log.e(TAG, String.format("Error parsing code %s", tok[0]));
660 return false;
661 }
662 if (code == VoldResponseCode.ShareStatusResult) {
663 if (tok[2].equals("available"))
664 return true;
665 return false;
666 } else {
667 Log.e(TAG, String.format("Unexpected response code %d", code));
668 return false;
669 }
670 }
671 Log.e(TAG, "Got an empty response");
672 return false;
673 }
674
675 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800676 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800677
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800678 if (DEBUG_EVENTS) Log.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800679 try {
680 mConnector.doCommand(String.format("volume mount %s", path));
681 } catch (NativeDaemonConnectorException e) {
682 /*
683 * Mount failed for some reason
684 */
685 Intent in = null;
686 int code = e.getCode();
687 if (code == VoldResponseCode.OpFailedNoMedia) {
688 /*
689 * Attempt to mount but no media inserted
690 */
San Mehatb1043402010-02-05 08:26:50 -0800691 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800692 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800693 if (DEBUG_EVENTS) Log.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800694 /*
695 * Media is blank or does not contain a supported filesystem
696 */
697 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
698 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800699 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800700 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800701 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800702 /*
703 * Volume consistency check failed
704 */
705 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
706 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800707 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800708 } else {
San Mehatb1043402010-02-05 08:26:50 -0800709 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800710 }
711
712 /*
713 * Send broadcast intent (if required for the failure)
714 */
715 if (in != null) {
716 mContext.sendBroadcast(in);
717 }
718 }
719
720 return rc;
721 }
722
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800723 /*
724 * If force is not set, we do not unmount if there are
725 * processes holding references to the volume about to be unmounted.
726 * If force is set, all the processes holding references need to be
727 * killed via the ActivityManager before actually unmounting the volume.
728 * This might even take a while and might be retried after timed delays
729 * to make sure we dont end up in an instable state and kill some core
730 * processes.
731 */
San Mehatd9709982010-02-18 11:43:03 -0800732 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800733 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800734 return VoldResponseCode.OpFailedVolNotMounted;
735 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800736 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700737 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800738 try {
San Mehatd9709982010-02-18 11:43:03 -0800739 mConnector.doCommand(String.format(
740 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700741 // We unmounted the volume. None of the asec containers are available now.
742 synchronized (mAsecMountSet) {
743 mAsecMountSet.clear();
744 }
San Mehatb1043402010-02-05 08:26:50 -0800745 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800746 } catch (NativeDaemonConnectorException e) {
747 // Don't worry about mismatch in PackageManager since the
748 // call back will handle the status changes any way.
749 int code = e.getCode();
750 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800751 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800752 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
753 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800754 } else {
San Mehatb1043402010-02-05 08:26:50 -0800755 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800756 }
757 }
758 }
759
760 private int doFormatVolume(String path) {
761 try {
762 String cmd = String.format("volume format %s", path);
763 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800764 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800765 } catch (NativeDaemonConnectorException e) {
766 int code = e.getCode();
767 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800768 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800769 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800770 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800771 } else {
San Mehatb1043402010-02-05 08:26:50 -0800772 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800773 }
774 }
775 }
776
San Mehatb1043402010-02-05 08:26:50 -0800777 private boolean doGetVolumeShared(String path, String method) {
778 String cmd = String.format("volume shared %s %s", path, method);
779 ArrayList<String> rsp = mConnector.doCommand(cmd);
780
781 for (String line : rsp) {
782 String []tok = line.split(" ");
783 int code;
784 try {
785 code = Integer.parseInt(tok[0]);
786 } catch (NumberFormatException nfe) {
787 Log.e(TAG, String.format("Error parsing code %s", tok[0]));
788 return false;
789 }
790 if (code == VoldResponseCode.ShareEnabledResult) {
791 if (tok[2].equals("enabled"))
792 return true;
793 return false;
794 } else {
795 Log.e(TAG, String.format("Unexpected response code %d", code));
796 return false;
797 }
798 }
799 Log.e(TAG, "Got an empty response");
800 return false;
801 }
802
San Mehat207e5382010-02-04 20:46:54 -0800803 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800804 if (!method.equals("ums")) {
805 Log.w(TAG, "Ignoring unsupported share method {" + method + "}");
806 return;
807 }
808
809 synchronized (mListeners) {
810 for (int i = mListeners.size() -1; i >= 0; i--) {
811 MountServiceBinderListener bl = mListeners.get(i);
812 try {
San Mehatb1043402010-02-05 08:26:50 -0800813 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800814 } catch (RemoteException rex) {
815 Log.e(TAG, "Listener dead");
816 mListeners.remove(i);
817 } catch (Exception ex) {
818 Log.e(TAG, "Listener failed", ex);
819 }
820 }
821 }
822
San Mehat207e5382010-02-04 20:46:54 -0800823 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800824 sendUmsIntent(avail);
825 } else {
826 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800827 }
San Mehat2fe718a2010-03-11 12:01:49 -0800828
829 final String path = Environment.getExternalStorageDirectory().getPath();
830 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
831 /*
832 * USB mass storage disconnected while enabled
833 */
834 new Thread() {
835 public void run() {
836 try {
837 int rc;
838 Log.w(TAG, "Disabling UMS after cable disconnect");
839 doShareUnshareVolume(path, "ums", false);
840 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
841 Log.e(TAG, String.format(
842 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
843 path, rc));
844 }
845 } catch (Exception ex) {
846 Log.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
847 }
848 }
849 }.start();
850 }
San Mehat4270e1e2010-01-29 05:32:19 -0800851 }
852
San Mehat6a965af22010-02-24 17:47:30 -0800853 private void sendUmsIntent(boolean c) {
854 mContext.sendBroadcast(
855 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
856 }
857
San Mehat207e5382010-02-04 20:46:54 -0800858 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -0800859 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
860 throw new SecurityException(String.format("Requires %s permission", perm));
861 }
862 }
863
864 /**
San Mehat207e5382010-02-04 20:46:54 -0800865 * Constructs a new MountService instance
866 *
867 * @param context Binder context for this service
868 */
869 public MountService(Context context) {
870 mContext = context;
871
San Mehat207e5382010-02-04 20:46:54 -0800872 // XXX: This will go away soon in favor of IMountServiceObserver
873 mPms = (PackageManagerService) ServiceManager.getService("package");
874
875 mContext.registerReceiver(mBroadcastReceiver,
876 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
877
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400878 mHandlerThread = new HandlerThread("MountService");
879 mHandlerThread.start();
880 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
881
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800882 /*
883 * Vold does not run in the simulator, so pretend the connector thread
884 * ran and did its thing.
885 */
886 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
887 mReady = true;
888 mUmsEnabling = true;
889 return;
890 }
891
San Mehat207e5382010-02-04 20:46:54 -0800892 mConnector = new NativeDaemonConnector(this, "vold", 10, "VoldConnector");
893 mReady = false;
894 Thread thread = new Thread(mConnector, NativeDaemonConnector.class.getName());
895 thread.start();
896 }
897
898 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800899 * Exposed API calls below here
900 */
901
902 public void registerListener(IMountServiceListener listener) {
903 synchronized (mListeners) {
904 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
905 try {
906 listener.asBinder().linkToDeath(bl, 0);
907 mListeners.add(bl);
908 } catch (RemoteException rex) {
909 Log.e(TAG, "Failed to link to listener death");
910 }
911 }
912 }
913
914 public void unregisterListener(IMountServiceListener listener) {
915 synchronized (mListeners) {
916 for(MountServiceBinderListener bl : mListeners) {
917 if (bl.mListener == listener) {
918 mListeners.remove(mListeners.indexOf(bl));
919 return;
920 }
921 }
922 }
923 }
924
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800925 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -0800926 validatePermission(android.Manifest.permission.SHUTDOWN);
927
928 Log.i(TAG, "Shutting down");
929
930 String path = Environment.getExternalStorageDirectory().getPath();
931 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -0800932
933 if (state.equals(Environment.MEDIA_SHARED)) {
934 /*
935 * If the media is currently shared, unshare it.
936 * XXX: This is still dangerous!. We should not
937 * be rebooting at *all* if UMS is enabled, since
938 * the UMS host could have dirty FAT cache entries
939 * yet to flush.
940 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800941 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -0800942 } else if (state.equals(Environment.MEDIA_CHECKING)) {
943 /*
944 * If the media is being checked, then we need to wait for
945 * it to complete before being able to proceed.
946 */
947 // XXX: @hackbod - Should we disable the ANR timer here?
948 int retries = 30;
949 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
950 try {
951 Thread.sleep(1000);
952 } catch (InterruptedException iex) {
953 Log.e(TAG, "Interrupted while waiting for media", iex);
954 break;
955 }
956 state = Environment.getExternalStorageState();
957 }
958 if (retries == 0) {
959 Log.e(TAG, "Timed out waiting for media to check");
960 }
961 }
962
963 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800964 // Post a unmount message.
965 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
966 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -0800967 }
968 }
969
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800970 private boolean getUmsEnabling() {
971 synchronized (mListeners) {
972 return mUmsEnabling;
973 }
974 }
975
976 private void setUmsEnabling(boolean enable) {
977 synchronized (mListeners) {
978 mUmsEnabling = true;
979 }
980 }
981
San Mehatb1043402010-02-05 08:26:50 -0800982 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -0800983 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -0800984
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800985 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -0800986 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -0800987 }
San Mehatb1043402010-02-05 08:26:50 -0800988 return doGetShareMethodAvailable("ums");
989 }
990
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800991 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -0800992 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800993 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -0800994
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800995 // TODO: Add support for multiple share methods
996
997 /*
998 * If the volume is mounted and we're enabling then unmount it
999 */
1000 String path = Environment.getExternalStorageDirectory().getPath();
1001 String vs = getVolumeState(path);
1002 String method = "ums";
1003 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1004 // Override for isUsbMassStorageEnabled()
1005 setUmsEnabling(enable);
1006 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1007 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1008 // Clear override
1009 setUmsEnabling(false);
1010 }
1011 /*
1012 * If we disabled UMS then mount the volume
1013 */
1014 if (!enable) {
1015 doShareUnshareVolume(path, method, enable);
1016 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
1017 Log.e(TAG, "Failed to remount " + path +
1018 " after disabling share method " + method);
1019 /*
1020 * Even though the mount failed, the unshare didn't so don't indicate an error.
1021 * The mountVolume() call will have set the storage state and sent the necessary
1022 * broadcasts.
1023 */
1024 }
1025 }
San Mehatb1043402010-02-05 08:26:50 -08001026 }
1027
1028 public boolean isUsbMassStorageEnabled() {
1029 waitForReady();
1030 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
San Mehat4270e1e2010-01-29 05:32:19 -08001032
San Mehat7fd0fee2009-12-17 07:12:23 -08001033 /**
1034 * @return state of the volume at the specified mount point
1035 */
San Mehat4270e1e2010-01-29 05:32:19 -08001036 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001037 /*
1038 * XXX: Until we have multiple volume discovery, just hardwire
1039 * this to /sdcard
1040 */
1041 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
1042 Log.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1043 throw new IllegalArgumentException();
1044 }
1045
1046 return mLegacyState;
1047 }
1048
San Mehat4270e1e2010-01-29 05:32:19 -08001049 public int mountVolume(String path) {
1050 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001051
San Mehat207e5382010-02-04 20:46:54 -08001052 waitForReady();
1053 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001056 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001057 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001058 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001060 String volState = getVolumeState(path);
1061 if (DEBUG_UNMOUNT) Log.i(TAG, "Unmounting " + path + " force = " + force);
1062 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1063 Environment.MEDIA_REMOVED.equals(volState) ||
1064 Environment.MEDIA_SHARED.equals(volState) ||
1065 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1066 // Media already unmounted or cannot be unmounted.
1067 // TODO return valid return code when adding observer call back.
1068 return;
1069 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001070 UnmountCallBack ucb = new UnmountCallBack(path, force);
1071 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073
San Mehat4270e1e2010-01-29 05:32:19 -08001074 public int formatVolume(String path) {
1075 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001076 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001077
San Mehat207e5382010-02-04 20:46:54 -08001078 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080
San Mehatc1b4ce92010-02-16 17:13:03 -08001081 public int []getStorageUsers(String path) {
1082 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1083 waitForReady();
1084 try {
1085 String[] r = mConnector.doListCommand(
1086 String.format("storage users %s", path),
1087 VoldResponseCode.StorageUsersListResult);
1088 // FMT: <pid> <process name>
1089 int[] data = new int[r.length];
1090 for (int i = 0; i < r.length; i++) {
1091 String []tok = r[i].split(" ");
1092 try {
1093 data[i] = Integer.parseInt(tok[0]);
1094 } catch (NumberFormatException nfe) {
1095 Log.e(TAG, String.format("Error parsing pid %s", tok[0]));
1096 return new int[0];
1097 }
1098 }
1099 return data;
1100 } catch (NativeDaemonConnectorException e) {
1101 Log.e(TAG, "Failed to retrieve storage users list", e);
1102 return new int[0];
1103 }
1104 }
1105
San Mehatb1043402010-02-05 08:26:50 -08001106 private void warnOnNotMounted() {
1107 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
1108 Log.w(TAG, "getSecureContainerList() called when storage not mounted");
1109 }
1110 }
1111
San Mehat4270e1e2010-01-29 05:32:19 -08001112 public String[] getSecureContainerList() {
1113 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001114 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001115 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001116
San Mehat4270e1e2010-01-29 05:32:19 -08001117 try {
1118 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1119 } catch (NativeDaemonConnectorException e) {
1120 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122 }
San Mehat36972292010-01-06 11:06:32 -08001123
San Mehat4270e1e2010-01-29 05:32:19 -08001124 public int createSecureContainer(String id, int sizeMb, String fstype,
1125 String key, int ownerUid) {
1126 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001127 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001128 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001129
San Mehatb1043402010-02-05 08:26:50 -08001130 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001131 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1132 try {
1133 mConnector.doCommand(cmd);
1134 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001135 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001136 }
San Mehata181b212010-02-11 06:50:20 -08001137
1138 if (rc == StorageResultCode.OperationSucceeded) {
1139 synchronized (mAsecMountSet) {
1140 mAsecMountSet.add(id);
1141 }
1142 }
San Mehat4270e1e2010-01-29 05:32:19 -08001143 return rc;
San Mehat36972292010-01-06 11:06:32 -08001144 }
1145
San Mehat4270e1e2010-01-29 05:32:19 -08001146 public int finalizeSecureContainer(String id) {
1147 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001148 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001149
San Mehatb1043402010-02-05 08:26:50 -08001150 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001151 try {
1152 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001153 /*
1154 * Finalization does a remount, so no need
1155 * to update mAsecMountSet
1156 */
San Mehat4270e1e2010-01-29 05:32:19 -08001157 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001158 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001159 }
San Mehat4270e1e2010-01-29 05:32:19 -08001160 return rc;
San Mehat36972292010-01-06 11:06:32 -08001161 }
1162
San Mehatd9709982010-02-18 11:43:03 -08001163 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001164 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001165 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001166 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001167
San Mehatb1043402010-02-05 08:26:50 -08001168 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001169 try {
San Mehatd9709982010-02-18 11:43:03 -08001170 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001171 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001172 int code = e.getCode();
1173 if (code == VoldResponseCode.OpFailedStorageBusy) {
1174 rc = StorageResultCode.OperationFailedStorageBusy;
1175 } else {
1176 rc = StorageResultCode.OperationFailedInternalError;
1177 }
San Mehat02735bc2010-01-26 15:18:08 -08001178 }
San Mehata181b212010-02-11 06:50:20 -08001179
1180 if (rc == StorageResultCode.OperationSucceeded) {
1181 synchronized (mAsecMountSet) {
1182 if (mAsecMountSet.contains(id)) {
1183 mAsecMountSet.remove(id);
1184 }
1185 }
1186 }
1187
San Mehat4270e1e2010-01-29 05:32:19 -08001188 return rc;
San Mehat36972292010-01-06 11:06:32 -08001189 }
1190
San Mehat4270e1e2010-01-29 05:32:19 -08001191 public int mountSecureContainer(String id, String key, int ownerUid) {
1192 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001193 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001194 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001195
San Mehata181b212010-02-11 06:50:20 -08001196 synchronized (mAsecMountSet) {
1197 if (mAsecMountSet.contains(id)) {
1198 return StorageResultCode.OperationFailedStorageMounted;
1199 }
1200 }
1201
San Mehatb1043402010-02-05 08:26:50 -08001202 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001203 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1204 try {
1205 mConnector.doCommand(cmd);
1206 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001207 int code = e.getCode();
1208 if (code != VoldResponseCode.OpFailedStorageBusy) {
1209 rc = StorageResultCode.OperationFailedInternalError;
1210 }
San Mehat02735bc2010-01-26 15:18:08 -08001211 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001212
1213 if (rc == StorageResultCode.OperationSucceeded) {
1214 synchronized (mAsecMountSet) {
1215 mAsecMountSet.add(id);
1216 }
1217 }
San Mehat4270e1e2010-01-29 05:32:19 -08001218 return rc;
San Mehat36972292010-01-06 11:06:32 -08001219 }
1220
San Mehatd9709982010-02-18 11:43:03 -08001221 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001222 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001223 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001224 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001225
San Mehat6cdd9c02010-02-09 14:45:20 -08001226 synchronized (mAsecMountSet) {
1227 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001228 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001229 }
1230 }
1231
San Mehatb1043402010-02-05 08:26:50 -08001232 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001233 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001234 try {
1235 mConnector.doCommand(cmd);
1236 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001237 int code = e.getCode();
1238 if (code == VoldResponseCode.OpFailedStorageBusy) {
1239 rc = StorageResultCode.OperationFailedStorageBusy;
1240 } else {
1241 rc = StorageResultCode.OperationFailedInternalError;
1242 }
San Mehat02735bc2010-01-26 15:18:08 -08001243 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001244
1245 if (rc == StorageResultCode.OperationSucceeded) {
1246 synchronized (mAsecMountSet) {
1247 mAsecMountSet.remove(id);
1248 }
1249 }
San Mehat4270e1e2010-01-29 05:32:19 -08001250 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001251 }
1252
San Mehat6cdd9c02010-02-09 14:45:20 -08001253 public boolean isSecureContainerMounted(String id) {
1254 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1255 waitForReady();
1256 warnOnNotMounted();
1257
1258 synchronized (mAsecMountSet) {
1259 return mAsecMountSet.contains(id);
1260 }
1261 }
1262
San Mehat4270e1e2010-01-29 05:32:19 -08001263 public int renameSecureContainer(String oldId, String newId) {
1264 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001265 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001266 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001267
San Mehata181b212010-02-11 06:50:20 -08001268 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001269 /*
1270 * Because a mounted container has active internal state which cannot be
1271 * changed while active, we must ensure both ids are not currently mounted.
1272 */
1273 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001274 return StorageResultCode.OperationFailedStorageMounted;
1275 }
1276 }
1277
San Mehatb1043402010-02-05 08:26:50 -08001278 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001279 String cmd = String.format("asec rename %s %s", oldId, newId);
1280 try {
1281 mConnector.doCommand(cmd);
1282 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001283 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001284 }
San Mehata181b212010-02-11 06:50:20 -08001285
San Mehat4270e1e2010-01-29 05:32:19 -08001286 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001287 }
1288
San Mehat4270e1e2010-01-29 05:32:19 -08001289 public String getSecureContainerPath(String id) {
1290 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001291 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001292 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001293
San Mehat2d66cef2010-03-23 11:12:52 -07001294 try {
1295 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1296 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001297 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001298 if (code != VoldResponseCode.AsecPathResult) {
1299 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1300 }
1301 return tok[1];
1302 } catch (NativeDaemonConnectorException e) {
1303 int code = e.getCode();
1304 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1305 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001306 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001307 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001308 }
1309 }
San Mehat22dd86e2010-01-12 12:21:18 -08001310 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001311
1312 public void finishMediaUpdate() {
1313 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315}
1316