blob: 62dec7ec3eb7b8e96f87434d7875cd89be97ff64 [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;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020import com.android.server.am.ActivityManagerService;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070029import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070032import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080033import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040034import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070035import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040036import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080037import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080038import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080039import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080040import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.storage.IMountService;
43import android.os.storage.IMountServiceListener;
44import android.os.storage.IMountShutdownObserver;
45import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070046import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070047import android.os.storage.StorageResultCode;
San Mehata5078592010-03-25 09:36:54 -070048import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070049
Kenny Root38cf8862010-09-26 14:18:51 -070050import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070051import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070052import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070053import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070054import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070055import java.security.spec.InvalidKeySpecException;
56import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080057import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070058import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080059import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070060import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070061import java.util.LinkedList;
62import java.util.List;
63import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070064import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Kenny Root3b1abba2010-10-13 15:00:07 -070066import javax.crypto.SecretKey;
67import javax.crypto.SecretKeyFactory;
68import javax.crypto.spec.PBEKeySpec;
69
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070/**
San Mehatb1043402010-02-05 08:26:50 -080071 * MountService implements back-end services for platform storage
72 * management.
73 * @hide - Applications should use android.os.storage.StorageManager
74 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 */
San Mehat22dd86e2010-01-12 12:21:18 -080076class MountService extends IMountService.Stub
77 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080078 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080079 private static final boolean DEBUG_UNMOUNT = false;
80 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070081 private static final boolean DEBUG_OBB = true;
82
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final String TAG = "MountService";
84
Kenny Root305bcbf2010-09-03 07:56:38 -070085 private static final String VOLD_TAG = "VoldConnector";
86
San Mehat4270e1e2010-01-29 05:32:19 -080087 /*
88 * Internal vold volume state constants
89 */
San Mehat7fd0fee2009-12-17 07:12:23 -080090 class VolumeState {
91 public static final int Init = -1;
92 public static final int NoMedia = 0;
93 public static final int Idle = 1;
94 public static final int Pending = 2;
95 public static final int Checking = 3;
96 public static final int Mounted = 4;
97 public static final int Unmounting = 5;
98 public static final int Formatting = 6;
99 public static final int Shared = 7;
100 public static final int SharedMnt = 8;
101 }
102
San Mehat4270e1e2010-01-29 05:32:19 -0800103 /*
104 * Internal vold response code constants
105 */
San Mehat22dd86e2010-01-12 12:21:18 -0800106 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800107 /*
108 * 100 series - Requestion action was initiated; expect another reply
109 * before proceeding with a new command.
110 */
San Mehat22dd86e2010-01-12 12:21:18 -0800111 public static final int VolumeListResult = 110;
112 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800113 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800114
San Mehat4270e1e2010-01-29 05:32:19 -0800115 /*
116 * 200 series - Requestion action has been successfully completed.
117 */
118 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800119 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800120 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800121
San Mehat4270e1e2010-01-29 05:32:19 -0800122 /*
123 * 400 series - Command was accepted, but the requested action
124 * did not take place.
125 */
126 public static final int OpFailedNoMedia = 401;
127 public static final int OpFailedMediaBlank = 402;
128 public static final int OpFailedMediaCorrupt = 403;
129 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800130 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700131 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800132
133 /*
134 * 600 series - Unsolicited broadcasts.
135 */
San Mehat22dd86e2010-01-12 12:21:18 -0800136 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800137 public static final int ShareAvailabilityChange = 620;
138 public static final int VolumeDiskInserted = 630;
139 public static final int VolumeDiskRemoved = 631;
140 public static final int VolumeBadRemoval = 632;
141 }
142
San Mehat4270e1e2010-01-29 05:32:19 -0800143 private Context mContext;
144 private NativeDaemonConnector mConnector;
145 private String mLegacyState = Environment.MEDIA_REMOVED;
146 private PackageManagerService mPms;
147 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800148 // Used as a lock for methods that register/unregister listeners.
149 final private ArrayList<MountServiceBinderListener> mListeners =
150 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800151 private boolean mBooted = false;
152 private boolean mReady = false;
153 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400154 // true if we should fake MEDIA_MOUNTED state for external storage
155 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800156
San Mehat6cdd9c02010-02-09 14:45:20 -0800157 /**
158 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800159 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800160 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800161 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800162
Kenny Root02c87302010-07-01 08:10:18 -0700163 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700164 * The size of the crypto algorithm key in bits for OBB files. Currently
165 * Twofish is used which takes 128-bit keys.
166 */
167 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
168
169 /**
170 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
171 * 1024 is reasonably secure and not too slow.
172 */
173 private static final int PBKDF2_HASH_ROUNDS = 1024;
174
175 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700176 * Mounted OBB tracking information. Used to track the current state of all
177 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700178 */
Kenny Root735de3b2010-09-30 14:11:39 -0700179 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700180 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
181
182 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700183 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700184 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700185 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700186 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700187 this.token = token;
188 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700189 }
190
191 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700192 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700193
194 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700195 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700196
Kenny Rootaf9d6672010-10-08 09:21:39 -0700197 // Token of remote Binder caller
198 final IObbActionListener token;
199
200 // Identifier to pass back to the token
201 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700202
Kenny Root735de3b2010-09-30 14:11:39 -0700203 public IBinder getBinder() {
204 return token.asBinder();
205 }
206
Kenny Roota02b8b02010-08-05 16:14:17 -0700207 @Override
208 public void binderDied() {
209 ObbAction action = new UnmountObbAction(this, true);
210 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700211 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700212
Kenny Root5919ac62010-10-05 09:49:40 -0700213 public void link() throws RemoteException {
214 getBinder().linkToDeath(this, 0);
215 }
216
217 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700218 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700219 }
Kenny Root38cf8862010-09-26 14:18:51 -0700220
221 @Override
222 public String toString() {
223 StringBuilder sb = new StringBuilder("ObbState{");
224 sb.append("filename=");
225 sb.append(filename);
226 sb.append(",token=");
227 sb.append(token.toString());
228 sb.append(",callerUid=");
229 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700230 sb.append('}');
231 return sb.toString();
232 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700233 }
234
235 // OBB Action Handler
236 final private ObbActionHandler mObbActionHandler;
237
238 // OBB action handler messages
239 private static final int OBB_RUN_ACTION = 1;
240 private static final int OBB_MCS_BOUND = 2;
241 private static final int OBB_MCS_UNBIND = 3;
242 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700243 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700244
245 /*
246 * Default Container Service information
247 */
248 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
249 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
250
251 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
252
253 class DefaultContainerConnection implements ServiceConnection {
254 public void onServiceConnected(ComponentName name, IBinder service) {
255 if (DEBUG_OBB)
256 Slog.i(TAG, "onServiceConnected");
257 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
258 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
259 }
260
261 public void onServiceDisconnected(ComponentName name) {
262 if (DEBUG_OBB)
263 Slog.i(TAG, "onServiceDisconnected");
264 }
265 };
266
267 // Used in the ObbActionHandler
268 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700269
270 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800271 private static final int H_UNMOUNT_PM_UPDATE = 1;
272 private static final int H_UNMOUNT_PM_DONE = 2;
273 private static final int H_UNMOUNT_MS = 3;
274 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
275 private static final int MAX_UNMOUNT_RETRIES = 4;
276
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800277 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700278 final String path;
279 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800280 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800281
282 UnmountCallBack(String path, boolean force) {
283 retries = 0;
284 this.path = path;
285 this.force = force;
286 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800287
288 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700289 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800290 doUnmountVolume(path, true);
291 }
292 }
293
294 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700295 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800296
297 UmsEnableCallBack(String path, String method, boolean force) {
298 super(path, force);
299 this.method = method;
300 }
301
302 @Override
303 void handleFinished() {
304 super.handleFinished();
305 doShareUnshareVolume(path, method, true);
306 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800307 }
308
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800309 class ShutdownCallBack extends UnmountCallBack {
310 IMountShutdownObserver observer;
311 ShutdownCallBack(String path, IMountShutdownObserver observer) {
312 super(path, true);
313 this.observer = observer;
314 }
315
316 @Override
317 void handleFinished() {
318 int ret = doUnmountVolume(path, true);
319 if (observer != null) {
320 try {
321 observer.onShutDownComplete(ret);
322 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700323 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800324 }
325 }
326 }
327 }
328
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400329 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800330 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700331 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800332
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400333 MountServiceHandler(Looper l) {
334 super(l);
335 }
336
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800337 public void handleMessage(Message msg) {
338 switch (msg.what) {
339 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700340 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800341 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
342 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700343 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800344 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700345 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700346 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700347 mUpdatingStatus = true;
348 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 }
350 break;
351 }
352 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700353 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700354 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700355 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800356 int size = mForceUnmounts.size();
357 int sizeArr[] = new int[size];
358 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700359 // Kill processes holding references first
360 ActivityManagerService ams = (ActivityManagerService)
361 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800362 for (int i = 0; i < size; i++) {
363 UnmountCallBack ucb = mForceUnmounts.get(i);
364 String path = ucb.path;
365 boolean done = false;
366 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800367 done = true;
368 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800369 int pids[] = getStorageUsers(path);
370 if (pids == null || pids.length == 0) {
371 done = true;
372 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800373 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700374 ams.killPids(pids, "unmount media");
375 // Confirm if file references have been freed.
376 pids = getStorageUsers(path);
377 if (pids == null || pids.length == 0) {
378 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800379 }
380 }
381 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700382 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
383 // Retry again
384 Slog.i(TAG, "Retrying to kill storage users again");
385 mHandler.sendMessageDelayed(
386 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
387 ucb.retries++),
388 RETRY_UNMOUNT_DELAY);
389 } else {
390 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
391 Slog.i(TAG, "Failed to unmount media inspite of " +
392 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
393 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800394 sizeArr[sizeArrN++] = i;
395 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
396 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800397 }
398 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800399 // Remove already processed elements from list.
400 for (int i = (sizeArrN-1); i >= 0; i--) {
401 mForceUnmounts.remove(sizeArr[i]);
402 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800403 break;
404 }
405 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700406 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800407 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800408 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 break;
410 }
411 }
412 }
413 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400414 final private HandlerThread mHandlerThread;
415 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800416
San Mehat207e5382010-02-04 20:46:54 -0800417 private void waitForReady() {
418 while (mReady == false) {
419 for (int retries = 5; retries > 0; retries--) {
420 if (mReady) {
421 return;
422 }
423 SystemClock.sleep(1000);
424 }
San Mehata5078592010-03-25 09:36:54 -0700425 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800426 }
San Mehat1f6301e2010-01-07 22:40:27 -0800427 }
Kenny Root02c87302010-07-01 08:10:18 -0700428
San Mehat207e5382010-02-04 20:46:54 -0800429 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800431 String action = intent.getAction();
432
433 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800434 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800435
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800436 /*
437 * In the simulator, we need to broadcast a volume mounted event
438 * to make the media scanner run.
439 */
440 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
441 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
442 return;
443 }
San Mehatfafb0412010-02-18 19:40:04 -0800444 new Thread() {
445 public void run() {
446 try {
447 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700448 String state = getVolumeState(path);
449
Mike Lockwood03559752010-07-19 18:25:03 -0400450 if (mEmulateExternalStorage) {
451 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Mounted);
452 } else if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800453 int rc = doMountVolume(path);
454 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700455 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800456 }
San Mehat6a254402010-03-22 10:21:00 -0700457 } else if (state.equals(Environment.MEDIA_SHARED)) {
458 /*
459 * Bootstrap UMS enabled state since vold indicates
460 * the volume is shared (runtime restart while ums enabled)
461 */
462 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800463 }
San Mehat6a254402010-03-22 10:21:00 -0700464
San Mehat6a965af22010-02-24 17:47:30 -0800465 /*
San Mehat6a254402010-03-22 10:21:00 -0700466 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800467 * now that we're up.
468 */
469 if (mSendUmsConnectedOnBoot) {
470 sendUmsIntent(true);
471 mSendUmsConnectedOnBoot = false;
472 }
San Mehatfafb0412010-02-18 19:40:04 -0800473 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700474 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800475 }
San Mehat207e5382010-02-04 20:46:54 -0800476 }
San Mehatfafb0412010-02-18 19:40:04 -0800477 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 }
479 }
480 };
481
San Mehat4270e1e2010-01-29 05:32:19 -0800482 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
483 final IMountServiceListener mListener;
484
485 MountServiceBinderListener(IMountServiceListener listener) {
486 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700487
San Mehat91c77612010-01-07 10:39:41 -0800488 }
489
San Mehat4270e1e2010-01-29 05:32:19 -0800490 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700491 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700492 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800493 mListeners.remove(this);
494 mListener.asBinder().unlinkToDeath(this, 0);
495 }
496 }
497 }
498
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800499 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800500 // TODO: Add support for multiple share methods
501 if (!method.equals("ums")) {
502 throw new IllegalArgumentException(String.format("Method %s not supported", method));
503 }
504
San Mehat4270e1e2010-01-29 05:32:19 -0800505 try {
506 mConnector.doCommand(String.format(
507 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
508 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700509 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800510 }
San Mehat4270e1e2010-01-29 05:32:19 -0800511 }
512
San Mehat207e5382010-02-04 20:46:54 -0800513 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800514 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700515 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800516 return;
517 }
San Mehatb1043402010-02-05 08:26:50 -0800518
519 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700520 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800521 return;
522 }
Mike Lockwood03559752010-07-19 18:25:03 -0400523 // Update state on PackageManager, but only of real events
524 if (!mEmulateExternalStorage) {
525 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
526 mPms.updateExternalMediaStatus(false, false);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700527
Kenny Root0a9b54e2010-10-13 15:43:35 -0700528 /*
529 * Some OBBs might have been unmounted when this volume was
530 * unmounted, so send a message to the handler to let it know to
531 * remove those from the list of mounted OBBS.
532 */
533 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_FLUSH_MOUNT_STATE,
534 path));
Mike Lockwood03559752010-07-19 18:25:03 -0400535 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
536 mPms.updateExternalMediaStatus(true, false);
537 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800538 }
Kenny Root38cf8862010-09-26 14:18:51 -0700539
San Mehat4270e1e2010-01-29 05:32:19 -0800540 String oldState = mLegacyState;
541 mLegacyState = state;
542
543 synchronized (mListeners) {
544 for (int i = mListeners.size() -1; i >= 0; i--) {
545 MountServiceBinderListener bl = mListeners.get(i);
546 try {
San Mehatb1043402010-02-05 08:26:50 -0800547 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800548 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700549 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800550 mListeners.remove(i);
551 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700552 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800553 }
554 }
555 }
556 }
557
558 /**
559 *
560 * Callback from NativeDaemonConnector
561 */
562 public void onDaemonConnected() {
563 /*
564 * Since we'll be calling back into the NativeDaemonConnector,
565 * we need to do our work in a new thread.
566 */
567 new Thread() {
568 public void run() {
569 /**
570 * Determine media state and UMS detection status
571 */
572 String path = Environment.getExternalStorageDirectory().getPath();
573 String state = Environment.MEDIA_REMOVED;
574
575 try {
576 String[] vols = mConnector.doListCommand(
577 "volume list", VoldResponseCode.VolumeListResult);
578 for (String volstr : vols) {
579 String[] tok = volstr.split(" ");
580 // FMT: <label> <mountpoint> <state>
581 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700582 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800583 "Skipping unknown volume '%s'",tok[1]));
584 continue;
585 }
586 int st = Integer.parseInt(tok[2]);
587 if (st == VolumeState.NoMedia) {
588 state = Environment.MEDIA_REMOVED;
589 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800590 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800591 } else if (st == VolumeState.Mounted) {
592 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700593 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800594 } else if (st == VolumeState.Shared) {
595 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700596 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800597 } else {
598 throw new Exception(String.format("Unexpected state %d", st));
599 }
600 }
601 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700602 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800603 updatePublicVolumeState(path, state);
604 }
605 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700606 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800607 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
608 }
609
610 try {
San Mehat207e5382010-02-04 20:46:54 -0800611 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800612 notifyShareAvailabilityChange("ums", avail);
613 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700614 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800615 }
San Mehat207e5382010-02-04 20:46:54 -0800616 /*
617 * Now that we've done our initialization, release
618 * the hounds!
619 */
620 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800621 }
622 }.start();
623 }
624
625 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800626 * Callback from NativeDaemonConnector
627 */
628 public boolean onEvent(int code, String raw, String[] cooked) {
629 Intent in = null;
630
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800631 if (DEBUG_EVENTS) {
632 StringBuilder builder = new StringBuilder();
633 builder.append("onEvent::");
634 builder.append(" raw= " + raw);
635 if (cooked != null) {
636 builder.append(" cooked = " );
637 for (String str : cooked) {
638 builder.append(" " + str);
639 }
640 }
San Mehata5078592010-03-25 09:36:54 -0700641 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800642 }
San Mehat4270e1e2010-01-29 05:32:19 -0800643 if (code == VoldResponseCode.VolumeStateChange) {
644 /*
645 * One of the volumes we're managing has changed state.
646 * Format: "NNN Volume <label> <path> state changed
647 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
648 */
649 notifyVolumeStateChange(
650 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
651 Integer.parseInt(cooked[10]));
652 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
653 // FMT: NNN Share method <method> now <available|unavailable>
654 boolean avail = false;
655 if (cooked[5].equals("available")) {
656 avail = true;
657 }
658 notifyShareAvailabilityChange(cooked[3], avail);
659 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
660 (code == VoldResponseCode.VolumeDiskRemoved) ||
661 (code == VoldResponseCode.VolumeBadRemoval)) {
662 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
663 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
664 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
665 final String label = cooked[2];
666 final String path = cooked[3];
667 int major = -1;
668 int minor = -1;
669
670 try {
671 String devComp = cooked[6].substring(1, cooked[6].length() -1);
672 String[] devTok = devComp.split(":");
673 major = Integer.parseInt(devTok[0]);
674 minor = Integer.parseInt(devTok[1]);
675 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700676 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800677 }
678
San Mehat4270e1e2010-01-29 05:32:19 -0800679 if (code == VoldResponseCode.VolumeDiskInserted) {
680 new Thread() {
681 public void run() {
682 try {
683 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800684 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700685 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800686 }
687 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700688 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800689 }
690 }
691 }.start();
692 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
693 /*
694 * This event gets trumped if we're already in BAD_REMOVAL state
695 */
696 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
697 return true;
698 }
699 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700700 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800701 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
702 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
703 mContext.sendBroadcast(in);
704
San Mehata5078592010-03-25 09:36:54 -0700705 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800706 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
707 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
708 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700709 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800710 /* Send the media unmounted event first */
711 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
712 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
713 mContext.sendBroadcast(in);
714
San Mehata5078592010-03-25 09:36:54 -0700715 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800716 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
717 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
718 } else {
San Mehata5078592010-03-25 09:36:54 -0700719 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800720 }
721 } else {
722 return false;
723 }
724
725 if (in != null) {
726 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400727 }
728 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800729 }
730
San Mehat207e5382010-02-04 20:46:54 -0800731 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800732 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700733 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800734
735 Intent in = null;
736
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500737 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700738 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500739 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
740 Uri.parse("file://" + path)));
741 }
742
San Mehat4270e1e2010-01-29 05:32:19 -0800743 if (newState == VolumeState.Init) {
744 } else if (newState == VolumeState.NoMedia) {
745 // NoMedia is handled via Disk Remove events
746 } else if (newState == VolumeState.Idle) {
747 /*
748 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
749 * if we're in the process of enabling UMS
750 */
751 if (!vs.equals(
752 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
753 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800754 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700755 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800756 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
757 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
758 }
759 } else if (newState == VolumeState.Pending) {
760 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700761 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800762 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
763 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
764 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700765 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800766 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800767 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
768 in.putExtra("read-only", false);
769 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800770 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
771 } else if (newState == VolumeState.Formatting) {
772 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700773 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800774 /* Send the media unmounted event first */
775 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
776 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
777 mContext.sendBroadcast(in);
778
San Mehata5078592010-03-25 09:36:54 -0700779 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800780 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
781 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700782 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800783 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700784 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800785 return;
786 } else {
San Mehata5078592010-03-25 09:36:54 -0700787 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800788 }
789
790 if (in != null) {
791 mContext.sendBroadcast(in);
792 }
793 }
794
San Mehat207e5382010-02-04 20:46:54 -0800795 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700796 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700797 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700798 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700799 } catch (NativeDaemonConnectorException ex) {
800 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
801 return false;
802 }
San Mehat207e5382010-02-04 20:46:54 -0800803
804 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700805 String[] tok = line.split(" ");
806 if (tok.length < 3) {
807 Slog.e(TAG, "Malformed response to share status " + method);
808 return false;
809 }
810
San Mehat207e5382010-02-04 20:46:54 -0800811 int code;
812 try {
813 code = Integer.parseInt(tok[0]);
814 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700815 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800816 return false;
817 }
818 if (code == VoldResponseCode.ShareStatusResult) {
819 if (tok[2].equals("available"))
820 return true;
821 return false;
822 } else {
San Mehata5078592010-03-25 09:36:54 -0700823 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800824 return false;
825 }
826 }
San Mehata5078592010-03-25 09:36:54 -0700827 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800828 return false;
829 }
830
831 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800832 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800833
San Mehata5078592010-03-25 09:36:54 -0700834 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800835 try {
836 mConnector.doCommand(String.format("volume mount %s", path));
837 } catch (NativeDaemonConnectorException e) {
838 /*
839 * Mount failed for some reason
840 */
841 Intent in = null;
842 int code = e.getCode();
843 if (code == VoldResponseCode.OpFailedNoMedia) {
844 /*
845 * Attempt to mount but no media inserted
846 */
San Mehatb1043402010-02-05 08:26:50 -0800847 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800848 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700849 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800850 /*
851 * Media is blank or does not contain a supported filesystem
852 */
853 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
854 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800855 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800856 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700857 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800858 /*
859 * Volume consistency check failed
860 */
861 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
862 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800863 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800864 } else {
San Mehatb1043402010-02-05 08:26:50 -0800865 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800866 }
867
868 /*
869 * Send broadcast intent (if required for the failure)
870 */
871 if (in != null) {
872 mContext.sendBroadcast(in);
873 }
874 }
875
876 return rc;
877 }
878
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800879 /*
880 * If force is not set, we do not unmount if there are
881 * processes holding references to the volume about to be unmounted.
882 * If force is set, all the processes holding references need to be
883 * killed via the ActivityManager before actually unmounting the volume.
884 * This might even take a while and might be retried after timed delays
885 * to make sure we dont end up in an instable state and kill some core
886 * processes.
887 */
San Mehatd9709982010-02-18 11:43:03 -0800888 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800889 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800890 return VoldResponseCode.OpFailedVolNotMounted;
891 }
Kenny Rootaa485402010-09-14 14:49:41 -0700892
893 /*
894 * Force a GC to make sure AssetManagers in other threads of the
895 * system_server are cleaned up. We have to do this since AssetManager
896 * instances are kept as a WeakReference and it's possible we have files
897 * open on the external storage.
898 */
899 Runtime.getRuntime().gc();
900
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800901 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700902 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800903 try {
San Mehatd9709982010-02-18 11:43:03 -0800904 mConnector.doCommand(String.format(
905 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700906 // We unmounted the volume. None of the asec containers are available now.
907 synchronized (mAsecMountSet) {
908 mAsecMountSet.clear();
909 }
San Mehatb1043402010-02-05 08:26:50 -0800910 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800911 } catch (NativeDaemonConnectorException e) {
912 // Don't worry about mismatch in PackageManager since the
913 // call back will handle the status changes any way.
914 int code = e.getCode();
915 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800916 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800917 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
918 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800919 } else {
San Mehatb1043402010-02-05 08:26:50 -0800920 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800921 }
922 }
923 }
924
925 private int doFormatVolume(String path) {
926 try {
927 String cmd = String.format("volume format %s", path);
928 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800929 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800930 } catch (NativeDaemonConnectorException e) {
931 int code = e.getCode();
932 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800933 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800934 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800935 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800936 } else {
San Mehatb1043402010-02-05 08:26:50 -0800937 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800938 }
939 }
940 }
941
San Mehatb1043402010-02-05 08:26:50 -0800942 private boolean doGetVolumeShared(String path, String method) {
943 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700944 ArrayList<String> rsp;
945
946 try {
947 rsp = mConnector.doCommand(cmd);
948 } catch (NativeDaemonConnectorException ex) {
949 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
950 return false;
951 }
San Mehatb1043402010-02-05 08:26:50 -0800952
953 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700954 String[] tok = line.split(" ");
955 if (tok.length < 3) {
956 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
957 return false;
958 }
959
San Mehatb1043402010-02-05 08:26:50 -0800960 int code;
961 try {
962 code = Integer.parseInt(tok[0]);
963 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700964 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800965 return false;
966 }
967 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700968 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800969 } else {
San Mehata5078592010-03-25 09:36:54 -0700970 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800971 return false;
972 }
973 }
San Mehata5078592010-03-25 09:36:54 -0700974 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800975 return false;
976 }
977
San Mehat207e5382010-02-04 20:46:54 -0800978 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800979 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700980 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800981 return;
982 }
983
984 synchronized (mListeners) {
985 for (int i = mListeners.size() -1; i >= 0; i--) {
986 MountServiceBinderListener bl = mListeners.get(i);
987 try {
San Mehatb1043402010-02-05 08:26:50 -0800988 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800989 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700990 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800991 mListeners.remove(i);
992 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700993 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800994 }
995 }
996 }
997
San Mehat207e5382010-02-04 20:46:54 -0800998 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800999 sendUmsIntent(avail);
1000 } else {
1001 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001002 }
San Mehat2fe718a2010-03-11 12:01:49 -08001003
1004 final String path = Environment.getExternalStorageDirectory().getPath();
1005 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1006 /*
1007 * USB mass storage disconnected while enabled
1008 */
1009 new Thread() {
1010 public void run() {
1011 try {
1012 int rc;
San Mehata5078592010-03-25 09:36:54 -07001013 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001014 doShareUnshareVolume(path, "ums", false);
1015 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001016 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001017 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1018 path, rc));
1019 }
1020 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001021 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001022 }
1023 }
1024 }.start();
1025 }
San Mehat4270e1e2010-01-29 05:32:19 -08001026 }
1027
San Mehat6a965af22010-02-24 17:47:30 -08001028 private void sendUmsIntent(boolean c) {
1029 mContext.sendBroadcast(
1030 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1031 }
1032
San Mehat207e5382010-02-04 20:46:54 -08001033 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001034 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1035 throw new SecurityException(String.format("Requires %s permission", perm));
1036 }
1037 }
1038
1039 /**
San Mehat207e5382010-02-04 20:46:54 -08001040 * Constructs a new MountService instance
1041 *
1042 * @param context Binder context for this service
1043 */
1044 public MountService(Context context) {
1045 mContext = context;
1046
Mike Lockwood03559752010-07-19 18:25:03 -04001047 mEmulateExternalStorage = context.getResources().getBoolean(
1048 com.android.internal.R.bool.config_emulateExternalStorage);
1049 if (mEmulateExternalStorage) {
1050 Slog.d(TAG, "using emulated external storage");
1051 mLegacyState = Environment.MEDIA_MOUNTED;
1052 }
1053
San Mehat207e5382010-02-04 20:46:54 -08001054 // XXX: This will go away soon in favor of IMountServiceObserver
1055 mPms = (PackageManagerService) ServiceManager.getService("package");
1056
1057 mContext.registerReceiver(mBroadcastReceiver,
1058 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1059
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001060 mHandlerThread = new HandlerThread("MountService");
1061 mHandlerThread.start();
1062 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1063
Kenny Roota02b8b02010-08-05 16:14:17 -07001064 // Add OBB Action Handler to MountService thread.
1065 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1066
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001067 /*
1068 * Vold does not run in the simulator, so pretend the connector thread
1069 * ran and did its thing.
1070 */
1071 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1072 mReady = true;
1073 mUmsEnabling = true;
1074 return;
1075 }
1076
Kenny Root305bcbf2010-09-03 07:56:38 -07001077 /*
1078 * Create the connection to vold with a maximum queue of twice the
1079 * amount of containers we'd ever expect to have. This keeps an
1080 * "asec list" from blocking a thread repeatedly.
1081 */
1082 mConnector = new NativeDaemonConnector(this, "vold",
1083 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001084 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001085 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001086 thread.start();
1087 }
1088
1089 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001090 * Exposed API calls below here
1091 */
1092
1093 public void registerListener(IMountServiceListener listener) {
1094 synchronized (mListeners) {
1095 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1096 try {
1097 listener.asBinder().linkToDeath(bl, 0);
1098 mListeners.add(bl);
1099 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001100 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001101 }
1102 }
1103 }
1104
1105 public void unregisterListener(IMountServiceListener listener) {
1106 synchronized (mListeners) {
1107 for(MountServiceBinderListener bl : mListeners) {
1108 if (bl.mListener == listener) {
1109 mListeners.remove(mListeners.indexOf(bl));
1110 return;
1111 }
1112 }
1113 }
1114 }
1115
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001116 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001117 validatePermission(android.Manifest.permission.SHUTDOWN);
1118
San Mehata5078592010-03-25 09:36:54 -07001119 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001120
1121 String path = Environment.getExternalStorageDirectory().getPath();
1122 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001123
1124 if (state.equals(Environment.MEDIA_SHARED)) {
1125 /*
1126 * If the media is currently shared, unshare it.
1127 * XXX: This is still dangerous!. We should not
1128 * be rebooting at *all* if UMS is enabled, since
1129 * the UMS host could have dirty FAT cache entries
1130 * yet to flush.
1131 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001132 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001133 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1134 /*
1135 * If the media is being checked, then we need to wait for
1136 * it to complete before being able to proceed.
1137 */
1138 // XXX: @hackbod - Should we disable the ANR timer here?
1139 int retries = 30;
1140 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1141 try {
1142 Thread.sleep(1000);
1143 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001144 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001145 break;
1146 }
1147 state = Environment.getExternalStorageState();
1148 }
1149 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001150 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001151 }
1152 }
1153
1154 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001155 // Post a unmount message.
1156 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1157 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001158 }
1159 }
1160
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001161 private boolean getUmsEnabling() {
1162 synchronized (mListeners) {
1163 return mUmsEnabling;
1164 }
1165 }
1166
1167 private void setUmsEnabling(boolean enable) {
1168 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001169 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001170 }
1171 }
1172
San Mehatb1043402010-02-05 08:26:50 -08001173 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001174 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001175
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001176 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001177 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001178 }
San Mehatb1043402010-02-05 08:26:50 -08001179 return doGetShareMethodAvailable("ums");
1180 }
1181
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001182 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001183 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001184 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001185
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001186 // TODO: Add support for multiple share methods
1187
1188 /*
1189 * If the volume is mounted and we're enabling then unmount it
1190 */
1191 String path = Environment.getExternalStorageDirectory().getPath();
1192 String vs = getVolumeState(path);
1193 String method = "ums";
1194 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1195 // Override for isUsbMassStorageEnabled()
1196 setUmsEnabling(enable);
1197 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1198 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1199 // Clear override
1200 setUmsEnabling(false);
1201 }
1202 /*
1203 * If we disabled UMS then mount the volume
1204 */
1205 if (!enable) {
1206 doShareUnshareVolume(path, method, enable);
1207 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001208 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001209 " after disabling share method " + method);
1210 /*
1211 * Even though the mount failed, the unshare didn't so don't indicate an error.
1212 * The mountVolume() call will have set the storage state and sent the necessary
1213 * broadcasts.
1214 */
1215 }
1216 }
San Mehatb1043402010-02-05 08:26:50 -08001217 }
1218
1219 public boolean isUsbMassStorageEnabled() {
1220 waitForReady();
1221 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
San Mehat4270e1e2010-01-29 05:32:19 -08001223
San Mehat7fd0fee2009-12-17 07:12:23 -08001224 /**
1225 * @return state of the volume at the specified mount point
1226 */
San Mehat4270e1e2010-01-29 05:32:19 -08001227 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001228 /*
1229 * XXX: Until we have multiple volume discovery, just hardwire
1230 * this to /sdcard
1231 */
1232 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001233 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001234 throw new IllegalArgumentException();
1235 }
1236
1237 return mLegacyState;
1238 }
1239
Kenny Roote1ff2142010-10-12 11:20:01 -07001240 public boolean isExternalStorageEmulated() {
1241 return mEmulateExternalStorage;
1242 }
1243
San Mehat4270e1e2010-01-29 05:32:19 -08001244 public int mountVolume(String path) {
1245 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001246
San Mehat207e5382010-02-04 20:46:54 -08001247 waitForReady();
1248 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 }
1250
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001251 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001252 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001253 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001255 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001256 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001257 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1258 Environment.MEDIA_REMOVED.equals(volState) ||
1259 Environment.MEDIA_SHARED.equals(volState) ||
1260 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1261 // Media already unmounted or cannot be unmounted.
1262 // TODO return valid return code when adding observer call back.
1263 return;
1264 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001265 UnmountCallBack ucb = new UnmountCallBack(path, force);
1266 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268
San Mehat4270e1e2010-01-29 05:32:19 -08001269 public int formatVolume(String path) {
1270 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001271 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001272
San Mehat207e5382010-02-04 20:46:54 -08001273 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
1275
San Mehatc1b4ce92010-02-16 17:13:03 -08001276 public int []getStorageUsers(String path) {
1277 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1278 waitForReady();
1279 try {
1280 String[] r = mConnector.doListCommand(
1281 String.format("storage users %s", path),
1282 VoldResponseCode.StorageUsersListResult);
1283 // FMT: <pid> <process name>
1284 int[] data = new int[r.length];
1285 for (int i = 0; i < r.length; i++) {
1286 String []tok = r[i].split(" ");
1287 try {
1288 data[i] = Integer.parseInt(tok[0]);
1289 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001290 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001291 return new int[0];
1292 }
1293 }
1294 return data;
1295 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001296 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001297 return new int[0];
1298 }
1299 }
1300
San Mehatb1043402010-02-05 08:26:50 -08001301 private void warnOnNotMounted() {
1302 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001303 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001304 }
1305 }
1306
San Mehat4270e1e2010-01-29 05:32:19 -08001307 public String[] getSecureContainerList() {
1308 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001309 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001310 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001311
San Mehat4270e1e2010-01-29 05:32:19 -08001312 try {
1313 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1314 } catch (NativeDaemonConnectorException e) {
1315 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
1317 }
San Mehat36972292010-01-06 11:06:32 -08001318
San Mehat4270e1e2010-01-29 05:32:19 -08001319 public int createSecureContainer(String id, int sizeMb, String fstype,
1320 String key, int ownerUid) {
1321 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001322 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001323 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001324
San Mehatb1043402010-02-05 08:26:50 -08001325 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001326 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1327 try {
1328 mConnector.doCommand(cmd);
1329 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001330 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001331 }
San Mehata181b212010-02-11 06:50:20 -08001332
1333 if (rc == StorageResultCode.OperationSucceeded) {
1334 synchronized (mAsecMountSet) {
1335 mAsecMountSet.add(id);
1336 }
1337 }
San Mehat4270e1e2010-01-29 05:32:19 -08001338 return rc;
San Mehat36972292010-01-06 11:06:32 -08001339 }
1340
San Mehat4270e1e2010-01-29 05:32:19 -08001341 public int finalizeSecureContainer(String id) {
1342 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001343 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001344
San Mehatb1043402010-02-05 08:26:50 -08001345 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001346 try {
1347 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001348 /*
1349 * Finalization does a remount, so no need
1350 * to update mAsecMountSet
1351 */
San Mehat4270e1e2010-01-29 05:32:19 -08001352 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001353 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001354 }
San Mehat4270e1e2010-01-29 05:32:19 -08001355 return rc;
San Mehat36972292010-01-06 11:06:32 -08001356 }
1357
San Mehatd9709982010-02-18 11:43:03 -08001358 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001359 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001360 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001361 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001362
Kenny Rootaa485402010-09-14 14:49:41 -07001363 /*
1364 * Force a GC to make sure AssetManagers in other threads of the
1365 * system_server are cleaned up. We have to do this since AssetManager
1366 * instances are kept as a WeakReference and it's possible we have files
1367 * open on the external storage.
1368 */
1369 Runtime.getRuntime().gc();
1370
San Mehatb1043402010-02-05 08:26:50 -08001371 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001372 try {
San Mehatd9709982010-02-18 11:43:03 -08001373 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001374 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001375 int code = e.getCode();
1376 if (code == VoldResponseCode.OpFailedStorageBusy) {
1377 rc = StorageResultCode.OperationFailedStorageBusy;
1378 } else {
1379 rc = StorageResultCode.OperationFailedInternalError;
1380 }
San Mehat02735bc2010-01-26 15:18:08 -08001381 }
San Mehata181b212010-02-11 06:50:20 -08001382
1383 if (rc == StorageResultCode.OperationSucceeded) {
1384 synchronized (mAsecMountSet) {
1385 if (mAsecMountSet.contains(id)) {
1386 mAsecMountSet.remove(id);
1387 }
1388 }
1389 }
1390
San Mehat4270e1e2010-01-29 05:32:19 -08001391 return rc;
San Mehat36972292010-01-06 11:06:32 -08001392 }
1393
San Mehat4270e1e2010-01-29 05:32:19 -08001394 public int mountSecureContainer(String id, String key, int ownerUid) {
1395 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001396 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001397 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001398
San Mehata181b212010-02-11 06:50:20 -08001399 synchronized (mAsecMountSet) {
1400 if (mAsecMountSet.contains(id)) {
1401 return StorageResultCode.OperationFailedStorageMounted;
1402 }
1403 }
1404
San Mehatb1043402010-02-05 08:26:50 -08001405 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001406 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1407 try {
1408 mConnector.doCommand(cmd);
1409 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001410 int code = e.getCode();
1411 if (code != VoldResponseCode.OpFailedStorageBusy) {
1412 rc = StorageResultCode.OperationFailedInternalError;
1413 }
San Mehat02735bc2010-01-26 15:18:08 -08001414 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001415
1416 if (rc == StorageResultCode.OperationSucceeded) {
1417 synchronized (mAsecMountSet) {
1418 mAsecMountSet.add(id);
1419 }
1420 }
San Mehat4270e1e2010-01-29 05:32:19 -08001421 return rc;
San Mehat36972292010-01-06 11:06:32 -08001422 }
1423
San Mehatd9709982010-02-18 11:43:03 -08001424 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001425 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001426 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001427 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001428
San Mehat6cdd9c02010-02-09 14:45:20 -08001429 synchronized (mAsecMountSet) {
1430 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001431 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001432 }
1433 }
1434
Kenny Rootaa485402010-09-14 14:49:41 -07001435 /*
1436 * Force a GC to make sure AssetManagers in other threads of the
1437 * system_server are cleaned up. We have to do this since AssetManager
1438 * instances are kept as a WeakReference and it's possible we have files
1439 * open on the external storage.
1440 */
1441 Runtime.getRuntime().gc();
1442
San Mehatb1043402010-02-05 08:26:50 -08001443 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001444 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001445 try {
1446 mConnector.doCommand(cmd);
1447 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001448 int code = e.getCode();
1449 if (code == VoldResponseCode.OpFailedStorageBusy) {
1450 rc = StorageResultCode.OperationFailedStorageBusy;
1451 } else {
1452 rc = StorageResultCode.OperationFailedInternalError;
1453 }
San Mehat02735bc2010-01-26 15:18:08 -08001454 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001455
1456 if (rc == StorageResultCode.OperationSucceeded) {
1457 synchronized (mAsecMountSet) {
1458 mAsecMountSet.remove(id);
1459 }
1460 }
San Mehat4270e1e2010-01-29 05:32:19 -08001461 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001462 }
1463
San Mehat6cdd9c02010-02-09 14:45:20 -08001464 public boolean isSecureContainerMounted(String id) {
1465 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1466 waitForReady();
1467 warnOnNotMounted();
1468
1469 synchronized (mAsecMountSet) {
1470 return mAsecMountSet.contains(id);
1471 }
1472 }
1473
San Mehat4270e1e2010-01-29 05:32:19 -08001474 public int renameSecureContainer(String oldId, String newId) {
1475 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001476 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001477 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001478
San Mehata181b212010-02-11 06:50:20 -08001479 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001480 /*
1481 * Because a mounted container has active internal state which cannot be
1482 * changed while active, we must ensure both ids are not currently mounted.
1483 */
1484 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001485 return StorageResultCode.OperationFailedStorageMounted;
1486 }
1487 }
1488
San Mehatb1043402010-02-05 08:26:50 -08001489 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001490 String cmd = String.format("asec rename %s %s", oldId, newId);
1491 try {
1492 mConnector.doCommand(cmd);
1493 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001494 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001495 }
San Mehata181b212010-02-11 06:50:20 -08001496
San Mehat4270e1e2010-01-29 05:32:19 -08001497 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001498 }
1499
San Mehat4270e1e2010-01-29 05:32:19 -08001500 public String getSecureContainerPath(String id) {
1501 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001502 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001503 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001504
San Mehat2d66cef2010-03-23 11:12:52 -07001505 try {
1506 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1507 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001508 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001509 if (code != VoldResponseCode.AsecPathResult) {
1510 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1511 }
1512 return tok[1];
1513 } catch (NativeDaemonConnectorException e) {
1514 int code = e.getCode();
1515 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1516 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001517 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001518 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001519 }
1520 }
San Mehat22dd86e2010-01-12 12:21:18 -08001521 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001522
1523 public void finishMediaUpdate() {
1524 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1525 }
Kenny Root02c87302010-07-01 08:10:18 -07001526
Kenny Roota02b8b02010-08-05 16:14:17 -07001527 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1528 if (callerUid == android.os.Process.SYSTEM_UID) {
1529 return true;
1530 }
1531
Kenny Root02c87302010-07-01 08:10:18 -07001532 if (packageName == null) {
1533 return false;
1534 }
1535
1536 final int packageUid = mPms.getPackageUid(packageName);
1537
1538 if (DEBUG_OBB) {
1539 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1540 packageUid + ", callerUid = " + callerUid);
1541 }
1542
1543 return callerUid == packageUid;
1544 }
1545
1546 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001547 if (filename == null) {
1548 throw new IllegalArgumentException("filename cannot be null");
1549 }
1550
Kenny Root02c87302010-07-01 08:10:18 -07001551 waitForReady();
1552 warnOnNotMounted();
1553
Kenny Root02c87302010-07-01 08:10:18 -07001554 try {
1555 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1556 String []tok = rsp.get(0).split(" ");
1557 int code = Integer.parseInt(tok[0]);
1558 if (code != VoldResponseCode.AsecPathResult) {
1559 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1560 }
1561 return tok[1];
1562 } catch (NativeDaemonConnectorException e) {
1563 int code = e.getCode();
1564 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001565 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001566 } else {
1567 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1568 }
1569 }
1570 }
1571
1572 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001573 if (filename == null) {
1574 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001575 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001576
1577 synchronized (mObbMounts) {
1578 return mObbPathToStateMap.containsKey(filename);
1579 }
Kenny Root02c87302010-07-01 08:10:18 -07001580 }
1581
Kenny Rootaf9d6672010-10-08 09:21:39 -07001582 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001583 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001584 if (filename == null) {
1585 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001586 }
1587
1588 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001589 throw new IllegalArgumentException("token cannot be null");
1590 }
1591
Kenny Rootaf9d6672010-10-08 09:21:39 -07001592 final int callerUid = Binder.getCallingUid();
1593 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1594 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001595 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1596
1597 if (DEBUG_OBB)
1598 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001599 }
1600
Kenny Rootaf9d6672010-10-08 09:21:39 -07001601 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1602 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001603 if (filename == null) {
1604 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001605 }
1606
Kenny Rootaf9d6672010-10-08 09:21:39 -07001607 final int callerUid = Binder.getCallingUid();
1608 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1609 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001610 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001611
Kenny Roota02b8b02010-08-05 16:14:17 -07001612 if (DEBUG_OBB)
1613 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1614 }
1615
Kenny Rootaf9d6672010-10-08 09:21:39 -07001616 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1617 final IBinder binder = obbState.getBinder();
1618 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001619
Kenny Rootaf9d6672010-10-08 09:21:39 -07001620 if (obbStates == null) {
1621 obbStates = new ArrayList<ObbState>();
1622 mObbMounts.put(binder, obbStates);
1623 } else {
1624 for (final ObbState o : obbStates) {
1625 if (o.filename.equals(obbState.filename)) {
1626 throw new IllegalStateException("Attempt to add ObbState twice. "
1627 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001628 }
1629 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001630 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001631
1632 obbStates.add(obbState);
1633 try {
1634 obbState.link();
1635 } catch (RemoteException e) {
1636 /*
1637 * The binder died before we could link it, so clean up our state
1638 * and return failure.
1639 */
1640 obbStates.remove(obbState);
1641 if (obbStates.isEmpty()) {
1642 mObbMounts.remove(binder);
1643 }
1644
1645 // Rethrow the error so mountObb can get it
1646 throw e;
1647 }
1648
1649 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001650 }
1651
Kenny Rootaf9d6672010-10-08 09:21:39 -07001652 private void removeObbStateLocked(ObbState obbState) {
1653 final IBinder binder = obbState.getBinder();
1654 final List<ObbState> obbStates = mObbMounts.get(binder);
1655 if (obbStates != null) {
1656 if (obbStates.remove(obbState)) {
1657 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001658 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001659 if (obbStates.isEmpty()) {
1660 mObbMounts.remove(binder);
1661 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001662 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001663
Kenny Rootaf9d6672010-10-08 09:21:39 -07001664 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001665 }
1666
Kenny Roota02b8b02010-08-05 16:14:17 -07001667 private class ObbActionHandler extends Handler {
1668 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001669 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001670
1671 ObbActionHandler(Looper l) {
1672 super(l);
1673 }
1674
1675 @Override
1676 public void handleMessage(Message msg) {
1677 switch (msg.what) {
1678 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001679 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001680
1681 if (DEBUG_OBB)
1682 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1683
1684 // If a bind was already initiated we don't really
1685 // need to do anything. The pending install
1686 // will be processed later on.
1687 if (!mBound) {
1688 // If this is the only one pending we might
1689 // have to bind to the service again.
1690 if (!connectToService()) {
1691 Slog.e(TAG, "Failed to bind to media container service");
1692 action.handleError();
1693 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001694 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001695 }
Kenny Root735de3b2010-09-30 14:11:39 -07001696
Kenny Root735de3b2010-09-30 14:11:39 -07001697 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001698 break;
1699 }
1700 case OBB_MCS_BOUND: {
1701 if (DEBUG_OBB)
1702 Slog.i(TAG, "OBB_MCS_BOUND");
1703 if (msg.obj != null) {
1704 mContainerService = (IMediaContainerService) msg.obj;
1705 }
1706 if (mContainerService == null) {
1707 // Something seriously wrong. Bail out
1708 Slog.e(TAG, "Cannot bind to media container service");
1709 for (ObbAction action : mActions) {
1710 // Indicate service bind error
1711 action.handleError();
1712 }
1713 mActions.clear();
1714 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001715 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001716 if (action != null) {
1717 action.execute(this);
1718 }
1719 } else {
1720 // Should never happen ideally.
1721 Slog.w(TAG, "Empty queue");
1722 }
1723 break;
1724 }
1725 case OBB_MCS_RECONNECT: {
1726 if (DEBUG_OBB)
1727 Slog.i(TAG, "OBB_MCS_RECONNECT");
1728 if (mActions.size() > 0) {
1729 if (mBound) {
1730 disconnectService();
1731 }
1732 if (!connectToService()) {
1733 Slog.e(TAG, "Failed to bind to media container service");
1734 for (ObbAction action : mActions) {
1735 // Indicate service bind error
1736 action.handleError();
1737 }
1738 mActions.clear();
1739 }
1740 }
1741 break;
1742 }
1743 case OBB_MCS_UNBIND: {
1744 if (DEBUG_OBB)
1745 Slog.i(TAG, "OBB_MCS_UNBIND");
1746
1747 // Delete pending install
1748 if (mActions.size() > 0) {
1749 mActions.remove(0);
1750 }
1751 if (mActions.size() == 0) {
1752 if (mBound) {
1753 disconnectService();
1754 }
1755 } else {
1756 // There are more pending requests in queue.
1757 // Just post MCS_BOUND message to trigger processing
1758 // of next pending install.
1759 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1760 }
1761 break;
1762 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001763 case OBB_FLUSH_MOUNT_STATE: {
1764 final String path = (String) msg.obj;
1765
1766 if (DEBUG_OBB)
1767 Slog.i(TAG, "Flushing all OBB state for path " + path);
1768
1769 synchronized (mObbMounts) {
1770 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1771
1772 final Iterator<Entry<String, ObbState>> i =
1773 mObbPathToStateMap.entrySet().iterator();
1774 while (i.hasNext()) {
1775 final Entry<String, ObbState> obbEntry = i.next();
1776
1777 /*
1778 * If this entry's source file is in the volume path
1779 * that got unmounted, remove it because it's no
1780 * longer valid.
1781 */
1782 if (obbEntry.getKey().startsWith(path)) {
1783 obbStatesToRemove.add(obbEntry.getValue());
1784 }
1785 }
1786
1787 for (final ObbState obbState : obbStatesToRemove) {
1788 if (DEBUG_OBB)
1789 Slog.i(TAG, "Removing state for " + obbState.filename);
1790
1791 removeObbStateLocked(obbState);
1792
1793 try {
1794 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1795 OnObbStateChangeListener.UNMOUNTED);
1796 } catch (RemoteException e) {
1797 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1798 + obbState.filename);
1799 }
1800 }
1801 }
1802 break;
1803 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001804 }
1805 }
1806
1807 private boolean connectToService() {
1808 if (DEBUG_OBB)
1809 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1810
1811 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1812 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1813 mBound = true;
1814 return true;
1815 }
1816 return false;
1817 }
1818
1819 private void disconnectService() {
1820 mContainerService = null;
1821 mBound = false;
1822 mContext.unbindService(mDefContainerConn);
1823 }
1824 }
1825
1826 abstract class ObbAction {
1827 private static final int MAX_RETRIES = 3;
1828 private int mRetries;
1829
1830 ObbState mObbState;
1831
1832 ObbAction(ObbState obbState) {
1833 mObbState = obbState;
1834 }
1835
1836 public void execute(ObbActionHandler handler) {
1837 try {
1838 if (DEBUG_OBB)
1839 Slog.i(TAG, "Starting to execute action: " + this.toString());
1840 mRetries++;
1841 if (mRetries > MAX_RETRIES) {
1842 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001843 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001844 handleError();
1845 return;
1846 } else {
1847 handleExecute();
1848 if (DEBUG_OBB)
1849 Slog.i(TAG, "Posting install MCS_UNBIND");
1850 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1851 }
1852 } catch (RemoteException e) {
1853 if (DEBUG_OBB)
1854 Slog.i(TAG, "Posting install MCS_RECONNECT");
1855 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1856 } catch (Exception e) {
1857 if (DEBUG_OBB)
1858 Slog.d(TAG, "Error handling OBB action", e);
1859 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001860 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001861 }
1862 }
1863
Kenny Root05105f72010-09-22 17:29:43 -07001864 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001865 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001866
1867 protected ObbInfo getObbInfo() throws IOException {
1868 ObbInfo obbInfo;
1869 try {
1870 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1871 } catch (RemoteException e) {
1872 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1873 + mObbState.filename);
1874 obbInfo = null;
1875 }
1876 if (obbInfo == null) {
1877 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1878 }
1879 return obbInfo;
1880 }
1881
Kenny Rootaf9d6672010-10-08 09:21:39 -07001882 protected void sendNewStatusOrIgnore(int status) {
1883 if (mObbState == null || mObbState.token == null) {
1884 return;
1885 }
1886
Kenny Root38cf8862010-09-26 14:18:51 -07001887 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001888 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07001889 } catch (RemoteException e) {
1890 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1891 }
1892 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001893 }
1894
1895 class MountObbAction extends ObbAction {
1896 private String mKey;
1897
1898 MountObbAction(ObbState obbState, String key) {
1899 super(obbState);
1900 mKey = key;
1901 }
1902
Kenny Root735de3b2010-09-30 14:11:39 -07001903 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001904 waitForReady();
1905 warnOnNotMounted();
1906
Kenny Root38cf8862010-09-26 14:18:51 -07001907 final ObbInfo obbInfo = getObbInfo();
1908
Kenny Roota02b8b02010-08-05 16:14:17 -07001909 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001910 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
1911 + " which is owned by " + obbInfo.packageName);
1912 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
1913 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001914 }
1915
Kenny Rootaf9d6672010-10-08 09:21:39 -07001916 final boolean isMounted;
1917 synchronized (mObbMounts) {
1918 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
1919 }
1920 if (isMounted) {
1921 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
1922 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
1923 return;
1924 }
1925
1926 /*
1927 * The filename passed in might not be the canonical name, so just
1928 * set the filename to the canonicalized version.
1929 */
1930 mObbState.filename = obbInfo.filename;
1931
1932 final String hashedKey;
1933 if (mKey == null) {
1934 hashedKey = "none";
1935 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001936 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07001937 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1938
1939 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
1940 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
1941 SecretKey key = factory.generateSecret(ks);
1942 BigInteger bi = new BigInteger(key.getEncoded());
1943 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001944 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07001945 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
1946 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
1947 return;
1948 } catch (InvalidKeySpecException e) {
1949 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
1950 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07001951 return;
1952 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001953 }
Kenny Root38cf8862010-09-26 14:18:51 -07001954
Kenny Rootaf9d6672010-10-08 09:21:39 -07001955 int rc = StorageResultCode.OperationSucceeded;
1956 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
1957 mObbState.callerUid);
1958 try {
1959 mConnector.doCommand(cmd);
1960 } catch (NativeDaemonConnectorException e) {
1961 int code = e.getCode();
1962 if (code != VoldResponseCode.OpFailedStorageBusy) {
1963 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07001964 }
1965 }
1966
Kenny Rootaf9d6672010-10-08 09:21:39 -07001967 if (rc == StorageResultCode.OperationSucceeded) {
1968 if (DEBUG_OBB)
1969 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
1970
1971 synchronized (mObbMounts) {
1972 addObbStateLocked(mObbState);
1973 }
1974
1975 sendNewStatusOrIgnore(OnObbStateChangeListener.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
Kenny Rootaf9d6672010-10-08 09:21:39 -07001979 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07001980 }
1981 }
1982
Kenny Roota02b8b02010-08-05 16:14:17 -07001983 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001984 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07001985 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001986
1987 @Override
1988 public String toString() {
1989 StringBuilder sb = new StringBuilder();
1990 sb.append("MountObbAction{");
1991 sb.append("filename=");
1992 sb.append(mObbState.filename);
1993 sb.append(",callerUid=");
1994 sb.append(mObbState.callerUid);
1995 sb.append(",token=");
1996 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001997 sb.append(",binder=");
1998 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07001999 sb.append('}');
2000 return sb.toString();
2001 }
2002 }
2003
2004 class UnmountObbAction extends ObbAction {
2005 private boolean mForceUnmount;
2006
2007 UnmountObbAction(ObbState obbState, boolean force) {
2008 super(obbState);
2009 mForceUnmount = force;
2010 }
2011
Kenny Root38cf8862010-09-26 14:18:51 -07002012 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002013 waitForReady();
2014 warnOnNotMounted();
2015
Kenny Root38cf8862010-09-26 14:18:51 -07002016 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002017
Kenny Rootaf9d6672010-10-08 09:21:39 -07002018 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002019 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002020 obbState = mObbPathToStateMap.get(obbInfo.filename);
2021 }
Kenny Root38cf8862010-09-26 14:18:51 -07002022
Kenny Rootaf9d6672010-10-08 09:21:39 -07002023 if (obbState == null) {
2024 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2025 return;
2026 }
2027
2028 if (obbState.callerUid != mObbState.callerUid) {
2029 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2030 + " (owned by " + obbInfo.packageName + ")");
2031 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2032 return;
2033 }
2034
2035 mObbState.filename = obbInfo.filename;
2036
2037 int rc = StorageResultCode.OperationSucceeded;
2038 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2039 (mForceUnmount ? " force" : ""));
2040 try {
2041 mConnector.doCommand(cmd);
2042 } catch (NativeDaemonConnectorException e) {
2043 int code = e.getCode();
2044 if (code == VoldResponseCode.OpFailedStorageBusy) {
2045 rc = StorageResultCode.OperationFailedStorageBusy;
2046 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2047 // If it's not mounted then we've already won.
2048 rc = StorageResultCode.OperationSucceeded;
2049 } else {
2050 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002051 }
2052 }
2053
Kenny Rootaf9d6672010-10-08 09:21:39 -07002054 if (rc == StorageResultCode.OperationSucceeded) {
2055 synchronized (mObbMounts) {
2056 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002057 }
2058
Kenny Rootaf9d6672010-10-08 09:21:39 -07002059 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002060 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002061 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2062 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002063 }
2064 }
2065
2066 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002067 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002068 }
2069
2070 @Override
2071 public String toString() {
2072 StringBuilder sb = new StringBuilder();
2073 sb.append("UnmountObbAction{");
2074 sb.append("filename=");
2075 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2076 sb.append(",force=");
2077 sb.append(mForceUnmount);
2078 sb.append(",callerUid=");
2079 sb.append(mObbState.callerUid);
2080 sb.append(",token=");
2081 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002082 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002083 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002084 sb.append('}');
2085 return sb.toString();
2086 }
Kenny Root02c87302010-07-01 08:10:18 -07002087 }
Kenny Root38cf8862010-09-26 14:18:51 -07002088
2089 @Override
2090 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2091 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2092 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2093 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2094 + " without permission " + android.Manifest.permission.DUMP);
2095 return;
2096 }
2097
Kenny Root38cf8862010-09-26 14:18:51 -07002098 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002099 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002100
Kenny Rootaf9d6672010-10-08 09:21:39 -07002101 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2102 while (binders.hasNext()) {
2103 Entry<IBinder, List<ObbState>> e = binders.next();
2104 pw.print(" Key="); pw.println(e.getKey().toString());
2105 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002106 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002107 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002108 }
2109 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002110
2111 pw.println("");
2112 pw.println(" mObbPathToStateMap:");
2113 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2114 while (maps.hasNext()) {
2115 final Entry<String, ObbState> e = maps.next();
2116 pw.print(" "); pw.print(e.getKey());
2117 pw.print(" -> "); pw.println(e.getValue().toString());
2118 }
Kenny Root38cf8862010-09-26 14:18:51 -07002119 }
2120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121}
2122