blob: baa5016fc032d379fd43faea24589480da533f64 [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
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Kenny Root735de3b2010-09-30 14:11:39 -070020import com.android.internal.util.HexDump;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
47import android.os.storage.StorageResultCode;
Kenny Root735de3b2010-09-30 14:11:39 -070048import android.security.MessageDigest;
San Mehata5078592010-03-25 09:36:54 -070049import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070050
Kenny Root38cf8862010-09-26 14:18:51 -070051import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070052import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.io.PrintWriter;
Kenny Root735de3b2010-09-30 14:11:39 -070054import java.security.NoSuchAlgorithmException;
San Mehat22dd86e2010-01-12 12:21:18 -080055import java.util.ArrayList;
Kenny Root38cf8862010-09-26 14:18:51 -070056import java.util.Collection;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080058import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070059import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.LinkedList;
61import java.util.List;
62import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
San Mehatb1043402010-02-05 08:26:50 -080066 * MountService implements back-end services for platform storage
67 * management.
68 * @hide - Applications should use android.os.storage.StorageManager
69 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 */
San Mehat22dd86e2010-01-12 12:21:18 -080071class MountService extends IMountService.Stub
72 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080073 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080074 private static final boolean DEBUG_UNMOUNT = false;
75 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070076 private static final boolean DEBUG_OBB = true;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "MountService";
79
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String VOLD_TAG = "VoldConnector";
81
San Mehat4270e1e2010-01-29 05:32:19 -080082 /*
83 * Internal vold volume state constants
84 */
San Mehat7fd0fee2009-12-17 07:12:23 -080085 class VolumeState {
86 public static final int Init = -1;
87 public static final int NoMedia = 0;
88 public static final int Idle = 1;
89 public static final int Pending = 2;
90 public static final int Checking = 3;
91 public static final int Mounted = 4;
92 public static final int Unmounting = 5;
93 public static final int Formatting = 6;
94 public static final int Shared = 7;
95 public static final int SharedMnt = 8;
96 }
97
San Mehat4270e1e2010-01-29 05:32:19 -080098 /*
99 * Internal vold response code constants
100 */
San Mehat22dd86e2010-01-12 12:21:18 -0800101 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800102 /*
103 * 100 series - Requestion action was initiated; expect another reply
104 * before proceeding with a new command.
105 */
San Mehat22dd86e2010-01-12 12:21:18 -0800106 public static final int VolumeListResult = 110;
107 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800108 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800109
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * 200 series - Requestion action has been successfully completed.
112 */
113 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800114 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800115 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800116
San Mehat4270e1e2010-01-29 05:32:19 -0800117 /*
118 * 400 series - Command was accepted, but the requested action
119 * did not take place.
120 */
121 public static final int OpFailedNoMedia = 401;
122 public static final int OpFailedMediaBlank = 402;
123 public static final int OpFailedMediaCorrupt = 403;
124 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800125 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700126 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800127
128 /*
129 * 600 series - Unsolicited broadcasts.
130 */
San Mehat22dd86e2010-01-12 12:21:18 -0800131 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800132 public static final int ShareAvailabilityChange = 620;
133 public static final int VolumeDiskInserted = 630;
134 public static final int VolumeDiskRemoved = 631;
135 public static final int VolumeBadRemoval = 632;
136 }
137
San Mehat4270e1e2010-01-29 05:32:19 -0800138 private Context mContext;
139 private NativeDaemonConnector mConnector;
140 private String mLegacyState = Environment.MEDIA_REMOVED;
141 private PackageManagerService mPms;
142 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800143 // Used as a lock for methods that register/unregister listeners.
144 final private ArrayList<MountServiceBinderListener> mListeners =
145 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800146 private boolean mBooted = false;
147 private boolean mReady = false;
148 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400149 // true if we should fake MEDIA_MOUNTED state for external storage
150 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800151
San Mehat6cdd9c02010-02-09 14:45:20 -0800152 /**
153 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800154 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800155 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800156 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800157
Kenny Root02c87302010-07-01 08:10:18 -0700158 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700159 * Mounted OBB tracking information. Used to track the current state of all
160 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700161 */
Kenny Root735de3b2010-09-30 14:11:39 -0700162 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700163 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
164
165 class ObbState implements IBinder.DeathRecipient {
Kenny Root735de3b2010-09-30 14:11:39 -0700166 public ObbState(String filename, IObbActionListener token, int callerUid)
167 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700168 this.filename = filename;
169 this.token = token;
170 this.callerUid = callerUid;
171 mounted = false;
172 }
173
174 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700175 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700176
177 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700178 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700179
180 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700181 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700182
183 // Whether this is mounted currently.
184 boolean mounted;
185
Kenny Root735de3b2010-09-30 14:11:39 -0700186 public IBinder getBinder() {
187 return token.asBinder();
188 }
189
Kenny Roota02b8b02010-08-05 16:14:17 -0700190 @Override
191 public void binderDied() {
192 ObbAction action = new UnmountObbAction(this, true);
193 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700194 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700195
Kenny Root5919ac62010-10-05 09:49:40 -0700196 public void link() throws RemoteException {
197 getBinder().linkToDeath(this, 0);
198 }
199
200 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700201 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700202 }
Kenny Root38cf8862010-09-26 14:18:51 -0700203
204 @Override
205 public String toString() {
206 StringBuilder sb = new StringBuilder("ObbState{");
207 sb.append("filename=");
208 sb.append(filename);
209 sb.append(",token=");
210 sb.append(token.toString());
211 sb.append(",callerUid=");
212 sb.append(callerUid);
213 sb.append(",mounted=");
214 sb.append(mounted);
215 sb.append('}');
216 return sb.toString();
217 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700218 }
219
220 // OBB Action Handler
221 final private ObbActionHandler mObbActionHandler;
222
223 // OBB action handler messages
224 private static final int OBB_RUN_ACTION = 1;
225 private static final int OBB_MCS_BOUND = 2;
226 private static final int OBB_MCS_UNBIND = 3;
227 private static final int OBB_MCS_RECONNECT = 4;
Kenny Roota02b8b02010-08-05 16:14:17 -0700228
229 /*
230 * Default Container Service information
231 */
232 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
233 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
234
235 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
236
237 class DefaultContainerConnection implements ServiceConnection {
238 public void onServiceConnected(ComponentName name, IBinder service) {
239 if (DEBUG_OBB)
240 Slog.i(TAG, "onServiceConnected");
241 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
242 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
243 }
244
245 public void onServiceDisconnected(ComponentName name) {
246 if (DEBUG_OBB)
247 Slog.i(TAG, "onServiceDisconnected");
248 }
249 };
250
251 // Used in the ObbActionHandler
252 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700253
254 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800255 private static final int H_UNMOUNT_PM_UPDATE = 1;
256 private static final int H_UNMOUNT_PM_DONE = 2;
257 private static final int H_UNMOUNT_MS = 3;
258 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
259 private static final int MAX_UNMOUNT_RETRIES = 4;
260
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800261 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700262 final String path;
263 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800264 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800265
266 UnmountCallBack(String path, boolean force) {
267 retries = 0;
268 this.path = path;
269 this.force = force;
270 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800271
272 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700273 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800274 doUnmountVolume(path, true);
275 }
276 }
277
278 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700279 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800280
281 UmsEnableCallBack(String path, String method, boolean force) {
282 super(path, force);
283 this.method = method;
284 }
285
286 @Override
287 void handleFinished() {
288 super.handleFinished();
289 doShareUnshareVolume(path, method, true);
290 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800291 }
292
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800293 class ShutdownCallBack extends UnmountCallBack {
294 IMountShutdownObserver observer;
295 ShutdownCallBack(String path, IMountShutdownObserver observer) {
296 super(path, true);
297 this.observer = observer;
298 }
299
300 @Override
301 void handleFinished() {
302 int ret = doUnmountVolume(path, true);
303 if (observer != null) {
304 try {
305 observer.onShutDownComplete(ret);
306 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700307 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800308 }
309 }
310 }
311 }
312
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400313 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800314 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700315 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800316
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400317 MountServiceHandler(Looper l) {
318 super(l);
319 }
320
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800321 public void handleMessage(Message msg) {
322 switch (msg.what) {
323 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700324 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800325 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
326 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700327 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800328 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700329 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700330 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700331 mUpdatingStatus = true;
332 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800333 }
334 break;
335 }
336 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700337 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700338 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700339 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800340 int size = mForceUnmounts.size();
341 int sizeArr[] = new int[size];
342 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700343 // Kill processes holding references first
344 ActivityManagerService ams = (ActivityManagerService)
345 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800346 for (int i = 0; i < size; i++) {
347 UnmountCallBack ucb = mForceUnmounts.get(i);
348 String path = ucb.path;
349 boolean done = false;
350 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800351 done = true;
352 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800353 int pids[] = getStorageUsers(path);
354 if (pids == null || pids.length == 0) {
355 done = true;
356 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800357 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700358 ams.killPids(pids, "unmount media");
359 // Confirm if file references have been freed.
360 pids = getStorageUsers(path);
361 if (pids == null || pids.length == 0) {
362 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800363 }
364 }
365 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700366 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
367 // Retry again
368 Slog.i(TAG, "Retrying to kill storage users again");
369 mHandler.sendMessageDelayed(
370 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
371 ucb.retries++),
372 RETRY_UNMOUNT_DELAY);
373 } else {
374 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
375 Slog.i(TAG, "Failed to unmount media inspite of " +
376 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
377 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800378 sizeArr[sizeArrN++] = i;
379 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
380 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800381 }
382 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 // Remove already processed elements from list.
384 for (int i = (sizeArrN-1); i >= 0; i--) {
385 mForceUnmounts.remove(sizeArr[i]);
386 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800387 break;
388 }
389 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700390 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800391 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800392 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800393 break;
394 }
395 }
396 }
397 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400398 final private HandlerThread mHandlerThread;
399 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800400
San Mehat207e5382010-02-04 20:46:54 -0800401 private void waitForReady() {
402 while (mReady == false) {
403 for (int retries = 5; retries > 0; retries--) {
404 if (mReady) {
405 return;
406 }
407 SystemClock.sleep(1000);
408 }
San Mehata5078592010-03-25 09:36:54 -0700409 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800410 }
San Mehat1f6301e2010-01-07 22:40:27 -0800411 }
Kenny Root02c87302010-07-01 08:10:18 -0700412
San Mehat207e5382010-02-04 20:46:54 -0800413 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800415 String action = intent.getAction();
416
417 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800418 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800419
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800420 /*
421 * In the simulator, we need to broadcast a volume mounted event
422 * to make the media scanner run.
423 */
424 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
425 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
426 return;
427 }
San Mehatfafb0412010-02-18 19:40:04 -0800428 new Thread() {
429 public void run() {
430 try {
431 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700432 String state = getVolumeState(path);
433
Mike Lockwood03559752010-07-19 18:25:03 -0400434 if (mEmulateExternalStorage) {
435 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Mounted);
436 } else if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800437 int rc = doMountVolume(path);
438 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700439 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800440 }
San Mehat6a254402010-03-22 10:21:00 -0700441 } else if (state.equals(Environment.MEDIA_SHARED)) {
442 /*
443 * Bootstrap UMS enabled state since vold indicates
444 * the volume is shared (runtime restart while ums enabled)
445 */
446 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800447 }
San Mehat6a254402010-03-22 10:21:00 -0700448
San Mehat6a965af22010-02-24 17:47:30 -0800449 /*
San Mehat6a254402010-03-22 10:21:00 -0700450 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800451 * now that we're up.
452 */
453 if (mSendUmsConnectedOnBoot) {
454 sendUmsIntent(true);
455 mSendUmsConnectedOnBoot = false;
456 }
San Mehatfafb0412010-02-18 19:40:04 -0800457 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700458 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800459 }
San Mehat207e5382010-02-04 20:46:54 -0800460 }
San Mehatfafb0412010-02-18 19:40:04 -0800461 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
463 }
464 };
465
San Mehat4270e1e2010-01-29 05:32:19 -0800466 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
467 final IMountServiceListener mListener;
468
469 MountServiceBinderListener(IMountServiceListener listener) {
470 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700471
San Mehat91c77612010-01-07 10:39:41 -0800472 }
473
San Mehat4270e1e2010-01-29 05:32:19 -0800474 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700475 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700476 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800477 mListeners.remove(this);
478 mListener.asBinder().unlinkToDeath(this, 0);
479 }
480 }
481 }
482
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800483 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800484 // TODO: Add support for multiple share methods
485 if (!method.equals("ums")) {
486 throw new IllegalArgumentException(String.format("Method %s not supported", method));
487 }
488
San Mehat4270e1e2010-01-29 05:32:19 -0800489 try {
490 mConnector.doCommand(String.format(
491 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
492 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700493 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800494 }
San Mehat4270e1e2010-01-29 05:32:19 -0800495 }
496
San Mehat207e5382010-02-04 20:46:54 -0800497 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800498 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700499 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800500 return;
501 }
San Mehatb1043402010-02-05 08:26:50 -0800502
503 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700504 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800505 return;
506 }
Mike Lockwood03559752010-07-19 18:25:03 -0400507 // Update state on PackageManager, but only of real events
508 if (!mEmulateExternalStorage) {
509 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
510 mPms.updateExternalMediaStatus(false, false);
511 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
512 mPms.updateExternalMediaStatus(true, false);
513 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800514 }
Kenny Root38cf8862010-09-26 14:18:51 -0700515
516 // Remove all OBB mappings and listeners from this path
517 synchronized (mObbMounts) {
518 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
519
520 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
521 while (i.hasNext()) {
522 final Entry<String, ObbState> obbEntry = i.next();
523
524 // If this entry's source file is in the volume path that got
525 // unmounted, remove it because it's no longer valid.
526 if (obbEntry.getKey().startsWith(path)) {
527 obbStatesToRemove.add(obbEntry.getValue());
528 }
529 }
530
531 for (final ObbState obbState : obbStatesToRemove) {
532 removeObbState(obbState);
533
534 try {
535 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
536 } catch (RemoteException e) {
537 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
538 + obbState.filename);
539 }
540 }
541 }
542
San Mehat4270e1e2010-01-29 05:32:19 -0800543 String oldState = mLegacyState;
544 mLegacyState = state;
545
546 synchronized (mListeners) {
547 for (int i = mListeners.size() -1; i >= 0; i--) {
548 MountServiceBinderListener bl = mListeners.get(i);
549 try {
San Mehatb1043402010-02-05 08:26:50 -0800550 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800551 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700552 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800553 mListeners.remove(i);
554 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700555 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800556 }
557 }
558 }
559 }
560
561 /**
562 *
563 * Callback from NativeDaemonConnector
564 */
565 public void onDaemonConnected() {
566 /*
567 * Since we'll be calling back into the NativeDaemonConnector,
568 * we need to do our work in a new thread.
569 */
570 new Thread() {
571 public void run() {
572 /**
573 * Determine media state and UMS detection status
574 */
575 String path = Environment.getExternalStorageDirectory().getPath();
576 String state = Environment.MEDIA_REMOVED;
577
578 try {
579 String[] vols = mConnector.doListCommand(
580 "volume list", VoldResponseCode.VolumeListResult);
581 for (String volstr : vols) {
582 String[] tok = volstr.split(" ");
583 // FMT: <label> <mountpoint> <state>
584 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700585 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800586 "Skipping unknown volume '%s'",tok[1]));
587 continue;
588 }
589 int st = Integer.parseInt(tok[2]);
590 if (st == VolumeState.NoMedia) {
591 state = Environment.MEDIA_REMOVED;
592 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800593 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800594 } else if (st == VolumeState.Mounted) {
595 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700596 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800597 } else if (st == VolumeState.Shared) {
598 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700599 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800600 } else {
601 throw new Exception(String.format("Unexpected state %d", st));
602 }
603 }
604 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700605 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800606 updatePublicVolumeState(path, state);
607 }
608 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700609 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800610 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
611 }
612
613 try {
San Mehat207e5382010-02-04 20:46:54 -0800614 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800615 notifyShareAvailabilityChange("ums", avail);
616 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700617 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800618 }
San Mehat207e5382010-02-04 20:46:54 -0800619 /*
620 * Now that we've done our initialization, release
621 * the hounds!
622 */
623 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800624 }
625 }.start();
626 }
627
628 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800629 * Callback from NativeDaemonConnector
630 */
631 public boolean onEvent(int code, String raw, String[] cooked) {
632 Intent in = null;
633
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800634 if (DEBUG_EVENTS) {
635 StringBuilder builder = new StringBuilder();
636 builder.append("onEvent::");
637 builder.append(" raw= " + raw);
638 if (cooked != null) {
639 builder.append(" cooked = " );
640 for (String str : cooked) {
641 builder.append(" " + str);
642 }
643 }
San Mehata5078592010-03-25 09:36:54 -0700644 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800645 }
San Mehat4270e1e2010-01-29 05:32:19 -0800646 if (code == VoldResponseCode.VolumeStateChange) {
647 /*
648 * One of the volumes we're managing has changed state.
649 * Format: "NNN Volume <label> <path> state changed
650 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
651 */
652 notifyVolumeStateChange(
653 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
654 Integer.parseInt(cooked[10]));
655 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
656 // FMT: NNN Share method <method> now <available|unavailable>
657 boolean avail = false;
658 if (cooked[5].equals("available")) {
659 avail = true;
660 }
661 notifyShareAvailabilityChange(cooked[3], avail);
662 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
663 (code == VoldResponseCode.VolumeDiskRemoved) ||
664 (code == VoldResponseCode.VolumeBadRemoval)) {
665 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
666 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
667 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
668 final String label = cooked[2];
669 final String path = cooked[3];
670 int major = -1;
671 int minor = -1;
672
673 try {
674 String devComp = cooked[6].substring(1, cooked[6].length() -1);
675 String[] devTok = devComp.split(":");
676 major = Integer.parseInt(devTok[0]);
677 minor = Integer.parseInt(devTok[1]);
678 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700679 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800680 }
681
San Mehat4270e1e2010-01-29 05:32:19 -0800682 if (code == VoldResponseCode.VolumeDiskInserted) {
683 new Thread() {
684 public void run() {
685 try {
686 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800687 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700688 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800689 }
690 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700691 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800692 }
693 }
694 }.start();
695 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
696 /*
697 * This event gets trumped if we're already in BAD_REMOVAL state
698 */
699 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
700 return true;
701 }
702 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700703 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800704 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
705 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
706 mContext.sendBroadcast(in);
707
San Mehata5078592010-03-25 09:36:54 -0700708 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800709 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
710 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
711 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700712 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800713 /* Send the media unmounted event first */
714 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
715 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
716 mContext.sendBroadcast(in);
717
San Mehata5078592010-03-25 09:36:54 -0700718 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800719 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
720 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
721 } else {
San Mehata5078592010-03-25 09:36:54 -0700722 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724 } else {
725 return false;
726 }
727
728 if (in != null) {
729 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400730 }
731 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800732 }
733
San Mehat207e5382010-02-04 20:46:54 -0800734 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800735 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700736 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800737
738 Intent in = null;
739
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500740 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700741 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500742 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
743 Uri.parse("file://" + path)));
744 }
745
San Mehat4270e1e2010-01-29 05:32:19 -0800746 if (newState == VolumeState.Init) {
747 } else if (newState == VolumeState.NoMedia) {
748 // NoMedia is handled via Disk Remove events
749 } else if (newState == VolumeState.Idle) {
750 /*
751 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
752 * if we're in the process of enabling UMS
753 */
754 if (!vs.equals(
755 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
756 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800757 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700758 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800759 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
760 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
761 }
762 } else if (newState == VolumeState.Pending) {
763 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700764 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800765 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
766 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
767 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700768 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800769 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800770 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
771 in.putExtra("read-only", false);
772 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800773 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
774 } else if (newState == VolumeState.Formatting) {
775 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700776 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800777 /* Send the media unmounted event first */
778 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
779 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
780 mContext.sendBroadcast(in);
781
San Mehata5078592010-03-25 09:36:54 -0700782 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800783 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
784 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700785 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800786 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700787 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800788 return;
789 } else {
San Mehata5078592010-03-25 09:36:54 -0700790 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800791 }
792
793 if (in != null) {
794 mContext.sendBroadcast(in);
795 }
796 }
797
San Mehat207e5382010-02-04 20:46:54 -0800798 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700799 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700800 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700801 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700802 } catch (NativeDaemonConnectorException ex) {
803 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
804 return false;
805 }
San Mehat207e5382010-02-04 20:46:54 -0800806
807 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700808 String[] tok = line.split(" ");
809 if (tok.length < 3) {
810 Slog.e(TAG, "Malformed response to share status " + method);
811 return false;
812 }
813
San Mehat207e5382010-02-04 20:46:54 -0800814 int code;
815 try {
816 code = Integer.parseInt(tok[0]);
817 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700818 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800819 return false;
820 }
821 if (code == VoldResponseCode.ShareStatusResult) {
822 if (tok[2].equals("available"))
823 return true;
824 return false;
825 } else {
San Mehata5078592010-03-25 09:36:54 -0700826 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800827 return false;
828 }
829 }
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800831 return false;
832 }
833
834 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800835 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800836
San Mehata5078592010-03-25 09:36:54 -0700837 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800838 try {
839 mConnector.doCommand(String.format("volume mount %s", path));
840 } catch (NativeDaemonConnectorException e) {
841 /*
842 * Mount failed for some reason
843 */
844 Intent in = null;
845 int code = e.getCode();
846 if (code == VoldResponseCode.OpFailedNoMedia) {
847 /*
848 * Attempt to mount but no media inserted
849 */
San Mehatb1043402010-02-05 08:26:50 -0800850 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800851 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700852 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800853 /*
854 * Media is blank or does not contain a supported filesystem
855 */
856 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
857 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800858 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800859 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700860 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800861 /*
862 * Volume consistency check failed
863 */
864 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
865 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800866 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800867 } else {
San Mehatb1043402010-02-05 08:26:50 -0800868 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800869 }
870
871 /*
872 * Send broadcast intent (if required for the failure)
873 */
874 if (in != null) {
875 mContext.sendBroadcast(in);
876 }
877 }
878
879 return rc;
880 }
881
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800882 /*
883 * If force is not set, we do not unmount if there are
884 * processes holding references to the volume about to be unmounted.
885 * If force is set, all the processes holding references need to be
886 * killed via the ActivityManager before actually unmounting the volume.
887 * This might even take a while and might be retried after timed delays
888 * to make sure we dont end up in an instable state and kill some core
889 * processes.
890 */
San Mehatd9709982010-02-18 11:43:03 -0800891 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800892 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800893 return VoldResponseCode.OpFailedVolNotMounted;
894 }
Kenny Rootaa485402010-09-14 14:49:41 -0700895
896 /*
897 * Force a GC to make sure AssetManagers in other threads of the
898 * system_server are cleaned up. We have to do this since AssetManager
899 * instances are kept as a WeakReference and it's possible we have files
900 * open on the external storage.
901 */
902 Runtime.getRuntime().gc();
903
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800904 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700905 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800906 try {
San Mehatd9709982010-02-18 11:43:03 -0800907 mConnector.doCommand(String.format(
908 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700909 // We unmounted the volume. None of the asec containers are available now.
910 synchronized (mAsecMountSet) {
911 mAsecMountSet.clear();
912 }
San Mehatb1043402010-02-05 08:26:50 -0800913 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800914 } catch (NativeDaemonConnectorException e) {
915 // Don't worry about mismatch in PackageManager since the
916 // call back will handle the status changes any way.
917 int code = e.getCode();
918 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800919 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800920 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
921 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800922 } else {
San Mehatb1043402010-02-05 08:26:50 -0800923 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800924 }
925 }
926 }
927
928 private int doFormatVolume(String path) {
929 try {
930 String cmd = String.format("volume format %s", path);
931 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800932 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800933 } catch (NativeDaemonConnectorException e) {
934 int code = e.getCode();
935 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800936 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800937 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800938 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800939 } else {
San Mehatb1043402010-02-05 08:26:50 -0800940 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800941 }
942 }
943 }
944
San Mehatb1043402010-02-05 08:26:50 -0800945 private boolean doGetVolumeShared(String path, String method) {
946 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700947 ArrayList<String> rsp;
948
949 try {
950 rsp = mConnector.doCommand(cmd);
951 } catch (NativeDaemonConnectorException ex) {
952 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
953 return false;
954 }
San Mehatb1043402010-02-05 08:26:50 -0800955
956 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700957 String[] tok = line.split(" ");
958 if (tok.length < 3) {
959 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
960 return false;
961 }
962
San Mehatb1043402010-02-05 08:26:50 -0800963 int code;
964 try {
965 code = Integer.parseInt(tok[0]);
966 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700967 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800968 return false;
969 }
970 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700971 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800972 } else {
San Mehata5078592010-03-25 09:36:54 -0700973 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800974 return false;
975 }
976 }
San Mehata5078592010-03-25 09:36:54 -0700977 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800978 return false;
979 }
980
San Mehat207e5382010-02-04 20:46:54 -0800981 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800982 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700983 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800984 return;
985 }
986
987 synchronized (mListeners) {
988 for (int i = mListeners.size() -1; i >= 0; i--) {
989 MountServiceBinderListener bl = mListeners.get(i);
990 try {
San Mehatb1043402010-02-05 08:26:50 -0800991 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800992 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700993 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800994 mListeners.remove(i);
995 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700996 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800997 }
998 }
999 }
1000
San Mehat207e5382010-02-04 20:46:54 -08001001 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001002 sendUmsIntent(avail);
1003 } else {
1004 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001005 }
San Mehat2fe718a2010-03-11 12:01:49 -08001006
1007 final String path = Environment.getExternalStorageDirectory().getPath();
1008 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1009 /*
1010 * USB mass storage disconnected while enabled
1011 */
1012 new Thread() {
1013 public void run() {
1014 try {
1015 int rc;
San Mehata5078592010-03-25 09:36:54 -07001016 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001017 doShareUnshareVolume(path, "ums", false);
1018 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001019 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001020 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1021 path, rc));
1022 }
1023 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001024 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001025 }
1026 }
1027 }.start();
1028 }
San Mehat4270e1e2010-01-29 05:32:19 -08001029 }
1030
San Mehat6a965af22010-02-24 17:47:30 -08001031 private void sendUmsIntent(boolean c) {
1032 mContext.sendBroadcast(
1033 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1034 }
1035
San Mehat207e5382010-02-04 20:46:54 -08001036 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001037 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1038 throw new SecurityException(String.format("Requires %s permission", perm));
1039 }
1040 }
1041
1042 /**
San Mehat207e5382010-02-04 20:46:54 -08001043 * Constructs a new MountService instance
1044 *
1045 * @param context Binder context for this service
1046 */
1047 public MountService(Context context) {
1048 mContext = context;
1049
Mike Lockwood03559752010-07-19 18:25:03 -04001050 mEmulateExternalStorage = context.getResources().getBoolean(
1051 com.android.internal.R.bool.config_emulateExternalStorage);
1052 if (mEmulateExternalStorage) {
1053 Slog.d(TAG, "using emulated external storage");
1054 mLegacyState = Environment.MEDIA_MOUNTED;
1055 }
1056
San Mehat207e5382010-02-04 20:46:54 -08001057 // XXX: This will go away soon in favor of IMountServiceObserver
1058 mPms = (PackageManagerService) ServiceManager.getService("package");
1059
1060 mContext.registerReceiver(mBroadcastReceiver,
1061 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1062
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001063 mHandlerThread = new HandlerThread("MountService");
1064 mHandlerThread.start();
1065 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1066
Kenny Roota02b8b02010-08-05 16:14:17 -07001067 // Add OBB Action Handler to MountService thread.
1068 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1069
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001070 /*
1071 * Vold does not run in the simulator, so pretend the connector thread
1072 * ran and did its thing.
1073 */
1074 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1075 mReady = true;
1076 mUmsEnabling = true;
1077 return;
1078 }
1079
Kenny Root305bcbf2010-09-03 07:56:38 -07001080 /*
1081 * Create the connection to vold with a maximum queue of twice the
1082 * amount of containers we'd ever expect to have. This keeps an
1083 * "asec list" from blocking a thread repeatedly.
1084 */
1085 mConnector = new NativeDaemonConnector(this, "vold",
1086 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001087 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001088 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001089 thread.start();
1090 }
1091
1092 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001093 * Exposed API calls below here
1094 */
1095
1096 public void registerListener(IMountServiceListener listener) {
1097 synchronized (mListeners) {
1098 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1099 try {
1100 listener.asBinder().linkToDeath(bl, 0);
1101 mListeners.add(bl);
1102 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001103 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001104 }
1105 }
1106 }
1107
1108 public void unregisterListener(IMountServiceListener listener) {
1109 synchronized (mListeners) {
1110 for(MountServiceBinderListener bl : mListeners) {
1111 if (bl.mListener == listener) {
1112 mListeners.remove(mListeners.indexOf(bl));
1113 return;
1114 }
1115 }
1116 }
1117 }
1118
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001119 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001120 validatePermission(android.Manifest.permission.SHUTDOWN);
1121
San Mehata5078592010-03-25 09:36:54 -07001122 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001123
1124 String path = Environment.getExternalStorageDirectory().getPath();
1125 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001126
1127 if (state.equals(Environment.MEDIA_SHARED)) {
1128 /*
1129 * If the media is currently shared, unshare it.
1130 * XXX: This is still dangerous!. We should not
1131 * be rebooting at *all* if UMS is enabled, since
1132 * the UMS host could have dirty FAT cache entries
1133 * yet to flush.
1134 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001135 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001136 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1137 /*
1138 * If the media is being checked, then we need to wait for
1139 * it to complete before being able to proceed.
1140 */
1141 // XXX: @hackbod - Should we disable the ANR timer here?
1142 int retries = 30;
1143 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1144 try {
1145 Thread.sleep(1000);
1146 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001147 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001148 break;
1149 }
1150 state = Environment.getExternalStorageState();
1151 }
1152 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001153 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001154 }
1155 }
1156
1157 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001158 // Post a unmount message.
1159 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1160 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001161 }
1162 }
1163
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001164 private boolean getUmsEnabling() {
1165 synchronized (mListeners) {
1166 return mUmsEnabling;
1167 }
1168 }
1169
1170 private void setUmsEnabling(boolean enable) {
1171 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001172 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001173 }
1174 }
1175
San Mehatb1043402010-02-05 08:26:50 -08001176 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001177 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001178
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001179 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001180 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001181 }
San Mehatb1043402010-02-05 08:26:50 -08001182 return doGetShareMethodAvailable("ums");
1183 }
1184
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001185 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001186 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001187 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001188
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001189 // TODO: Add support for multiple share methods
1190
1191 /*
1192 * If the volume is mounted and we're enabling then unmount it
1193 */
1194 String path = Environment.getExternalStorageDirectory().getPath();
1195 String vs = getVolumeState(path);
1196 String method = "ums";
1197 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1198 // Override for isUsbMassStorageEnabled()
1199 setUmsEnabling(enable);
1200 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1201 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1202 // Clear override
1203 setUmsEnabling(false);
1204 }
1205 /*
1206 * If we disabled UMS then mount the volume
1207 */
1208 if (!enable) {
1209 doShareUnshareVolume(path, method, enable);
1210 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001211 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001212 " after disabling share method " + method);
1213 /*
1214 * Even though the mount failed, the unshare didn't so don't indicate an error.
1215 * The mountVolume() call will have set the storage state and sent the necessary
1216 * broadcasts.
1217 */
1218 }
1219 }
San Mehatb1043402010-02-05 08:26:50 -08001220 }
1221
1222 public boolean isUsbMassStorageEnabled() {
1223 waitForReady();
1224 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
San Mehat4270e1e2010-01-29 05:32:19 -08001226
San Mehat7fd0fee2009-12-17 07:12:23 -08001227 /**
1228 * @return state of the volume at the specified mount point
1229 */
San Mehat4270e1e2010-01-29 05:32:19 -08001230 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001231 /*
1232 * XXX: Until we have multiple volume discovery, just hardwire
1233 * this to /sdcard
1234 */
1235 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001236 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001237 throw new IllegalArgumentException();
1238 }
1239
1240 return mLegacyState;
1241 }
1242
Kenny Roote1ff2142010-10-12 11:20:01 -07001243 public boolean isExternalStorageEmulated() {
1244 return mEmulateExternalStorage;
1245 }
1246
San Mehat4270e1e2010-01-29 05:32:19 -08001247 public int mountVolume(String path) {
1248 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001249
San Mehat207e5382010-02-04 20:46:54 -08001250 waitForReady();
1251 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 }
1253
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001254 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001255 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001256 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001258 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001259 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001260 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1261 Environment.MEDIA_REMOVED.equals(volState) ||
1262 Environment.MEDIA_SHARED.equals(volState) ||
1263 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1264 // Media already unmounted or cannot be unmounted.
1265 // TODO return valid return code when adding observer call back.
1266 return;
1267 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001268 UnmountCallBack ucb = new UnmountCallBack(path, force);
1269 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271
San Mehat4270e1e2010-01-29 05:32:19 -08001272 public int formatVolume(String path) {
1273 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001274 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001275
San Mehat207e5382010-02-04 20:46:54 -08001276 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278
San Mehatc1b4ce92010-02-16 17:13:03 -08001279 public int []getStorageUsers(String path) {
1280 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1281 waitForReady();
1282 try {
1283 String[] r = mConnector.doListCommand(
1284 String.format("storage users %s", path),
1285 VoldResponseCode.StorageUsersListResult);
1286 // FMT: <pid> <process name>
1287 int[] data = new int[r.length];
1288 for (int i = 0; i < r.length; i++) {
1289 String []tok = r[i].split(" ");
1290 try {
1291 data[i] = Integer.parseInt(tok[0]);
1292 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001293 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001294 return new int[0];
1295 }
1296 }
1297 return data;
1298 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001299 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001300 return new int[0];
1301 }
1302 }
1303
San Mehatb1043402010-02-05 08:26:50 -08001304 private void warnOnNotMounted() {
1305 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001306 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001307 }
1308 }
1309
San Mehat4270e1e2010-01-29 05:32:19 -08001310 public String[] getSecureContainerList() {
1311 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001312 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001313 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001314
San Mehat4270e1e2010-01-29 05:32:19 -08001315 try {
1316 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1317 } catch (NativeDaemonConnectorException e) {
1318 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320 }
San Mehat36972292010-01-06 11:06:32 -08001321
San Mehat4270e1e2010-01-29 05:32:19 -08001322 public int createSecureContainer(String id, int sizeMb, String fstype,
1323 String key, int ownerUid) {
1324 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001325 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001326 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001327
San Mehatb1043402010-02-05 08:26:50 -08001328 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001329 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1330 try {
1331 mConnector.doCommand(cmd);
1332 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001333 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001334 }
San Mehata181b212010-02-11 06:50:20 -08001335
1336 if (rc == StorageResultCode.OperationSucceeded) {
1337 synchronized (mAsecMountSet) {
1338 mAsecMountSet.add(id);
1339 }
1340 }
San Mehat4270e1e2010-01-29 05:32:19 -08001341 return rc;
San Mehat36972292010-01-06 11:06:32 -08001342 }
1343
San Mehat4270e1e2010-01-29 05:32:19 -08001344 public int finalizeSecureContainer(String id) {
1345 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001346 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001347
San Mehatb1043402010-02-05 08:26:50 -08001348 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001349 try {
1350 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001351 /*
1352 * Finalization does a remount, so no need
1353 * to update mAsecMountSet
1354 */
San Mehat4270e1e2010-01-29 05:32:19 -08001355 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001356 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001357 }
San Mehat4270e1e2010-01-29 05:32:19 -08001358 return rc;
San Mehat36972292010-01-06 11:06:32 -08001359 }
1360
San Mehatd9709982010-02-18 11:43:03 -08001361 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001362 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001363 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001364 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001365
Kenny Rootaa485402010-09-14 14:49:41 -07001366 /*
1367 * Force a GC to make sure AssetManagers in other threads of the
1368 * system_server are cleaned up. We have to do this since AssetManager
1369 * instances are kept as a WeakReference and it's possible we have files
1370 * open on the external storage.
1371 */
1372 Runtime.getRuntime().gc();
1373
San Mehatb1043402010-02-05 08:26:50 -08001374 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001375 try {
San Mehatd9709982010-02-18 11:43:03 -08001376 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001377 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001378 int code = e.getCode();
1379 if (code == VoldResponseCode.OpFailedStorageBusy) {
1380 rc = StorageResultCode.OperationFailedStorageBusy;
1381 } else {
1382 rc = StorageResultCode.OperationFailedInternalError;
1383 }
San Mehat02735bc2010-01-26 15:18:08 -08001384 }
San Mehata181b212010-02-11 06:50:20 -08001385
1386 if (rc == StorageResultCode.OperationSucceeded) {
1387 synchronized (mAsecMountSet) {
1388 if (mAsecMountSet.contains(id)) {
1389 mAsecMountSet.remove(id);
1390 }
1391 }
1392 }
1393
San Mehat4270e1e2010-01-29 05:32:19 -08001394 return rc;
San Mehat36972292010-01-06 11:06:32 -08001395 }
1396
San Mehat4270e1e2010-01-29 05:32:19 -08001397 public int mountSecureContainer(String id, String key, int ownerUid) {
1398 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001399 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001400 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001401
San Mehata181b212010-02-11 06:50:20 -08001402 synchronized (mAsecMountSet) {
1403 if (mAsecMountSet.contains(id)) {
1404 return StorageResultCode.OperationFailedStorageMounted;
1405 }
1406 }
1407
San Mehatb1043402010-02-05 08:26:50 -08001408 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001409 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1410 try {
1411 mConnector.doCommand(cmd);
1412 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001413 int code = e.getCode();
1414 if (code != VoldResponseCode.OpFailedStorageBusy) {
1415 rc = StorageResultCode.OperationFailedInternalError;
1416 }
San Mehat02735bc2010-01-26 15:18:08 -08001417 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001418
1419 if (rc == StorageResultCode.OperationSucceeded) {
1420 synchronized (mAsecMountSet) {
1421 mAsecMountSet.add(id);
1422 }
1423 }
San Mehat4270e1e2010-01-29 05:32:19 -08001424 return rc;
San Mehat36972292010-01-06 11:06:32 -08001425 }
1426
San Mehatd9709982010-02-18 11:43:03 -08001427 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001428 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001429 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001430 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001431
San Mehat6cdd9c02010-02-09 14:45:20 -08001432 synchronized (mAsecMountSet) {
1433 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001434 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001435 }
1436 }
1437
Kenny Rootaa485402010-09-14 14:49:41 -07001438 /*
1439 * Force a GC to make sure AssetManagers in other threads of the
1440 * system_server are cleaned up. We have to do this since AssetManager
1441 * instances are kept as a WeakReference and it's possible we have files
1442 * open on the external storage.
1443 */
1444 Runtime.getRuntime().gc();
1445
San Mehatb1043402010-02-05 08:26:50 -08001446 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001447 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001448 try {
1449 mConnector.doCommand(cmd);
1450 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001451 int code = e.getCode();
1452 if (code == VoldResponseCode.OpFailedStorageBusy) {
1453 rc = StorageResultCode.OperationFailedStorageBusy;
1454 } else {
1455 rc = StorageResultCode.OperationFailedInternalError;
1456 }
San Mehat02735bc2010-01-26 15:18:08 -08001457 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001458
1459 if (rc == StorageResultCode.OperationSucceeded) {
1460 synchronized (mAsecMountSet) {
1461 mAsecMountSet.remove(id);
1462 }
1463 }
San Mehat4270e1e2010-01-29 05:32:19 -08001464 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001465 }
1466
San Mehat6cdd9c02010-02-09 14:45:20 -08001467 public boolean isSecureContainerMounted(String id) {
1468 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1469 waitForReady();
1470 warnOnNotMounted();
1471
1472 synchronized (mAsecMountSet) {
1473 return mAsecMountSet.contains(id);
1474 }
1475 }
1476
San Mehat4270e1e2010-01-29 05:32:19 -08001477 public int renameSecureContainer(String oldId, String newId) {
1478 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001479 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001480 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001481
San Mehata181b212010-02-11 06:50:20 -08001482 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001483 /*
1484 * Because a mounted container has active internal state which cannot be
1485 * changed while active, we must ensure both ids are not currently mounted.
1486 */
1487 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001488 return StorageResultCode.OperationFailedStorageMounted;
1489 }
1490 }
1491
San Mehatb1043402010-02-05 08:26:50 -08001492 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001493 String cmd = String.format("asec rename %s %s", oldId, newId);
1494 try {
1495 mConnector.doCommand(cmd);
1496 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001497 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001498 }
San Mehata181b212010-02-11 06:50:20 -08001499
San Mehat4270e1e2010-01-29 05:32:19 -08001500 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001501 }
1502
San Mehat4270e1e2010-01-29 05:32:19 -08001503 public String getSecureContainerPath(String id) {
1504 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001505 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001506 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001507
San Mehat2d66cef2010-03-23 11:12:52 -07001508 try {
1509 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1510 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001511 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001512 if (code != VoldResponseCode.AsecPathResult) {
1513 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1514 }
1515 return tok[1];
1516 } catch (NativeDaemonConnectorException e) {
1517 int code = e.getCode();
1518 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1519 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001520 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001521 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001522 }
1523 }
San Mehat22dd86e2010-01-12 12:21:18 -08001524 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001525
1526 public void finishMediaUpdate() {
1527 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1528 }
Kenny Root02c87302010-07-01 08:10:18 -07001529
Kenny Roota02b8b02010-08-05 16:14:17 -07001530 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1531 if (callerUid == android.os.Process.SYSTEM_UID) {
1532 return true;
1533 }
1534
Kenny Root02c87302010-07-01 08:10:18 -07001535 if (packageName == null) {
1536 return false;
1537 }
1538
1539 final int packageUid = mPms.getPackageUid(packageName);
1540
1541 if (DEBUG_OBB) {
1542 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1543 packageUid + ", callerUid = " + callerUid);
1544 }
1545
1546 return callerUid == packageUid;
1547 }
1548
1549 public String getMountedObbPath(String filename) {
1550 waitForReady();
1551 warnOnNotMounted();
1552
Kenny Root02c87302010-07-01 08:10:18 -07001553 try {
1554 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1555 String []tok = rsp.get(0).split(" ");
1556 int code = Integer.parseInt(tok[0]);
1557 if (code != VoldResponseCode.AsecPathResult) {
1558 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1559 }
1560 return tok[1];
1561 } catch (NativeDaemonConnectorException e) {
1562 int code = e.getCode();
1563 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001564 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001565 } else {
1566 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1567 }
1568 }
1569 }
1570
1571 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001572 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001573 final ObbState obbState = mObbPathToStateMap.get(filename);
1574 if (obbState != null) {
1575 synchronized (obbState) {
1576 return obbState.mounted;
1577 }
1578 }
Kenny Root02c87302010-07-01 08:10:18 -07001579 }
Kenny Root38cf8862010-09-26 14:18:51 -07001580 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001581 }
1582
Kenny Root735de3b2010-09-30 14:11:39 -07001583 public void mountObb(String filename, String key, IObbActionListener token)
1584 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001585 waitForReady();
1586 warnOnNotMounted();
1587
Kenny Rootf1121dc2010-09-29 07:30:53 -07001588 if (filename == null) {
1589 throw new IllegalArgumentException("filename cannot be null");
1590 } else if (token == null) {
1591 throw new IllegalArgumentException("token cannot be null");
1592 }
1593
Kenny Roota02b8b02010-08-05 16:14:17 -07001594 final ObbState obbState;
1595
1596 synchronized (mObbMounts) {
1597 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001598 try {
1599 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1600 } catch (RemoteException e) {
1601 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1602 }
1603 return;
Kenny Root02c87302010-07-01 08:10:18 -07001604 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001605
Kenny Roota02b8b02010-08-05 16:14:17 -07001606 final int callerUid = Binder.getCallingUid();
1607 obbState = new ObbState(filename, token, callerUid);
1608 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001609 }
1610
Kenny Root29423912010-10-01 08:37:20 -07001611 String hashedKey = null;
1612 if (key != null) {
1613 final MessageDigest md;
Kenny Root735de3b2010-09-30 14:11:39 -07001614 try {
Kenny Root29423912010-10-01 08:37:20 -07001615 md = MessageDigest.getInstance("MD5");
1616 } catch (NoSuchAlgorithmException e) {
1617 Slog.e(TAG, "Could not load MD5 algorithm", e);
1618 try {
1619 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1620 } catch (RemoteException e1) {
1621 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1622 }
1623 return;
Kenny Root735de3b2010-09-30 14:11:39 -07001624 }
Kenny Root02c87302010-07-01 08:10:18 -07001625
Kenny Root29423912010-10-01 08:37:20 -07001626 hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1627 }
Kenny Root735de3b2010-09-30 14:11:39 -07001628
1629 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001630 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1631
1632 if (DEBUG_OBB)
1633 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001634 }
1635
Kenny Roota02b8b02010-08-05 16:14:17 -07001636 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001637 if (filename == null) {
1638 throw new IllegalArgumentException("filename cannot be null");
1639 } else if (token == null) {
1640 throw new IllegalArgumentException("token cannot be null");
1641 }
1642
Kenny Roota02b8b02010-08-05 16:14:17 -07001643 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001644
Kenny Roota02b8b02010-08-05 16:14:17 -07001645 synchronized (mObbMounts) {
1646 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001647 try {
1648 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1649 } catch (RemoteException e) {
1650 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1651 }
1652 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001653 }
Kenny Root38cf8862010-09-26 14:18:51 -07001654
Kenny Roota02b8b02010-08-05 16:14:17 -07001655 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001656
1657 if (Binder.getCallingUid() != obbState.callerUid) {
1658 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001659 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001660 throw new SecurityException("caller does not match original mount caller");
1661 }
Kenny Root02c87302010-07-01 08:10:18 -07001662 }
1663
Kenny Root38cf8862010-09-26 14:18:51 -07001664 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001665 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001666
Kenny Roota02b8b02010-08-05 16:14:17 -07001667 if (DEBUG_OBB)
1668 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1669 }
1670
Kenny Root5919ac62010-10-05 09:49:40 -07001671 private void addObbState(ObbState obbState) throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -07001672 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001673 final IBinder binder = obbState.getBinder();
1674 List<ObbState> obbStates = mObbMounts.get(binder);
1675 final boolean unique;
1676
Kenny Root05105f72010-09-22 17:29:43 -07001677 if (obbStates == null) {
1678 obbStates = new ArrayList<ObbState>();
Kenny Root5919ac62010-10-05 09:49:40 -07001679 mObbMounts.put(binder, obbStates);
1680 unique = true;
1681 } else {
1682 unique = obbStates.contains(obbState);
Kenny Root05105f72010-09-22 17:29:43 -07001683 }
Kenny Root5919ac62010-10-05 09:49:40 -07001684
1685 if (unique) {
1686 obbStates.add(obbState);
1687 try {
1688 obbState.link();
1689 } catch (RemoteException e) {
1690 /*
1691 * The binder died before we could link it, so clean up our
1692 * state and return failure.
1693 */
1694 obbStates.remove(obbState);
1695 if (obbStates.isEmpty()) {
1696 mObbMounts.remove(binder);
1697 }
1698
1699 // Rethrow the error so mountObb can get it
1700 throw e;
1701 }
1702 }
1703
Kenny Roota02b8b02010-08-05 16:14:17 -07001704 mObbPathToStateMap.put(obbState.filename, obbState);
1705 }
1706 }
1707
1708 private void removeObbState(ObbState obbState) {
1709 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001710 final IBinder binder = obbState.getBinder();
1711 final List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root05105f72010-09-22 17:29:43 -07001712 if (obbStates != null) {
Kenny Root5919ac62010-10-05 09:49:40 -07001713 if (obbStates.remove(obbState)) {
1714 obbState.unlink();
1715 }
1716 if (obbStates.isEmpty()) {
1717 mObbMounts.remove(binder);
1718 }
Kenny Root05105f72010-09-22 17:29:43 -07001719 }
Kenny Root5919ac62010-10-05 09:49:40 -07001720
Kenny Roota02b8b02010-08-05 16:14:17 -07001721 mObbPathToStateMap.remove(obbState.filename);
1722 }
1723 }
1724
Kenny Root5919ac62010-10-05 09:49:40 -07001725 private void replaceObbState(ObbState oldObbState, ObbState newObbState) throws RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001726 synchronized (mObbMounts) {
1727 removeObbState(oldObbState);
1728 addObbState(newObbState);
1729 }
1730 }
1731
Kenny Roota02b8b02010-08-05 16:14:17 -07001732 private class ObbActionHandler extends Handler {
1733 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001734 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001735
1736 ObbActionHandler(Looper l) {
1737 super(l);
1738 }
1739
1740 @Override
1741 public void handleMessage(Message msg) {
1742 switch (msg.what) {
1743 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001744 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001745
1746 if (DEBUG_OBB)
1747 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1748
1749 // If a bind was already initiated we don't really
1750 // need to do anything. The pending install
1751 // will be processed later on.
1752 if (!mBound) {
1753 // If this is the only one pending we might
1754 // have to bind to the service again.
1755 if (!connectToService()) {
1756 Slog.e(TAG, "Failed to bind to media container service");
1757 action.handleError();
1758 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001759 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001760 }
Kenny Root735de3b2010-09-30 14:11:39 -07001761
Kenny Root735de3b2010-09-30 14:11:39 -07001762 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001763 break;
1764 }
1765 case OBB_MCS_BOUND: {
1766 if (DEBUG_OBB)
1767 Slog.i(TAG, "OBB_MCS_BOUND");
1768 if (msg.obj != null) {
1769 mContainerService = (IMediaContainerService) msg.obj;
1770 }
1771 if (mContainerService == null) {
1772 // Something seriously wrong. Bail out
1773 Slog.e(TAG, "Cannot bind to media container service");
1774 for (ObbAction action : mActions) {
1775 // Indicate service bind error
1776 action.handleError();
1777 }
1778 mActions.clear();
1779 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001780 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001781 if (action != null) {
1782 action.execute(this);
1783 }
1784 } else {
1785 // Should never happen ideally.
1786 Slog.w(TAG, "Empty queue");
1787 }
1788 break;
1789 }
1790 case OBB_MCS_RECONNECT: {
1791 if (DEBUG_OBB)
1792 Slog.i(TAG, "OBB_MCS_RECONNECT");
1793 if (mActions.size() > 0) {
1794 if (mBound) {
1795 disconnectService();
1796 }
1797 if (!connectToService()) {
1798 Slog.e(TAG, "Failed to bind to media container service");
1799 for (ObbAction action : mActions) {
1800 // Indicate service bind error
1801 action.handleError();
1802 }
1803 mActions.clear();
1804 }
1805 }
1806 break;
1807 }
1808 case OBB_MCS_UNBIND: {
1809 if (DEBUG_OBB)
1810 Slog.i(TAG, "OBB_MCS_UNBIND");
1811
1812 // Delete pending install
1813 if (mActions.size() > 0) {
1814 mActions.remove(0);
1815 }
1816 if (mActions.size() == 0) {
1817 if (mBound) {
1818 disconnectService();
1819 }
1820 } else {
1821 // There are more pending requests in queue.
1822 // Just post MCS_BOUND message to trigger processing
1823 // of next pending install.
1824 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1825 }
1826 break;
1827 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001828 }
1829 }
1830
1831 private boolean connectToService() {
1832 if (DEBUG_OBB)
1833 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1834
1835 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1836 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1837 mBound = true;
1838 return true;
1839 }
1840 return false;
1841 }
1842
1843 private void disconnectService() {
1844 mContainerService = null;
1845 mBound = false;
1846 mContext.unbindService(mDefContainerConn);
1847 }
1848 }
1849
1850 abstract class ObbAction {
1851 private static final int MAX_RETRIES = 3;
1852 private int mRetries;
1853
1854 ObbState mObbState;
1855
1856 ObbAction(ObbState obbState) {
1857 mObbState = obbState;
1858 }
1859
1860 public void execute(ObbActionHandler handler) {
1861 try {
1862 if (DEBUG_OBB)
1863 Slog.i(TAG, "Starting to execute action: " + this.toString());
1864 mRetries++;
1865 if (mRetries > MAX_RETRIES) {
1866 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001867 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001868 handleError();
1869 return;
1870 } else {
1871 handleExecute();
1872 if (DEBUG_OBB)
1873 Slog.i(TAG, "Posting install MCS_UNBIND");
1874 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1875 }
1876 } catch (RemoteException e) {
1877 if (DEBUG_OBB)
1878 Slog.i(TAG, "Posting install MCS_RECONNECT");
1879 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1880 } catch (Exception e) {
1881 if (DEBUG_OBB)
1882 Slog.d(TAG, "Error handling OBB action", e);
1883 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001884 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001885 }
1886 }
1887
Kenny Root05105f72010-09-22 17:29:43 -07001888 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001889 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001890
1891 protected ObbInfo getObbInfo() throws IOException {
1892 ObbInfo obbInfo;
1893 try {
1894 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1895 } catch (RemoteException e) {
1896 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1897 + mObbState.filename);
1898 obbInfo = null;
1899 }
1900 if (obbInfo == null) {
1901 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1902 }
1903 return obbInfo;
1904 }
1905
1906 protected void sendNewStatusOrIgnore(String filename, String status) {
1907 try {
1908 mObbState.token.onObbResult(filename, status);
1909 } catch (RemoteException e) {
1910 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1911 }
1912 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001913 }
1914
1915 class MountObbAction extends ObbAction {
1916 private String mKey;
1917
1918 MountObbAction(ObbState obbState, String key) {
1919 super(obbState);
1920 mKey = key;
1921 }
1922
Kenny Root735de3b2010-09-30 14:11:39 -07001923 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001924 final ObbInfo obbInfo = getObbInfo();
1925
1926 /*
1927 * If someone tried to trick us with some weird characters, rectify
1928 * it here.
1929 */
1930 if (!mObbState.filename.equals(obbInfo.filename)) {
1931 if (DEBUG_OBB)
1932 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1933 + obbInfo.filename);
1934
1935 synchronized (mObbMounts) {
1936 /*
1937 * If the real filename is already mounted, discard this
1938 * state and notify the caller that the OBB is already
1939 * mounted.
1940 */
1941 if (isObbMounted(obbInfo.filename)) {
1942 if (DEBUG_OBB)
1943 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1944
1945 removeObbState(mObbState);
1946 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1947 return;
1948 }
1949
1950 /*
1951 * It's not already mounted, so we have to replace the state
1952 * with the state containing the actual filename.
1953 */
1954 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1955 mObbState.callerUid);
1956 replaceObbState(mObbState, newObbState);
1957 mObbState = newObbState;
1958 }
Kenny Root05105f72010-09-22 17:29:43 -07001959 }
1960
Kenny Roota02b8b02010-08-05 16:14:17 -07001961 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1962 throw new IllegalArgumentException("Caller package does not match OBB file");
1963 }
1964
Kenny Root38cf8862010-09-26 14:18:51 -07001965 boolean mounted = false;
1966 int rc;
1967 synchronized (mObbState) {
1968 if (mObbState.mounted) {
1969 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1970 return;
1971 }
1972
1973 rc = StorageResultCode.OperationSucceeded;
Kenny Root12ffd9b2010-10-01 12:56:59 -07001974 String cmd = String.format("obb mount %s %s %d", mObbState.filename,
1975 mKey != null ? mKey : "none",
Kenny Root38cf8862010-09-26 14:18:51 -07001976 mObbState.callerUid);
1977 try {
1978 mConnector.doCommand(cmd);
1979 } catch (NativeDaemonConnectorException e) {
1980 int code = e.getCode();
1981 if (code != VoldResponseCode.OpFailedStorageBusy) {
1982 rc = StorageResultCode.OperationFailedInternalError;
1983 }
1984 }
1985
1986 if (rc == StorageResultCode.OperationSucceeded) {
1987 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001988 }
1989 }
1990
Kenny Root38cf8862010-09-26 14:18:51 -07001991 if (mounted) {
1992 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001993 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001994 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001995
1996 // We didn't succeed, so remove this from the mount-set.
1997 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07001998
Kenny Root38cf8862010-09-26 14:18:51 -07001999 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002000 }
2001 }
2002
Kenny Roota02b8b02010-08-05 16:14:17 -07002003 public void handleError() {
2004 removeObbState(mObbState);
2005
Kenny Root38cf8862010-09-26 14:18:51 -07002006 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07002007 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002008
2009 @Override
2010 public String toString() {
2011 StringBuilder sb = new StringBuilder();
2012 sb.append("MountObbAction{");
2013 sb.append("filename=");
2014 sb.append(mObbState.filename);
2015 sb.append(",callerUid=");
2016 sb.append(mObbState.callerUid);
2017 sb.append(",token=");
2018 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2019 sb.append('}');
2020 return sb.toString();
2021 }
2022 }
2023
2024 class UnmountObbAction extends ObbAction {
2025 private boolean mForceUnmount;
2026
2027 UnmountObbAction(ObbState obbState, boolean force) {
2028 super(obbState);
2029 mForceUnmount = force;
2030 }
2031
Kenny Root38cf8862010-09-26 14:18:51 -07002032 public void handleExecute() throws IOException {
2033 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002034
Kenny Root38cf8862010-09-26 14:18:51 -07002035 /*
2036 * If someone tried to trick us with some weird characters, rectify
2037 * it here.
2038 */
2039 synchronized (mObbMounts) {
2040 if (!isObbMounted(obbInfo.filename)) {
2041 removeObbState(mObbState);
2042 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2043 return;
2044 }
2045
2046 if (!mObbState.filename.equals(obbInfo.filename)) {
2047 removeObbState(mObbState);
2048 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002049 }
2050 }
2051
Kenny Root38cf8862010-09-26 14:18:51 -07002052 boolean unmounted = false;
2053 synchronized (mObbState) {
2054 if (!mObbState.mounted) {
2055 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2056 return;
2057 }
2058
2059 int rc = StorageResultCode.OperationSucceeded;
2060 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2061 (mForceUnmount ? " force" : ""));
2062 try {
2063 mConnector.doCommand(cmd);
2064 } catch (NativeDaemonConnectorException e) {
2065 int code = e.getCode();
2066 if (code == VoldResponseCode.OpFailedStorageBusy) {
2067 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002068 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2069 // If it's not mounted then we've already won.
2070 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002071 } else {
2072 rc = StorageResultCode.OperationFailedInternalError;
2073 }
2074 }
2075
2076 if (rc == StorageResultCode.OperationSucceeded) {
2077 mObbState.mounted = false;
2078 unmounted = true;
2079 }
2080 }
2081
2082 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002083 removeObbState(mObbState);
2084
Kenny Root38cf8862010-09-26 14:18:51 -07002085 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002086 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002087 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002088 }
2089 }
2090
2091 public void handleError() {
2092 removeObbState(mObbState);
2093
Kenny Root38cf8862010-09-26 14:18:51 -07002094 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002095 }
2096
2097 @Override
2098 public String toString() {
2099 StringBuilder sb = new StringBuilder();
2100 sb.append("UnmountObbAction{");
2101 sb.append("filename=");
2102 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2103 sb.append(",force=");
2104 sb.append(mForceUnmount);
2105 sb.append(",callerUid=");
2106 sb.append(mObbState.callerUid);
2107 sb.append(",token=");
2108 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002109 sb.append(",binder=");
2110 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002111 sb.append('}');
2112 return sb.toString();
2113 }
Kenny Root02c87302010-07-01 08:10:18 -07002114 }
Kenny Root38cf8862010-09-26 14:18:51 -07002115
2116 @Override
2117 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2118 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2119 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2120 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2121 + " without permission " + android.Manifest.permission.DUMP);
2122 return;
2123 }
2124
2125 pw.println(" mObbMounts:");
2126
2127 synchronized (mObbMounts) {
2128 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2129
2130 for (final List<ObbState> obbStates : obbStateLists) {
2131 for (final ObbState obbState : obbStates) {
2132 pw.print(" "); pw.println(obbState.toString());
2133 }
2134 }
2135 }
2136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137}
2138