blob: 295047c8b752551f4c36fa29f57b97931e2df44c [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
San Mehat4270e1e2010-01-29 05:32:19 -08001243 public int mountVolume(String path) {
1244 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001245
San Mehat207e5382010-02-04 20:46:54 -08001246 waitForReady();
1247 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
1249
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001250 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001251 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001252 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001254 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001255 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001256 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1257 Environment.MEDIA_REMOVED.equals(volState) ||
1258 Environment.MEDIA_SHARED.equals(volState) ||
1259 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1260 // Media already unmounted or cannot be unmounted.
1261 // TODO return valid return code when adding observer call back.
1262 return;
1263 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001264 UnmountCallBack ucb = new UnmountCallBack(path, force);
1265 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
1267
San Mehat4270e1e2010-01-29 05:32:19 -08001268 public int formatVolume(String path) {
1269 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001270 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001271
San Mehat207e5382010-02-04 20:46:54 -08001272 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274
San Mehatc1b4ce92010-02-16 17:13:03 -08001275 public int []getStorageUsers(String path) {
1276 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1277 waitForReady();
1278 try {
1279 String[] r = mConnector.doListCommand(
1280 String.format("storage users %s", path),
1281 VoldResponseCode.StorageUsersListResult);
1282 // FMT: <pid> <process name>
1283 int[] data = new int[r.length];
1284 for (int i = 0; i < r.length; i++) {
1285 String []tok = r[i].split(" ");
1286 try {
1287 data[i] = Integer.parseInt(tok[0]);
1288 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001289 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001290 return new int[0];
1291 }
1292 }
1293 return data;
1294 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001295 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001296 return new int[0];
1297 }
1298 }
1299
San Mehatb1043402010-02-05 08:26:50 -08001300 private void warnOnNotMounted() {
1301 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001302 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001303 }
1304 }
1305
San Mehat4270e1e2010-01-29 05:32:19 -08001306 public String[] getSecureContainerList() {
1307 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001308 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001309 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001310
San Mehat4270e1e2010-01-29 05:32:19 -08001311 try {
1312 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1313 } catch (NativeDaemonConnectorException e) {
1314 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 }
San Mehat36972292010-01-06 11:06:32 -08001317
San Mehat4270e1e2010-01-29 05:32:19 -08001318 public int createSecureContainer(String id, int sizeMb, String fstype,
1319 String key, int ownerUid) {
1320 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001321 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001322 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001323
San Mehatb1043402010-02-05 08:26:50 -08001324 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001325 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1326 try {
1327 mConnector.doCommand(cmd);
1328 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001329 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001330 }
San Mehata181b212010-02-11 06:50:20 -08001331
1332 if (rc == StorageResultCode.OperationSucceeded) {
1333 synchronized (mAsecMountSet) {
1334 mAsecMountSet.add(id);
1335 }
1336 }
San Mehat4270e1e2010-01-29 05:32:19 -08001337 return rc;
San Mehat36972292010-01-06 11:06:32 -08001338 }
1339
San Mehat4270e1e2010-01-29 05:32:19 -08001340 public int finalizeSecureContainer(String id) {
1341 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001342 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001343
San Mehatb1043402010-02-05 08:26:50 -08001344 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001345 try {
1346 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001347 /*
1348 * Finalization does a remount, so no need
1349 * to update mAsecMountSet
1350 */
San Mehat4270e1e2010-01-29 05:32:19 -08001351 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001352 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001353 }
San Mehat4270e1e2010-01-29 05:32:19 -08001354 return rc;
San Mehat36972292010-01-06 11:06:32 -08001355 }
1356
San Mehatd9709982010-02-18 11:43:03 -08001357 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001358 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001359 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001360 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001361
Kenny Rootaa485402010-09-14 14:49:41 -07001362 /*
1363 * Force a GC to make sure AssetManagers in other threads of the
1364 * system_server are cleaned up. We have to do this since AssetManager
1365 * instances are kept as a WeakReference and it's possible we have files
1366 * open on the external storage.
1367 */
1368 Runtime.getRuntime().gc();
1369
San Mehatb1043402010-02-05 08:26:50 -08001370 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001371 try {
San Mehatd9709982010-02-18 11:43:03 -08001372 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001373 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001374 int code = e.getCode();
1375 if (code == VoldResponseCode.OpFailedStorageBusy) {
1376 rc = StorageResultCode.OperationFailedStorageBusy;
1377 } else {
1378 rc = StorageResultCode.OperationFailedInternalError;
1379 }
San Mehat02735bc2010-01-26 15:18:08 -08001380 }
San Mehata181b212010-02-11 06:50:20 -08001381
1382 if (rc == StorageResultCode.OperationSucceeded) {
1383 synchronized (mAsecMountSet) {
1384 if (mAsecMountSet.contains(id)) {
1385 mAsecMountSet.remove(id);
1386 }
1387 }
1388 }
1389
San Mehat4270e1e2010-01-29 05:32:19 -08001390 return rc;
San Mehat36972292010-01-06 11:06:32 -08001391 }
1392
San Mehat4270e1e2010-01-29 05:32:19 -08001393 public int mountSecureContainer(String id, String key, int ownerUid) {
1394 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001395 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001396 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001397
San Mehata181b212010-02-11 06:50:20 -08001398 synchronized (mAsecMountSet) {
1399 if (mAsecMountSet.contains(id)) {
1400 return StorageResultCode.OperationFailedStorageMounted;
1401 }
1402 }
1403
San Mehatb1043402010-02-05 08:26:50 -08001404 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001405 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1406 try {
1407 mConnector.doCommand(cmd);
1408 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001409 int code = e.getCode();
1410 if (code != VoldResponseCode.OpFailedStorageBusy) {
1411 rc = StorageResultCode.OperationFailedInternalError;
1412 }
San Mehat02735bc2010-01-26 15:18:08 -08001413 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001414
1415 if (rc == StorageResultCode.OperationSucceeded) {
1416 synchronized (mAsecMountSet) {
1417 mAsecMountSet.add(id);
1418 }
1419 }
San Mehat4270e1e2010-01-29 05:32:19 -08001420 return rc;
San Mehat36972292010-01-06 11:06:32 -08001421 }
1422
San Mehatd9709982010-02-18 11:43:03 -08001423 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001424 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001425 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001426 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001427
San Mehat6cdd9c02010-02-09 14:45:20 -08001428 synchronized (mAsecMountSet) {
1429 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001430 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001431 }
1432 }
1433
Kenny Rootaa485402010-09-14 14:49:41 -07001434 /*
1435 * Force a GC to make sure AssetManagers in other threads of the
1436 * system_server are cleaned up. We have to do this since AssetManager
1437 * instances are kept as a WeakReference and it's possible we have files
1438 * open on the external storage.
1439 */
1440 Runtime.getRuntime().gc();
1441
San Mehatb1043402010-02-05 08:26:50 -08001442 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001443 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001444 try {
1445 mConnector.doCommand(cmd);
1446 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001447 int code = e.getCode();
1448 if (code == VoldResponseCode.OpFailedStorageBusy) {
1449 rc = StorageResultCode.OperationFailedStorageBusy;
1450 } else {
1451 rc = StorageResultCode.OperationFailedInternalError;
1452 }
San Mehat02735bc2010-01-26 15:18:08 -08001453 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001454
1455 if (rc == StorageResultCode.OperationSucceeded) {
1456 synchronized (mAsecMountSet) {
1457 mAsecMountSet.remove(id);
1458 }
1459 }
San Mehat4270e1e2010-01-29 05:32:19 -08001460 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001461 }
1462
San Mehat6cdd9c02010-02-09 14:45:20 -08001463 public boolean isSecureContainerMounted(String id) {
1464 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1465 waitForReady();
1466 warnOnNotMounted();
1467
1468 synchronized (mAsecMountSet) {
1469 return mAsecMountSet.contains(id);
1470 }
1471 }
1472
San Mehat4270e1e2010-01-29 05:32:19 -08001473 public int renameSecureContainer(String oldId, String newId) {
1474 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001475 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001476 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001477
San Mehata181b212010-02-11 06:50:20 -08001478 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001479 /*
1480 * Because a mounted container has active internal state which cannot be
1481 * changed while active, we must ensure both ids are not currently mounted.
1482 */
1483 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001484 return StorageResultCode.OperationFailedStorageMounted;
1485 }
1486 }
1487
San Mehatb1043402010-02-05 08:26:50 -08001488 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001489 String cmd = String.format("asec rename %s %s", oldId, newId);
1490 try {
1491 mConnector.doCommand(cmd);
1492 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001493 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001494 }
San Mehata181b212010-02-11 06:50:20 -08001495
San Mehat4270e1e2010-01-29 05:32:19 -08001496 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001497 }
1498
San Mehat4270e1e2010-01-29 05:32:19 -08001499 public String getSecureContainerPath(String id) {
1500 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001501 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001502 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001503
San Mehat2d66cef2010-03-23 11:12:52 -07001504 try {
1505 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1506 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001507 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001508 if (code != VoldResponseCode.AsecPathResult) {
1509 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1510 }
1511 return tok[1];
1512 } catch (NativeDaemonConnectorException e) {
1513 int code = e.getCode();
1514 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1515 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001516 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001517 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001518 }
1519 }
San Mehat22dd86e2010-01-12 12:21:18 -08001520 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001521
1522 public void finishMediaUpdate() {
1523 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1524 }
Kenny Root02c87302010-07-01 08:10:18 -07001525
Kenny Roota02b8b02010-08-05 16:14:17 -07001526 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1527 if (callerUid == android.os.Process.SYSTEM_UID) {
1528 return true;
1529 }
1530
Kenny Root02c87302010-07-01 08:10:18 -07001531 if (packageName == null) {
1532 return false;
1533 }
1534
1535 final int packageUid = mPms.getPackageUid(packageName);
1536
1537 if (DEBUG_OBB) {
1538 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1539 packageUid + ", callerUid = " + callerUid);
1540 }
1541
1542 return callerUid == packageUid;
1543 }
1544
1545 public String getMountedObbPath(String filename) {
1546 waitForReady();
1547 warnOnNotMounted();
1548
Kenny Root02c87302010-07-01 08:10:18 -07001549 try {
1550 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1551 String []tok = rsp.get(0).split(" ");
1552 int code = Integer.parseInt(tok[0]);
1553 if (code != VoldResponseCode.AsecPathResult) {
1554 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1555 }
1556 return tok[1];
1557 } catch (NativeDaemonConnectorException e) {
1558 int code = e.getCode();
1559 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001560 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001561 } else {
1562 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1563 }
1564 }
1565 }
1566
1567 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001568 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001569 final ObbState obbState = mObbPathToStateMap.get(filename);
1570 if (obbState != null) {
1571 synchronized (obbState) {
1572 return obbState.mounted;
1573 }
1574 }
Kenny Root02c87302010-07-01 08:10:18 -07001575 }
Kenny Root38cf8862010-09-26 14:18:51 -07001576 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001577 }
1578
Kenny Root735de3b2010-09-30 14:11:39 -07001579 public void mountObb(String filename, String key, IObbActionListener token)
1580 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001581 waitForReady();
1582 warnOnNotMounted();
1583
Kenny Rootf1121dc2010-09-29 07:30:53 -07001584 if (filename == null) {
1585 throw new IllegalArgumentException("filename cannot be null");
1586 } else if (token == null) {
1587 throw new IllegalArgumentException("token cannot be null");
1588 }
1589
Kenny Roota02b8b02010-08-05 16:14:17 -07001590 final ObbState obbState;
1591
1592 synchronized (mObbMounts) {
1593 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001594 try {
1595 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1596 } catch (RemoteException e) {
1597 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1598 }
1599 return;
Kenny Root02c87302010-07-01 08:10:18 -07001600 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001601
Kenny Roota02b8b02010-08-05 16:14:17 -07001602 final int callerUid = Binder.getCallingUid();
1603 obbState = new ObbState(filename, token, callerUid);
1604 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001605 }
1606
Kenny Root29423912010-10-01 08:37:20 -07001607 String hashedKey = null;
1608 if (key != null) {
1609 final MessageDigest md;
Kenny Root735de3b2010-09-30 14:11:39 -07001610 try {
Kenny Root29423912010-10-01 08:37:20 -07001611 md = MessageDigest.getInstance("MD5");
1612 } catch (NoSuchAlgorithmException e) {
1613 Slog.e(TAG, "Could not load MD5 algorithm", e);
1614 try {
1615 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1616 } catch (RemoteException e1) {
1617 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1618 }
1619 return;
Kenny Root735de3b2010-09-30 14:11:39 -07001620 }
Kenny Root02c87302010-07-01 08:10:18 -07001621
Kenny Root29423912010-10-01 08:37:20 -07001622 hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1623 }
Kenny Root735de3b2010-09-30 14:11:39 -07001624
1625 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001626 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1627
1628 if (DEBUG_OBB)
1629 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001630 }
1631
Kenny Roota02b8b02010-08-05 16:14:17 -07001632 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001633 if (filename == null) {
1634 throw new IllegalArgumentException("filename cannot be null");
1635 } else if (token == null) {
1636 throw new IllegalArgumentException("token cannot be null");
1637 }
1638
Kenny Roota02b8b02010-08-05 16:14:17 -07001639 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001640
Kenny Roota02b8b02010-08-05 16:14:17 -07001641 synchronized (mObbMounts) {
1642 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001643 try {
1644 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1645 } catch (RemoteException e) {
1646 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1647 }
1648 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001649 }
Kenny Root38cf8862010-09-26 14:18:51 -07001650
Kenny Roota02b8b02010-08-05 16:14:17 -07001651 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001652
1653 if (Binder.getCallingUid() != obbState.callerUid) {
1654 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001655 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001656 throw new SecurityException("caller does not match original mount caller");
1657 }
Kenny Root02c87302010-07-01 08:10:18 -07001658 }
1659
Kenny Root38cf8862010-09-26 14:18:51 -07001660 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001661 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001662
Kenny Roota02b8b02010-08-05 16:14:17 -07001663 if (DEBUG_OBB)
1664 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1665 }
1666
Kenny Root5919ac62010-10-05 09:49:40 -07001667 private void addObbState(ObbState obbState) throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -07001668 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001669 final IBinder binder = obbState.getBinder();
1670 List<ObbState> obbStates = mObbMounts.get(binder);
1671 final boolean unique;
1672
Kenny Root05105f72010-09-22 17:29:43 -07001673 if (obbStates == null) {
1674 obbStates = new ArrayList<ObbState>();
Kenny Root5919ac62010-10-05 09:49:40 -07001675 mObbMounts.put(binder, obbStates);
1676 unique = true;
1677 } else {
1678 unique = obbStates.contains(obbState);
Kenny Root05105f72010-09-22 17:29:43 -07001679 }
Kenny Root5919ac62010-10-05 09:49:40 -07001680
1681 if (unique) {
1682 obbStates.add(obbState);
1683 try {
1684 obbState.link();
1685 } catch (RemoteException e) {
1686 /*
1687 * The binder died before we could link it, so clean up our
1688 * state and return failure.
1689 */
1690 obbStates.remove(obbState);
1691 if (obbStates.isEmpty()) {
1692 mObbMounts.remove(binder);
1693 }
1694
1695 // Rethrow the error so mountObb can get it
1696 throw e;
1697 }
1698 }
1699
Kenny Roota02b8b02010-08-05 16:14:17 -07001700 mObbPathToStateMap.put(obbState.filename, obbState);
1701 }
1702 }
1703
1704 private void removeObbState(ObbState obbState) {
1705 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001706 final IBinder binder = obbState.getBinder();
1707 final List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root05105f72010-09-22 17:29:43 -07001708 if (obbStates != null) {
Kenny Root5919ac62010-10-05 09:49:40 -07001709 if (obbStates.remove(obbState)) {
1710 obbState.unlink();
1711 }
1712 if (obbStates.isEmpty()) {
1713 mObbMounts.remove(binder);
1714 }
Kenny Root05105f72010-09-22 17:29:43 -07001715 }
Kenny Root5919ac62010-10-05 09:49:40 -07001716
Kenny Roota02b8b02010-08-05 16:14:17 -07001717 mObbPathToStateMap.remove(obbState.filename);
1718 }
1719 }
1720
Kenny Root5919ac62010-10-05 09:49:40 -07001721 private void replaceObbState(ObbState oldObbState, ObbState newObbState) throws RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001722 synchronized (mObbMounts) {
1723 removeObbState(oldObbState);
1724 addObbState(newObbState);
1725 }
1726 }
1727
Kenny Roota02b8b02010-08-05 16:14:17 -07001728 private class ObbActionHandler extends Handler {
1729 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001730 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001731
1732 ObbActionHandler(Looper l) {
1733 super(l);
1734 }
1735
1736 @Override
1737 public void handleMessage(Message msg) {
1738 switch (msg.what) {
1739 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001740 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001741
1742 if (DEBUG_OBB)
1743 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1744
1745 // If a bind was already initiated we don't really
1746 // need to do anything. The pending install
1747 // will be processed later on.
1748 if (!mBound) {
1749 // If this is the only one pending we might
1750 // have to bind to the service again.
1751 if (!connectToService()) {
1752 Slog.e(TAG, "Failed to bind to media container service");
1753 action.handleError();
1754 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001755 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001756 }
Kenny Root735de3b2010-09-30 14:11:39 -07001757
Kenny Root735de3b2010-09-30 14:11:39 -07001758 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001759 break;
1760 }
1761 case OBB_MCS_BOUND: {
1762 if (DEBUG_OBB)
1763 Slog.i(TAG, "OBB_MCS_BOUND");
1764 if (msg.obj != null) {
1765 mContainerService = (IMediaContainerService) msg.obj;
1766 }
1767 if (mContainerService == null) {
1768 // Something seriously wrong. Bail out
1769 Slog.e(TAG, "Cannot bind to media container service");
1770 for (ObbAction action : mActions) {
1771 // Indicate service bind error
1772 action.handleError();
1773 }
1774 mActions.clear();
1775 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001776 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001777 if (action != null) {
1778 action.execute(this);
1779 }
1780 } else {
1781 // Should never happen ideally.
1782 Slog.w(TAG, "Empty queue");
1783 }
1784 break;
1785 }
1786 case OBB_MCS_RECONNECT: {
1787 if (DEBUG_OBB)
1788 Slog.i(TAG, "OBB_MCS_RECONNECT");
1789 if (mActions.size() > 0) {
1790 if (mBound) {
1791 disconnectService();
1792 }
1793 if (!connectToService()) {
1794 Slog.e(TAG, "Failed to bind to media container service");
1795 for (ObbAction action : mActions) {
1796 // Indicate service bind error
1797 action.handleError();
1798 }
1799 mActions.clear();
1800 }
1801 }
1802 break;
1803 }
1804 case OBB_MCS_UNBIND: {
1805 if (DEBUG_OBB)
1806 Slog.i(TAG, "OBB_MCS_UNBIND");
1807
1808 // Delete pending install
1809 if (mActions.size() > 0) {
1810 mActions.remove(0);
1811 }
1812 if (mActions.size() == 0) {
1813 if (mBound) {
1814 disconnectService();
1815 }
1816 } else {
1817 // There are more pending requests in queue.
1818 // Just post MCS_BOUND message to trigger processing
1819 // of next pending install.
1820 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1821 }
1822 break;
1823 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001824 }
1825 }
1826
1827 private boolean connectToService() {
1828 if (DEBUG_OBB)
1829 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1830
1831 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1832 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1833 mBound = true;
1834 return true;
1835 }
1836 return false;
1837 }
1838
1839 private void disconnectService() {
1840 mContainerService = null;
1841 mBound = false;
1842 mContext.unbindService(mDefContainerConn);
1843 }
1844 }
1845
1846 abstract class ObbAction {
1847 private static final int MAX_RETRIES = 3;
1848 private int mRetries;
1849
1850 ObbState mObbState;
1851
1852 ObbAction(ObbState obbState) {
1853 mObbState = obbState;
1854 }
1855
1856 public void execute(ObbActionHandler handler) {
1857 try {
1858 if (DEBUG_OBB)
1859 Slog.i(TAG, "Starting to execute action: " + this.toString());
1860 mRetries++;
1861 if (mRetries > MAX_RETRIES) {
1862 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001863 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001864 handleError();
1865 return;
1866 } else {
1867 handleExecute();
1868 if (DEBUG_OBB)
1869 Slog.i(TAG, "Posting install MCS_UNBIND");
1870 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1871 }
1872 } catch (RemoteException e) {
1873 if (DEBUG_OBB)
1874 Slog.i(TAG, "Posting install MCS_RECONNECT");
1875 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1876 } catch (Exception e) {
1877 if (DEBUG_OBB)
1878 Slog.d(TAG, "Error handling OBB action", e);
1879 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001880 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001881 }
1882 }
1883
Kenny Root05105f72010-09-22 17:29:43 -07001884 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001885 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001886
1887 protected ObbInfo getObbInfo() throws IOException {
1888 ObbInfo obbInfo;
1889 try {
1890 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1891 } catch (RemoteException e) {
1892 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1893 + mObbState.filename);
1894 obbInfo = null;
1895 }
1896 if (obbInfo == null) {
1897 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1898 }
1899 return obbInfo;
1900 }
1901
1902 protected void sendNewStatusOrIgnore(String filename, String status) {
1903 try {
1904 mObbState.token.onObbResult(filename, status);
1905 } catch (RemoteException e) {
1906 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1907 }
1908 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001909 }
1910
1911 class MountObbAction extends ObbAction {
1912 private String mKey;
1913
1914 MountObbAction(ObbState obbState, String key) {
1915 super(obbState);
1916 mKey = key;
1917 }
1918
Kenny Root735de3b2010-09-30 14:11:39 -07001919 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001920 final ObbInfo obbInfo = getObbInfo();
1921
1922 /*
1923 * If someone tried to trick us with some weird characters, rectify
1924 * it here.
1925 */
1926 if (!mObbState.filename.equals(obbInfo.filename)) {
1927 if (DEBUG_OBB)
1928 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1929 + obbInfo.filename);
1930
1931 synchronized (mObbMounts) {
1932 /*
1933 * If the real filename is already mounted, discard this
1934 * state and notify the caller that the OBB is already
1935 * mounted.
1936 */
1937 if (isObbMounted(obbInfo.filename)) {
1938 if (DEBUG_OBB)
1939 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1940
1941 removeObbState(mObbState);
1942 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1943 return;
1944 }
1945
1946 /*
1947 * It's not already mounted, so we have to replace the state
1948 * with the state containing the actual filename.
1949 */
1950 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1951 mObbState.callerUid);
1952 replaceObbState(mObbState, newObbState);
1953 mObbState = newObbState;
1954 }
Kenny Root05105f72010-09-22 17:29:43 -07001955 }
1956
Kenny Roota02b8b02010-08-05 16:14:17 -07001957 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1958 throw new IllegalArgumentException("Caller package does not match OBB file");
1959 }
1960
Kenny Root38cf8862010-09-26 14:18:51 -07001961 boolean mounted = false;
1962 int rc;
1963 synchronized (mObbState) {
1964 if (mObbState.mounted) {
1965 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1966 return;
1967 }
1968
1969 rc = StorageResultCode.OperationSucceeded;
Kenny Root12ffd9b2010-10-01 12:56:59 -07001970 String cmd = String.format("obb mount %s %s %d", mObbState.filename,
1971 mKey != null ? mKey : "none",
Kenny Root38cf8862010-09-26 14:18:51 -07001972 mObbState.callerUid);
1973 try {
1974 mConnector.doCommand(cmd);
1975 } catch (NativeDaemonConnectorException e) {
1976 int code = e.getCode();
1977 if (code != VoldResponseCode.OpFailedStorageBusy) {
1978 rc = StorageResultCode.OperationFailedInternalError;
1979 }
1980 }
1981
1982 if (rc == StorageResultCode.OperationSucceeded) {
1983 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 }
1985 }
1986
Kenny Root38cf8862010-09-26 14:18:51 -07001987 if (mounted) {
1988 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001989 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001990 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001991
1992 // We didn't succeed, so remove this from the mount-set.
1993 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07001994
Kenny Root38cf8862010-09-26 14:18:51 -07001995 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001996 }
1997 }
1998
Kenny Roota02b8b02010-08-05 16:14:17 -07001999 public void handleError() {
2000 removeObbState(mObbState);
2001
Kenny Root38cf8862010-09-26 14:18:51 -07002002 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07002003 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002004
2005 @Override
2006 public String toString() {
2007 StringBuilder sb = new StringBuilder();
2008 sb.append("MountObbAction{");
2009 sb.append("filename=");
2010 sb.append(mObbState.filename);
2011 sb.append(",callerUid=");
2012 sb.append(mObbState.callerUid);
2013 sb.append(",token=");
2014 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2015 sb.append('}');
2016 return sb.toString();
2017 }
2018 }
2019
2020 class UnmountObbAction extends ObbAction {
2021 private boolean mForceUnmount;
2022
2023 UnmountObbAction(ObbState obbState, boolean force) {
2024 super(obbState);
2025 mForceUnmount = force;
2026 }
2027
Kenny Root38cf8862010-09-26 14:18:51 -07002028 public void handleExecute() throws IOException {
2029 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002030
Kenny Root38cf8862010-09-26 14:18:51 -07002031 /*
2032 * If someone tried to trick us with some weird characters, rectify
2033 * it here.
2034 */
2035 synchronized (mObbMounts) {
2036 if (!isObbMounted(obbInfo.filename)) {
2037 removeObbState(mObbState);
2038 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2039 return;
2040 }
2041
2042 if (!mObbState.filename.equals(obbInfo.filename)) {
2043 removeObbState(mObbState);
2044 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002045 }
2046 }
2047
Kenny Root38cf8862010-09-26 14:18:51 -07002048 boolean unmounted = false;
2049 synchronized (mObbState) {
2050 if (!mObbState.mounted) {
2051 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2052 return;
2053 }
2054
2055 int rc = StorageResultCode.OperationSucceeded;
2056 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2057 (mForceUnmount ? " force" : ""));
2058 try {
2059 mConnector.doCommand(cmd);
2060 } catch (NativeDaemonConnectorException e) {
2061 int code = e.getCode();
2062 if (code == VoldResponseCode.OpFailedStorageBusy) {
2063 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002064 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2065 // If it's not mounted then we've already won.
2066 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002067 } else {
2068 rc = StorageResultCode.OperationFailedInternalError;
2069 }
2070 }
2071
2072 if (rc == StorageResultCode.OperationSucceeded) {
2073 mObbState.mounted = false;
2074 unmounted = true;
2075 }
2076 }
2077
2078 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002079 removeObbState(mObbState);
2080
Kenny Root38cf8862010-09-26 14:18:51 -07002081 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002082 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002083 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002084 }
2085 }
2086
2087 public void handleError() {
2088 removeObbState(mObbState);
2089
Kenny Root38cf8862010-09-26 14:18:51 -07002090 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002091 }
2092
2093 @Override
2094 public String toString() {
2095 StringBuilder sb = new StringBuilder();
2096 sb.append("UnmountObbAction{");
2097 sb.append("filename=");
2098 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2099 sb.append(",force=");
2100 sb.append(mForceUnmount);
2101 sb.append(",callerUid=");
2102 sb.append(mObbState.callerUid);
2103 sb.append(",token=");
2104 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002105 sb.append(",binder=");
2106 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002107 sb.append('}');
2108 return sb.toString();
2109 }
Kenny Root02c87302010-07-01 08:10:18 -07002110 }
Kenny Root38cf8862010-09-26 14:18:51 -07002111
2112 @Override
2113 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2114 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2115 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2116 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2117 + " without permission " + android.Manifest.permission.DUMP);
2118 return;
2119 }
2120
2121 pw.println(" mObbMounts:");
2122
2123 synchronized (mObbMounts) {
2124 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2125
2126 for (final List<ObbState> obbStates : obbStateLists) {
2127 for (final ObbState obbState : obbStates) {
2128 pw.print(" "); pw.println(obbState.toString());
2129 }
2130 }
2131 }
2132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133}
2134