blob: 64cd66128dc427cd741dd9dcbcec2e6e32890a0a [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));
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001158 } else if (observer != null) {
1159 /*
1160 * Observer is waiting for onShutDownComplete when we are done.
1161 * Since nothing will be done send notification directly so shutdown
1162 * sequence can continue.
1163 */
1164 try {
1165 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1166 } catch (RemoteException e) {
1167 Slog.w(TAG, "RemoteException when shutting down");
1168 }
San Mehat4270e1e2010-01-29 05:32:19 -08001169 }
1170 }
1171
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001172 private boolean getUmsEnabling() {
1173 synchronized (mListeners) {
1174 return mUmsEnabling;
1175 }
1176 }
1177
1178 private void setUmsEnabling(boolean enable) {
1179 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001180 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001181 }
1182 }
1183
San Mehatb1043402010-02-05 08:26:50 -08001184 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001185 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001186
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001187 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001188 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001189 }
San Mehatb1043402010-02-05 08:26:50 -08001190 return doGetShareMethodAvailable("ums");
1191 }
1192
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001193 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001194 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001195 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001196
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001197 // TODO: Add support for multiple share methods
1198
1199 /*
1200 * If the volume is mounted and we're enabling then unmount it
1201 */
1202 String path = Environment.getExternalStorageDirectory().getPath();
1203 String vs = getVolumeState(path);
1204 String method = "ums";
1205 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1206 // Override for isUsbMassStorageEnabled()
1207 setUmsEnabling(enable);
1208 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1209 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1210 // Clear override
1211 setUmsEnabling(false);
1212 }
1213 /*
1214 * If we disabled UMS then mount the volume
1215 */
1216 if (!enable) {
1217 doShareUnshareVolume(path, method, enable);
1218 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001219 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001220 " after disabling share method " + method);
1221 /*
1222 * Even though the mount failed, the unshare didn't so don't indicate an error.
1223 * The mountVolume() call will have set the storage state and sent the necessary
1224 * broadcasts.
1225 */
1226 }
1227 }
San Mehatb1043402010-02-05 08:26:50 -08001228 }
1229
1230 public boolean isUsbMassStorageEnabled() {
1231 waitForReady();
1232 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
San Mehat4270e1e2010-01-29 05:32:19 -08001234
San Mehat7fd0fee2009-12-17 07:12:23 -08001235 /**
1236 * @return state of the volume at the specified mount point
1237 */
San Mehat4270e1e2010-01-29 05:32:19 -08001238 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001239 /*
1240 * XXX: Until we have multiple volume discovery, just hardwire
1241 * this to /sdcard
1242 */
1243 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001244 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001245 throw new IllegalArgumentException();
1246 }
1247
1248 return mLegacyState;
1249 }
1250
Kenny Roote1ff2142010-10-12 11:20:01 -07001251 public boolean isExternalStorageEmulated() {
1252 return mEmulateExternalStorage;
1253 }
1254
San Mehat4270e1e2010-01-29 05:32:19 -08001255 public int mountVolume(String path) {
1256 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001257
San Mehat207e5382010-02-04 20:46:54 -08001258 waitForReady();
1259 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001262 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001263 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001264 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001266 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001267 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001268 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1269 Environment.MEDIA_REMOVED.equals(volState) ||
1270 Environment.MEDIA_SHARED.equals(volState) ||
1271 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1272 // Media already unmounted or cannot be unmounted.
1273 // TODO return valid return code when adding observer call back.
1274 return;
1275 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001276 UnmountCallBack ucb = new UnmountCallBack(path, force);
1277 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
1279
San Mehat4270e1e2010-01-29 05:32:19 -08001280 public int formatVolume(String path) {
1281 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001282 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001283
San Mehat207e5382010-02-04 20:46:54 -08001284 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
San Mehatc1b4ce92010-02-16 17:13:03 -08001287 public int []getStorageUsers(String path) {
1288 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1289 waitForReady();
1290 try {
1291 String[] r = mConnector.doListCommand(
1292 String.format("storage users %s", path),
1293 VoldResponseCode.StorageUsersListResult);
1294 // FMT: <pid> <process name>
1295 int[] data = new int[r.length];
1296 for (int i = 0; i < r.length; i++) {
1297 String []tok = r[i].split(" ");
1298 try {
1299 data[i] = Integer.parseInt(tok[0]);
1300 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001301 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001302 return new int[0];
1303 }
1304 }
1305 return data;
1306 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001307 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001308 return new int[0];
1309 }
1310 }
1311
San Mehatb1043402010-02-05 08:26:50 -08001312 private void warnOnNotMounted() {
1313 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001314 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001315 }
1316 }
1317
San Mehat4270e1e2010-01-29 05:32:19 -08001318 public String[] getSecureContainerList() {
1319 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001320 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001321 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001322
San Mehat4270e1e2010-01-29 05:32:19 -08001323 try {
1324 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1325 } catch (NativeDaemonConnectorException e) {
1326 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 }
San Mehat36972292010-01-06 11:06:32 -08001329
San Mehat4270e1e2010-01-29 05:32:19 -08001330 public int createSecureContainer(String id, int sizeMb, String fstype,
1331 String key, int ownerUid) {
1332 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001333 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001334 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001335
San Mehatb1043402010-02-05 08:26:50 -08001336 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001337 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1338 try {
1339 mConnector.doCommand(cmd);
1340 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001341 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001342 }
San Mehata181b212010-02-11 06:50:20 -08001343
1344 if (rc == StorageResultCode.OperationSucceeded) {
1345 synchronized (mAsecMountSet) {
1346 mAsecMountSet.add(id);
1347 }
1348 }
San Mehat4270e1e2010-01-29 05:32:19 -08001349 return rc;
San Mehat36972292010-01-06 11:06:32 -08001350 }
1351
San Mehat4270e1e2010-01-29 05:32:19 -08001352 public int finalizeSecureContainer(String id) {
1353 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001354 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001355
San Mehatb1043402010-02-05 08:26:50 -08001356 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001357 try {
1358 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001359 /*
1360 * Finalization does a remount, so no need
1361 * to update mAsecMountSet
1362 */
San Mehat4270e1e2010-01-29 05:32:19 -08001363 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001364 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001365 }
San Mehat4270e1e2010-01-29 05:32:19 -08001366 return rc;
San Mehat36972292010-01-06 11:06:32 -08001367 }
1368
San Mehatd9709982010-02-18 11:43:03 -08001369 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001370 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001371 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001372 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001373
Kenny Rootaa485402010-09-14 14:49:41 -07001374 /*
1375 * Force a GC to make sure AssetManagers in other threads of the
1376 * system_server are cleaned up. We have to do this since AssetManager
1377 * instances are kept as a WeakReference and it's possible we have files
1378 * open on the external storage.
1379 */
1380 Runtime.getRuntime().gc();
1381
San Mehatb1043402010-02-05 08:26:50 -08001382 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001383 try {
San Mehatd9709982010-02-18 11:43:03 -08001384 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001385 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001386 int code = e.getCode();
1387 if (code == VoldResponseCode.OpFailedStorageBusy) {
1388 rc = StorageResultCode.OperationFailedStorageBusy;
1389 } else {
1390 rc = StorageResultCode.OperationFailedInternalError;
1391 }
San Mehat02735bc2010-01-26 15:18:08 -08001392 }
San Mehata181b212010-02-11 06:50:20 -08001393
1394 if (rc == StorageResultCode.OperationSucceeded) {
1395 synchronized (mAsecMountSet) {
1396 if (mAsecMountSet.contains(id)) {
1397 mAsecMountSet.remove(id);
1398 }
1399 }
1400 }
1401
San Mehat4270e1e2010-01-29 05:32:19 -08001402 return rc;
San Mehat36972292010-01-06 11:06:32 -08001403 }
1404
San Mehat4270e1e2010-01-29 05:32:19 -08001405 public int mountSecureContainer(String id, String key, int ownerUid) {
1406 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001407 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001408 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001409
San Mehata181b212010-02-11 06:50:20 -08001410 synchronized (mAsecMountSet) {
1411 if (mAsecMountSet.contains(id)) {
1412 return StorageResultCode.OperationFailedStorageMounted;
1413 }
1414 }
1415
San Mehatb1043402010-02-05 08:26:50 -08001416 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001417 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1418 try {
1419 mConnector.doCommand(cmd);
1420 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001421 int code = e.getCode();
1422 if (code != VoldResponseCode.OpFailedStorageBusy) {
1423 rc = StorageResultCode.OperationFailedInternalError;
1424 }
San Mehat02735bc2010-01-26 15:18:08 -08001425 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001426
1427 if (rc == StorageResultCode.OperationSucceeded) {
1428 synchronized (mAsecMountSet) {
1429 mAsecMountSet.add(id);
1430 }
1431 }
San Mehat4270e1e2010-01-29 05:32:19 -08001432 return rc;
San Mehat36972292010-01-06 11:06:32 -08001433 }
1434
San Mehatd9709982010-02-18 11:43:03 -08001435 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001436 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001437 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001438 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001439
San Mehat6cdd9c02010-02-09 14:45:20 -08001440 synchronized (mAsecMountSet) {
1441 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001442 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001443 }
1444 }
1445
Kenny Rootaa485402010-09-14 14:49:41 -07001446 /*
1447 * Force a GC to make sure AssetManagers in other threads of the
1448 * system_server are cleaned up. We have to do this since AssetManager
1449 * instances are kept as a WeakReference and it's possible we have files
1450 * open on the external storage.
1451 */
1452 Runtime.getRuntime().gc();
1453
San Mehatb1043402010-02-05 08:26:50 -08001454 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001455 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001456 try {
1457 mConnector.doCommand(cmd);
1458 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001459 int code = e.getCode();
1460 if (code == VoldResponseCode.OpFailedStorageBusy) {
1461 rc = StorageResultCode.OperationFailedStorageBusy;
1462 } else {
1463 rc = StorageResultCode.OperationFailedInternalError;
1464 }
San Mehat02735bc2010-01-26 15:18:08 -08001465 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001466
1467 if (rc == StorageResultCode.OperationSucceeded) {
1468 synchronized (mAsecMountSet) {
1469 mAsecMountSet.remove(id);
1470 }
1471 }
San Mehat4270e1e2010-01-29 05:32:19 -08001472 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001473 }
1474
San Mehat6cdd9c02010-02-09 14:45:20 -08001475 public boolean isSecureContainerMounted(String id) {
1476 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1477 waitForReady();
1478 warnOnNotMounted();
1479
1480 synchronized (mAsecMountSet) {
1481 return mAsecMountSet.contains(id);
1482 }
1483 }
1484
San Mehat4270e1e2010-01-29 05:32:19 -08001485 public int renameSecureContainer(String oldId, String newId) {
1486 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001487 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001488 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001489
San Mehata181b212010-02-11 06:50:20 -08001490 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001491 /*
1492 * Because a mounted container has active internal state which cannot be
1493 * changed while active, we must ensure both ids are not currently mounted.
1494 */
1495 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001496 return StorageResultCode.OperationFailedStorageMounted;
1497 }
1498 }
1499
San Mehatb1043402010-02-05 08:26:50 -08001500 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001501 String cmd = String.format("asec rename %s %s", oldId, newId);
1502 try {
1503 mConnector.doCommand(cmd);
1504 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001505 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001506 }
San Mehata181b212010-02-11 06:50:20 -08001507
San Mehat4270e1e2010-01-29 05:32:19 -08001508 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001509 }
1510
San Mehat4270e1e2010-01-29 05:32:19 -08001511 public String getSecureContainerPath(String id) {
1512 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001513 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001514 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001515
San Mehat2d66cef2010-03-23 11:12:52 -07001516 try {
1517 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1518 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001519 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001520 if (code != VoldResponseCode.AsecPathResult) {
1521 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1522 }
1523 return tok[1];
1524 } catch (NativeDaemonConnectorException e) {
1525 int code = e.getCode();
1526 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1527 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001528 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001529 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001530 }
1531 }
San Mehat22dd86e2010-01-12 12:21:18 -08001532 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001533
1534 public void finishMediaUpdate() {
1535 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1536 }
Kenny Root02c87302010-07-01 08:10:18 -07001537
Kenny Roota02b8b02010-08-05 16:14:17 -07001538 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1539 if (callerUid == android.os.Process.SYSTEM_UID) {
1540 return true;
1541 }
1542
Kenny Root02c87302010-07-01 08:10:18 -07001543 if (packageName == null) {
1544 return false;
1545 }
1546
1547 final int packageUid = mPms.getPackageUid(packageName);
1548
1549 if (DEBUG_OBB) {
1550 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1551 packageUid + ", callerUid = " + callerUid);
1552 }
1553
1554 return callerUid == packageUid;
1555 }
1556
1557 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001558 if (filename == null) {
1559 throw new IllegalArgumentException("filename cannot be null");
1560 }
1561
Kenny Root02c87302010-07-01 08:10:18 -07001562 waitForReady();
1563 warnOnNotMounted();
1564
Kenny Root02c87302010-07-01 08:10:18 -07001565 try {
1566 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1567 String []tok = rsp.get(0).split(" ");
1568 int code = Integer.parseInt(tok[0]);
1569 if (code != VoldResponseCode.AsecPathResult) {
1570 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1571 }
1572 return tok[1];
1573 } catch (NativeDaemonConnectorException e) {
1574 int code = e.getCode();
1575 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001576 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001577 } else {
1578 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1579 }
1580 }
1581 }
1582
1583 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001584 if (filename == null) {
1585 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001586 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001587
1588 synchronized (mObbMounts) {
1589 return mObbPathToStateMap.containsKey(filename);
1590 }
Kenny Root02c87302010-07-01 08:10:18 -07001591 }
1592
Kenny Rootaf9d6672010-10-08 09:21:39 -07001593 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001594 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001595 if (filename == null) {
1596 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001597 }
1598
1599 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001600 throw new IllegalArgumentException("token cannot be null");
1601 }
1602
Kenny Rootaf9d6672010-10-08 09:21:39 -07001603 final int callerUid = Binder.getCallingUid();
1604 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1605 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001606 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1607
1608 if (DEBUG_OBB)
1609 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001610 }
1611
Kenny Rootaf9d6672010-10-08 09:21:39 -07001612 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1613 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001614 if (filename == null) {
1615 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001616 }
1617
Kenny Rootaf9d6672010-10-08 09:21:39 -07001618 final int callerUid = Binder.getCallingUid();
1619 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1620 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001621 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001622
Kenny Roota02b8b02010-08-05 16:14:17 -07001623 if (DEBUG_OBB)
1624 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1625 }
1626
Kenny Rootaf9d6672010-10-08 09:21:39 -07001627 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1628 final IBinder binder = obbState.getBinder();
1629 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001630
Kenny Rootaf9d6672010-10-08 09:21:39 -07001631 if (obbStates == null) {
1632 obbStates = new ArrayList<ObbState>();
1633 mObbMounts.put(binder, obbStates);
1634 } else {
1635 for (final ObbState o : obbStates) {
1636 if (o.filename.equals(obbState.filename)) {
1637 throw new IllegalStateException("Attempt to add ObbState twice. "
1638 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001639 }
1640 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001641 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001642
1643 obbStates.add(obbState);
1644 try {
1645 obbState.link();
1646 } catch (RemoteException e) {
1647 /*
1648 * The binder died before we could link it, so clean up our state
1649 * and return failure.
1650 */
1651 obbStates.remove(obbState);
1652 if (obbStates.isEmpty()) {
1653 mObbMounts.remove(binder);
1654 }
1655
1656 // Rethrow the error so mountObb can get it
1657 throw e;
1658 }
1659
1660 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001661 }
1662
Kenny Rootaf9d6672010-10-08 09:21:39 -07001663 private void removeObbStateLocked(ObbState obbState) {
1664 final IBinder binder = obbState.getBinder();
1665 final List<ObbState> obbStates = mObbMounts.get(binder);
1666 if (obbStates != null) {
1667 if (obbStates.remove(obbState)) {
1668 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001669 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001670 if (obbStates.isEmpty()) {
1671 mObbMounts.remove(binder);
1672 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001673 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001674
Kenny Rootaf9d6672010-10-08 09:21:39 -07001675 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001676 }
1677
Kenny Roota02b8b02010-08-05 16:14:17 -07001678 private class ObbActionHandler extends Handler {
1679 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001680 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001681
1682 ObbActionHandler(Looper l) {
1683 super(l);
1684 }
1685
1686 @Override
1687 public void handleMessage(Message msg) {
1688 switch (msg.what) {
1689 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001690 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001691
1692 if (DEBUG_OBB)
1693 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1694
1695 // If a bind was already initiated we don't really
1696 // need to do anything. The pending install
1697 // will be processed later on.
1698 if (!mBound) {
1699 // If this is the only one pending we might
1700 // have to bind to the service again.
1701 if (!connectToService()) {
1702 Slog.e(TAG, "Failed to bind to media container service");
1703 action.handleError();
1704 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001705 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001706 }
Kenny Root735de3b2010-09-30 14:11:39 -07001707
Kenny Root735de3b2010-09-30 14:11:39 -07001708 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001709 break;
1710 }
1711 case OBB_MCS_BOUND: {
1712 if (DEBUG_OBB)
1713 Slog.i(TAG, "OBB_MCS_BOUND");
1714 if (msg.obj != null) {
1715 mContainerService = (IMediaContainerService) msg.obj;
1716 }
1717 if (mContainerService == null) {
1718 // Something seriously wrong. Bail out
1719 Slog.e(TAG, "Cannot bind to media container service");
1720 for (ObbAction action : mActions) {
1721 // Indicate service bind error
1722 action.handleError();
1723 }
1724 mActions.clear();
1725 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001726 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001727 if (action != null) {
1728 action.execute(this);
1729 }
1730 } else {
1731 // Should never happen ideally.
1732 Slog.w(TAG, "Empty queue");
1733 }
1734 break;
1735 }
1736 case OBB_MCS_RECONNECT: {
1737 if (DEBUG_OBB)
1738 Slog.i(TAG, "OBB_MCS_RECONNECT");
1739 if (mActions.size() > 0) {
1740 if (mBound) {
1741 disconnectService();
1742 }
1743 if (!connectToService()) {
1744 Slog.e(TAG, "Failed to bind to media container service");
1745 for (ObbAction action : mActions) {
1746 // Indicate service bind error
1747 action.handleError();
1748 }
1749 mActions.clear();
1750 }
1751 }
1752 break;
1753 }
1754 case OBB_MCS_UNBIND: {
1755 if (DEBUG_OBB)
1756 Slog.i(TAG, "OBB_MCS_UNBIND");
1757
1758 // Delete pending install
1759 if (mActions.size() > 0) {
1760 mActions.remove(0);
1761 }
1762 if (mActions.size() == 0) {
1763 if (mBound) {
1764 disconnectService();
1765 }
1766 } else {
1767 // There are more pending requests in queue.
1768 // Just post MCS_BOUND message to trigger processing
1769 // of next pending install.
1770 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1771 }
1772 break;
1773 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001774 case OBB_FLUSH_MOUNT_STATE: {
1775 final String path = (String) msg.obj;
1776
1777 if (DEBUG_OBB)
1778 Slog.i(TAG, "Flushing all OBB state for path " + path);
1779
1780 synchronized (mObbMounts) {
1781 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1782
1783 final Iterator<Entry<String, ObbState>> i =
1784 mObbPathToStateMap.entrySet().iterator();
1785 while (i.hasNext()) {
1786 final Entry<String, ObbState> obbEntry = i.next();
1787
1788 /*
1789 * If this entry's source file is in the volume path
1790 * that got unmounted, remove it because it's no
1791 * longer valid.
1792 */
1793 if (obbEntry.getKey().startsWith(path)) {
1794 obbStatesToRemove.add(obbEntry.getValue());
1795 }
1796 }
1797
1798 for (final ObbState obbState : obbStatesToRemove) {
1799 if (DEBUG_OBB)
1800 Slog.i(TAG, "Removing state for " + obbState.filename);
1801
1802 removeObbStateLocked(obbState);
1803
1804 try {
1805 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1806 OnObbStateChangeListener.UNMOUNTED);
1807 } catch (RemoteException e) {
1808 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1809 + obbState.filename);
1810 }
1811 }
1812 }
1813 break;
1814 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001815 }
1816 }
1817
1818 private boolean connectToService() {
1819 if (DEBUG_OBB)
1820 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1821
1822 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1823 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1824 mBound = true;
1825 return true;
1826 }
1827 return false;
1828 }
1829
1830 private void disconnectService() {
1831 mContainerService = null;
1832 mBound = false;
1833 mContext.unbindService(mDefContainerConn);
1834 }
1835 }
1836
1837 abstract class ObbAction {
1838 private static final int MAX_RETRIES = 3;
1839 private int mRetries;
1840
1841 ObbState mObbState;
1842
1843 ObbAction(ObbState obbState) {
1844 mObbState = obbState;
1845 }
1846
1847 public void execute(ObbActionHandler handler) {
1848 try {
1849 if (DEBUG_OBB)
1850 Slog.i(TAG, "Starting to execute action: " + this.toString());
1851 mRetries++;
1852 if (mRetries > MAX_RETRIES) {
1853 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001854 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001855 handleError();
1856 return;
1857 } else {
1858 handleExecute();
1859 if (DEBUG_OBB)
1860 Slog.i(TAG, "Posting install MCS_UNBIND");
1861 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1862 }
1863 } catch (RemoteException e) {
1864 if (DEBUG_OBB)
1865 Slog.i(TAG, "Posting install MCS_RECONNECT");
1866 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1867 } catch (Exception e) {
1868 if (DEBUG_OBB)
1869 Slog.d(TAG, "Error handling OBB action", e);
1870 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001871 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001872 }
1873 }
1874
Kenny Root05105f72010-09-22 17:29:43 -07001875 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001876 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001877
1878 protected ObbInfo getObbInfo() throws IOException {
1879 ObbInfo obbInfo;
1880 try {
1881 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1882 } catch (RemoteException e) {
1883 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1884 + mObbState.filename);
1885 obbInfo = null;
1886 }
1887 if (obbInfo == null) {
1888 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1889 }
1890 return obbInfo;
1891 }
1892
Kenny Rootaf9d6672010-10-08 09:21:39 -07001893 protected void sendNewStatusOrIgnore(int status) {
1894 if (mObbState == null || mObbState.token == null) {
1895 return;
1896 }
1897
Kenny Root38cf8862010-09-26 14:18:51 -07001898 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001899 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07001900 } catch (RemoteException e) {
1901 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1902 }
1903 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001904 }
1905
1906 class MountObbAction extends ObbAction {
1907 private String mKey;
1908
1909 MountObbAction(ObbState obbState, String key) {
1910 super(obbState);
1911 mKey = key;
1912 }
1913
Kenny Root735de3b2010-09-30 14:11:39 -07001914 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001915 waitForReady();
1916 warnOnNotMounted();
1917
Kenny Root38cf8862010-09-26 14:18:51 -07001918 final ObbInfo obbInfo = getObbInfo();
1919
Kenny Roota02b8b02010-08-05 16:14:17 -07001920 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001921 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
1922 + " which is owned by " + obbInfo.packageName);
1923 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
1924 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001925 }
1926
Kenny Rootaf9d6672010-10-08 09:21:39 -07001927 final boolean isMounted;
1928 synchronized (mObbMounts) {
1929 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
1930 }
1931 if (isMounted) {
1932 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
1933 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
1934 return;
1935 }
1936
1937 /*
1938 * The filename passed in might not be the canonical name, so just
1939 * set the filename to the canonicalized version.
1940 */
1941 mObbState.filename = obbInfo.filename;
1942
1943 final String hashedKey;
1944 if (mKey == null) {
1945 hashedKey = "none";
1946 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001947 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07001948 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1949
1950 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
1951 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
1952 SecretKey key = factory.generateSecret(ks);
1953 BigInteger bi = new BigInteger(key.getEncoded());
1954 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001955 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07001956 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
1957 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
1958 return;
1959 } catch (InvalidKeySpecException e) {
1960 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
1961 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07001962 return;
1963 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001964 }
Kenny Root38cf8862010-09-26 14:18:51 -07001965
Kenny Rootaf9d6672010-10-08 09:21:39 -07001966 int rc = StorageResultCode.OperationSucceeded;
1967 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
1968 mObbState.callerUid);
1969 try {
1970 mConnector.doCommand(cmd);
1971 } catch (NativeDaemonConnectorException e) {
1972 int code = e.getCode();
1973 if (code != VoldResponseCode.OpFailedStorageBusy) {
1974 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07001975 }
1976 }
1977
Kenny Rootaf9d6672010-10-08 09:21:39 -07001978 if (rc == StorageResultCode.OperationSucceeded) {
1979 if (DEBUG_OBB)
1980 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
1981
1982 synchronized (mObbMounts) {
1983 addObbStateLocked(mObbState);
1984 }
1985
1986 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001987 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001988 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001989
Kenny Rootaf9d6672010-10-08 09:21:39 -07001990 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07001991 }
1992 }
1993
Kenny Roota02b8b02010-08-05 16:14:17 -07001994 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001995 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07001996 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001997
1998 @Override
1999 public String toString() {
2000 StringBuilder sb = new StringBuilder();
2001 sb.append("MountObbAction{");
2002 sb.append("filename=");
2003 sb.append(mObbState.filename);
2004 sb.append(",callerUid=");
2005 sb.append(mObbState.callerUid);
2006 sb.append(",token=");
2007 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002008 sb.append(",binder=");
2009 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002010 sb.append('}');
2011 return sb.toString();
2012 }
2013 }
2014
2015 class UnmountObbAction extends ObbAction {
2016 private boolean mForceUnmount;
2017
2018 UnmountObbAction(ObbState obbState, boolean force) {
2019 super(obbState);
2020 mForceUnmount = force;
2021 }
2022
Kenny Root38cf8862010-09-26 14:18:51 -07002023 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002024 waitForReady();
2025 warnOnNotMounted();
2026
Kenny Root38cf8862010-09-26 14:18:51 -07002027 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002028
Kenny Rootaf9d6672010-10-08 09:21:39 -07002029 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002030 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002031 obbState = mObbPathToStateMap.get(obbInfo.filename);
2032 }
Kenny Root38cf8862010-09-26 14:18:51 -07002033
Kenny Rootaf9d6672010-10-08 09:21:39 -07002034 if (obbState == null) {
2035 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2036 return;
2037 }
2038
2039 if (obbState.callerUid != mObbState.callerUid) {
2040 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2041 + " (owned by " + obbInfo.packageName + ")");
2042 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2043 return;
2044 }
2045
2046 mObbState.filename = obbInfo.filename;
2047
2048 int rc = StorageResultCode.OperationSucceeded;
2049 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2050 (mForceUnmount ? " force" : ""));
2051 try {
2052 mConnector.doCommand(cmd);
2053 } catch (NativeDaemonConnectorException e) {
2054 int code = e.getCode();
2055 if (code == VoldResponseCode.OpFailedStorageBusy) {
2056 rc = StorageResultCode.OperationFailedStorageBusy;
2057 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2058 // If it's not mounted then we've already won.
2059 rc = StorageResultCode.OperationSucceeded;
2060 } else {
2061 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002062 }
2063 }
2064
Kenny Rootaf9d6672010-10-08 09:21:39 -07002065 if (rc == StorageResultCode.OperationSucceeded) {
2066 synchronized (mObbMounts) {
2067 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002068 }
2069
Kenny Rootaf9d6672010-10-08 09:21:39 -07002070 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002071 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002072 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2073 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002074 }
2075 }
2076
2077 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002078 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002079 }
2080
2081 @Override
2082 public String toString() {
2083 StringBuilder sb = new StringBuilder();
2084 sb.append("UnmountObbAction{");
2085 sb.append("filename=");
2086 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2087 sb.append(",force=");
2088 sb.append(mForceUnmount);
2089 sb.append(",callerUid=");
2090 sb.append(mObbState.callerUid);
2091 sb.append(",token=");
2092 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002093 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002094 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002095 sb.append('}');
2096 return sb.toString();
2097 }
Kenny Root02c87302010-07-01 08:10:18 -07002098 }
Kenny Root38cf8862010-09-26 14:18:51 -07002099
2100 @Override
2101 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2102 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2103 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2104 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2105 + " without permission " + android.Manifest.permission.DUMP);
2106 return;
2107 }
2108
Kenny Root38cf8862010-09-26 14:18:51 -07002109 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002110 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002111
Kenny Rootaf9d6672010-10-08 09:21:39 -07002112 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2113 while (binders.hasNext()) {
2114 Entry<IBinder, List<ObbState>> e = binders.next();
2115 pw.print(" Key="); pw.println(e.getKey().toString());
2116 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002117 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002118 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002119 }
2120 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002121
2122 pw.println("");
2123 pw.println(" mObbPathToStateMap:");
2124 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2125 while (maps.hasNext()) {
2126 final Entry<String, ObbState> e = maps.next();
2127 pw.print(" "); pw.print(e.getKey());
2128 pw.print(" -> "); pw.println(e.getValue().toString());
2129 }
Kenny Root38cf8862010-09-26 14:18:51 -07002130 }
2131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132}
2133