blob: d50f591051ab03119a3cb1793f3e5fcf9414074b [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 Mehat4270e1e2010-01-29 05:32:19 -0800103
104 /*
105 * 600 series - Unsolicited broadcasts.
106 */
San Mehat22dd86e2010-01-12 12:21:18 -0800107 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800108 public static final int ShareAvailabilityChange = 620;
109 public static final int VolumeDiskInserted = 630;
110 public static final int VolumeDiskRemoved = 631;
111 public static final int VolumeBadRemoval = 632;
112 }
113
San Mehat4270e1e2010-01-29 05:32:19 -0800114 private Context mContext;
115 private NativeDaemonConnector mConnector;
116 private String mLegacyState = Environment.MEDIA_REMOVED;
117 private PackageManagerService mPms;
118 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800119 // Used as a lock for methods that register/unregister listeners.
120 final private ArrayList<MountServiceBinderListener> mListeners =
121 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800122 private boolean mBooted = false;
123 private boolean mReady = false;
124 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800125
San Mehat6cdd9c02010-02-09 14:45:20 -0800126 /**
127 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800128 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800129 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800130 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800131
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800132 private static final int H_UNMOUNT_PM_UPDATE = 1;
133 private static final int H_UNMOUNT_PM_DONE = 2;
134 private static final int H_UNMOUNT_MS = 3;
135 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
136 private static final int MAX_UNMOUNT_RETRIES = 4;
137
138 private IntentFilter mPmFilter = new IntentFilter(
139 Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
140 private BroadcastReceiver mPmReceiver = new BroadcastReceiver() {
141 public void onReceive(Context context, Intent intent) {
142 String action = intent.getAction();
143 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
144 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
145 }
146 }
147 };
148
149 class UnmountCallBack {
150 String path;
151 int retries;
152 boolean force;
153
154 UnmountCallBack(String path, boolean force) {
155 retries = 0;
156 this.path = path;
157 this.force = force;
158 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800159
160 void handleFinished() {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800161 if (DEBUG_UNMOUNT) Log.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800162 doUnmountVolume(path, true);
163 }
164 }
165
166 class UmsEnableCallBack extends UnmountCallBack {
167 String method;
168
169 UmsEnableCallBack(String path, String method, boolean force) {
170 super(path, force);
171 this.method = method;
172 }
173
174 @Override
175 void handleFinished() {
176 super.handleFinished();
177 doShareUnshareVolume(path, method, true);
178 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800179 }
180
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800181 class ShutdownCallBack extends UnmountCallBack {
182 IMountShutdownObserver observer;
183 ShutdownCallBack(String path, IMountShutdownObserver observer) {
184 super(path, true);
185 this.observer = observer;
186 }
187
188 @Override
189 void handleFinished() {
190 int ret = doUnmountVolume(path, true);
191 if (observer != null) {
192 try {
193 observer.onShutDownComplete(ret);
194 } catch (RemoteException e) {
195 Log.w(TAG, "RemoteException when shutting down");
196 }
197 }
198 }
199 }
200
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400201 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800202 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800203 boolean mRegistered = false;
204
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400205 MountServiceHandler(Looper l) {
206 super(l);
207 }
208
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800209 void registerReceiver() {
210 mRegistered = true;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800211 if (DEBUG_UNMOUNT) Log.i(TAG, "Registering receiver");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800212 mContext.registerReceiver(mPmReceiver, mPmFilter);
213 }
214
215 void unregisterReceiver() {
216 mRegistered = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800217 if (DEBUG_UNMOUNT) Log.i(TAG, "Unregistering receiver");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800218 mContext.unregisterReceiver(mPmReceiver);
219 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800220
221 public void handleMessage(Message msg) {
222 switch (msg.what) {
223 case H_UNMOUNT_PM_UPDATE: {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800224 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800225 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
226 mForceUnmounts.add(ucb);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800227 if (DEBUG_UNMOUNT) Log.i(TAG, " registered = " + mRegistered);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800228 // Register only if needed.
229 if (!mRegistered) {
230 registerReceiver();
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800231 if (DEBUG_UNMOUNT) Log.i(TAG, "Updating external media status");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800232 boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
233 if (!hasExtPkgs) {
234 // Unregister right away
235 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
236 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800237 }
238 break;
239 }
240 case H_UNMOUNT_PM_DONE: {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800241 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_PM_DONE");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800242 // Unregister now.
243 if (mRegistered) {
244 unregisterReceiver();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800245 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800246 int size = mForceUnmounts.size();
247 int sizeArr[] = new int[size];
248 int sizeArrN = 0;
249 for (int i = 0; i < size; i++) {
250 UnmountCallBack ucb = mForceUnmounts.get(i);
251 String path = ucb.path;
252 boolean done = false;
253 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800254 done = true;
255 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800256 int pids[] = getStorageUsers(path);
257 if (pids == null || pids.length == 0) {
258 done = true;
259 } else {
260 // Kill processes holding references first
261 ActivityManagerService ams = (ActivityManagerService)
262 ServiceManager.getService("activity");
263 // Eliminate system process here?
264 boolean ret = ams.killPidsForMemory(pids);
265 if (ret) {
266 // Confirm if file references have been freed.
267 pids = getStorageUsers(path);
268 if (pids == null || pids.length == 0) {
269 done = true;
270 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800271 }
272 }
273 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800274 if (done) {
275 sizeArr[sizeArrN++] = i;
276 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
277 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800278 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800279 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
280 Log.i(TAG, "Cannot unmount inspite of " +
281 MAX_UNMOUNT_RETRIES + " to unmount media");
282 // Send final broadcast indicating failure to unmount.
283 } else {
284 mHandler.sendMessageDelayed(
285 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
286 ucb.retries++),
287 RETRY_UNMOUNT_DELAY);
288 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800289 }
290 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800291 // Remove already processed elements from list.
292 for (int i = (sizeArrN-1); i >= 0; i--) {
293 mForceUnmounts.remove(sizeArr[i]);
294 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800295 break;
296 }
297 case H_UNMOUNT_MS : {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800298 if (DEBUG_UNMOUNT) Log.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800299 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800300 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800301 break;
302 }
303 }
304 }
305 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400306 final private HandlerThread mHandlerThread;
307 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800308
San Mehat207e5382010-02-04 20:46:54 -0800309 private void waitForReady() {
310 while (mReady == false) {
311 for (int retries = 5; retries > 0; retries--) {
312 if (mReady) {
313 return;
314 }
315 SystemClock.sleep(1000);
316 }
317 Log.w(TAG, "Waiting too long for mReady!");
318 }
San Mehat1f6301e2010-01-07 22:40:27 -0800319 }
320
San Mehat207e5382010-02-04 20:46:54 -0800321 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800323 String action = intent.getAction();
324
325 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800326 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800327
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800328 /*
329 * In the simulator, we need to broadcast a volume mounted event
330 * to make the media scanner run.
331 */
332 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
333 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
334 return;
335 }
San Mehatfafb0412010-02-18 19:40:04 -0800336 new Thread() {
337 public void run() {
338 try {
339 String path = Environment.getExternalStorageDirectory().getPath();
340 if (getVolumeState(
341 Environment.getExternalStorageDirectory().getPath()).equals(
342 Environment.MEDIA_UNMOUNTED)) {
343 int rc = doMountVolume(path);
344 if (rc != StorageResultCode.OperationSucceeded) {
345 Log.e(TAG, String.format("Boot-time mount failed (%d)", rc));
346 }
347 }
San Mehat6a965af22010-02-24 17:47:30 -0800348 /*
349 * If UMS is connected in boot, send the connected event
350 * now that we're up.
351 */
352 if (mSendUmsConnectedOnBoot) {
353 sendUmsIntent(true);
354 mSendUmsConnectedOnBoot = false;
355 }
San Mehatfafb0412010-02-18 19:40:04 -0800356 } catch (Exception ex) {
357 Log.e(TAG, "Boot-time mount exception", ex);
358 }
San Mehat207e5382010-02-04 20:46:54 -0800359 }
San Mehatfafb0412010-02-18 19:40:04 -0800360 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362 }
363 };
364
San Mehat4270e1e2010-01-29 05:32:19 -0800365 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
366 final IMountServiceListener mListener;
367
368 MountServiceBinderListener(IMountServiceListener listener) {
369 mListener = listener;
370
San Mehat91c77612010-01-07 10:39:41 -0800371 }
372
San Mehat4270e1e2010-01-29 05:32:19 -0800373 public void binderDied() {
San Mehatb1043402010-02-05 08:26:50 -0800374 if (LOCAL_LOGD) Log.d(TAG, "An IMountServiceListener has died!");
San Mehat4270e1e2010-01-29 05:32:19 -0800375 synchronized(mListeners) {
376 mListeners.remove(this);
377 mListener.asBinder().unlinkToDeath(this, 0);
378 }
379 }
380 }
381
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800382 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800383 // TODO: Add support for multiple share methods
384 if (!method.equals("ums")) {
385 throw new IllegalArgumentException(String.format("Method %s not supported", method));
386 }
387
San Mehat4270e1e2010-01-29 05:32:19 -0800388 try {
389 mConnector.doCommand(String.format(
390 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
391 } catch (NativeDaemonConnectorException e) {
392 Log.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800393 }
San Mehat4270e1e2010-01-29 05:32:19 -0800394 }
395
San Mehat207e5382010-02-04 20:46:54 -0800396 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800397 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
398 Log.w(TAG, "Multiple volumes not currently supported");
399 return;
400 }
San Mehatb1043402010-02-05 08:26:50 -0800401
402 if (mLegacyState.equals(state)) {
403 Log.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
404 return;
405 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800406 // Update state on PackageManager
407 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
408 mPms.updateExternalMediaStatus(false);
409 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
410 mPms.updateExternalMediaStatus(true);
411 }
San Mehat4270e1e2010-01-29 05:32:19 -0800412 String oldState = mLegacyState;
413 mLegacyState = state;
414
415 synchronized (mListeners) {
416 for (int i = mListeners.size() -1; i >= 0; i--) {
417 MountServiceBinderListener bl = mListeners.get(i);
418 try {
San Mehatb1043402010-02-05 08:26:50 -0800419 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800420 } catch (RemoteException rex) {
421 Log.e(TAG, "Listener dead");
422 mListeners.remove(i);
423 } catch (Exception ex) {
424 Log.e(TAG, "Listener failed", ex);
425 }
426 }
427 }
428 }
429
430 /**
431 *
432 * Callback from NativeDaemonConnector
433 */
434 public void onDaemonConnected() {
435 /*
436 * Since we'll be calling back into the NativeDaemonConnector,
437 * we need to do our work in a new thread.
438 */
439 new Thread() {
440 public void run() {
441 /**
442 * Determine media state and UMS detection status
443 */
444 String path = Environment.getExternalStorageDirectory().getPath();
445 String state = Environment.MEDIA_REMOVED;
446
447 try {
448 String[] vols = mConnector.doListCommand(
449 "volume list", VoldResponseCode.VolumeListResult);
450 for (String volstr : vols) {
451 String[] tok = volstr.split(" ");
452 // FMT: <label> <mountpoint> <state>
453 if (!tok[1].equals(path)) {
454 Log.w(TAG, String.format(
455 "Skipping unknown volume '%s'",tok[1]));
456 continue;
457 }
458 int st = Integer.parseInt(tok[2]);
459 if (st == VolumeState.NoMedia) {
460 state = Environment.MEDIA_REMOVED;
461 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800462 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800463 } else if (st == VolumeState.Mounted) {
464 state = Environment.MEDIA_MOUNTED;
465 Log.i(TAG, "Media already mounted on daemon connection");
466 } else if (st == VolumeState.Shared) {
467 state = Environment.MEDIA_SHARED;
468 Log.i(TAG, "Media shared on daemon connection");
469 } else {
470 throw new Exception(String.format("Unexpected state %d", st));
471 }
472 }
473 if (state != null) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800474 if (DEBUG_EVENTS) Log.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800475 updatePublicVolumeState(path, state);
476 }
477 } catch (Exception e) {
478 Log.e(TAG, "Error processing initial volume state", e);
479 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
480 }
481
482 try {
San Mehat207e5382010-02-04 20:46:54 -0800483 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800484 notifyShareAvailabilityChange("ums", avail);
485 } catch (Exception ex) {
486 Log.w(TAG, "Failed to get share availability");
487 }
San Mehat207e5382010-02-04 20:46:54 -0800488 /*
489 * Now that we've done our initialization, release
490 * the hounds!
491 */
492 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800493 }
494 }.start();
495 }
496
497 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800498 * Callback from NativeDaemonConnector
499 */
500 public boolean onEvent(int code, String raw, String[] cooked) {
501 Intent in = null;
502
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800503 if (DEBUG_EVENTS) {
504 StringBuilder builder = new StringBuilder();
505 builder.append("onEvent::");
506 builder.append(" raw= " + raw);
507 if (cooked != null) {
508 builder.append(" cooked = " );
509 for (String str : cooked) {
510 builder.append(" " + str);
511 }
512 }
513 Log.i(TAG, builder.toString());
514 }
San Mehat4270e1e2010-01-29 05:32:19 -0800515 if (code == VoldResponseCode.VolumeStateChange) {
516 /*
517 * One of the volumes we're managing has changed state.
518 * Format: "NNN Volume <label> <path> state changed
519 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
520 */
521 notifyVolumeStateChange(
522 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
523 Integer.parseInt(cooked[10]));
524 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
525 // FMT: NNN Share method <method> now <available|unavailable>
526 boolean avail = false;
527 if (cooked[5].equals("available")) {
528 avail = true;
529 }
530 notifyShareAvailabilityChange(cooked[3], avail);
531 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
532 (code == VoldResponseCode.VolumeDiskRemoved) ||
533 (code == VoldResponseCode.VolumeBadRemoval)) {
534 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
535 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
536 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
537 final String label = cooked[2];
538 final String path = cooked[3];
539 int major = -1;
540 int minor = -1;
541
542 try {
543 String devComp = cooked[6].substring(1, cooked[6].length() -1);
544 String[] devTok = devComp.split(":");
545 major = Integer.parseInt(devTok[0]);
546 minor = Integer.parseInt(devTok[1]);
547 } catch (Exception ex) {
548 Log.e(TAG, "Failed to parse major/minor", ex);
549 }
550
San Mehat4270e1e2010-01-29 05:32:19 -0800551 if (code == VoldResponseCode.VolumeDiskInserted) {
552 new Thread() {
553 public void run() {
554 try {
555 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800556 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehat4270e1e2010-01-29 05:32:19 -0800557 Log.w(TAG, String.format("Insertion mount failed (%d)", rc));
558 }
559 } catch (Exception ex) {
560 Log.w(TAG, "Failed to mount media on insertion", ex);
561 }
562 }
563 }.start();
564 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
565 /*
566 * This event gets trumped if we're already in BAD_REMOVAL state
567 */
568 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
569 return true;
570 }
571 /* Send the media unmounted event first */
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800572 if (DEBUG_EVENTS) Log.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800573 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
574 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
575 mContext.sendBroadcast(in);
576
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800577 if (DEBUG_EVENTS) Log.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800578 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
579 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
580 } else if (code == VoldResponseCode.VolumeBadRemoval) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800581 if (DEBUG_EVENTS) Log.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800582 /* Send the media unmounted event first */
583 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
584 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
585 mContext.sendBroadcast(in);
586
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800587 if (DEBUG_EVENTS) Log.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800588 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
589 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
590 } else {
591 Log.e(TAG, String.format("Unknown code {%d}", code));
592 }
593 } else {
594 return false;
595 }
596
597 if (in != null) {
598 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400599 }
600 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800601 }
602
San Mehat207e5382010-02-04 20:46:54 -0800603 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800604 String vs = getVolumeState(path);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800605 if (DEBUG_EVENTS) Log.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800606
607 Intent in = null;
608
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500609 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehat2fe718a2010-03-11 12:01:49 -0800610 if (LOCAL_LOGD) Log.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500611 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
612 Uri.parse("file://" + path)));
613 }
614
San Mehat4270e1e2010-01-29 05:32:19 -0800615 if (newState == VolumeState.Init) {
616 } else if (newState == VolumeState.NoMedia) {
617 // NoMedia is handled via Disk Remove events
618 } else if (newState == VolumeState.Idle) {
619 /*
620 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
621 * if we're in the process of enabling UMS
622 */
623 if (!vs.equals(
624 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
625 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800626 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800627 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800628 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
629 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
630 }
631 } else if (newState == VolumeState.Pending) {
632 } else if (newState == VolumeState.Checking) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800633 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800634 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
635 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
636 } else if (newState == VolumeState.Mounted) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800637 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800638 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800639 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
640 in.putExtra("read-only", false);
641 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800642 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
643 } else if (newState == VolumeState.Formatting) {
644 } else if (newState == VolumeState.Shared) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800645 if (DEBUG_EVENTS) Log.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800646 /* Send the media unmounted event first */
647 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
648 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
649 mContext.sendBroadcast(in);
650
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800651 if (DEBUG_EVENTS) Log.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800652 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
653 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehat2fe718a2010-03-11 12:01:49 -0800654 if (LOCAL_LOGD) Log.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800655 } else if (newState == VolumeState.SharedMnt) {
656 Log.e(TAG, "Live shared mounts not supported yet!");
657 return;
658 } else {
659 Log.e(TAG, "Unhandled VolumeState {" + newState + "}");
660 }
661
662 if (in != null) {
663 mContext.sendBroadcast(in);
664 }
665 }
666
San Mehat207e5382010-02-04 20:46:54 -0800667 private boolean doGetShareMethodAvailable(String method) {
668 ArrayList<String> rsp = mConnector.doCommand("share status " + method);
669
670 for (String line : rsp) {
671 String []tok = line.split(" ");
672 int code;
673 try {
674 code = Integer.parseInt(tok[0]);
675 } catch (NumberFormatException nfe) {
676 Log.e(TAG, String.format("Error parsing code %s", tok[0]));
677 return false;
678 }
679 if (code == VoldResponseCode.ShareStatusResult) {
680 if (tok[2].equals("available"))
681 return true;
682 return false;
683 } else {
684 Log.e(TAG, String.format("Unexpected response code %d", code));
685 return false;
686 }
687 }
688 Log.e(TAG, "Got an empty response");
689 return false;
690 }
691
692 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800693 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800694
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800695 if (DEBUG_EVENTS) Log.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800696 try {
697 mConnector.doCommand(String.format("volume mount %s", path));
698 } catch (NativeDaemonConnectorException e) {
699 /*
700 * Mount failed for some reason
701 */
702 Intent in = null;
703 int code = e.getCode();
704 if (code == VoldResponseCode.OpFailedNoMedia) {
705 /*
706 * Attempt to mount but no media inserted
707 */
San Mehatb1043402010-02-05 08:26:50 -0800708 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800709 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800710 if (DEBUG_EVENTS) Log.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800711 /*
712 * Media is blank or does not contain a supported filesystem
713 */
714 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
715 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800716 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800717 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800718 if (DEBUG_EVENTS) Log.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800719 /*
720 * Volume consistency check failed
721 */
722 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
723 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800724 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800725 } else {
San Mehatb1043402010-02-05 08:26:50 -0800726 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800727 }
728
729 /*
730 * Send broadcast intent (if required for the failure)
731 */
732 if (in != null) {
733 mContext.sendBroadcast(in);
734 }
735 }
736
737 return rc;
738 }
739
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800740 /*
741 * If force is not set, we do not unmount if there are
742 * processes holding references to the volume about to be unmounted.
743 * If force is set, all the processes holding references need to be
744 * killed via the ActivityManager before actually unmounting the volume.
745 * This might even take a while and might be retried after timed delays
746 * to make sure we dont end up in an instable state and kill some core
747 * processes.
748 */
San Mehatd9709982010-02-18 11:43:03 -0800749 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800750 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800751 return VoldResponseCode.OpFailedVolNotMounted;
752 }
753
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800754 // We unmounted the volume. No of the asec containers are available now.
755 synchronized (mAsecMountSet) {
756 mAsecMountSet.clear();
757 }
San Mehat207e5382010-02-04 20:46:54 -0800758 // Notify PackageManager of potential media removal and deal with
759 // return code later on. The caller of this api should be aware or have been
760 // notified that the applications installed on the media will be killed.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800761 // Redundant probably. But no harm in updating state again.
San Mehat207e5382010-02-04 20:46:54 -0800762 mPms.updateExternalMediaStatus(false);
763 try {
San Mehatd9709982010-02-18 11:43:03 -0800764 mConnector.doCommand(String.format(
765 "volume unmount %s%s", path, (force ? " force" : "")));
San Mehatb1043402010-02-05 08:26:50 -0800766 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800767 } catch (NativeDaemonConnectorException e) {
768 // Don't worry about mismatch in PackageManager since the
769 // call back will handle the status changes any way.
770 int code = e.getCode();
771 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800772 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800773 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
774 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800775 } else {
San Mehatb1043402010-02-05 08:26:50 -0800776 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800777 }
778 }
779 }
780
781 private int doFormatVolume(String path) {
782 try {
783 String cmd = String.format("volume format %s", path);
784 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800785 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800786 } catch (NativeDaemonConnectorException e) {
787 int code = e.getCode();
788 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800789 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800790 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800791 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800792 } else {
San Mehatb1043402010-02-05 08:26:50 -0800793 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800794 }
795 }
796 }
797
San Mehatb1043402010-02-05 08:26:50 -0800798 private boolean doGetVolumeShared(String path, String method) {
799 String cmd = String.format("volume shared %s %s", path, method);
800 ArrayList<String> rsp = mConnector.doCommand(cmd);
801
802 for (String line : rsp) {
803 String []tok = line.split(" ");
804 int code;
805 try {
806 code = Integer.parseInt(tok[0]);
807 } catch (NumberFormatException nfe) {
808 Log.e(TAG, String.format("Error parsing code %s", tok[0]));
809 return false;
810 }
811 if (code == VoldResponseCode.ShareEnabledResult) {
812 if (tok[2].equals("enabled"))
813 return true;
814 return false;
815 } else {
816 Log.e(TAG, String.format("Unexpected response code %d", code));
817 return false;
818 }
819 }
820 Log.e(TAG, "Got an empty response");
821 return false;
822 }
823
San Mehat207e5382010-02-04 20:46:54 -0800824 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800825 if (!method.equals("ums")) {
826 Log.w(TAG, "Ignoring unsupported share method {" + method + "}");
827 return;
828 }
829
830 synchronized (mListeners) {
831 for (int i = mListeners.size() -1; i >= 0; i--) {
832 MountServiceBinderListener bl = mListeners.get(i);
833 try {
San Mehatb1043402010-02-05 08:26:50 -0800834 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800835 } catch (RemoteException rex) {
836 Log.e(TAG, "Listener dead");
837 mListeners.remove(i);
838 } catch (Exception ex) {
839 Log.e(TAG, "Listener failed", ex);
840 }
841 }
842 }
843
San Mehat207e5382010-02-04 20:46:54 -0800844 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800845 sendUmsIntent(avail);
846 } else {
847 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800848 }
San Mehat2fe718a2010-03-11 12:01:49 -0800849
850 final String path = Environment.getExternalStorageDirectory().getPath();
851 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
852 /*
853 * USB mass storage disconnected while enabled
854 */
855 new Thread() {
856 public void run() {
857 try {
858 int rc;
859 Log.w(TAG, "Disabling UMS after cable disconnect");
860 doShareUnshareVolume(path, "ums", false);
861 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
862 Log.e(TAG, String.format(
863 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
864 path, rc));
865 }
866 } catch (Exception ex) {
867 Log.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
868 }
869 }
870 }.start();
871 }
San Mehat4270e1e2010-01-29 05:32:19 -0800872 }
873
San Mehat6a965af22010-02-24 17:47:30 -0800874 private void sendUmsIntent(boolean c) {
875 mContext.sendBroadcast(
876 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
877 }
878
San Mehat207e5382010-02-04 20:46:54 -0800879 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -0800880 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
881 throw new SecurityException(String.format("Requires %s permission", perm));
882 }
883 }
884
885 /**
San Mehat207e5382010-02-04 20:46:54 -0800886 * Constructs a new MountService instance
887 *
888 * @param context Binder context for this service
889 */
890 public MountService(Context context) {
891 mContext = context;
892
San Mehat207e5382010-02-04 20:46:54 -0800893 // XXX: This will go away soon in favor of IMountServiceObserver
894 mPms = (PackageManagerService) ServiceManager.getService("package");
895
896 mContext.registerReceiver(mBroadcastReceiver,
897 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
898
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400899 mHandlerThread = new HandlerThread("MountService");
900 mHandlerThread.start();
901 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
902
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800903 /*
904 * Vold does not run in the simulator, so pretend the connector thread
905 * ran and did its thing.
906 */
907 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
908 mReady = true;
909 mUmsEnabling = true;
910 return;
911 }
912
San Mehat207e5382010-02-04 20:46:54 -0800913 mConnector = new NativeDaemonConnector(this, "vold", 10, "VoldConnector");
914 mReady = false;
915 Thread thread = new Thread(mConnector, NativeDaemonConnector.class.getName());
916 thread.start();
917 }
918
919 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800920 * Exposed API calls below here
921 */
922
923 public void registerListener(IMountServiceListener listener) {
924 synchronized (mListeners) {
925 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
926 try {
927 listener.asBinder().linkToDeath(bl, 0);
928 mListeners.add(bl);
929 } catch (RemoteException rex) {
930 Log.e(TAG, "Failed to link to listener death");
931 }
932 }
933 }
934
935 public void unregisterListener(IMountServiceListener listener) {
936 synchronized (mListeners) {
937 for(MountServiceBinderListener bl : mListeners) {
938 if (bl.mListener == listener) {
939 mListeners.remove(mListeners.indexOf(bl));
940 return;
941 }
942 }
943 }
944 }
945
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800946 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -0800947 validatePermission(android.Manifest.permission.SHUTDOWN);
948
949 Log.i(TAG, "Shutting down");
950
951 String path = Environment.getExternalStorageDirectory().getPath();
952 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -0800953
954 if (state.equals(Environment.MEDIA_SHARED)) {
955 /*
956 * If the media is currently shared, unshare it.
957 * XXX: This is still dangerous!. We should not
958 * be rebooting at *all* if UMS is enabled, since
959 * the UMS host could have dirty FAT cache entries
960 * yet to flush.
961 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800962 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -0800963 } else if (state.equals(Environment.MEDIA_CHECKING)) {
964 /*
965 * If the media is being checked, then we need to wait for
966 * it to complete before being able to proceed.
967 */
968 // XXX: @hackbod - Should we disable the ANR timer here?
969 int retries = 30;
970 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
971 try {
972 Thread.sleep(1000);
973 } catch (InterruptedException iex) {
974 Log.e(TAG, "Interrupted while waiting for media", iex);
975 break;
976 }
977 state = Environment.getExternalStorageState();
978 }
979 if (retries == 0) {
980 Log.e(TAG, "Timed out waiting for media to check");
981 }
982 }
983
984 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800985 // Post a unmount message.
986 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
987 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -0800988 }
989 }
990
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800991 private boolean getUmsEnabling() {
992 synchronized (mListeners) {
993 return mUmsEnabling;
994 }
995 }
996
997 private void setUmsEnabling(boolean enable) {
998 synchronized (mListeners) {
999 mUmsEnabling = true;
1000 }
1001 }
1002
San Mehatb1043402010-02-05 08:26:50 -08001003 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001004 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001005
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001006 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001007 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001008 }
San Mehatb1043402010-02-05 08:26:50 -08001009 return doGetShareMethodAvailable("ums");
1010 }
1011
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001012 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001013 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001014 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001015
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001016 // TODO: Add support for multiple share methods
1017
1018 /*
1019 * If the volume is mounted and we're enabling then unmount it
1020 */
1021 String path = Environment.getExternalStorageDirectory().getPath();
1022 String vs = getVolumeState(path);
1023 String method = "ums";
1024 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1025 // Override for isUsbMassStorageEnabled()
1026 setUmsEnabling(enable);
1027 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1028 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1029 // Clear override
1030 setUmsEnabling(false);
1031 }
1032 /*
1033 * If we disabled UMS then mount the volume
1034 */
1035 if (!enable) {
1036 doShareUnshareVolume(path, method, enable);
1037 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
1038 Log.e(TAG, "Failed to remount " + path +
1039 " after disabling share method " + method);
1040 /*
1041 * Even though the mount failed, the unshare didn't so don't indicate an error.
1042 * The mountVolume() call will have set the storage state and sent the necessary
1043 * broadcasts.
1044 */
1045 }
1046 }
San Mehatb1043402010-02-05 08:26:50 -08001047 }
1048
1049 public boolean isUsbMassStorageEnabled() {
1050 waitForReady();
1051 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
San Mehat4270e1e2010-01-29 05:32:19 -08001053
San Mehat7fd0fee2009-12-17 07:12:23 -08001054 /**
1055 * @return state of the volume at the specified mount point
1056 */
San Mehat4270e1e2010-01-29 05:32:19 -08001057 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001058 /*
1059 * XXX: Until we have multiple volume discovery, just hardwire
1060 * this to /sdcard
1061 */
1062 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
1063 Log.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1064 throw new IllegalArgumentException();
1065 }
1066
1067 return mLegacyState;
1068 }
1069
San Mehat4270e1e2010-01-29 05:32:19 -08001070 public int mountVolume(String path) {
1071 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001072
San Mehat207e5382010-02-04 20:46:54 -08001073 waitForReady();
1074 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001077 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001078 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001079 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001081 String volState = getVolumeState(path);
1082 if (DEBUG_UNMOUNT) Log.i(TAG, "Unmounting " + path + " force = " + force);
1083 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1084 Environment.MEDIA_REMOVED.equals(volState) ||
1085 Environment.MEDIA_SHARED.equals(volState) ||
1086 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1087 // Media already unmounted or cannot be unmounted.
1088 // TODO return valid return code when adding observer call back.
1089 return;
1090 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001091 UnmountCallBack ucb = new UnmountCallBack(path, force);
1092 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094
San Mehat4270e1e2010-01-29 05:32:19 -08001095 public int formatVolume(String path) {
1096 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001097 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001098
San Mehat207e5382010-02-04 20:46:54 -08001099 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
1101
San Mehatc1b4ce92010-02-16 17:13:03 -08001102 public int []getStorageUsers(String path) {
1103 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1104 waitForReady();
1105 try {
1106 String[] r = mConnector.doListCommand(
1107 String.format("storage users %s", path),
1108 VoldResponseCode.StorageUsersListResult);
1109 // FMT: <pid> <process name>
1110 int[] data = new int[r.length];
1111 for (int i = 0; i < r.length; i++) {
1112 String []tok = r[i].split(" ");
1113 try {
1114 data[i] = Integer.parseInt(tok[0]);
1115 } catch (NumberFormatException nfe) {
1116 Log.e(TAG, String.format("Error parsing pid %s", tok[0]));
1117 return new int[0];
1118 }
1119 }
1120 return data;
1121 } catch (NativeDaemonConnectorException e) {
1122 Log.e(TAG, "Failed to retrieve storage users list", e);
1123 return new int[0];
1124 }
1125 }
1126
San Mehatb1043402010-02-05 08:26:50 -08001127 private void warnOnNotMounted() {
1128 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
1129 Log.w(TAG, "getSecureContainerList() called when storage not mounted");
1130 }
1131 }
1132
San Mehat4270e1e2010-01-29 05:32:19 -08001133 public String[] getSecureContainerList() {
1134 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001135 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001136 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001137
San Mehat4270e1e2010-01-29 05:32:19 -08001138 try {
1139 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1140 } catch (NativeDaemonConnectorException e) {
1141 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
1143 }
San Mehat36972292010-01-06 11:06:32 -08001144
San Mehat4270e1e2010-01-29 05:32:19 -08001145 public int createSecureContainer(String id, int sizeMb, String fstype,
1146 String key, int ownerUid) {
1147 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001148 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001149 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001150
San Mehatb1043402010-02-05 08:26:50 -08001151 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001152 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1153 try {
1154 mConnector.doCommand(cmd);
1155 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001156 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001157 }
San Mehata181b212010-02-11 06:50:20 -08001158
1159 if (rc == StorageResultCode.OperationSucceeded) {
1160 synchronized (mAsecMountSet) {
1161 mAsecMountSet.add(id);
1162 }
1163 }
San Mehat4270e1e2010-01-29 05:32:19 -08001164 return rc;
San Mehat36972292010-01-06 11:06:32 -08001165 }
1166
San Mehat4270e1e2010-01-29 05:32:19 -08001167 public int finalizeSecureContainer(String id) {
1168 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001169 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001170
San Mehatb1043402010-02-05 08:26:50 -08001171 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001172 try {
1173 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001174 /*
1175 * Finalization does a remount, so no need
1176 * to update mAsecMountSet
1177 */
San Mehat4270e1e2010-01-29 05:32:19 -08001178 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001179 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001180 }
San Mehat4270e1e2010-01-29 05:32:19 -08001181 return rc;
San Mehat36972292010-01-06 11:06:32 -08001182 }
1183
San Mehatd9709982010-02-18 11:43:03 -08001184 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001185 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001186 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001187 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001188
San Mehatb1043402010-02-05 08:26:50 -08001189 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001190 try {
San Mehatd9709982010-02-18 11:43:03 -08001191 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001192 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001193 int code = e.getCode();
1194 if (code == VoldResponseCode.OpFailedStorageBusy) {
1195 rc = StorageResultCode.OperationFailedStorageBusy;
1196 } else {
1197 rc = StorageResultCode.OperationFailedInternalError;
1198 }
San Mehat02735bc2010-01-26 15:18:08 -08001199 }
San Mehata181b212010-02-11 06:50:20 -08001200
1201 if (rc == StorageResultCode.OperationSucceeded) {
1202 synchronized (mAsecMountSet) {
1203 if (mAsecMountSet.contains(id)) {
1204 mAsecMountSet.remove(id);
1205 }
1206 }
1207 }
1208
San Mehat4270e1e2010-01-29 05:32:19 -08001209 return rc;
San Mehat36972292010-01-06 11:06:32 -08001210 }
1211
San Mehat4270e1e2010-01-29 05:32:19 -08001212 public int mountSecureContainer(String id, String key, int ownerUid) {
1213 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001214 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001215 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001216
San Mehata181b212010-02-11 06:50:20 -08001217 synchronized (mAsecMountSet) {
1218 if (mAsecMountSet.contains(id)) {
1219 return StorageResultCode.OperationFailedStorageMounted;
1220 }
1221 }
1222
San Mehatb1043402010-02-05 08:26:50 -08001223 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001224 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1225 try {
1226 mConnector.doCommand(cmd);
1227 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001228 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001229 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001230
1231 if (rc == StorageResultCode.OperationSucceeded) {
1232 synchronized (mAsecMountSet) {
1233 mAsecMountSet.add(id);
1234 }
1235 }
San Mehat4270e1e2010-01-29 05:32:19 -08001236 return rc;
San Mehat36972292010-01-06 11:06:32 -08001237 }
1238
San Mehatd9709982010-02-18 11:43:03 -08001239 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001240 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001241 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001242 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001243
San Mehat6cdd9c02010-02-09 14:45:20 -08001244 synchronized (mAsecMountSet) {
1245 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001246 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001247 }
1248 }
1249
San Mehatb1043402010-02-05 08:26:50 -08001250 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001251 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001252 try {
1253 mConnector.doCommand(cmd);
1254 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001255 int code = e.getCode();
1256 if (code == VoldResponseCode.OpFailedStorageBusy) {
1257 rc = StorageResultCode.OperationFailedStorageBusy;
1258 } else {
1259 rc = StorageResultCode.OperationFailedInternalError;
1260 }
San Mehat02735bc2010-01-26 15:18:08 -08001261 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001262
1263 if (rc == StorageResultCode.OperationSucceeded) {
1264 synchronized (mAsecMountSet) {
1265 mAsecMountSet.remove(id);
1266 }
1267 }
San Mehat4270e1e2010-01-29 05:32:19 -08001268 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001269 }
1270
San Mehat6cdd9c02010-02-09 14:45:20 -08001271 public boolean isSecureContainerMounted(String id) {
1272 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1273 waitForReady();
1274 warnOnNotMounted();
1275
1276 synchronized (mAsecMountSet) {
1277 return mAsecMountSet.contains(id);
1278 }
1279 }
1280
San Mehat4270e1e2010-01-29 05:32:19 -08001281 public int renameSecureContainer(String oldId, String newId) {
1282 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001283 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001284 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001285
San Mehata181b212010-02-11 06:50:20 -08001286 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001287 /*
1288 * Because a mounted container has active internal state which cannot be
1289 * changed while active, we must ensure both ids are not currently mounted.
1290 */
1291 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001292 return StorageResultCode.OperationFailedStorageMounted;
1293 }
1294 }
1295
San Mehatb1043402010-02-05 08:26:50 -08001296 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001297 String cmd = String.format("asec rename %s %s", oldId, newId);
1298 try {
1299 mConnector.doCommand(cmd);
1300 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001301 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001302 }
San Mehata181b212010-02-11 06:50:20 -08001303
San Mehat4270e1e2010-01-29 05:32:19 -08001304 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001305 }
1306
San Mehat4270e1e2010-01-29 05:32:19 -08001307 public String getSecureContainerPath(String id) {
1308 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001309 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001310 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001311
San Mehat4270e1e2010-01-29 05:32:19 -08001312 ArrayList<String> rsp = mConnector.doCommand("asec path " + id);
San Mehat36972292010-01-06 11:06:32 -08001313
San Mehat22dd86e2010-01-12 12:21:18 -08001314 for (String line : rsp) {
1315 String []tok = line.split(" ");
1316 int code = Integer.parseInt(tok[0]);
1317 if (code == VoldResponseCode.AsecPathResult) {
1318 return tok[1];
1319 } else {
San Mehat4270e1e2010-01-29 05:32:19 -08001320 Log.e(TAG, String.format("Unexpected response code %d", code));
1321 return "";
San Mehat22dd86e2010-01-12 12:21:18 -08001322 }
1323 }
San Mehat4270e1e2010-01-29 05:32:19 -08001324
1325 Log.e(TAG, "Got an empty response");
1326 return "";
San Mehat22dd86e2010-01-12 12:21:18 -08001327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328}
1329