blob: 3b2d83600faf3f311b9c129b50597b8e0b2c7652 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Kenny Root735de3b2010-09-30 14:11:39 -070020import com.android.internal.util.HexDump;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
47import android.os.storage.StorageResultCode;
Kenny Root735de3b2010-09-30 14:11:39 -070048import android.security.MessageDigest;
San Mehata5078592010-03-25 09:36:54 -070049import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070050
Kenny Root38cf8862010-09-26 14:18:51 -070051import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070052import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.io.PrintWriter;
Kenny Root735de3b2010-09-30 14:11:39 -070054import java.security.NoSuchAlgorithmException;
San Mehat22dd86e2010-01-12 12:21:18 -080055import java.util.ArrayList;
Kenny Root38cf8862010-09-26 14:18:51 -070056import java.util.Collection;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080058import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070059import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.LinkedList;
61import java.util.List;
62import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
San Mehatb1043402010-02-05 08:26:50 -080066 * MountService implements back-end services for platform storage
67 * management.
68 * @hide - Applications should use android.os.storage.StorageManager
69 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 */
San Mehat22dd86e2010-01-12 12:21:18 -080071class MountService extends IMountService.Stub
72 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080073 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080074 private static final boolean DEBUG_UNMOUNT = false;
75 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070076 private static final boolean DEBUG_OBB = true;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "MountService";
79
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String VOLD_TAG = "VoldConnector";
81
San Mehat4270e1e2010-01-29 05:32:19 -080082 /*
83 * Internal vold volume state constants
84 */
San Mehat7fd0fee2009-12-17 07:12:23 -080085 class VolumeState {
86 public static final int Init = -1;
87 public static final int NoMedia = 0;
88 public static final int Idle = 1;
89 public static final int Pending = 2;
90 public static final int Checking = 3;
91 public static final int Mounted = 4;
92 public static final int Unmounting = 5;
93 public static final int Formatting = 6;
94 public static final int Shared = 7;
95 public static final int SharedMnt = 8;
96 }
97
San Mehat4270e1e2010-01-29 05:32:19 -080098 /*
99 * Internal vold response code constants
100 */
San Mehat22dd86e2010-01-12 12:21:18 -0800101 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800102 /*
103 * 100 series - Requestion action was initiated; expect another reply
104 * before proceeding with a new command.
105 */
San Mehat22dd86e2010-01-12 12:21:18 -0800106 public static final int VolumeListResult = 110;
107 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800108 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800109
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * 200 series - Requestion action has been successfully completed.
112 */
113 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800114 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800115 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800116
San Mehat4270e1e2010-01-29 05:32:19 -0800117 /*
118 * 400 series - Command was accepted, but the requested action
119 * did not take place.
120 */
121 public static final int OpFailedNoMedia = 401;
122 public static final int OpFailedMediaBlank = 402;
123 public static final int OpFailedMediaCorrupt = 403;
124 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800125 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700126 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800127
128 /*
129 * 600 series - Unsolicited broadcasts.
130 */
San Mehat22dd86e2010-01-12 12:21:18 -0800131 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800132 public static final int ShareAvailabilityChange = 620;
133 public static final int VolumeDiskInserted = 630;
134 public static final int VolumeDiskRemoved = 631;
135 public static final int VolumeBadRemoval = 632;
136 }
137
San Mehat4270e1e2010-01-29 05:32:19 -0800138 private Context mContext;
139 private NativeDaemonConnector mConnector;
140 private String mLegacyState = Environment.MEDIA_REMOVED;
141 private PackageManagerService mPms;
142 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800143 // Used as a lock for methods that register/unregister listeners.
144 final private ArrayList<MountServiceBinderListener> mListeners =
145 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800146 private boolean mBooted = false;
147 private boolean mReady = false;
148 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800149
San Mehat6cdd9c02010-02-09 14:45:20 -0800150 /**
151 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800152 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800153 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800154 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800155
Kenny Root02c87302010-07-01 08:10:18 -0700156 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700157 * Mounted OBB tracking information. Used to track the current state of all
158 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700159 */
Kenny Root735de3b2010-09-30 14:11:39 -0700160 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700161 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
162
163 class ObbState implements IBinder.DeathRecipient {
Kenny Root735de3b2010-09-30 14:11:39 -0700164 public ObbState(String filename, IObbActionListener token, int callerUid)
165 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700166 this.filename = filename;
167 this.token = token;
168 this.callerUid = callerUid;
169 mounted = false;
170 }
171
172 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700173 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700174
175 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700176 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700177
178 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700179 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700180
181 // Whether this is mounted currently.
182 boolean mounted;
183
Kenny Root735de3b2010-09-30 14:11:39 -0700184 public IBinder getBinder() {
185 return token.asBinder();
186 }
187
Kenny Roota02b8b02010-08-05 16:14:17 -0700188 @Override
189 public void binderDied() {
190 ObbAction action = new UnmountObbAction(this, true);
191 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700192 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700193
Kenny Root5919ac62010-10-05 09:49:40 -0700194 public void link() throws RemoteException {
195 getBinder().linkToDeath(this, 0);
196 }
197
198 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700199 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700200 }
Kenny Root38cf8862010-09-26 14:18:51 -0700201
202 @Override
203 public String toString() {
204 StringBuilder sb = new StringBuilder("ObbState{");
205 sb.append("filename=");
206 sb.append(filename);
207 sb.append(",token=");
208 sb.append(token.toString());
209 sb.append(",callerUid=");
210 sb.append(callerUid);
211 sb.append(",mounted=");
212 sb.append(mounted);
213 sb.append('}');
214 return sb.toString();
215 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700216 }
217
218 // OBB Action Handler
219 final private ObbActionHandler mObbActionHandler;
220
221 // OBB action handler messages
222 private static final int OBB_RUN_ACTION = 1;
223 private static final int OBB_MCS_BOUND = 2;
224 private static final int OBB_MCS_UNBIND = 3;
225 private static final int OBB_MCS_RECONNECT = 4;
Kenny Roota02b8b02010-08-05 16:14:17 -0700226
227 /*
228 * Default Container Service information
229 */
230 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
231 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
232
233 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
234
235 class DefaultContainerConnection implements ServiceConnection {
236 public void onServiceConnected(ComponentName name, IBinder service) {
237 if (DEBUG_OBB)
238 Slog.i(TAG, "onServiceConnected");
239 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
240 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
241 }
242
243 public void onServiceDisconnected(ComponentName name) {
244 if (DEBUG_OBB)
245 Slog.i(TAG, "onServiceDisconnected");
246 }
247 };
248
249 // Used in the ObbActionHandler
250 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700251
252 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800253 private static final int H_UNMOUNT_PM_UPDATE = 1;
254 private static final int H_UNMOUNT_PM_DONE = 2;
255 private static final int H_UNMOUNT_MS = 3;
256 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
257 private static final int MAX_UNMOUNT_RETRIES = 4;
258
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800259 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700260 final String path;
261 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800262 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800263
264 UnmountCallBack(String path, boolean force) {
265 retries = 0;
266 this.path = path;
267 this.force = force;
268 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800269
270 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700271 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800272 doUnmountVolume(path, true);
273 }
274 }
275
276 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700277 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800278
279 UmsEnableCallBack(String path, String method, boolean force) {
280 super(path, force);
281 this.method = method;
282 }
283
284 @Override
285 void handleFinished() {
286 super.handleFinished();
287 doShareUnshareVolume(path, method, true);
288 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800289 }
290
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800291 class ShutdownCallBack extends UnmountCallBack {
292 IMountShutdownObserver observer;
293 ShutdownCallBack(String path, IMountShutdownObserver observer) {
294 super(path, true);
295 this.observer = observer;
296 }
297
298 @Override
299 void handleFinished() {
300 int ret = doUnmountVolume(path, true);
301 if (observer != null) {
302 try {
303 observer.onShutDownComplete(ret);
304 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700305 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800306 }
307 }
308 }
309 }
310
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400311 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800312 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700313 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800314
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400315 MountServiceHandler(Looper l) {
316 super(l);
317 }
318
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800319 public void handleMessage(Message msg) {
320 switch (msg.what) {
321 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700322 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800323 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
324 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700325 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800326 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700327 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700328 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700329 mUpdatingStatus = true;
330 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800331 }
332 break;
333 }
334 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700335 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700336 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700337 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800338 int size = mForceUnmounts.size();
339 int sizeArr[] = new int[size];
340 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700341 // Kill processes holding references first
342 ActivityManagerService ams = (ActivityManagerService)
343 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800344 for (int i = 0; i < size; i++) {
345 UnmountCallBack ucb = mForceUnmounts.get(i);
346 String path = ucb.path;
347 boolean done = false;
348 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 done = true;
350 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800351 int pids[] = getStorageUsers(path);
352 if (pids == null || pids.length == 0) {
353 done = true;
354 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800355 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700356 ams.killPids(pids, "unmount media");
357 // Confirm if file references have been freed.
358 pids = getStorageUsers(path);
359 if (pids == null || pids.length == 0) {
360 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800361 }
362 }
363 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700364 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
365 // Retry again
366 Slog.i(TAG, "Retrying to kill storage users again");
367 mHandler.sendMessageDelayed(
368 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
369 ucb.retries++),
370 RETRY_UNMOUNT_DELAY);
371 } else {
372 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
373 Slog.i(TAG, "Failed to unmount media inspite of " +
374 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
375 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800376 sizeArr[sizeArrN++] = i;
377 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
378 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800379 }
380 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800381 // Remove already processed elements from list.
382 for (int i = (sizeArrN-1); i >= 0; i--) {
383 mForceUnmounts.remove(sizeArr[i]);
384 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800385 break;
386 }
387 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700388 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800389 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800390 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800391 break;
392 }
393 }
394 }
395 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400396 final private HandlerThread mHandlerThread;
397 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800398
San Mehat207e5382010-02-04 20:46:54 -0800399 private void waitForReady() {
400 while (mReady == false) {
401 for (int retries = 5; retries > 0; retries--) {
402 if (mReady) {
403 return;
404 }
405 SystemClock.sleep(1000);
406 }
San Mehata5078592010-03-25 09:36:54 -0700407 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800408 }
San Mehat1f6301e2010-01-07 22:40:27 -0800409 }
Kenny Root02c87302010-07-01 08:10:18 -0700410
San Mehat207e5382010-02-04 20:46:54 -0800411 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800413 String action = intent.getAction();
414
415 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800416 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800417
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800418 /*
419 * In the simulator, we need to broadcast a volume mounted event
420 * to make the media scanner run.
421 */
422 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
423 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
424 return;
425 }
San Mehatfafb0412010-02-18 19:40:04 -0800426 new Thread() {
427 public void run() {
428 try {
429 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700430 String state = getVolumeState(path);
431
432 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800433 int rc = doMountVolume(path);
434 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700435 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800436 }
San Mehat6a254402010-03-22 10:21:00 -0700437 } else if (state.equals(Environment.MEDIA_SHARED)) {
438 /*
439 * Bootstrap UMS enabled state since vold indicates
440 * the volume is shared (runtime restart while ums enabled)
441 */
442 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800443 }
San Mehat6a254402010-03-22 10:21:00 -0700444
San Mehat6a965af22010-02-24 17:47:30 -0800445 /*
San Mehat6a254402010-03-22 10:21:00 -0700446 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800447 * now that we're up.
448 */
449 if (mSendUmsConnectedOnBoot) {
450 sendUmsIntent(true);
451 mSendUmsConnectedOnBoot = false;
452 }
San Mehatfafb0412010-02-18 19:40:04 -0800453 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700454 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800455 }
San Mehat207e5382010-02-04 20:46:54 -0800456 }
San Mehatfafb0412010-02-18 19:40:04 -0800457 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 }
459 }
460 };
461
San Mehat4270e1e2010-01-29 05:32:19 -0800462 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
463 final IMountServiceListener mListener;
464
465 MountServiceBinderListener(IMountServiceListener listener) {
466 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700467
San Mehat91c77612010-01-07 10:39:41 -0800468 }
469
San Mehat4270e1e2010-01-29 05:32:19 -0800470 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700471 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700472 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800473 mListeners.remove(this);
474 mListener.asBinder().unlinkToDeath(this, 0);
475 }
476 }
477 }
478
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800479 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800480 // TODO: Add support for multiple share methods
481 if (!method.equals("ums")) {
482 throw new IllegalArgumentException(String.format("Method %s not supported", method));
483 }
484
San Mehat4270e1e2010-01-29 05:32:19 -0800485 try {
486 mConnector.doCommand(String.format(
487 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
488 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700489 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800490 }
San Mehat4270e1e2010-01-29 05:32:19 -0800491 }
492
San Mehat207e5382010-02-04 20:46:54 -0800493 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800494 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700495 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800496 return;
497 }
San Mehatb1043402010-02-05 08:26:50 -0800498
499 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700500 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800501 return;
502 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800503 // Update state on PackageManager
504 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700505 mPms.updateExternalMediaStatus(false, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800506 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700507 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800508 }
Kenny Root38cf8862010-09-26 14:18:51 -0700509
510 // Remove all OBB mappings and listeners from this path
511 synchronized (mObbMounts) {
512 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
513
514 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
515 while (i.hasNext()) {
516 final Entry<String, ObbState> obbEntry = i.next();
517
518 // If this entry's source file is in the volume path that got
519 // unmounted, remove it because it's no longer valid.
520 if (obbEntry.getKey().startsWith(path)) {
521 obbStatesToRemove.add(obbEntry.getValue());
522 }
523 }
524
525 for (final ObbState obbState : obbStatesToRemove) {
526 removeObbState(obbState);
527
528 try {
529 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
530 } catch (RemoteException e) {
531 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
532 + obbState.filename);
533 }
534 }
535 }
536
San Mehat4270e1e2010-01-29 05:32:19 -0800537 String oldState = mLegacyState;
538 mLegacyState = state;
539
540 synchronized (mListeners) {
541 for (int i = mListeners.size() -1; i >= 0; i--) {
542 MountServiceBinderListener bl = mListeners.get(i);
543 try {
San Mehatb1043402010-02-05 08:26:50 -0800544 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800545 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700546 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800547 mListeners.remove(i);
548 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700549 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800550 }
551 }
552 }
553 }
554
555 /**
556 *
557 * Callback from NativeDaemonConnector
558 */
559 public void onDaemonConnected() {
560 /*
561 * Since we'll be calling back into the NativeDaemonConnector,
562 * we need to do our work in a new thread.
563 */
564 new Thread() {
565 public void run() {
566 /**
567 * Determine media state and UMS detection status
568 */
569 String path = Environment.getExternalStorageDirectory().getPath();
570 String state = Environment.MEDIA_REMOVED;
571
572 try {
573 String[] vols = mConnector.doListCommand(
574 "volume list", VoldResponseCode.VolumeListResult);
575 for (String volstr : vols) {
576 String[] tok = volstr.split(" ");
577 // FMT: <label> <mountpoint> <state>
578 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700579 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800580 "Skipping unknown volume '%s'",tok[1]));
581 continue;
582 }
583 int st = Integer.parseInt(tok[2]);
584 if (st == VolumeState.NoMedia) {
585 state = Environment.MEDIA_REMOVED;
586 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800587 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800588 } else if (st == VolumeState.Mounted) {
589 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700590 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800591 } else if (st == VolumeState.Shared) {
592 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700593 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800594 } else {
595 throw new Exception(String.format("Unexpected state %d", st));
596 }
597 }
598 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700599 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800600 updatePublicVolumeState(path, state);
601 }
602 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700603 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800604 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
605 }
606
607 try {
San Mehat207e5382010-02-04 20:46:54 -0800608 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800609 notifyShareAvailabilityChange("ums", avail);
610 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700611 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800612 }
San Mehat207e5382010-02-04 20:46:54 -0800613 /*
614 * Now that we've done our initialization, release
615 * the hounds!
616 */
617 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800618 }
619 }.start();
620 }
621
622 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800623 * Callback from NativeDaemonConnector
624 */
625 public boolean onEvent(int code, String raw, String[] cooked) {
626 Intent in = null;
627
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800628 if (DEBUG_EVENTS) {
629 StringBuilder builder = new StringBuilder();
630 builder.append("onEvent::");
631 builder.append(" raw= " + raw);
632 if (cooked != null) {
633 builder.append(" cooked = " );
634 for (String str : cooked) {
635 builder.append(" " + str);
636 }
637 }
San Mehata5078592010-03-25 09:36:54 -0700638 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800639 }
San Mehat4270e1e2010-01-29 05:32:19 -0800640 if (code == VoldResponseCode.VolumeStateChange) {
641 /*
642 * One of the volumes we're managing has changed state.
643 * Format: "NNN Volume <label> <path> state changed
644 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
645 */
646 notifyVolumeStateChange(
647 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
648 Integer.parseInt(cooked[10]));
649 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
650 // FMT: NNN Share method <method> now <available|unavailable>
651 boolean avail = false;
652 if (cooked[5].equals("available")) {
653 avail = true;
654 }
655 notifyShareAvailabilityChange(cooked[3], avail);
656 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
657 (code == VoldResponseCode.VolumeDiskRemoved) ||
658 (code == VoldResponseCode.VolumeBadRemoval)) {
659 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
660 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
661 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
662 final String label = cooked[2];
663 final String path = cooked[3];
664 int major = -1;
665 int minor = -1;
666
667 try {
668 String devComp = cooked[6].substring(1, cooked[6].length() -1);
669 String[] devTok = devComp.split(":");
670 major = Integer.parseInt(devTok[0]);
671 minor = Integer.parseInt(devTok[1]);
672 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700673 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800674 }
675
San Mehat4270e1e2010-01-29 05:32:19 -0800676 if (code == VoldResponseCode.VolumeDiskInserted) {
677 new Thread() {
678 public void run() {
679 try {
680 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800681 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700682 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800683 }
684 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700685 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800686 }
687 }
688 }.start();
689 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
690 /*
691 * This event gets trumped if we're already in BAD_REMOVAL state
692 */
693 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
694 return true;
695 }
696 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700697 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800698 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
699 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
700 mContext.sendBroadcast(in);
701
San Mehata5078592010-03-25 09:36:54 -0700702 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800703 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
704 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
705 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700706 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800707 /* Send the media unmounted event first */
708 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
709 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
710 mContext.sendBroadcast(in);
711
San Mehata5078592010-03-25 09:36:54 -0700712 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800713 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
714 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
715 } else {
San Mehata5078592010-03-25 09:36:54 -0700716 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800717 }
718 } else {
719 return false;
720 }
721
722 if (in != null) {
723 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400724 }
725 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800726 }
727
San Mehat207e5382010-02-04 20:46:54 -0800728 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800729 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700730 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800731
732 Intent in = null;
733
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500734 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700735 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500736 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
737 Uri.parse("file://" + path)));
738 }
739
San Mehat4270e1e2010-01-29 05:32:19 -0800740 if (newState == VolumeState.Init) {
741 } else if (newState == VolumeState.NoMedia) {
742 // NoMedia is handled via Disk Remove events
743 } else if (newState == VolumeState.Idle) {
744 /*
745 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
746 * if we're in the process of enabling UMS
747 */
748 if (!vs.equals(
749 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
750 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800751 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700752 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800753 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
754 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
755 }
756 } else if (newState == VolumeState.Pending) {
757 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700758 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800759 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
760 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
761 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700762 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800763 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800764 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
765 in.putExtra("read-only", false);
766 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800767 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
768 } else if (newState == VolumeState.Formatting) {
769 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700770 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800771 /* Send the media unmounted event first */
772 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
773 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
774 mContext.sendBroadcast(in);
775
San Mehata5078592010-03-25 09:36:54 -0700776 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800777 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
778 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700779 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800780 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700781 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800782 return;
783 } else {
San Mehata5078592010-03-25 09:36:54 -0700784 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800785 }
786
787 if (in != null) {
788 mContext.sendBroadcast(in);
789 }
790 }
791
San Mehat207e5382010-02-04 20:46:54 -0800792 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700793 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700794 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700795 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700796 } catch (NativeDaemonConnectorException ex) {
797 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
798 return false;
799 }
San Mehat207e5382010-02-04 20:46:54 -0800800
801 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700802 String[] tok = line.split(" ");
803 if (tok.length < 3) {
804 Slog.e(TAG, "Malformed response to share status " + method);
805 return false;
806 }
807
San Mehat207e5382010-02-04 20:46:54 -0800808 int code;
809 try {
810 code = Integer.parseInt(tok[0]);
811 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700812 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800813 return false;
814 }
815 if (code == VoldResponseCode.ShareStatusResult) {
816 if (tok[2].equals("available"))
817 return true;
818 return false;
819 } else {
San Mehata5078592010-03-25 09:36:54 -0700820 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800821 return false;
822 }
823 }
San Mehata5078592010-03-25 09:36:54 -0700824 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800825 return false;
826 }
827
828 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800829 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800830
San Mehata5078592010-03-25 09:36:54 -0700831 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800832 try {
833 mConnector.doCommand(String.format("volume mount %s", path));
834 } catch (NativeDaemonConnectorException e) {
835 /*
836 * Mount failed for some reason
837 */
838 Intent in = null;
839 int code = e.getCode();
840 if (code == VoldResponseCode.OpFailedNoMedia) {
841 /*
842 * Attempt to mount but no media inserted
843 */
San Mehatb1043402010-02-05 08:26:50 -0800844 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800845 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700846 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800847 /*
848 * Media is blank or does not contain a supported filesystem
849 */
850 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
851 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800852 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800853 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700854 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800855 /*
856 * Volume consistency check failed
857 */
858 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
859 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800860 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800861 } else {
San Mehatb1043402010-02-05 08:26:50 -0800862 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800863 }
864
865 /*
866 * Send broadcast intent (if required for the failure)
867 */
868 if (in != null) {
869 mContext.sendBroadcast(in);
870 }
871 }
872
873 return rc;
874 }
875
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800876 /*
877 * If force is not set, we do not unmount if there are
878 * processes holding references to the volume about to be unmounted.
879 * If force is set, all the processes holding references need to be
880 * killed via the ActivityManager before actually unmounting the volume.
881 * This might even take a while and might be retried after timed delays
882 * to make sure we dont end up in an instable state and kill some core
883 * processes.
884 */
San Mehatd9709982010-02-18 11:43:03 -0800885 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800886 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800887 return VoldResponseCode.OpFailedVolNotMounted;
888 }
Kenny Rootaa485402010-09-14 14:49:41 -0700889
890 /*
891 * Force a GC to make sure AssetManagers in other threads of the
892 * system_server are cleaned up. We have to do this since AssetManager
893 * instances are kept as a WeakReference and it's possible we have files
894 * open on the external storage.
895 */
896 Runtime.getRuntime().gc();
897
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800898 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700899 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800900 try {
San Mehatd9709982010-02-18 11:43:03 -0800901 mConnector.doCommand(String.format(
902 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700903 // We unmounted the volume. None of the asec containers are available now.
904 synchronized (mAsecMountSet) {
905 mAsecMountSet.clear();
906 }
San Mehatb1043402010-02-05 08:26:50 -0800907 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800908 } catch (NativeDaemonConnectorException e) {
909 // Don't worry about mismatch in PackageManager since the
910 // call back will handle the status changes any way.
911 int code = e.getCode();
912 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800913 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800914 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
915 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800916 } else {
San Mehatb1043402010-02-05 08:26:50 -0800917 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800918 }
919 }
920 }
921
922 private int doFormatVolume(String path) {
923 try {
924 String cmd = String.format("volume format %s", path);
925 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800926 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800927 } catch (NativeDaemonConnectorException e) {
928 int code = e.getCode();
929 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800930 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800931 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800932 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800933 } else {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800935 }
936 }
937 }
938
San Mehatb1043402010-02-05 08:26:50 -0800939 private boolean doGetVolumeShared(String path, String method) {
940 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700941 ArrayList<String> rsp;
942
943 try {
944 rsp = mConnector.doCommand(cmd);
945 } catch (NativeDaemonConnectorException ex) {
946 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
947 return false;
948 }
San Mehatb1043402010-02-05 08:26:50 -0800949
950 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700951 String[] tok = line.split(" ");
952 if (tok.length < 3) {
953 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
954 return false;
955 }
956
San Mehatb1043402010-02-05 08:26:50 -0800957 int code;
958 try {
959 code = Integer.parseInt(tok[0]);
960 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700961 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800962 return false;
963 }
964 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700965 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800966 } else {
San Mehata5078592010-03-25 09:36:54 -0700967 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800968 return false;
969 }
970 }
San Mehata5078592010-03-25 09:36:54 -0700971 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800972 return false;
973 }
974
San Mehat207e5382010-02-04 20:46:54 -0800975 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800976 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700977 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800978 return;
979 }
980
981 synchronized (mListeners) {
982 for (int i = mListeners.size() -1; i >= 0; i--) {
983 MountServiceBinderListener bl = mListeners.get(i);
984 try {
San Mehatb1043402010-02-05 08:26:50 -0800985 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800986 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700987 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800988 mListeners.remove(i);
989 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700990 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800991 }
992 }
993 }
994
San Mehat207e5382010-02-04 20:46:54 -0800995 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800996 sendUmsIntent(avail);
997 } else {
998 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800999 }
San Mehat2fe718a2010-03-11 12:01:49 -08001000
1001 final String path = Environment.getExternalStorageDirectory().getPath();
1002 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1003 /*
1004 * USB mass storage disconnected while enabled
1005 */
1006 new Thread() {
1007 public void run() {
1008 try {
1009 int rc;
San Mehata5078592010-03-25 09:36:54 -07001010 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001011 doShareUnshareVolume(path, "ums", false);
1012 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001013 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001014 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1015 path, rc));
1016 }
1017 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001018 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001019 }
1020 }
1021 }.start();
1022 }
San Mehat4270e1e2010-01-29 05:32:19 -08001023 }
1024
San Mehat6a965af22010-02-24 17:47:30 -08001025 private void sendUmsIntent(boolean c) {
1026 mContext.sendBroadcast(
1027 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1028 }
1029
San Mehat207e5382010-02-04 20:46:54 -08001030 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001031 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1032 throw new SecurityException(String.format("Requires %s permission", perm));
1033 }
1034 }
1035
1036 /**
San Mehat207e5382010-02-04 20:46:54 -08001037 * Constructs a new MountService instance
1038 *
1039 * @param context Binder context for this service
1040 */
1041 public MountService(Context context) {
1042 mContext = context;
1043
San Mehat207e5382010-02-04 20:46:54 -08001044 // XXX: This will go away soon in favor of IMountServiceObserver
1045 mPms = (PackageManagerService) ServiceManager.getService("package");
1046
1047 mContext.registerReceiver(mBroadcastReceiver,
1048 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1049
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001050 mHandlerThread = new HandlerThread("MountService");
1051 mHandlerThread.start();
1052 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1053
Kenny Roota02b8b02010-08-05 16:14:17 -07001054 // Add OBB Action Handler to MountService thread.
1055 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1056
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001057 /*
1058 * Vold does not run in the simulator, so pretend the connector thread
1059 * ran and did its thing.
1060 */
1061 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1062 mReady = true;
1063 mUmsEnabling = true;
1064 return;
1065 }
1066
Kenny Root305bcbf2010-09-03 07:56:38 -07001067 /*
1068 * Create the connection to vold with a maximum queue of twice the
1069 * amount of containers we'd ever expect to have. This keeps an
1070 * "asec list" from blocking a thread repeatedly.
1071 */
1072 mConnector = new NativeDaemonConnector(this, "vold",
1073 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001074 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001075 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001076 thread.start();
1077 }
1078
1079 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001080 * Exposed API calls below here
1081 */
1082
1083 public void registerListener(IMountServiceListener listener) {
1084 synchronized (mListeners) {
1085 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1086 try {
1087 listener.asBinder().linkToDeath(bl, 0);
1088 mListeners.add(bl);
1089 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001090 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001091 }
1092 }
1093 }
1094
1095 public void unregisterListener(IMountServiceListener listener) {
1096 synchronized (mListeners) {
1097 for(MountServiceBinderListener bl : mListeners) {
1098 if (bl.mListener == listener) {
1099 mListeners.remove(mListeners.indexOf(bl));
1100 return;
1101 }
1102 }
1103 }
1104 }
1105
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001106 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001107 validatePermission(android.Manifest.permission.SHUTDOWN);
1108
San Mehata5078592010-03-25 09:36:54 -07001109 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001110
1111 String path = Environment.getExternalStorageDirectory().getPath();
1112 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001113
1114 if (state.equals(Environment.MEDIA_SHARED)) {
1115 /*
1116 * If the media is currently shared, unshare it.
1117 * XXX: This is still dangerous!. We should not
1118 * be rebooting at *all* if UMS is enabled, since
1119 * the UMS host could have dirty FAT cache entries
1120 * yet to flush.
1121 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001122 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001123 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1124 /*
1125 * If the media is being checked, then we need to wait for
1126 * it to complete before being able to proceed.
1127 */
1128 // XXX: @hackbod - Should we disable the ANR timer here?
1129 int retries = 30;
1130 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1131 try {
1132 Thread.sleep(1000);
1133 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001134 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001135 break;
1136 }
1137 state = Environment.getExternalStorageState();
1138 }
1139 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001140 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001141 }
1142 }
1143
1144 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001145 // Post a unmount message.
1146 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1147 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001148 }
1149 }
1150
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001151 private boolean getUmsEnabling() {
1152 synchronized (mListeners) {
1153 return mUmsEnabling;
1154 }
1155 }
1156
1157 private void setUmsEnabling(boolean enable) {
1158 synchronized (mListeners) {
1159 mUmsEnabling = true;
1160 }
1161 }
1162
San Mehatb1043402010-02-05 08:26:50 -08001163 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001164 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001165
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001166 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001167 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001168 }
San Mehatb1043402010-02-05 08:26:50 -08001169 return doGetShareMethodAvailable("ums");
1170 }
1171
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001172 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001173 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001174 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001175
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001176 // TODO: Add support for multiple share methods
1177
1178 /*
1179 * If the volume is mounted and we're enabling then unmount it
1180 */
1181 String path = Environment.getExternalStorageDirectory().getPath();
1182 String vs = getVolumeState(path);
1183 String method = "ums";
1184 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1185 // Override for isUsbMassStorageEnabled()
1186 setUmsEnabling(enable);
1187 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1188 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1189 // Clear override
1190 setUmsEnabling(false);
1191 }
1192 /*
1193 * If we disabled UMS then mount the volume
1194 */
1195 if (!enable) {
1196 doShareUnshareVolume(path, method, enable);
1197 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001198 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001199 " after disabling share method " + method);
1200 /*
1201 * Even though the mount failed, the unshare didn't so don't indicate an error.
1202 * The mountVolume() call will have set the storage state and sent the necessary
1203 * broadcasts.
1204 */
1205 }
1206 }
San Mehatb1043402010-02-05 08:26:50 -08001207 }
1208
1209 public boolean isUsbMassStorageEnabled() {
1210 waitForReady();
1211 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
San Mehat4270e1e2010-01-29 05:32:19 -08001213
San Mehat7fd0fee2009-12-17 07:12:23 -08001214 /**
1215 * @return state of the volume at the specified mount point
1216 */
San Mehat4270e1e2010-01-29 05:32:19 -08001217 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001218 /*
1219 * XXX: Until we have multiple volume discovery, just hardwire
1220 * this to /sdcard
1221 */
1222 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001223 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001224 throw new IllegalArgumentException();
1225 }
1226
1227 return mLegacyState;
1228 }
1229
San Mehat4270e1e2010-01-29 05:32:19 -08001230 public int mountVolume(String path) {
1231 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001232
San Mehat207e5382010-02-04 20:46:54 -08001233 waitForReady();
1234 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001237 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001238 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001239 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001241 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001242 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001243 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1244 Environment.MEDIA_REMOVED.equals(volState) ||
1245 Environment.MEDIA_SHARED.equals(volState) ||
1246 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1247 // Media already unmounted or cannot be unmounted.
1248 // TODO return valid return code when adding observer call back.
1249 return;
1250 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001251 UnmountCallBack ucb = new UnmountCallBack(path, force);
1252 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
1254
San Mehat4270e1e2010-01-29 05:32:19 -08001255 public int formatVolume(String path) {
1256 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001257 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001258
San Mehat207e5382010-02-04 20:46:54 -08001259 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261
San Mehatc1b4ce92010-02-16 17:13:03 -08001262 public int []getStorageUsers(String path) {
1263 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1264 waitForReady();
1265 try {
1266 String[] r = mConnector.doListCommand(
1267 String.format("storage users %s", path),
1268 VoldResponseCode.StorageUsersListResult);
1269 // FMT: <pid> <process name>
1270 int[] data = new int[r.length];
1271 for (int i = 0; i < r.length; i++) {
1272 String []tok = r[i].split(" ");
1273 try {
1274 data[i] = Integer.parseInt(tok[0]);
1275 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001276 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001277 return new int[0];
1278 }
1279 }
1280 return data;
1281 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001282 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001283 return new int[0];
1284 }
1285 }
1286
San Mehatb1043402010-02-05 08:26:50 -08001287 private void warnOnNotMounted() {
1288 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001289 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001290 }
1291 }
1292
San Mehat4270e1e2010-01-29 05:32:19 -08001293 public String[] getSecureContainerList() {
1294 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001295 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001296 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001297
San Mehat4270e1e2010-01-29 05:32:19 -08001298 try {
1299 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1300 } catch (NativeDaemonConnectorException e) {
1301 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 }
San Mehat36972292010-01-06 11:06:32 -08001304
San Mehat4270e1e2010-01-29 05:32:19 -08001305 public int createSecureContainer(String id, int sizeMb, String fstype,
1306 String key, int ownerUid) {
1307 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001308 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001309 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001310
San Mehatb1043402010-02-05 08:26:50 -08001311 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001312 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1313 try {
1314 mConnector.doCommand(cmd);
1315 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001316 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001317 }
San Mehata181b212010-02-11 06:50:20 -08001318
1319 if (rc == StorageResultCode.OperationSucceeded) {
1320 synchronized (mAsecMountSet) {
1321 mAsecMountSet.add(id);
1322 }
1323 }
San Mehat4270e1e2010-01-29 05:32:19 -08001324 return rc;
San Mehat36972292010-01-06 11:06:32 -08001325 }
1326
San Mehat4270e1e2010-01-29 05:32:19 -08001327 public int finalizeSecureContainer(String id) {
1328 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001329 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001330
San Mehatb1043402010-02-05 08:26:50 -08001331 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001332 try {
1333 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001334 /*
1335 * Finalization does a remount, so no need
1336 * to update mAsecMountSet
1337 */
San Mehat4270e1e2010-01-29 05:32:19 -08001338 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001339 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001340 }
San Mehat4270e1e2010-01-29 05:32:19 -08001341 return rc;
San Mehat36972292010-01-06 11:06:32 -08001342 }
1343
San Mehatd9709982010-02-18 11:43:03 -08001344 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001345 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001346 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001347 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001348
Kenny Rootaa485402010-09-14 14:49:41 -07001349 /*
1350 * Force a GC to make sure AssetManagers in other threads of the
1351 * system_server are cleaned up. We have to do this since AssetManager
1352 * instances are kept as a WeakReference and it's possible we have files
1353 * open on the external storage.
1354 */
1355 Runtime.getRuntime().gc();
1356
San Mehatb1043402010-02-05 08:26:50 -08001357 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001358 try {
San Mehatd9709982010-02-18 11:43:03 -08001359 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001360 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001361 int code = e.getCode();
1362 if (code == VoldResponseCode.OpFailedStorageBusy) {
1363 rc = StorageResultCode.OperationFailedStorageBusy;
1364 } else {
1365 rc = StorageResultCode.OperationFailedInternalError;
1366 }
San Mehat02735bc2010-01-26 15:18:08 -08001367 }
San Mehata181b212010-02-11 06:50:20 -08001368
1369 if (rc == StorageResultCode.OperationSucceeded) {
1370 synchronized (mAsecMountSet) {
1371 if (mAsecMountSet.contains(id)) {
1372 mAsecMountSet.remove(id);
1373 }
1374 }
1375 }
1376
San Mehat4270e1e2010-01-29 05:32:19 -08001377 return rc;
San Mehat36972292010-01-06 11:06:32 -08001378 }
1379
San Mehat4270e1e2010-01-29 05:32:19 -08001380 public int mountSecureContainer(String id, String key, int ownerUid) {
1381 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001382 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001383 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001384
San Mehata181b212010-02-11 06:50:20 -08001385 synchronized (mAsecMountSet) {
1386 if (mAsecMountSet.contains(id)) {
1387 return StorageResultCode.OperationFailedStorageMounted;
1388 }
1389 }
1390
San Mehatb1043402010-02-05 08:26:50 -08001391 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001392 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1393 try {
1394 mConnector.doCommand(cmd);
1395 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001396 int code = e.getCode();
1397 if (code != VoldResponseCode.OpFailedStorageBusy) {
1398 rc = StorageResultCode.OperationFailedInternalError;
1399 }
San Mehat02735bc2010-01-26 15:18:08 -08001400 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001401
1402 if (rc == StorageResultCode.OperationSucceeded) {
1403 synchronized (mAsecMountSet) {
1404 mAsecMountSet.add(id);
1405 }
1406 }
San Mehat4270e1e2010-01-29 05:32:19 -08001407 return rc;
San Mehat36972292010-01-06 11:06:32 -08001408 }
1409
San Mehatd9709982010-02-18 11:43:03 -08001410 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001411 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001412 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001413 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001414
San Mehat6cdd9c02010-02-09 14:45:20 -08001415 synchronized (mAsecMountSet) {
1416 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001417 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001418 }
1419 }
1420
Kenny Rootaa485402010-09-14 14:49:41 -07001421 /*
1422 * Force a GC to make sure AssetManagers in other threads of the
1423 * system_server are cleaned up. We have to do this since AssetManager
1424 * instances are kept as a WeakReference and it's possible we have files
1425 * open on the external storage.
1426 */
1427 Runtime.getRuntime().gc();
1428
San Mehatb1043402010-02-05 08:26:50 -08001429 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001430 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001431 try {
1432 mConnector.doCommand(cmd);
1433 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001434 int code = e.getCode();
1435 if (code == VoldResponseCode.OpFailedStorageBusy) {
1436 rc = StorageResultCode.OperationFailedStorageBusy;
1437 } else {
1438 rc = StorageResultCode.OperationFailedInternalError;
1439 }
San Mehat02735bc2010-01-26 15:18:08 -08001440 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001441
1442 if (rc == StorageResultCode.OperationSucceeded) {
1443 synchronized (mAsecMountSet) {
1444 mAsecMountSet.remove(id);
1445 }
1446 }
San Mehat4270e1e2010-01-29 05:32:19 -08001447 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001448 }
1449
San Mehat6cdd9c02010-02-09 14:45:20 -08001450 public boolean isSecureContainerMounted(String id) {
1451 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1452 waitForReady();
1453 warnOnNotMounted();
1454
1455 synchronized (mAsecMountSet) {
1456 return mAsecMountSet.contains(id);
1457 }
1458 }
1459
San Mehat4270e1e2010-01-29 05:32:19 -08001460 public int renameSecureContainer(String oldId, String newId) {
1461 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001462 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001463 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001464
San Mehata181b212010-02-11 06:50:20 -08001465 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001466 /*
1467 * Because a mounted container has active internal state which cannot be
1468 * changed while active, we must ensure both ids are not currently mounted.
1469 */
1470 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001471 return StorageResultCode.OperationFailedStorageMounted;
1472 }
1473 }
1474
San Mehatb1043402010-02-05 08:26:50 -08001475 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001476 String cmd = String.format("asec rename %s %s", oldId, newId);
1477 try {
1478 mConnector.doCommand(cmd);
1479 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001480 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001481 }
San Mehata181b212010-02-11 06:50:20 -08001482
San Mehat4270e1e2010-01-29 05:32:19 -08001483 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001484 }
1485
San Mehat4270e1e2010-01-29 05:32:19 -08001486 public String getSecureContainerPath(String id) {
1487 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001488 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001489 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001490
San Mehat2d66cef2010-03-23 11:12:52 -07001491 try {
1492 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1493 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001494 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001495 if (code != VoldResponseCode.AsecPathResult) {
1496 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1497 }
1498 return tok[1];
1499 } catch (NativeDaemonConnectorException e) {
1500 int code = e.getCode();
1501 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1502 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001503 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001504 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001505 }
1506 }
San Mehat22dd86e2010-01-12 12:21:18 -08001507 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001508
1509 public void finishMediaUpdate() {
1510 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1511 }
Kenny Root02c87302010-07-01 08:10:18 -07001512
Kenny Roota02b8b02010-08-05 16:14:17 -07001513 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1514 if (callerUid == android.os.Process.SYSTEM_UID) {
1515 return true;
1516 }
1517
Kenny Root02c87302010-07-01 08:10:18 -07001518 if (packageName == null) {
1519 return false;
1520 }
1521
1522 final int packageUid = mPms.getPackageUid(packageName);
1523
1524 if (DEBUG_OBB) {
1525 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1526 packageUid + ", callerUid = " + callerUid);
1527 }
1528
1529 return callerUid == packageUid;
1530 }
1531
1532 public String getMountedObbPath(String filename) {
1533 waitForReady();
1534 warnOnNotMounted();
1535
Kenny Root02c87302010-07-01 08:10:18 -07001536 try {
1537 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1538 String []tok = rsp.get(0).split(" ");
1539 int code = Integer.parseInt(tok[0]);
1540 if (code != VoldResponseCode.AsecPathResult) {
1541 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1542 }
1543 return tok[1];
1544 } catch (NativeDaemonConnectorException e) {
1545 int code = e.getCode();
1546 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001547 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001548 } else {
1549 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1550 }
1551 }
1552 }
1553
1554 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001555 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001556 final ObbState obbState = mObbPathToStateMap.get(filename);
1557 if (obbState != null) {
1558 synchronized (obbState) {
1559 return obbState.mounted;
1560 }
1561 }
Kenny Root02c87302010-07-01 08:10:18 -07001562 }
Kenny Root38cf8862010-09-26 14:18:51 -07001563 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001564 }
1565
Kenny Root735de3b2010-09-30 14:11:39 -07001566 public void mountObb(String filename, String key, IObbActionListener token)
1567 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001568 waitForReady();
1569 warnOnNotMounted();
1570
Kenny Rootf1121dc2010-09-29 07:30:53 -07001571 if (filename == null) {
1572 throw new IllegalArgumentException("filename cannot be null");
1573 } else if (token == null) {
1574 throw new IllegalArgumentException("token cannot be null");
1575 }
1576
Kenny Roota02b8b02010-08-05 16:14:17 -07001577 final ObbState obbState;
1578
1579 synchronized (mObbMounts) {
1580 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001581 try {
1582 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1583 } catch (RemoteException e) {
1584 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1585 }
1586 return;
Kenny Root02c87302010-07-01 08:10:18 -07001587 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001588
Kenny Roota02b8b02010-08-05 16:14:17 -07001589 final int callerUid = Binder.getCallingUid();
1590 obbState = new ObbState(filename, token, callerUid);
1591 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001592 }
1593
Kenny Root29423912010-10-01 08:37:20 -07001594 String hashedKey = null;
1595 if (key != null) {
1596 final MessageDigest md;
Kenny Root735de3b2010-09-30 14:11:39 -07001597 try {
Kenny Root29423912010-10-01 08:37:20 -07001598 md = MessageDigest.getInstance("MD5");
1599 } catch (NoSuchAlgorithmException e) {
1600 Slog.e(TAG, "Could not load MD5 algorithm", e);
1601 try {
1602 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1603 } catch (RemoteException e1) {
1604 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1605 }
1606 return;
Kenny Root735de3b2010-09-30 14:11:39 -07001607 }
Kenny Root02c87302010-07-01 08:10:18 -07001608
Kenny Root29423912010-10-01 08:37:20 -07001609 hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1610 }
Kenny Root735de3b2010-09-30 14:11:39 -07001611
1612 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001613 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1614
1615 if (DEBUG_OBB)
1616 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001617 }
1618
Kenny Roota02b8b02010-08-05 16:14:17 -07001619 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001620 if (filename == null) {
1621 throw new IllegalArgumentException("filename cannot be null");
1622 } else if (token == null) {
1623 throw new IllegalArgumentException("token cannot be null");
1624 }
1625
Kenny Roota02b8b02010-08-05 16:14:17 -07001626 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001627
Kenny Roota02b8b02010-08-05 16:14:17 -07001628 synchronized (mObbMounts) {
1629 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001630 try {
1631 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1632 } catch (RemoteException e) {
1633 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1634 }
1635 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001636 }
Kenny Root38cf8862010-09-26 14:18:51 -07001637
Kenny Roota02b8b02010-08-05 16:14:17 -07001638 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001639
1640 if (Binder.getCallingUid() != obbState.callerUid) {
1641 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001642 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001643 throw new SecurityException("caller does not match original mount caller");
1644 }
Kenny Root02c87302010-07-01 08:10:18 -07001645 }
1646
Kenny Root38cf8862010-09-26 14:18:51 -07001647 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001648 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001649
Kenny Roota02b8b02010-08-05 16:14:17 -07001650 if (DEBUG_OBB)
1651 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1652 }
1653
Kenny Root5919ac62010-10-05 09:49:40 -07001654 private void addObbState(ObbState obbState) throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -07001655 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001656 final IBinder binder = obbState.getBinder();
1657 List<ObbState> obbStates = mObbMounts.get(binder);
1658 final boolean unique;
1659
Kenny Root05105f72010-09-22 17:29:43 -07001660 if (obbStates == null) {
1661 obbStates = new ArrayList<ObbState>();
Kenny Root5919ac62010-10-05 09:49:40 -07001662 mObbMounts.put(binder, obbStates);
1663 unique = true;
1664 } else {
1665 unique = obbStates.contains(obbState);
Kenny Root05105f72010-09-22 17:29:43 -07001666 }
Kenny Root5919ac62010-10-05 09:49:40 -07001667
1668 if (unique) {
1669 obbStates.add(obbState);
1670 try {
1671 obbState.link();
1672 } catch (RemoteException e) {
1673 /*
1674 * The binder died before we could link it, so clean up our
1675 * state and return failure.
1676 */
1677 obbStates.remove(obbState);
1678 if (obbStates.isEmpty()) {
1679 mObbMounts.remove(binder);
1680 }
1681
1682 // Rethrow the error so mountObb can get it
1683 throw e;
1684 }
1685 }
1686
Kenny Roota02b8b02010-08-05 16:14:17 -07001687 mObbPathToStateMap.put(obbState.filename, obbState);
1688 }
1689 }
1690
1691 private void removeObbState(ObbState obbState) {
1692 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001693 final IBinder binder = obbState.getBinder();
1694 final List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root05105f72010-09-22 17:29:43 -07001695 if (obbStates != null) {
Kenny Root5919ac62010-10-05 09:49:40 -07001696 if (obbStates.remove(obbState)) {
1697 obbState.unlink();
1698 }
1699 if (obbStates.isEmpty()) {
1700 mObbMounts.remove(binder);
1701 }
Kenny Root05105f72010-09-22 17:29:43 -07001702 }
Kenny Root5919ac62010-10-05 09:49:40 -07001703
Kenny Roota02b8b02010-08-05 16:14:17 -07001704 mObbPathToStateMap.remove(obbState.filename);
1705 }
1706 }
1707
Kenny Root5919ac62010-10-05 09:49:40 -07001708 private void replaceObbState(ObbState oldObbState, ObbState newObbState) throws RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001709 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;
Kenny Root480afe72010-10-07 10:17:50 -07001717 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001718
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: {
Kenny Root480afe72010-10-07 10:17:50 -07001727 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001728
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 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001743 }
Kenny Root735de3b2010-09-30 14:11:39 -07001744
Kenny Root735de3b2010-09-30 14:11:39 -07001745 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001746 break;
1747 }
1748 case OBB_MCS_BOUND: {
1749 if (DEBUG_OBB)
1750 Slog.i(TAG, "OBB_MCS_BOUND");
1751 if (msg.obj != null) {
1752 mContainerService = (IMediaContainerService) msg.obj;
1753 }
1754 if (mContainerService == null) {
1755 // Something seriously wrong. Bail out
1756 Slog.e(TAG, "Cannot bind to media container service");
1757 for (ObbAction action : mActions) {
1758 // Indicate service bind error
1759 action.handleError();
1760 }
1761 mActions.clear();
1762 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001763 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001764 if (action != null) {
1765 action.execute(this);
1766 }
1767 } else {
1768 // Should never happen ideally.
1769 Slog.w(TAG, "Empty queue");
1770 }
1771 break;
1772 }
1773 case OBB_MCS_RECONNECT: {
1774 if (DEBUG_OBB)
1775 Slog.i(TAG, "OBB_MCS_RECONNECT");
1776 if (mActions.size() > 0) {
1777 if (mBound) {
1778 disconnectService();
1779 }
1780 if (!connectToService()) {
1781 Slog.e(TAG, "Failed to bind to media container service");
1782 for (ObbAction action : mActions) {
1783 // Indicate service bind error
1784 action.handleError();
1785 }
1786 mActions.clear();
1787 }
1788 }
1789 break;
1790 }
1791 case OBB_MCS_UNBIND: {
1792 if (DEBUG_OBB)
1793 Slog.i(TAG, "OBB_MCS_UNBIND");
1794
1795 // Delete pending install
1796 if (mActions.size() > 0) {
1797 mActions.remove(0);
1798 }
1799 if (mActions.size() == 0) {
1800 if (mBound) {
1801 disconnectService();
1802 }
1803 } else {
1804 // There are more pending requests in queue.
1805 // Just post MCS_BOUND message to trigger processing
1806 // of next pending install.
1807 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1808 }
1809 break;
1810 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001811 }
1812 }
1813
1814 private boolean connectToService() {
1815 if (DEBUG_OBB)
1816 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1817
1818 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1819 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1820 mBound = true;
1821 return true;
1822 }
1823 return false;
1824 }
1825
1826 private void disconnectService() {
1827 mContainerService = null;
1828 mBound = false;
1829 mContext.unbindService(mDefContainerConn);
1830 }
1831 }
1832
1833 abstract class ObbAction {
1834 private static final int MAX_RETRIES = 3;
1835 private int mRetries;
1836
1837 ObbState mObbState;
1838
1839 ObbAction(ObbState obbState) {
1840 mObbState = obbState;
1841 }
1842
1843 public void execute(ObbActionHandler handler) {
1844 try {
1845 if (DEBUG_OBB)
1846 Slog.i(TAG, "Starting to execute action: " + this.toString());
1847 mRetries++;
1848 if (mRetries > MAX_RETRIES) {
1849 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001850 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001851 handleError();
1852 return;
1853 } else {
1854 handleExecute();
1855 if (DEBUG_OBB)
1856 Slog.i(TAG, "Posting install MCS_UNBIND");
1857 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1858 }
1859 } catch (RemoteException e) {
1860 if (DEBUG_OBB)
1861 Slog.i(TAG, "Posting install MCS_RECONNECT");
1862 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1863 } catch (Exception e) {
1864 if (DEBUG_OBB)
1865 Slog.d(TAG, "Error handling OBB action", e);
1866 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001867 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001868 }
1869 }
1870
Kenny Root05105f72010-09-22 17:29:43 -07001871 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001872 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001873
1874 protected ObbInfo getObbInfo() throws IOException {
1875 ObbInfo obbInfo;
1876 try {
1877 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1878 } catch (RemoteException e) {
1879 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1880 + mObbState.filename);
1881 obbInfo = null;
1882 }
1883 if (obbInfo == null) {
1884 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1885 }
1886 return obbInfo;
1887 }
1888
1889 protected void sendNewStatusOrIgnore(String filename, String status) {
1890 try {
1891 mObbState.token.onObbResult(filename, status);
1892 } catch (RemoteException e) {
1893 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1894 }
1895 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001896 }
1897
1898 class MountObbAction extends ObbAction {
1899 private String mKey;
1900
1901 MountObbAction(ObbState obbState, String key) {
1902 super(obbState);
1903 mKey = key;
1904 }
1905
Kenny Root735de3b2010-09-30 14:11:39 -07001906 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001907 final ObbInfo obbInfo = getObbInfo();
1908
1909 /*
1910 * If someone tried to trick us with some weird characters, rectify
1911 * it here.
1912 */
1913 if (!mObbState.filename.equals(obbInfo.filename)) {
1914 if (DEBUG_OBB)
1915 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1916 + obbInfo.filename);
1917
1918 synchronized (mObbMounts) {
1919 /*
1920 * If the real filename is already mounted, discard this
1921 * state and notify the caller that the OBB is already
1922 * mounted.
1923 */
1924 if (isObbMounted(obbInfo.filename)) {
1925 if (DEBUG_OBB)
1926 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1927
1928 removeObbState(mObbState);
1929 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1930 return;
1931 }
1932
1933 /*
1934 * It's not already mounted, so we have to replace the state
1935 * with the state containing the actual filename.
1936 */
1937 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1938 mObbState.callerUid);
1939 replaceObbState(mObbState, newObbState);
1940 mObbState = newObbState;
1941 }
Kenny Root05105f72010-09-22 17:29:43 -07001942 }
1943
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1945 throw new IllegalArgumentException("Caller package does not match OBB file");
1946 }
1947
Kenny Root38cf8862010-09-26 14:18:51 -07001948 boolean mounted = false;
1949 int rc;
1950 synchronized (mObbState) {
1951 if (mObbState.mounted) {
1952 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1953 return;
1954 }
1955
1956 rc = StorageResultCode.OperationSucceeded;
Kenny Root12ffd9b2010-10-01 12:56:59 -07001957 String cmd = String.format("obb mount %s %s %d", mObbState.filename,
1958 mKey != null ? mKey : "none",
Kenny Root38cf8862010-09-26 14:18:51 -07001959 mObbState.callerUid);
1960 try {
1961 mConnector.doCommand(cmd);
1962 } catch (NativeDaemonConnectorException e) {
1963 int code = e.getCode();
1964 if (code != VoldResponseCode.OpFailedStorageBusy) {
1965 rc = StorageResultCode.OperationFailedInternalError;
1966 }
1967 }
1968
1969 if (rc == StorageResultCode.OperationSucceeded) {
1970 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001971 }
1972 }
1973
Kenny Root38cf8862010-09-26 14:18:51 -07001974 if (mounted) {
1975 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001976 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001977 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001978
1979 // We didn't succeed, so remove this from the mount-set.
1980 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07001981
Kenny Root38cf8862010-09-26 14:18:51 -07001982 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001983 }
1984 }
1985
Kenny Roota02b8b02010-08-05 16:14:17 -07001986 public void handleError() {
1987 removeObbState(mObbState);
1988
Kenny Root38cf8862010-09-26 14:18:51 -07001989 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07001990 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001991
1992 @Override
1993 public String toString() {
1994 StringBuilder sb = new StringBuilder();
1995 sb.append("MountObbAction{");
1996 sb.append("filename=");
1997 sb.append(mObbState.filename);
1998 sb.append(",callerUid=");
1999 sb.append(mObbState.callerUid);
2000 sb.append(",token=");
2001 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2002 sb.append('}');
2003 return sb.toString();
2004 }
2005 }
2006
2007 class UnmountObbAction extends ObbAction {
2008 private boolean mForceUnmount;
2009
2010 UnmountObbAction(ObbState obbState, boolean force) {
2011 super(obbState);
2012 mForceUnmount = force;
2013 }
2014
Kenny Root38cf8862010-09-26 14:18:51 -07002015 public void handleExecute() throws IOException {
2016 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002017
Kenny Root38cf8862010-09-26 14:18:51 -07002018 /*
2019 * If someone tried to trick us with some weird characters, rectify
2020 * it here.
2021 */
2022 synchronized (mObbMounts) {
2023 if (!isObbMounted(obbInfo.filename)) {
2024 removeObbState(mObbState);
2025 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2026 return;
2027 }
2028
2029 if (!mObbState.filename.equals(obbInfo.filename)) {
2030 removeObbState(mObbState);
2031 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002032 }
2033 }
2034
Kenny Root38cf8862010-09-26 14:18:51 -07002035 boolean unmounted = false;
2036 synchronized (mObbState) {
2037 if (!mObbState.mounted) {
2038 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2039 return;
2040 }
2041
2042 int rc = StorageResultCode.OperationSucceeded;
2043 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2044 (mForceUnmount ? " force" : ""));
2045 try {
2046 mConnector.doCommand(cmd);
2047 } catch (NativeDaemonConnectorException e) {
2048 int code = e.getCode();
2049 if (code == VoldResponseCode.OpFailedStorageBusy) {
2050 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002051 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2052 // If it's not mounted then we've already won.
2053 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002054 } else {
2055 rc = StorageResultCode.OperationFailedInternalError;
2056 }
2057 }
2058
2059 if (rc == StorageResultCode.OperationSucceeded) {
2060 mObbState.mounted = false;
2061 unmounted = true;
2062 }
2063 }
2064
2065 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002066 removeObbState(mObbState);
2067
Kenny Root38cf8862010-09-26 14:18:51 -07002068 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002069 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002070 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002071 }
2072 }
2073
2074 public void handleError() {
2075 removeObbState(mObbState);
2076
Kenny Root38cf8862010-09-26 14:18:51 -07002077 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002078 }
2079
2080 @Override
2081 public String toString() {
2082 StringBuilder sb = new StringBuilder();
2083 sb.append("UnmountObbAction{");
2084 sb.append("filename=");
2085 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2086 sb.append(",force=");
2087 sb.append(mForceUnmount);
2088 sb.append(",callerUid=");
2089 sb.append(mObbState.callerUid);
2090 sb.append(",token=");
2091 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002092 sb.append(",binder=");
2093 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002094 sb.append('}');
2095 return sb.toString();
2096 }
Kenny Root02c87302010-07-01 08:10:18 -07002097 }
Kenny Root38cf8862010-09-26 14:18:51 -07002098
2099 @Override
2100 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2101 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2102 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2103 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2104 + " without permission " + android.Manifest.permission.DUMP);
2105 return;
2106 }
2107
2108 pw.println(" mObbMounts:");
2109
2110 synchronized (mObbMounts) {
2111 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2112
2113 for (final List<ObbState> obbStates : obbStateLists) {
2114 for (final ObbState obbState : obbStates) {
2115 pw.print(" "); pw.println(obbState.toString());
2116 }
2117 }
2118 }
2119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120}
2121