blob: d6ee075cdedda53451fb8331d13a0652925f6cb9 [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
Kenny Root27358a62010-09-29 19:27:20 -070082 protected static final int MAX_OBBS = 8;
83
San Mehat4270e1e2010-01-29 05:32:19 -080084 /*
85 * Internal vold volume state constants
86 */
San Mehat7fd0fee2009-12-17 07:12:23 -080087 class VolumeState {
88 public static final int Init = -1;
89 public static final int NoMedia = 0;
90 public static final int Idle = 1;
91 public static final int Pending = 2;
92 public static final int Checking = 3;
93 public static final int Mounted = 4;
94 public static final int Unmounting = 5;
95 public static final int Formatting = 6;
96 public static final int Shared = 7;
97 public static final int SharedMnt = 8;
98 }
99
San Mehat4270e1e2010-01-29 05:32:19 -0800100 /*
101 * Internal vold response code constants
102 */
San Mehat22dd86e2010-01-12 12:21:18 -0800103 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800104 /*
105 * 100 series - Requestion action was initiated; expect another reply
106 * before proceeding with a new command.
107 */
San Mehat22dd86e2010-01-12 12:21:18 -0800108 public static final int VolumeListResult = 110;
109 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800110 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800111
San Mehat4270e1e2010-01-29 05:32:19 -0800112 /*
113 * 200 series - Requestion action has been successfully completed.
114 */
115 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800116 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800117 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800118
San Mehat4270e1e2010-01-29 05:32:19 -0800119 /*
120 * 400 series - Command was accepted, but the requested action
121 * did not take place.
122 */
123 public static final int OpFailedNoMedia = 401;
124 public static final int OpFailedMediaBlank = 402;
125 public static final int OpFailedMediaCorrupt = 403;
126 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800127 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700128 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800129
130 /*
131 * 600 series - Unsolicited broadcasts.
132 */
San Mehat22dd86e2010-01-12 12:21:18 -0800133 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800134 public static final int ShareAvailabilityChange = 620;
135 public static final int VolumeDiskInserted = 630;
136 public static final int VolumeDiskRemoved = 631;
137 public static final int VolumeBadRemoval = 632;
138 }
139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 private Context mContext;
141 private NativeDaemonConnector mConnector;
142 private String mLegacyState = Environment.MEDIA_REMOVED;
143 private PackageManagerService mPms;
144 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800145 // Used as a lock for methods that register/unregister listeners.
146 final private ArrayList<MountServiceBinderListener> mListeners =
147 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800148 private boolean mBooted = false;
149 private boolean mReady = false;
150 private boolean mSendUmsConnectedOnBoot = 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 Root27358a62010-09-29 19:27:20 -0700162 final private Map<Integer, Integer> mObbUidUsage = new HashMap<Integer, Integer>();
Kenny Root735de3b2010-09-30 14:11:39 -0700163 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700164 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
165
166 class ObbState implements IBinder.DeathRecipient {
Kenny Root735de3b2010-09-30 14:11:39 -0700167 public ObbState(String filename, IObbActionListener token, int callerUid)
168 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700169 this.filename = filename;
170 this.token = token;
171 this.callerUid = callerUid;
172 mounted = false;
Kenny Root735de3b2010-09-30 14:11:39 -0700173
174 getBinder().linkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700175 }
176
177 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700178 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700179
180 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700181 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700182
183 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700184 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700185
186 // Whether this is mounted currently.
187 boolean mounted;
188
Kenny Root735de3b2010-09-30 14:11:39 -0700189 public IBinder getBinder() {
190 return token.asBinder();
191 }
192
Kenny Roota02b8b02010-08-05 16:14:17 -0700193 @Override
194 public void binderDied() {
195 ObbAction action = new UnmountObbAction(this, true);
196 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700197 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700198
Kenny Root735de3b2010-09-30 14:11:39 -0700199 public void cleanUp() {
200 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700201 }
Kenny Root38cf8862010-09-26 14:18:51 -0700202
203 @Override
204 public String toString() {
205 StringBuilder sb = new StringBuilder("ObbState{");
206 sb.append("filename=");
207 sb.append(filename);
208 sb.append(",token=");
209 sb.append(token.toString());
210 sb.append(",callerUid=");
211 sb.append(callerUid);
212 sb.append(",mounted=");
213 sb.append(mounted);
214 sb.append('}');
215 return sb.toString();
216 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700217 }
218
219 // OBB Action Handler
220 final private ObbActionHandler mObbActionHandler;
221
222 // OBB action handler messages
223 private static final int OBB_RUN_ACTION = 1;
224 private static final int OBB_MCS_BOUND = 2;
225 private static final int OBB_MCS_UNBIND = 3;
226 private static final int OBB_MCS_RECONNECT = 4;
227 private static final int OBB_MCS_GIVE_UP = 5;
228
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
434 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800435 int rc = doMountVolume(path);
436 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700437 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800438 }
San Mehat6a254402010-03-22 10:21:00 -0700439 } else if (state.equals(Environment.MEDIA_SHARED)) {
440 /*
441 * Bootstrap UMS enabled state since vold indicates
442 * the volume is shared (runtime restart while ums enabled)
443 */
444 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800445 }
San Mehat6a254402010-03-22 10:21:00 -0700446
San Mehat6a965af22010-02-24 17:47:30 -0800447 /*
San Mehat6a254402010-03-22 10:21:00 -0700448 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800449 * now that we're up.
450 */
451 if (mSendUmsConnectedOnBoot) {
452 sendUmsIntent(true);
453 mSendUmsConnectedOnBoot = false;
454 }
San Mehatfafb0412010-02-18 19:40:04 -0800455 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700456 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800457 }
San Mehat207e5382010-02-04 20:46:54 -0800458 }
San Mehatfafb0412010-02-18 19:40:04 -0800459 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
461 }
462 };
463
San Mehat4270e1e2010-01-29 05:32:19 -0800464 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
465 final IMountServiceListener mListener;
466
467 MountServiceBinderListener(IMountServiceListener listener) {
468 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700469
San Mehat91c77612010-01-07 10:39:41 -0800470 }
471
San Mehat4270e1e2010-01-29 05:32:19 -0800472 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700473 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700474 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800475 mListeners.remove(this);
476 mListener.asBinder().unlinkToDeath(this, 0);
477 }
478 }
479 }
480
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800481 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800482 // TODO: Add support for multiple share methods
483 if (!method.equals("ums")) {
484 throw new IllegalArgumentException(String.format("Method %s not supported", method));
485 }
486
San Mehat4270e1e2010-01-29 05:32:19 -0800487 try {
488 mConnector.doCommand(String.format(
489 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
490 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700491 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800492 }
San Mehat4270e1e2010-01-29 05:32:19 -0800493 }
494
San Mehat207e5382010-02-04 20:46:54 -0800495 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800496 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700497 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800498 return;
499 }
San Mehatb1043402010-02-05 08:26:50 -0800500
501 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700502 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800503 return;
504 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800505 // Update state on PackageManager
506 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700507 mPms.updateExternalMediaStatus(false, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800508 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700509 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800510 }
Kenny Root38cf8862010-09-26 14:18:51 -0700511
512 // Remove all OBB mappings and listeners from this path
513 synchronized (mObbMounts) {
514 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
515
516 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
517 while (i.hasNext()) {
518 final Entry<String, ObbState> obbEntry = i.next();
519
520 // If this entry's source file is in the volume path that got
521 // unmounted, remove it because it's no longer valid.
522 if (obbEntry.getKey().startsWith(path)) {
523 obbStatesToRemove.add(obbEntry.getValue());
524 }
525 }
526
527 for (final ObbState obbState : obbStatesToRemove) {
528 removeObbState(obbState);
529
530 try {
531 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
532 } catch (RemoteException e) {
533 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
534 + obbState.filename);
535 }
536 }
537 }
538
San Mehat4270e1e2010-01-29 05:32:19 -0800539 String oldState = mLegacyState;
540 mLegacyState = state;
541
542 synchronized (mListeners) {
543 for (int i = mListeners.size() -1; i >= 0; i--) {
544 MountServiceBinderListener bl = mListeners.get(i);
545 try {
San Mehatb1043402010-02-05 08:26:50 -0800546 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800547 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700548 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800549 mListeners.remove(i);
550 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700551 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800552 }
553 }
554 }
555 }
556
557 /**
558 *
559 * Callback from NativeDaemonConnector
560 */
561 public void onDaemonConnected() {
562 /*
563 * Since we'll be calling back into the NativeDaemonConnector,
564 * we need to do our work in a new thread.
565 */
566 new Thread() {
567 public void run() {
568 /**
569 * Determine media state and UMS detection status
570 */
571 String path = Environment.getExternalStorageDirectory().getPath();
572 String state = Environment.MEDIA_REMOVED;
573
574 try {
575 String[] vols = mConnector.doListCommand(
576 "volume list", VoldResponseCode.VolumeListResult);
577 for (String volstr : vols) {
578 String[] tok = volstr.split(" ");
579 // FMT: <label> <mountpoint> <state>
580 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700581 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800582 "Skipping unknown volume '%s'",tok[1]));
583 continue;
584 }
585 int st = Integer.parseInt(tok[2]);
586 if (st == VolumeState.NoMedia) {
587 state = Environment.MEDIA_REMOVED;
588 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800589 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800590 } else if (st == VolumeState.Mounted) {
591 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700592 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800593 } else if (st == VolumeState.Shared) {
594 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700595 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800596 } else {
597 throw new Exception(String.format("Unexpected state %d", st));
598 }
599 }
600 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700601 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800602 updatePublicVolumeState(path, state);
603 }
604 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700605 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800606 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
607 }
608
609 try {
San Mehat207e5382010-02-04 20:46:54 -0800610 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800611 notifyShareAvailabilityChange("ums", avail);
612 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700613 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800614 }
San Mehat207e5382010-02-04 20:46:54 -0800615 /*
616 * Now that we've done our initialization, release
617 * the hounds!
618 */
619 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800620 }
621 }.start();
622 }
623
624 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800625 * Callback from NativeDaemonConnector
626 */
627 public boolean onEvent(int code, String raw, String[] cooked) {
628 Intent in = null;
629
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800630 if (DEBUG_EVENTS) {
631 StringBuilder builder = new StringBuilder();
632 builder.append("onEvent::");
633 builder.append(" raw= " + raw);
634 if (cooked != null) {
635 builder.append(" cooked = " );
636 for (String str : cooked) {
637 builder.append(" " + str);
638 }
639 }
San Mehata5078592010-03-25 09:36:54 -0700640 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800641 }
San Mehat4270e1e2010-01-29 05:32:19 -0800642 if (code == VoldResponseCode.VolumeStateChange) {
643 /*
644 * One of the volumes we're managing has changed state.
645 * Format: "NNN Volume <label> <path> state changed
646 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
647 */
648 notifyVolumeStateChange(
649 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
650 Integer.parseInt(cooked[10]));
651 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
652 // FMT: NNN Share method <method> now <available|unavailable>
653 boolean avail = false;
654 if (cooked[5].equals("available")) {
655 avail = true;
656 }
657 notifyShareAvailabilityChange(cooked[3], avail);
658 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
659 (code == VoldResponseCode.VolumeDiskRemoved) ||
660 (code == VoldResponseCode.VolumeBadRemoval)) {
661 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
662 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
663 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
664 final String label = cooked[2];
665 final String path = cooked[3];
666 int major = -1;
667 int minor = -1;
668
669 try {
670 String devComp = cooked[6].substring(1, cooked[6].length() -1);
671 String[] devTok = devComp.split(":");
672 major = Integer.parseInt(devTok[0]);
673 minor = Integer.parseInt(devTok[1]);
674 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700675 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800676 }
677
San Mehat4270e1e2010-01-29 05:32:19 -0800678 if (code == VoldResponseCode.VolumeDiskInserted) {
679 new Thread() {
680 public void run() {
681 try {
682 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800683 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700684 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800685 }
686 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700687 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800688 }
689 }
690 }.start();
691 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
692 /*
693 * This event gets trumped if we're already in BAD_REMOVAL state
694 */
695 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
696 return true;
697 }
698 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700699 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800700 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
701 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
702 mContext.sendBroadcast(in);
703
San Mehata5078592010-03-25 09:36:54 -0700704 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800705 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
706 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
707 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700708 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800709 /* Send the media unmounted event first */
710 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
711 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
712 mContext.sendBroadcast(in);
713
San Mehata5078592010-03-25 09:36:54 -0700714 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800715 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
716 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
717 } else {
San Mehata5078592010-03-25 09:36:54 -0700718 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800719 }
720 } else {
721 return false;
722 }
723
724 if (in != null) {
725 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400726 }
727 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800728 }
729
San Mehat207e5382010-02-04 20:46:54 -0800730 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800731 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700732 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800733
734 Intent in = null;
735
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500736 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700737 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500738 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
739 Uri.parse("file://" + path)));
740 }
741
San Mehat4270e1e2010-01-29 05:32:19 -0800742 if (newState == VolumeState.Init) {
743 } else if (newState == VolumeState.NoMedia) {
744 // NoMedia is handled via Disk Remove events
745 } else if (newState == VolumeState.Idle) {
746 /*
747 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
748 * if we're in the process of enabling UMS
749 */
750 if (!vs.equals(
751 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
752 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800753 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700754 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800755 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
756 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
757 }
758 } else if (newState == VolumeState.Pending) {
759 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700760 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800761 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
762 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
763 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700764 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800765 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800766 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
767 in.putExtra("read-only", false);
768 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800769 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
770 } else if (newState == VolumeState.Formatting) {
771 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700772 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800773 /* Send the media unmounted event first */
774 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
775 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
776 mContext.sendBroadcast(in);
777
San Mehata5078592010-03-25 09:36:54 -0700778 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800779 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
780 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700781 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800782 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700783 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800784 return;
785 } else {
San Mehata5078592010-03-25 09:36:54 -0700786 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800787 }
788
789 if (in != null) {
790 mContext.sendBroadcast(in);
791 }
792 }
793
San Mehat207e5382010-02-04 20:46:54 -0800794 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700795 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700796 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700797 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700798 } catch (NativeDaemonConnectorException ex) {
799 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
800 return false;
801 }
San Mehat207e5382010-02-04 20:46:54 -0800802
803 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700804 String[] tok = line.split(" ");
805 if (tok.length < 3) {
806 Slog.e(TAG, "Malformed response to share status " + method);
807 return false;
808 }
809
San Mehat207e5382010-02-04 20:46:54 -0800810 int code;
811 try {
812 code = Integer.parseInt(tok[0]);
813 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700814 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800815 return false;
816 }
817 if (code == VoldResponseCode.ShareStatusResult) {
818 if (tok[2].equals("available"))
819 return true;
820 return false;
821 } else {
San Mehata5078592010-03-25 09:36:54 -0700822 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800823 return false;
824 }
825 }
San Mehata5078592010-03-25 09:36:54 -0700826 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800827 return false;
828 }
829
830 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800831 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800832
San Mehata5078592010-03-25 09:36:54 -0700833 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800834 try {
835 mConnector.doCommand(String.format("volume mount %s", path));
836 } catch (NativeDaemonConnectorException e) {
837 /*
838 * Mount failed for some reason
839 */
840 Intent in = null;
841 int code = e.getCode();
842 if (code == VoldResponseCode.OpFailedNoMedia) {
843 /*
844 * Attempt to mount but no media inserted
845 */
San Mehatb1043402010-02-05 08:26:50 -0800846 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800847 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700848 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800849 /*
850 * Media is blank or does not contain a supported filesystem
851 */
852 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
853 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800854 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800855 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700856 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800857 /*
858 * Volume consistency check failed
859 */
860 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
861 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800862 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800863 } else {
San Mehatb1043402010-02-05 08:26:50 -0800864 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800865 }
866
867 /*
868 * Send broadcast intent (if required for the failure)
869 */
870 if (in != null) {
871 mContext.sendBroadcast(in);
872 }
873 }
874
875 return rc;
876 }
877
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800878 /*
879 * If force is not set, we do not unmount if there are
880 * processes holding references to the volume about to be unmounted.
881 * If force is set, all the processes holding references need to be
882 * killed via the ActivityManager before actually unmounting the volume.
883 * This might even take a while and might be retried after timed delays
884 * to make sure we dont end up in an instable state and kill some core
885 * processes.
886 */
San Mehatd9709982010-02-18 11:43:03 -0800887 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800888 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800889 return VoldResponseCode.OpFailedVolNotMounted;
890 }
Kenny Rootaa485402010-09-14 14:49:41 -0700891
892 /*
893 * Force a GC to make sure AssetManagers in other threads of the
894 * system_server are cleaned up. We have to do this since AssetManager
895 * instances are kept as a WeakReference and it's possible we have files
896 * open on the external storage.
897 */
898 Runtime.getRuntime().gc();
899
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800900 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700901 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800902 try {
San Mehatd9709982010-02-18 11:43:03 -0800903 mConnector.doCommand(String.format(
904 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700905 // We unmounted the volume. None of the asec containers are available now.
906 synchronized (mAsecMountSet) {
907 mAsecMountSet.clear();
908 }
San Mehatb1043402010-02-05 08:26:50 -0800909 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800910 } catch (NativeDaemonConnectorException e) {
911 // Don't worry about mismatch in PackageManager since the
912 // call back will handle the status changes any way.
913 int code = e.getCode();
914 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800915 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800916 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
917 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800918 } else {
San Mehatb1043402010-02-05 08:26:50 -0800919 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800920 }
921 }
922 }
923
924 private int doFormatVolume(String path) {
925 try {
926 String cmd = String.format("volume format %s", path);
927 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800928 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800929 } catch (NativeDaemonConnectorException e) {
930 int code = e.getCode();
931 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800932 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800933 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800935 } else {
San Mehatb1043402010-02-05 08:26:50 -0800936 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800937 }
938 }
939 }
940
San Mehatb1043402010-02-05 08:26:50 -0800941 private boolean doGetVolumeShared(String path, String method) {
942 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700943 ArrayList<String> rsp;
944
945 try {
946 rsp = mConnector.doCommand(cmd);
947 } catch (NativeDaemonConnectorException ex) {
948 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
949 return false;
950 }
San Mehatb1043402010-02-05 08:26:50 -0800951
952 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700953 String[] tok = line.split(" ");
954 if (tok.length < 3) {
955 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
956 return false;
957 }
958
San Mehatb1043402010-02-05 08:26:50 -0800959 int code;
960 try {
961 code = Integer.parseInt(tok[0]);
962 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700963 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800964 return false;
965 }
966 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700967 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800968 } else {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800970 return false;
971 }
972 }
San Mehata5078592010-03-25 09:36:54 -0700973 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800974 return false;
975 }
976
San Mehat207e5382010-02-04 20:46:54 -0800977 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800978 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700979 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800980 return;
981 }
982
983 synchronized (mListeners) {
984 for (int i = mListeners.size() -1; i >= 0; i--) {
985 MountServiceBinderListener bl = mListeners.get(i);
986 try {
San Mehatb1043402010-02-05 08:26:50 -0800987 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800988 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700989 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800990 mListeners.remove(i);
991 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700992 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800993 }
994 }
995 }
996
San Mehat207e5382010-02-04 20:46:54 -0800997 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800998 sendUmsIntent(avail);
999 } else {
1000 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001001 }
San Mehat2fe718a2010-03-11 12:01:49 -08001002
1003 final String path = Environment.getExternalStorageDirectory().getPath();
1004 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1005 /*
1006 * USB mass storage disconnected while enabled
1007 */
1008 new Thread() {
1009 public void run() {
1010 try {
1011 int rc;
San Mehata5078592010-03-25 09:36:54 -07001012 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001013 doShareUnshareVolume(path, "ums", false);
1014 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001015 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001016 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1017 path, rc));
1018 }
1019 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001020 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001021 }
1022 }
1023 }.start();
1024 }
San Mehat4270e1e2010-01-29 05:32:19 -08001025 }
1026
San Mehat6a965af22010-02-24 17:47:30 -08001027 private void sendUmsIntent(boolean c) {
1028 mContext.sendBroadcast(
1029 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1030 }
1031
San Mehat207e5382010-02-04 20:46:54 -08001032 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001033 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1034 throw new SecurityException(String.format("Requires %s permission", perm));
1035 }
1036 }
1037
1038 /**
San Mehat207e5382010-02-04 20:46:54 -08001039 * Constructs a new MountService instance
1040 *
1041 * @param context Binder context for this service
1042 */
1043 public MountService(Context context) {
1044 mContext = context;
1045
San Mehat207e5382010-02-04 20:46:54 -08001046 // XXX: This will go away soon in favor of IMountServiceObserver
1047 mPms = (PackageManagerService) ServiceManager.getService("package");
1048
1049 mContext.registerReceiver(mBroadcastReceiver,
1050 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1051
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001052 mHandlerThread = new HandlerThread("MountService");
1053 mHandlerThread.start();
1054 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1055
Kenny Roota02b8b02010-08-05 16:14:17 -07001056 // Add OBB Action Handler to MountService thread.
1057 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1058
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001059 /*
1060 * Vold does not run in the simulator, so pretend the connector thread
1061 * ran and did its thing.
1062 */
1063 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1064 mReady = true;
1065 mUmsEnabling = true;
1066 return;
1067 }
1068
Kenny Root305bcbf2010-09-03 07:56:38 -07001069 /*
1070 * Create the connection to vold with a maximum queue of twice the
1071 * amount of containers we'd ever expect to have. This keeps an
1072 * "asec list" from blocking a thread repeatedly.
1073 */
1074 mConnector = new NativeDaemonConnector(this, "vold",
1075 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001076 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001077 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001078 thread.start();
1079 }
1080
1081 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001082 * Exposed API calls below here
1083 */
1084
1085 public void registerListener(IMountServiceListener listener) {
1086 synchronized (mListeners) {
1087 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1088 try {
1089 listener.asBinder().linkToDeath(bl, 0);
1090 mListeners.add(bl);
1091 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001092 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001093 }
1094 }
1095 }
1096
1097 public void unregisterListener(IMountServiceListener listener) {
1098 synchronized (mListeners) {
1099 for(MountServiceBinderListener bl : mListeners) {
1100 if (bl.mListener == listener) {
1101 mListeners.remove(mListeners.indexOf(bl));
1102 return;
1103 }
1104 }
1105 }
1106 }
1107
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001108 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001109 validatePermission(android.Manifest.permission.SHUTDOWN);
1110
San Mehata5078592010-03-25 09:36:54 -07001111 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001112
1113 String path = Environment.getExternalStorageDirectory().getPath();
1114 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001115
1116 if (state.equals(Environment.MEDIA_SHARED)) {
1117 /*
1118 * If the media is currently shared, unshare it.
1119 * XXX: This is still dangerous!. We should not
1120 * be rebooting at *all* if UMS is enabled, since
1121 * the UMS host could have dirty FAT cache entries
1122 * yet to flush.
1123 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001124 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001125 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1126 /*
1127 * If the media is being checked, then we need to wait for
1128 * it to complete before being able to proceed.
1129 */
1130 // XXX: @hackbod - Should we disable the ANR timer here?
1131 int retries = 30;
1132 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1133 try {
1134 Thread.sleep(1000);
1135 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001136 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001137 break;
1138 }
1139 state = Environment.getExternalStorageState();
1140 }
1141 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001142 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001143 }
1144 }
1145
1146 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001147 // Post a unmount message.
1148 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1149 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001150 }
1151 }
1152
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001153 private boolean getUmsEnabling() {
1154 synchronized (mListeners) {
1155 return mUmsEnabling;
1156 }
1157 }
1158
1159 private void setUmsEnabling(boolean enable) {
1160 synchronized (mListeners) {
1161 mUmsEnabling = true;
1162 }
1163 }
1164
San Mehatb1043402010-02-05 08:26:50 -08001165 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001166 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001167
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001168 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001169 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001170 }
San Mehatb1043402010-02-05 08:26:50 -08001171 return doGetShareMethodAvailable("ums");
1172 }
1173
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001174 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001175 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001176 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001177
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001178 // TODO: Add support for multiple share methods
1179
1180 /*
1181 * If the volume is mounted and we're enabling then unmount it
1182 */
1183 String path = Environment.getExternalStorageDirectory().getPath();
1184 String vs = getVolumeState(path);
1185 String method = "ums";
1186 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1187 // Override for isUsbMassStorageEnabled()
1188 setUmsEnabling(enable);
1189 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1190 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1191 // Clear override
1192 setUmsEnabling(false);
1193 }
1194 /*
1195 * If we disabled UMS then mount the volume
1196 */
1197 if (!enable) {
1198 doShareUnshareVolume(path, method, enable);
1199 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001200 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001201 " after disabling share method " + method);
1202 /*
1203 * Even though the mount failed, the unshare didn't so don't indicate an error.
1204 * The mountVolume() call will have set the storage state and sent the necessary
1205 * broadcasts.
1206 */
1207 }
1208 }
San Mehatb1043402010-02-05 08:26:50 -08001209 }
1210
1211 public boolean isUsbMassStorageEnabled() {
1212 waitForReady();
1213 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
San Mehat4270e1e2010-01-29 05:32:19 -08001215
San Mehat7fd0fee2009-12-17 07:12:23 -08001216 /**
1217 * @return state of the volume at the specified mount point
1218 */
San Mehat4270e1e2010-01-29 05:32:19 -08001219 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001220 /*
1221 * XXX: Until we have multiple volume discovery, just hardwire
1222 * this to /sdcard
1223 */
1224 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001225 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001226 throw new IllegalArgumentException();
1227 }
1228
1229 return mLegacyState;
1230 }
1231
San Mehat4270e1e2010-01-29 05:32:19 -08001232 public int mountVolume(String path) {
1233 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001234
San Mehat207e5382010-02-04 20:46:54 -08001235 waitForReady();
1236 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001239 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001240 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001241 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001243 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001244 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001245 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1246 Environment.MEDIA_REMOVED.equals(volState) ||
1247 Environment.MEDIA_SHARED.equals(volState) ||
1248 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1249 // Media already unmounted or cannot be unmounted.
1250 // TODO return valid return code when adding observer call back.
1251 return;
1252 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001253 UnmountCallBack ucb = new UnmountCallBack(path, force);
1254 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256
San Mehat4270e1e2010-01-29 05:32:19 -08001257 public int formatVolume(String path) {
1258 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001259 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001260
San Mehat207e5382010-02-04 20:46:54 -08001261 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
1263
San Mehatc1b4ce92010-02-16 17:13:03 -08001264 public int []getStorageUsers(String path) {
1265 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1266 waitForReady();
1267 try {
1268 String[] r = mConnector.doListCommand(
1269 String.format("storage users %s", path),
1270 VoldResponseCode.StorageUsersListResult);
1271 // FMT: <pid> <process name>
1272 int[] data = new int[r.length];
1273 for (int i = 0; i < r.length; i++) {
1274 String []tok = r[i].split(" ");
1275 try {
1276 data[i] = Integer.parseInt(tok[0]);
1277 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001278 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001279 return new int[0];
1280 }
1281 }
1282 return data;
1283 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001284 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001285 return new int[0];
1286 }
1287 }
1288
San Mehatb1043402010-02-05 08:26:50 -08001289 private void warnOnNotMounted() {
1290 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001291 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001292 }
1293 }
1294
San Mehat4270e1e2010-01-29 05:32:19 -08001295 public String[] getSecureContainerList() {
1296 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001297 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001298 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001299
San Mehat4270e1e2010-01-29 05:32:19 -08001300 try {
1301 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1302 } catch (NativeDaemonConnectorException e) {
1303 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 }
San Mehat36972292010-01-06 11:06:32 -08001306
San Mehat4270e1e2010-01-29 05:32:19 -08001307 public int createSecureContainer(String id, int sizeMb, String fstype,
1308 String key, int ownerUid) {
1309 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001310 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001311 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001312
San Mehatb1043402010-02-05 08:26:50 -08001313 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001314 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1315 try {
1316 mConnector.doCommand(cmd);
1317 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001318 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001319 }
San Mehata181b212010-02-11 06:50:20 -08001320
1321 if (rc == StorageResultCode.OperationSucceeded) {
1322 synchronized (mAsecMountSet) {
1323 mAsecMountSet.add(id);
1324 }
1325 }
San Mehat4270e1e2010-01-29 05:32:19 -08001326 return rc;
San Mehat36972292010-01-06 11:06:32 -08001327 }
1328
San Mehat4270e1e2010-01-29 05:32:19 -08001329 public int finalizeSecureContainer(String id) {
1330 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001331 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001332
San Mehatb1043402010-02-05 08:26:50 -08001333 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001334 try {
1335 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001336 /*
1337 * Finalization does a remount, so no need
1338 * to update mAsecMountSet
1339 */
San Mehat4270e1e2010-01-29 05:32:19 -08001340 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001341 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001342 }
San Mehat4270e1e2010-01-29 05:32:19 -08001343 return rc;
San Mehat36972292010-01-06 11:06:32 -08001344 }
1345
San Mehatd9709982010-02-18 11:43:03 -08001346 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001347 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001348 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001349 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001350
Kenny Rootaa485402010-09-14 14:49:41 -07001351 /*
1352 * Force a GC to make sure AssetManagers in other threads of the
1353 * system_server are cleaned up. We have to do this since AssetManager
1354 * instances are kept as a WeakReference and it's possible we have files
1355 * open on the external storage.
1356 */
1357 Runtime.getRuntime().gc();
1358
San Mehatb1043402010-02-05 08:26:50 -08001359 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001360 try {
San Mehatd9709982010-02-18 11:43:03 -08001361 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001362 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001363 int code = e.getCode();
1364 if (code == VoldResponseCode.OpFailedStorageBusy) {
1365 rc = StorageResultCode.OperationFailedStorageBusy;
1366 } else {
1367 rc = StorageResultCode.OperationFailedInternalError;
1368 }
San Mehat02735bc2010-01-26 15:18:08 -08001369 }
San Mehata181b212010-02-11 06:50:20 -08001370
1371 if (rc == StorageResultCode.OperationSucceeded) {
1372 synchronized (mAsecMountSet) {
1373 if (mAsecMountSet.contains(id)) {
1374 mAsecMountSet.remove(id);
1375 }
1376 }
1377 }
1378
San Mehat4270e1e2010-01-29 05:32:19 -08001379 return rc;
San Mehat36972292010-01-06 11:06:32 -08001380 }
1381
San Mehat4270e1e2010-01-29 05:32:19 -08001382 public int mountSecureContainer(String id, String key, int ownerUid) {
1383 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001384 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001385 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001386
San Mehata181b212010-02-11 06:50:20 -08001387 synchronized (mAsecMountSet) {
1388 if (mAsecMountSet.contains(id)) {
1389 return StorageResultCode.OperationFailedStorageMounted;
1390 }
1391 }
1392
San Mehatb1043402010-02-05 08:26:50 -08001393 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001394 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1395 try {
1396 mConnector.doCommand(cmd);
1397 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001398 int code = e.getCode();
1399 if (code != VoldResponseCode.OpFailedStorageBusy) {
1400 rc = StorageResultCode.OperationFailedInternalError;
1401 }
San Mehat02735bc2010-01-26 15:18:08 -08001402 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001403
1404 if (rc == StorageResultCode.OperationSucceeded) {
1405 synchronized (mAsecMountSet) {
1406 mAsecMountSet.add(id);
1407 }
1408 }
San Mehat4270e1e2010-01-29 05:32:19 -08001409 return rc;
San Mehat36972292010-01-06 11:06:32 -08001410 }
1411
San Mehatd9709982010-02-18 11:43:03 -08001412 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001413 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001414 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001415 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001416
San Mehat6cdd9c02010-02-09 14:45:20 -08001417 synchronized (mAsecMountSet) {
1418 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001419 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001420 }
1421 }
1422
Kenny Rootaa485402010-09-14 14:49:41 -07001423 /*
1424 * Force a GC to make sure AssetManagers in other threads of the
1425 * system_server are cleaned up. We have to do this since AssetManager
1426 * instances are kept as a WeakReference and it's possible we have files
1427 * open on the external storage.
1428 */
1429 Runtime.getRuntime().gc();
1430
San Mehatb1043402010-02-05 08:26:50 -08001431 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001432 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001433 try {
1434 mConnector.doCommand(cmd);
1435 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001436 int code = e.getCode();
1437 if (code == VoldResponseCode.OpFailedStorageBusy) {
1438 rc = StorageResultCode.OperationFailedStorageBusy;
1439 } else {
1440 rc = StorageResultCode.OperationFailedInternalError;
1441 }
San Mehat02735bc2010-01-26 15:18:08 -08001442 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001443
1444 if (rc == StorageResultCode.OperationSucceeded) {
1445 synchronized (mAsecMountSet) {
1446 mAsecMountSet.remove(id);
1447 }
1448 }
San Mehat4270e1e2010-01-29 05:32:19 -08001449 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001450 }
1451
San Mehat6cdd9c02010-02-09 14:45:20 -08001452 public boolean isSecureContainerMounted(String id) {
1453 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1454 waitForReady();
1455 warnOnNotMounted();
1456
1457 synchronized (mAsecMountSet) {
1458 return mAsecMountSet.contains(id);
1459 }
1460 }
1461
San Mehat4270e1e2010-01-29 05:32:19 -08001462 public int renameSecureContainer(String oldId, String newId) {
1463 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001464 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001465 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001466
San Mehata181b212010-02-11 06:50:20 -08001467 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001468 /*
1469 * Because a mounted container has active internal state which cannot be
1470 * changed while active, we must ensure both ids are not currently mounted.
1471 */
1472 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001473 return StorageResultCode.OperationFailedStorageMounted;
1474 }
1475 }
1476
San Mehatb1043402010-02-05 08:26:50 -08001477 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001478 String cmd = String.format("asec rename %s %s", oldId, newId);
1479 try {
1480 mConnector.doCommand(cmd);
1481 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001482 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001483 }
San Mehata181b212010-02-11 06:50:20 -08001484
San Mehat4270e1e2010-01-29 05:32:19 -08001485 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001486 }
1487
San Mehat4270e1e2010-01-29 05:32:19 -08001488 public String getSecureContainerPath(String id) {
1489 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001490 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001491 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001492
San Mehat2d66cef2010-03-23 11:12:52 -07001493 try {
1494 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1495 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001496 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001497 if (code != VoldResponseCode.AsecPathResult) {
1498 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1499 }
1500 return tok[1];
1501 } catch (NativeDaemonConnectorException e) {
1502 int code = e.getCode();
1503 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1504 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001505 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001506 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001507 }
1508 }
San Mehat22dd86e2010-01-12 12:21:18 -08001509 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001510
1511 public void finishMediaUpdate() {
1512 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1513 }
Kenny Root02c87302010-07-01 08:10:18 -07001514
Kenny Roota02b8b02010-08-05 16:14:17 -07001515 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1516 if (callerUid == android.os.Process.SYSTEM_UID) {
1517 return true;
1518 }
1519
Kenny Root02c87302010-07-01 08:10:18 -07001520 if (packageName == null) {
1521 return false;
1522 }
1523
1524 final int packageUid = mPms.getPackageUid(packageName);
1525
1526 if (DEBUG_OBB) {
1527 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1528 packageUid + ", callerUid = " + callerUid);
1529 }
1530
1531 return callerUid == packageUid;
1532 }
1533
1534 public String getMountedObbPath(String filename) {
1535 waitForReady();
1536 warnOnNotMounted();
1537
Kenny Root02c87302010-07-01 08:10:18 -07001538 try {
1539 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1540 String []tok = rsp.get(0).split(" ");
1541 int code = Integer.parseInt(tok[0]);
1542 if (code != VoldResponseCode.AsecPathResult) {
1543 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1544 }
1545 return tok[1];
1546 } catch (NativeDaemonConnectorException e) {
1547 int code = e.getCode();
1548 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001549 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001550 } else {
1551 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1552 }
1553 }
1554 }
1555
1556 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001557 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001558 final ObbState obbState = mObbPathToStateMap.get(filename);
1559 if (obbState != null) {
1560 synchronized (obbState) {
1561 return obbState.mounted;
1562 }
1563 }
Kenny Root02c87302010-07-01 08:10:18 -07001564 }
Kenny Root38cf8862010-09-26 14:18:51 -07001565 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001566 }
1567
Kenny Root735de3b2010-09-30 14:11:39 -07001568 public void mountObb(String filename, String key, IObbActionListener token)
1569 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001570 waitForReady();
1571 warnOnNotMounted();
1572
Kenny Rootf1121dc2010-09-29 07:30:53 -07001573 if (filename == null) {
1574 throw new IllegalArgumentException("filename cannot be null");
1575 } else if (token == null) {
1576 throw new IllegalArgumentException("token cannot be null");
1577 }
1578
Kenny Roota02b8b02010-08-05 16:14:17 -07001579 final ObbState obbState;
1580
1581 synchronized (mObbMounts) {
1582 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001583 try {
1584 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1585 } catch (RemoteException e) {
1586 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1587 }
1588 return;
Kenny Root02c87302010-07-01 08:10:18 -07001589 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001590
Kenny Roota02b8b02010-08-05 16:14:17 -07001591 final int callerUid = Binder.getCallingUid();
Kenny Root27358a62010-09-29 19:27:20 -07001592
1593 final Integer uidUsage = mObbUidUsage.get(callerUid);
1594 if (uidUsage != null && uidUsage > MAX_OBBS) {
1595 throw new IllegalStateException("Maximum number of OBBs mounted!");
1596 }
1597
Kenny Roota02b8b02010-08-05 16:14:17 -07001598 obbState = new ObbState(filename, token, callerUid);
1599 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001600 }
1601
Kenny Root735de3b2010-09-30 14:11:39 -07001602 final MessageDigest md;
Kenny Root02c87302010-07-01 08:10:18 -07001603 try {
Kenny Root735de3b2010-09-30 14:11:39 -07001604 md = MessageDigest.getInstance("MD5");
1605 } catch (NoSuchAlgorithmException e) {
1606 Slog.e(TAG, "Could not load MD5 algorithm", e);
1607 try {
1608 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1609 } catch (RemoteException e1) {
1610 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1611 }
1612 return;
Kenny Root02c87302010-07-01 08:10:18 -07001613 }
1614
Kenny Root735de3b2010-09-30 14:11:39 -07001615 String hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1616
1617 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001618 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1619
1620 if (DEBUG_OBB)
1621 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001622 }
1623
Kenny Roota02b8b02010-08-05 16:14:17 -07001624 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001625 if (filename == null) {
1626 throw new IllegalArgumentException("filename cannot be null");
1627 } else if (token == null) {
1628 throw new IllegalArgumentException("token cannot be null");
1629 }
1630
Kenny Roota02b8b02010-08-05 16:14:17 -07001631 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001632
Kenny Roota02b8b02010-08-05 16:14:17 -07001633 synchronized (mObbMounts) {
1634 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001635 try {
1636 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1637 } catch (RemoteException e) {
1638 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1639 }
1640 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001641 }
Kenny Root38cf8862010-09-26 14:18:51 -07001642
Kenny Roota02b8b02010-08-05 16:14:17 -07001643 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001644
1645 if (Binder.getCallingUid() != obbState.callerUid) {
1646 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001647 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001648 throw new SecurityException("caller does not match original mount caller");
1649 }
Kenny Root02c87302010-07-01 08:10:18 -07001650 }
1651
Kenny Root38cf8862010-09-26 14:18:51 -07001652 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001653 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001654
Kenny Roota02b8b02010-08-05 16:14:17 -07001655 if (DEBUG_OBB)
1656 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1657 }
1658
1659 private void addObbState(ObbState obbState) {
1660 synchronized (mObbMounts) {
Kenny Root735de3b2010-09-30 14:11:39 -07001661 List<ObbState> obbStates = mObbMounts.get(obbState.getBinder());
Kenny Root05105f72010-09-22 17:29:43 -07001662 if (obbStates == null) {
1663 obbStates = new ArrayList<ObbState>();
Kenny Root735de3b2010-09-30 14:11:39 -07001664 mObbMounts.put(obbState.getBinder(), obbStates);
Kenny Root05105f72010-09-22 17:29:43 -07001665 }
1666 obbStates.add(obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001667 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Root27358a62010-09-29 19:27:20 -07001668
1669 // Track the number of OBBs used by this UID.
1670 final int uid = obbState.callerUid;
1671 final Integer uidUsage = mObbUidUsage.get(uid);
1672 if (uidUsage == null) {
1673 mObbUidUsage.put(uid, 1);
1674 } else {
1675 mObbUidUsage.put(uid, uidUsage + 1);
1676 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001677 }
1678 }
1679
1680 private void removeObbState(ObbState obbState) {
1681 synchronized (mObbMounts) {
Kenny Root735de3b2010-09-30 14:11:39 -07001682 final List<ObbState> obbStates = mObbMounts.get(obbState.getBinder());
Kenny Root05105f72010-09-22 17:29:43 -07001683 if (obbStates != null) {
1684 obbStates.remove(obbState);
1685 }
1686 if (obbStates == null || obbStates.isEmpty()) {
Kenny Root735de3b2010-09-30 14:11:39 -07001687 mObbMounts.remove(obbState.getBinder());
1688 obbState.cleanUp();
Kenny Root05105f72010-09-22 17:29:43 -07001689 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001690 mObbPathToStateMap.remove(obbState.filename);
Kenny Root27358a62010-09-29 19:27:20 -07001691
1692 // Track the number of OBBs used by this UID.
1693 final int uid = obbState.callerUid;
1694 final Integer uidUsage = mObbUidUsage.get(uid);
1695 if (uidUsage == null) {
1696 Slog.e(TAG, "Called removeObbState for UID that isn't in map: " + uid);
1697 } else {
1698 final int newUsage = uidUsage - 1;
1699 if (newUsage == 0) {
1700 mObbUidUsage.remove(uid);
1701 } else {
1702 mObbUidUsage.put(uid, newUsage);
1703 }
1704 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001705 }
1706 }
1707
Kenny Root38cf8862010-09-26 14:18:51 -07001708 private void replaceObbState(ObbState oldObbState, ObbState newObbState) {
1709 synchronized (mObbMounts) {
1710 removeObbState(oldObbState);
1711 addObbState(newObbState);
1712 }
1713 }
1714
Kenny Roota02b8b02010-08-05 16:14:17 -07001715 private class ObbActionHandler extends Handler {
1716 private boolean mBound = false;
1717 private List<ObbAction> mActions = new LinkedList<ObbAction>();
1718
1719 ObbActionHandler(Looper l) {
1720 super(l);
1721 }
1722
1723 @Override
1724 public void handleMessage(Message msg) {
1725 switch (msg.what) {
1726 case OBB_RUN_ACTION: {
1727 ObbAction action = (ObbAction) msg.obj;
1728
1729 if (DEBUG_OBB)
1730 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1731
1732 // If a bind was already initiated we don't really
1733 // need to do anything. The pending install
1734 // will be processed later on.
1735 if (!mBound) {
1736 // If this is the only one pending we might
1737 // have to bind to the service again.
1738 if (!connectToService()) {
1739 Slog.e(TAG, "Failed to bind to media container service");
1740 action.handleError();
1741 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001742 }
1743
1744 mActions.add(action);
Kenny Root735de3b2010-09-30 14:11:39 -07001745 break;
Kenny Roota02b8b02010-08-05 16:14:17 -07001746 }
Kenny Root735de3b2010-09-30 14:11:39 -07001747
1748 // Once we bind to the service, the first
1749 // pending request will be processed.
1750 mActions.add(action);
1751 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001752 break;
1753 }
1754 case OBB_MCS_BOUND: {
1755 if (DEBUG_OBB)
1756 Slog.i(TAG, "OBB_MCS_BOUND");
1757 if (msg.obj != null) {
1758 mContainerService = (IMediaContainerService) msg.obj;
1759 }
1760 if (mContainerService == null) {
1761 // Something seriously wrong. Bail out
1762 Slog.e(TAG, "Cannot bind to media container service");
1763 for (ObbAction action : mActions) {
1764 // Indicate service bind error
1765 action.handleError();
1766 }
1767 mActions.clear();
1768 } else if (mActions.size() > 0) {
1769 ObbAction action = mActions.get(0);
1770 if (action != null) {
1771 action.execute(this);
1772 }
1773 } else {
1774 // Should never happen ideally.
1775 Slog.w(TAG, "Empty queue");
1776 }
1777 break;
1778 }
1779 case OBB_MCS_RECONNECT: {
1780 if (DEBUG_OBB)
1781 Slog.i(TAG, "OBB_MCS_RECONNECT");
1782 if (mActions.size() > 0) {
1783 if (mBound) {
1784 disconnectService();
1785 }
1786 if (!connectToService()) {
1787 Slog.e(TAG, "Failed to bind to media container service");
1788 for (ObbAction action : mActions) {
1789 // Indicate service bind error
1790 action.handleError();
1791 }
1792 mActions.clear();
1793 }
1794 }
1795 break;
1796 }
1797 case OBB_MCS_UNBIND: {
1798 if (DEBUG_OBB)
1799 Slog.i(TAG, "OBB_MCS_UNBIND");
1800
1801 // Delete pending install
1802 if (mActions.size() > 0) {
1803 mActions.remove(0);
1804 }
1805 if (mActions.size() == 0) {
1806 if (mBound) {
1807 disconnectService();
1808 }
1809 } else {
1810 // There are more pending requests in queue.
1811 // Just post MCS_BOUND message to trigger processing
1812 // of next pending install.
1813 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1814 }
1815 break;
1816 }
1817 case OBB_MCS_GIVE_UP: {
1818 if (DEBUG_OBB)
1819 Slog.i(TAG, "OBB_MCS_GIVE_UP");
1820 mActions.remove(0);
1821 break;
1822 }
1823 }
1824 }
1825
1826 private boolean connectToService() {
1827 if (DEBUG_OBB)
1828 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1829
1830 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1831 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1832 mBound = true;
1833 return true;
1834 }
1835 return false;
1836 }
1837
1838 private void disconnectService() {
1839 mContainerService = null;
1840 mBound = false;
1841 mContext.unbindService(mDefContainerConn);
1842 }
1843 }
1844
1845 abstract class ObbAction {
1846 private static final int MAX_RETRIES = 3;
1847 private int mRetries;
1848
1849 ObbState mObbState;
1850
1851 ObbAction(ObbState obbState) {
1852 mObbState = obbState;
1853 }
1854
1855 public void execute(ObbActionHandler handler) {
1856 try {
1857 if (DEBUG_OBB)
1858 Slog.i(TAG, "Starting to execute action: " + this.toString());
1859 mRetries++;
1860 if (mRetries > MAX_RETRIES) {
1861 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
1862 mObbActionHandler.sendEmptyMessage(OBB_MCS_GIVE_UP);
1863 handleError();
1864 return;
1865 } else {
1866 handleExecute();
1867 if (DEBUG_OBB)
1868 Slog.i(TAG, "Posting install MCS_UNBIND");
1869 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1870 }
1871 } catch (RemoteException e) {
1872 if (DEBUG_OBB)
1873 Slog.i(TAG, "Posting install MCS_RECONNECT");
1874 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1875 } catch (Exception e) {
1876 if (DEBUG_OBB)
1877 Slog.d(TAG, "Error handling OBB action", e);
1878 handleError();
1879 }
1880 }
1881
Kenny Root05105f72010-09-22 17:29:43 -07001882 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001883 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001884
1885 protected ObbInfo getObbInfo() throws IOException {
1886 ObbInfo obbInfo;
1887 try {
1888 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1889 } catch (RemoteException e) {
1890 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1891 + mObbState.filename);
1892 obbInfo = null;
1893 }
1894 if (obbInfo == null) {
1895 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1896 }
1897 return obbInfo;
1898 }
1899
1900 protected void sendNewStatusOrIgnore(String filename, String status) {
1901 try {
1902 mObbState.token.onObbResult(filename, status);
1903 } catch (RemoteException e) {
1904 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1905 }
1906 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001907 }
1908
1909 class MountObbAction extends ObbAction {
1910 private String mKey;
1911
1912 MountObbAction(ObbState obbState, String key) {
1913 super(obbState);
1914 mKey = key;
1915 }
1916
Kenny Root735de3b2010-09-30 14:11:39 -07001917 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001918 final ObbInfo obbInfo = getObbInfo();
1919
1920 /*
1921 * If someone tried to trick us with some weird characters, rectify
1922 * it here.
1923 */
1924 if (!mObbState.filename.equals(obbInfo.filename)) {
1925 if (DEBUG_OBB)
1926 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1927 + obbInfo.filename);
1928
1929 synchronized (mObbMounts) {
1930 /*
1931 * If the real filename is already mounted, discard this
1932 * state and notify the caller that the OBB is already
1933 * mounted.
1934 */
1935 if (isObbMounted(obbInfo.filename)) {
1936 if (DEBUG_OBB)
1937 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1938
1939 removeObbState(mObbState);
1940 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1941 return;
1942 }
1943
1944 /*
1945 * It's not already mounted, so we have to replace the state
1946 * with the state containing the actual filename.
1947 */
1948 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1949 mObbState.callerUid);
1950 replaceObbState(mObbState, newObbState);
1951 mObbState = newObbState;
1952 }
Kenny Root05105f72010-09-22 17:29:43 -07001953 }
1954
Kenny Roota02b8b02010-08-05 16:14:17 -07001955 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1956 throw new IllegalArgumentException("Caller package does not match OBB file");
1957 }
1958
1959 if (mKey == null) {
1960 mKey = "none";
1961 }
1962
Kenny Root38cf8862010-09-26 14:18:51 -07001963 boolean mounted = false;
1964 int rc;
1965 synchronized (mObbState) {
1966 if (mObbState.mounted) {
1967 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1968 return;
1969 }
1970
1971 rc = StorageResultCode.OperationSucceeded;
1972 String cmd = String.format("obb mount %s %s %d", mObbState.filename, mKey,
1973 mObbState.callerUid);
1974 try {
1975 mConnector.doCommand(cmd);
1976 } catch (NativeDaemonConnectorException e) {
1977 int code = e.getCode();
1978 if (code != VoldResponseCode.OpFailedStorageBusy) {
1979 rc = StorageResultCode.OperationFailedInternalError;
1980 }
1981 }
1982
1983 if (rc == StorageResultCode.OperationSucceeded) {
1984 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001985 }
1986 }
1987
Kenny Root38cf8862010-09-26 14:18:51 -07001988 if (mounted) {
1989 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001990 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001991 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001992
1993 // We didn't succeed, so remove this from the mount-set.
1994 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07001995
Kenny Root38cf8862010-09-26 14:18:51 -07001996 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001997 }
1998 }
1999
Kenny Roota02b8b02010-08-05 16:14:17 -07002000 public void handleError() {
2001 removeObbState(mObbState);
2002
Kenny Root38cf8862010-09-26 14:18:51 -07002003 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07002004 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002005
2006 @Override
2007 public String toString() {
2008 StringBuilder sb = new StringBuilder();
2009 sb.append("MountObbAction{");
2010 sb.append("filename=");
2011 sb.append(mObbState.filename);
2012 sb.append(",callerUid=");
2013 sb.append(mObbState.callerUid);
2014 sb.append(",token=");
2015 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2016 sb.append('}');
2017 return sb.toString();
2018 }
2019 }
2020
2021 class UnmountObbAction extends ObbAction {
2022 private boolean mForceUnmount;
2023
2024 UnmountObbAction(ObbState obbState, boolean force) {
2025 super(obbState);
2026 mForceUnmount = force;
2027 }
2028
Kenny Root38cf8862010-09-26 14:18:51 -07002029 public void handleExecute() throws IOException {
2030 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002031
Kenny Root38cf8862010-09-26 14:18:51 -07002032 /*
2033 * If someone tried to trick us with some weird characters, rectify
2034 * it here.
2035 */
2036 synchronized (mObbMounts) {
2037 if (!isObbMounted(obbInfo.filename)) {
2038 removeObbState(mObbState);
2039 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2040 return;
2041 }
2042
2043 if (!mObbState.filename.equals(obbInfo.filename)) {
2044 removeObbState(mObbState);
2045 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002046 }
2047 }
2048
Kenny Root38cf8862010-09-26 14:18:51 -07002049 boolean unmounted = false;
2050 synchronized (mObbState) {
2051 if (!mObbState.mounted) {
2052 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2053 return;
2054 }
2055
2056 int rc = StorageResultCode.OperationSucceeded;
2057 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2058 (mForceUnmount ? " force" : ""));
2059 try {
2060 mConnector.doCommand(cmd);
2061 } catch (NativeDaemonConnectorException e) {
2062 int code = e.getCode();
2063 if (code == VoldResponseCode.OpFailedStorageBusy) {
2064 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002065 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2066 // If it's not mounted then we've already won.
2067 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002068 } else {
2069 rc = StorageResultCode.OperationFailedInternalError;
2070 }
2071 }
2072
2073 if (rc == StorageResultCode.OperationSucceeded) {
2074 mObbState.mounted = false;
2075 unmounted = true;
2076 }
2077 }
2078
2079 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002080 removeObbState(mObbState);
2081
Kenny Root38cf8862010-09-26 14:18:51 -07002082 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002083 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002084 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002085 }
2086 }
2087
2088 public void handleError() {
2089 removeObbState(mObbState);
2090
Kenny Root38cf8862010-09-26 14:18:51 -07002091 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002092 }
2093
2094 @Override
2095 public String toString() {
2096 StringBuilder sb = new StringBuilder();
2097 sb.append("UnmountObbAction{");
2098 sb.append("filename=");
2099 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2100 sb.append(",force=");
2101 sb.append(mForceUnmount);
2102 sb.append(",callerUid=");
2103 sb.append(mObbState.callerUid);
2104 sb.append(",token=");
2105 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002106 sb.append(",binder=");
2107 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002108 sb.append('}');
2109 return sb.toString();
2110 }
Kenny Root02c87302010-07-01 08:10:18 -07002111 }
Kenny Root38cf8862010-09-26 14:18:51 -07002112
2113 @Override
2114 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2115 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2116 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2117 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2118 + " without permission " + android.Manifest.permission.DUMP);
2119 return;
2120 }
2121
2122 pw.println(" mObbMounts:");
2123
2124 synchronized (mObbMounts) {
2125 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2126
2127 for (final List<ObbState> obbStates : obbStateLists) {
2128 for (final ObbState obbState : obbStates) {
2129 pw.print(" "); pw.println(obbState.toString());
2130 }
2131 }
2132 }
2133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134}
2135