blob: 85bb3aa134cc0e52fb9d9794717851409cacb7a6 [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;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800154
San Mehat6cdd9c02010-02-09 14:45:20 -0800155 /**
156 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800157 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800158 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800159 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800160
Kenny Root02c87302010-07-01 08:10:18 -0700161 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700162 * The size of the crypto algorithm key in bits for OBB files. Currently
163 * Twofish is used which takes 128-bit keys.
164 */
165 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
166
167 /**
168 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
169 * 1024 is reasonably secure and not too slow.
170 */
171 private static final int PBKDF2_HASH_ROUNDS = 1024;
172
173 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700174 * Mounted OBB tracking information. Used to track the current state of all
175 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700176 */
Kenny Root735de3b2010-09-30 14:11:39 -0700177 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700178 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
179
180 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700181 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700182 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700183 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700184 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700185 this.token = token;
186 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700187 }
188
189 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700190 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700191
192 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700193 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700194
Kenny Rootaf9d6672010-10-08 09:21:39 -0700195 // Token of remote Binder caller
196 final IObbActionListener token;
197
198 // Identifier to pass back to the token
199 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700200
Kenny Root735de3b2010-09-30 14:11:39 -0700201 public IBinder getBinder() {
202 return token.asBinder();
203 }
204
Kenny Roota02b8b02010-08-05 16:14:17 -0700205 @Override
206 public void binderDied() {
207 ObbAction action = new UnmountObbAction(this, true);
208 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700209 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700210
Kenny Root5919ac62010-10-05 09:49:40 -0700211 public void link() throws RemoteException {
212 getBinder().linkToDeath(this, 0);
213 }
214
215 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700216 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700217 }
Kenny Root38cf8862010-09-26 14:18:51 -0700218
219 @Override
220 public String toString() {
221 StringBuilder sb = new StringBuilder("ObbState{");
222 sb.append("filename=");
223 sb.append(filename);
224 sb.append(",token=");
225 sb.append(token.toString());
226 sb.append(",callerUid=");
227 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700228 sb.append('}');
229 return sb.toString();
230 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700231 }
232
233 // OBB Action Handler
234 final private ObbActionHandler mObbActionHandler;
235
236 // OBB action handler messages
237 private static final int OBB_RUN_ACTION = 1;
238 private static final int OBB_MCS_BOUND = 2;
239 private static final int OBB_MCS_UNBIND = 3;
240 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700241 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700242
243 /*
244 * Default Container Service information
245 */
246 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
247 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
248
249 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
250
251 class DefaultContainerConnection implements ServiceConnection {
252 public void onServiceConnected(ComponentName name, IBinder service) {
253 if (DEBUG_OBB)
254 Slog.i(TAG, "onServiceConnected");
255 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
256 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
257 }
258
259 public void onServiceDisconnected(ComponentName name) {
260 if (DEBUG_OBB)
261 Slog.i(TAG, "onServiceDisconnected");
262 }
263 };
264
265 // Used in the ObbActionHandler
266 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700267
268 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800269 private static final int H_UNMOUNT_PM_UPDATE = 1;
270 private static final int H_UNMOUNT_PM_DONE = 2;
271 private static final int H_UNMOUNT_MS = 3;
272 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
273 private static final int MAX_UNMOUNT_RETRIES = 4;
274
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800275 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700276 final String path;
277 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800278 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800279
280 UnmountCallBack(String path, boolean force) {
281 retries = 0;
282 this.path = path;
283 this.force = force;
284 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800285
286 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700287 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800288 doUnmountVolume(path, true);
289 }
290 }
291
292 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700293 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800294
295 UmsEnableCallBack(String path, String method, boolean force) {
296 super(path, force);
297 this.method = method;
298 }
299
300 @Override
301 void handleFinished() {
302 super.handleFinished();
303 doShareUnshareVolume(path, method, true);
304 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800305 }
306
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800307 class ShutdownCallBack extends UnmountCallBack {
308 IMountShutdownObserver observer;
309 ShutdownCallBack(String path, IMountShutdownObserver observer) {
310 super(path, true);
311 this.observer = observer;
312 }
313
314 @Override
315 void handleFinished() {
316 int ret = doUnmountVolume(path, true);
317 if (observer != null) {
318 try {
319 observer.onShutDownComplete(ret);
320 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700321 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800322 }
323 }
324 }
325 }
326
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400327 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800328 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700329 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800330
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400331 MountServiceHandler(Looper l) {
332 super(l);
333 }
334
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800335 public void handleMessage(Message msg) {
336 switch (msg.what) {
337 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700338 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800339 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
340 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700341 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800342 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700343 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700344 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700345 mUpdatingStatus = true;
346 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800347 }
348 break;
349 }
350 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700351 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700352 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700353 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800354 int size = mForceUnmounts.size();
355 int sizeArr[] = new int[size];
356 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700357 // Kill processes holding references first
358 ActivityManagerService ams = (ActivityManagerService)
359 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800360 for (int i = 0; i < size; i++) {
361 UnmountCallBack ucb = mForceUnmounts.get(i);
362 String path = ucb.path;
363 boolean done = false;
364 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 done = true;
366 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800367 int pids[] = getStorageUsers(path);
368 if (pids == null || pids.length == 0) {
369 done = true;
370 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800371 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700372 ams.killPids(pids, "unmount media");
373 // Confirm if file references have been freed.
374 pids = getStorageUsers(path);
375 if (pids == null || pids.length == 0) {
376 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800377 }
378 }
379 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700380 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
381 // Retry again
382 Slog.i(TAG, "Retrying to kill storage users again");
383 mHandler.sendMessageDelayed(
384 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
385 ucb.retries++),
386 RETRY_UNMOUNT_DELAY);
387 } else {
388 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
389 Slog.i(TAG, "Failed to unmount media inspite of " +
390 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
391 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 sizeArr[sizeArrN++] = i;
393 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
394 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800395 }
396 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800397 // Remove already processed elements from list.
398 for (int i = (sizeArrN-1); i >= 0; i--) {
399 mForceUnmounts.remove(sizeArr[i]);
400 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 break;
402 }
403 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700404 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800405 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800406 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800407 break;
408 }
409 }
410 }
411 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400412 final private HandlerThread mHandlerThread;
413 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800414
San Mehat207e5382010-02-04 20:46:54 -0800415 private void waitForReady() {
416 while (mReady == false) {
417 for (int retries = 5; retries > 0; retries--) {
418 if (mReady) {
419 return;
420 }
421 SystemClock.sleep(1000);
422 }
San Mehata5078592010-03-25 09:36:54 -0700423 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800424 }
San Mehat1f6301e2010-01-07 22:40:27 -0800425 }
Kenny Root02c87302010-07-01 08:10:18 -0700426
San Mehat207e5382010-02-04 20:46:54 -0800427 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800429 String action = intent.getAction();
430
431 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800432 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800433
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800434 /*
435 * In the simulator, we need to broadcast a volume mounted event
436 * to make the media scanner run.
437 */
438 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
439 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
440 return;
441 }
San Mehatfafb0412010-02-18 19:40:04 -0800442 new Thread() {
443 public void run() {
444 try {
445 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700446 String state = getVolumeState(path);
447
448 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800449 int rc = doMountVolume(path);
450 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700451 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800452 }
San Mehat6a254402010-03-22 10:21:00 -0700453 } else if (state.equals(Environment.MEDIA_SHARED)) {
454 /*
455 * Bootstrap UMS enabled state since vold indicates
456 * the volume is shared (runtime restart while ums enabled)
457 */
458 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800459 }
San Mehat6a254402010-03-22 10:21:00 -0700460
San Mehat6a965af22010-02-24 17:47:30 -0800461 /*
San Mehat6a254402010-03-22 10:21:00 -0700462 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800463 * now that we're up.
464 */
465 if (mSendUmsConnectedOnBoot) {
466 sendUmsIntent(true);
467 mSendUmsConnectedOnBoot = false;
468 }
San Mehatfafb0412010-02-18 19:40:04 -0800469 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700470 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800471 }
San Mehat207e5382010-02-04 20:46:54 -0800472 }
San Mehatfafb0412010-02-18 19:40:04 -0800473 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 }
475 }
476 };
477
San Mehat4270e1e2010-01-29 05:32:19 -0800478 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
479 final IMountServiceListener mListener;
480
481 MountServiceBinderListener(IMountServiceListener listener) {
482 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700483
San Mehat91c77612010-01-07 10:39:41 -0800484 }
485
San Mehat4270e1e2010-01-29 05:32:19 -0800486 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700487 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700488 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800489 mListeners.remove(this);
490 mListener.asBinder().unlinkToDeath(this, 0);
491 }
492 }
493 }
494
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800495 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800496 // TODO: Add support for multiple share methods
497 if (!method.equals("ums")) {
498 throw new IllegalArgumentException(String.format("Method %s not supported", method));
499 }
500
San Mehat4270e1e2010-01-29 05:32:19 -0800501 try {
502 mConnector.doCommand(String.format(
503 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
504 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700505 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800506 }
San Mehat4270e1e2010-01-29 05:32:19 -0800507 }
508
San Mehat207e5382010-02-04 20:46:54 -0800509 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800510 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700511 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800512 return;
513 }
San Mehatb1043402010-02-05 08:26:50 -0800514
515 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700516 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800517 return;
518 }
Kenny Rootaf9d6672010-10-08 09:21:39 -0700519
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800520 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700521 // Tell the package manager the media is gone.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700522 mPms.updateExternalMediaStatus(false, false);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700523
524 /*
525 * Some OBBs might have been unmounted when this volume was
526 * unmounted, so send a message to the handler to let it know to
527 * remove those from the list of mounted OBBS.
528 */
529 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_FLUSH_MOUNT_STATE,
530 path));
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800531 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700532 // Tell the package manager the media is available for use.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700533 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800534 }
Kenny Root38cf8862010-09-26 14:18:51 -0700535
San Mehat4270e1e2010-01-29 05:32:19 -0800536 String oldState = mLegacyState;
537 mLegacyState = state;
538
539 synchronized (mListeners) {
540 for (int i = mListeners.size() -1; i >= 0; i--) {
541 MountServiceBinderListener bl = mListeners.get(i);
542 try {
San Mehatb1043402010-02-05 08:26:50 -0800543 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800544 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700545 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800546 mListeners.remove(i);
547 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700548 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800549 }
550 }
551 }
552 }
553
554 /**
555 *
556 * Callback from NativeDaemonConnector
557 */
558 public void onDaemonConnected() {
559 /*
560 * Since we'll be calling back into the NativeDaemonConnector,
561 * we need to do our work in a new thread.
562 */
563 new Thread() {
564 public void run() {
565 /**
566 * Determine media state and UMS detection status
567 */
568 String path = Environment.getExternalStorageDirectory().getPath();
569 String state = Environment.MEDIA_REMOVED;
570
571 try {
572 String[] vols = mConnector.doListCommand(
573 "volume list", VoldResponseCode.VolumeListResult);
574 for (String volstr : vols) {
575 String[] tok = volstr.split(" ");
576 // FMT: <label> <mountpoint> <state>
577 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700578 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800579 "Skipping unknown volume '%s'",tok[1]));
580 continue;
581 }
582 int st = Integer.parseInt(tok[2]);
583 if (st == VolumeState.NoMedia) {
584 state = Environment.MEDIA_REMOVED;
585 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800586 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800587 } else if (st == VolumeState.Mounted) {
588 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700589 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800590 } else if (st == VolumeState.Shared) {
591 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700592 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800593 } else {
594 throw new Exception(String.format("Unexpected state %d", st));
595 }
596 }
597 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700598 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800599 updatePublicVolumeState(path, state);
600 }
601 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700602 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800603 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
604 }
605
606 try {
San Mehat207e5382010-02-04 20:46:54 -0800607 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800608 notifyShareAvailabilityChange("ums", avail);
609 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700610 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800611 }
San Mehat207e5382010-02-04 20:46:54 -0800612 /*
613 * Now that we've done our initialization, release
614 * the hounds!
615 */
616 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800617 }
618 }.start();
619 }
620
621 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800622 * Callback from NativeDaemonConnector
623 */
624 public boolean onEvent(int code, String raw, String[] cooked) {
625 Intent in = null;
626
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800627 if (DEBUG_EVENTS) {
628 StringBuilder builder = new StringBuilder();
629 builder.append("onEvent::");
630 builder.append(" raw= " + raw);
631 if (cooked != null) {
632 builder.append(" cooked = " );
633 for (String str : cooked) {
634 builder.append(" " + str);
635 }
636 }
San Mehata5078592010-03-25 09:36:54 -0700637 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800638 }
San Mehat4270e1e2010-01-29 05:32:19 -0800639 if (code == VoldResponseCode.VolumeStateChange) {
640 /*
641 * One of the volumes we're managing has changed state.
642 * Format: "NNN Volume <label> <path> state changed
643 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
644 */
645 notifyVolumeStateChange(
646 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
647 Integer.parseInt(cooked[10]));
648 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
649 // FMT: NNN Share method <method> now <available|unavailable>
650 boolean avail = false;
651 if (cooked[5].equals("available")) {
652 avail = true;
653 }
654 notifyShareAvailabilityChange(cooked[3], avail);
655 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
656 (code == VoldResponseCode.VolumeDiskRemoved) ||
657 (code == VoldResponseCode.VolumeBadRemoval)) {
658 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
659 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
660 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
661 final String label = cooked[2];
662 final String path = cooked[3];
663 int major = -1;
664 int minor = -1;
665
666 try {
667 String devComp = cooked[6].substring(1, cooked[6].length() -1);
668 String[] devTok = devComp.split(":");
669 major = Integer.parseInt(devTok[0]);
670 minor = Integer.parseInt(devTok[1]);
671 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700672 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800673 }
674
San Mehat4270e1e2010-01-29 05:32:19 -0800675 if (code == VoldResponseCode.VolumeDiskInserted) {
676 new Thread() {
677 public void run() {
678 try {
679 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800680 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700681 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800682 }
683 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700684 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800685 }
686 }
687 }.start();
688 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
689 /*
690 * This event gets trumped if we're already in BAD_REMOVAL state
691 */
692 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
693 return true;
694 }
695 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700696 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800697 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
698 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
699 mContext.sendBroadcast(in);
700
San Mehata5078592010-03-25 09:36:54 -0700701 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800702 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
703 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
704 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700705 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800706 /* Send the media unmounted event first */
707 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
708 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
709 mContext.sendBroadcast(in);
710
San Mehata5078592010-03-25 09:36:54 -0700711 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800712 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
713 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
714 } else {
San Mehata5078592010-03-25 09:36:54 -0700715 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800716 }
717 } else {
718 return false;
719 }
720
721 if (in != null) {
722 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400723 }
724 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800725 }
726
San Mehat207e5382010-02-04 20:46:54 -0800727 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800728 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700729 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800730
731 Intent in = null;
732
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500733 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700734 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500735 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
736 Uri.parse("file://" + path)));
737 }
738
San Mehat4270e1e2010-01-29 05:32:19 -0800739 if (newState == VolumeState.Init) {
740 } else if (newState == VolumeState.NoMedia) {
741 // NoMedia is handled via Disk Remove events
742 } else if (newState == VolumeState.Idle) {
743 /*
744 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
745 * if we're in the process of enabling UMS
746 */
747 if (!vs.equals(
748 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
749 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800750 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700751 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
753 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
754 }
755 } else if (newState == VolumeState.Pending) {
756 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700757 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800758 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
759 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
760 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700761 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800762 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800763 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
764 in.putExtra("read-only", false);
765 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800766 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
767 } else if (newState == VolumeState.Formatting) {
768 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700769 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800770 /* Send the media unmounted event first */
771 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
772 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
773 mContext.sendBroadcast(in);
774
San Mehata5078592010-03-25 09:36:54 -0700775 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800776 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
777 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700778 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800779 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700780 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800781 return;
782 } else {
San Mehata5078592010-03-25 09:36:54 -0700783 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800784 }
785
786 if (in != null) {
787 mContext.sendBroadcast(in);
788 }
789 }
790
San Mehat207e5382010-02-04 20:46:54 -0800791 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700792 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700793 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700794 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700795 } catch (NativeDaemonConnectorException ex) {
796 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
797 return false;
798 }
San Mehat207e5382010-02-04 20:46:54 -0800799
800 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700801 String[] tok = line.split(" ");
802 if (tok.length < 3) {
803 Slog.e(TAG, "Malformed response to share status " + method);
804 return false;
805 }
806
San Mehat207e5382010-02-04 20:46:54 -0800807 int code;
808 try {
809 code = Integer.parseInt(tok[0]);
810 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700811 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800812 return false;
813 }
814 if (code == VoldResponseCode.ShareStatusResult) {
815 if (tok[2].equals("available"))
816 return true;
817 return false;
818 } else {
San Mehata5078592010-03-25 09:36:54 -0700819 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800820 return false;
821 }
822 }
San Mehata5078592010-03-25 09:36:54 -0700823 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800824 return false;
825 }
826
827 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800828 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800829
San Mehata5078592010-03-25 09:36:54 -0700830 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800831 try {
832 mConnector.doCommand(String.format("volume mount %s", path));
833 } catch (NativeDaemonConnectorException e) {
834 /*
835 * Mount failed for some reason
836 */
837 Intent in = null;
838 int code = e.getCode();
839 if (code == VoldResponseCode.OpFailedNoMedia) {
840 /*
841 * Attempt to mount but no media inserted
842 */
San Mehatb1043402010-02-05 08:26:50 -0800843 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800844 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700845 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800846 /*
847 * Media is blank or does not contain a supported filesystem
848 */
849 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
850 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800851 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800852 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700853 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800854 /*
855 * Volume consistency check failed
856 */
857 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
858 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800859 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800860 } else {
San Mehatb1043402010-02-05 08:26:50 -0800861 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800862 }
863
864 /*
865 * Send broadcast intent (if required for the failure)
866 */
867 if (in != null) {
868 mContext.sendBroadcast(in);
869 }
870 }
871
872 return rc;
873 }
874
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800875 /*
876 * If force is not set, we do not unmount if there are
877 * processes holding references to the volume about to be unmounted.
878 * If force is set, all the processes holding references need to be
879 * killed via the ActivityManager before actually unmounting the volume.
880 * This might even take a while and might be retried after timed delays
881 * to make sure we dont end up in an instable state and kill some core
882 * processes.
883 */
San Mehatd9709982010-02-18 11:43:03 -0800884 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800885 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800886 return VoldResponseCode.OpFailedVolNotMounted;
887 }
Kenny Rootaa485402010-09-14 14:49:41 -0700888
889 /*
890 * Force a GC to make sure AssetManagers in other threads of the
891 * system_server are cleaned up. We have to do this since AssetManager
892 * instances are kept as a WeakReference and it's possible we have files
893 * open on the external storage.
894 */
895 Runtime.getRuntime().gc();
896
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800897 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700898 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800899 try {
San Mehatd9709982010-02-18 11:43:03 -0800900 mConnector.doCommand(String.format(
901 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700902 // We unmounted the volume. None of the asec containers are available now.
903 synchronized (mAsecMountSet) {
904 mAsecMountSet.clear();
905 }
San Mehatb1043402010-02-05 08:26:50 -0800906 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800907 } catch (NativeDaemonConnectorException e) {
908 // Don't worry about mismatch in PackageManager since the
909 // call back will handle the status changes any way.
910 int code = e.getCode();
911 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800912 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800913 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
914 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800915 } else {
San Mehatb1043402010-02-05 08:26:50 -0800916 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800917 }
918 }
919 }
920
921 private int doFormatVolume(String path) {
922 try {
923 String cmd = String.format("volume format %s", path);
924 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800925 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800926 } catch (NativeDaemonConnectorException e) {
927 int code = e.getCode();
928 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800929 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800930 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800931 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800932 } else {
San Mehatb1043402010-02-05 08:26:50 -0800933 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800934 }
935 }
936 }
937
San Mehatb1043402010-02-05 08:26:50 -0800938 private boolean doGetVolumeShared(String path, String method) {
939 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700940 ArrayList<String> rsp;
941
942 try {
943 rsp = mConnector.doCommand(cmd);
944 } catch (NativeDaemonConnectorException ex) {
945 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
946 return false;
947 }
San Mehatb1043402010-02-05 08:26:50 -0800948
949 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700950 String[] tok = line.split(" ");
951 if (tok.length < 3) {
952 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
953 return false;
954 }
955
San Mehatb1043402010-02-05 08:26:50 -0800956 int code;
957 try {
958 code = Integer.parseInt(tok[0]);
959 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700960 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800961 return false;
962 }
963 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700964 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800965 } else {
San Mehata5078592010-03-25 09:36:54 -0700966 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800967 return false;
968 }
969 }
San Mehata5078592010-03-25 09:36:54 -0700970 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800971 return false;
972 }
973
San Mehat207e5382010-02-04 20:46:54 -0800974 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800975 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700976 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800977 return;
978 }
979
980 synchronized (mListeners) {
981 for (int i = mListeners.size() -1; i >= 0; i--) {
982 MountServiceBinderListener bl = mListeners.get(i);
983 try {
San Mehatb1043402010-02-05 08:26:50 -0800984 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800985 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700986 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800987 mListeners.remove(i);
988 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700989 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800990 }
991 }
992 }
993
San Mehat207e5382010-02-04 20:46:54 -0800994 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800995 sendUmsIntent(avail);
996 } else {
997 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800998 }
San Mehat2fe718a2010-03-11 12:01:49 -0800999
1000 final String path = Environment.getExternalStorageDirectory().getPath();
1001 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1002 /*
1003 * USB mass storage disconnected while enabled
1004 */
1005 new Thread() {
1006 public void run() {
1007 try {
1008 int rc;
San Mehata5078592010-03-25 09:36:54 -07001009 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001010 doShareUnshareVolume(path, "ums", false);
1011 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001012 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001013 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1014 path, rc));
1015 }
1016 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001017 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001018 }
1019 }
1020 }.start();
1021 }
San Mehat4270e1e2010-01-29 05:32:19 -08001022 }
1023
San Mehat6a965af22010-02-24 17:47:30 -08001024 private void sendUmsIntent(boolean c) {
1025 mContext.sendBroadcast(
1026 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1027 }
1028
San Mehat207e5382010-02-04 20:46:54 -08001029 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001030 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1031 throw new SecurityException(String.format("Requires %s permission", perm));
1032 }
1033 }
1034
1035 /**
San Mehat207e5382010-02-04 20:46:54 -08001036 * Constructs a new MountService instance
1037 *
1038 * @param context Binder context for this service
1039 */
1040 public MountService(Context context) {
1041 mContext = context;
1042
San Mehat207e5382010-02-04 20:46:54 -08001043 // XXX: This will go away soon in favor of IMountServiceObserver
1044 mPms = (PackageManagerService) ServiceManager.getService("package");
1045
1046 mContext.registerReceiver(mBroadcastReceiver,
1047 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1048
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001049 mHandlerThread = new HandlerThread("MountService");
1050 mHandlerThread.start();
1051 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1052
Kenny Roota02b8b02010-08-05 16:14:17 -07001053 // Add OBB Action Handler to MountService thread.
1054 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1055
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001056 /*
1057 * Vold does not run in the simulator, so pretend the connector thread
1058 * ran and did its thing.
1059 */
1060 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1061 mReady = true;
1062 mUmsEnabling = true;
1063 return;
1064 }
1065
Kenny Root305bcbf2010-09-03 07:56:38 -07001066 /*
1067 * Create the connection to vold with a maximum queue of twice the
1068 * amount of containers we'd ever expect to have. This keeps an
1069 * "asec list" from blocking a thread repeatedly.
1070 */
1071 mConnector = new NativeDaemonConnector(this, "vold",
1072 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001073 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001074 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001075 thread.start();
1076 }
1077
1078 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001079 * Exposed API calls below here
1080 */
1081
1082 public void registerListener(IMountServiceListener listener) {
1083 synchronized (mListeners) {
1084 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1085 try {
1086 listener.asBinder().linkToDeath(bl, 0);
1087 mListeners.add(bl);
1088 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001089 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001090 }
1091 }
1092 }
1093
1094 public void unregisterListener(IMountServiceListener listener) {
1095 synchronized (mListeners) {
1096 for(MountServiceBinderListener bl : mListeners) {
1097 if (bl.mListener == listener) {
1098 mListeners.remove(mListeners.indexOf(bl));
1099 return;
1100 }
1101 }
1102 }
1103 }
1104
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001105 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001106 validatePermission(android.Manifest.permission.SHUTDOWN);
1107
San Mehata5078592010-03-25 09:36:54 -07001108 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001109
1110 String path = Environment.getExternalStorageDirectory().getPath();
1111 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001112
1113 if (state.equals(Environment.MEDIA_SHARED)) {
1114 /*
1115 * If the media is currently shared, unshare it.
1116 * XXX: This is still dangerous!. We should not
1117 * be rebooting at *all* if UMS is enabled, since
1118 * the UMS host could have dirty FAT cache entries
1119 * yet to flush.
1120 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001121 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001122 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1123 /*
1124 * If the media is being checked, then we need to wait for
1125 * it to complete before being able to proceed.
1126 */
1127 // XXX: @hackbod - Should we disable the ANR timer here?
1128 int retries = 30;
1129 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1130 try {
1131 Thread.sleep(1000);
1132 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001133 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001134 break;
1135 }
1136 state = Environment.getExternalStorageState();
1137 }
1138 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001139 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001140 }
1141 }
1142
1143 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001144 // Post a unmount message.
1145 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1146 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001147 }
1148 }
1149
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001150 private boolean getUmsEnabling() {
1151 synchronized (mListeners) {
1152 return mUmsEnabling;
1153 }
1154 }
1155
1156 private void setUmsEnabling(boolean enable) {
1157 synchronized (mListeners) {
Tony Wub09773d2010-08-09 16:49:19 +08001158 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001159 }
1160 }
1161
San Mehatb1043402010-02-05 08:26:50 -08001162 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001163 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001164
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001165 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001166 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001167 }
San Mehatb1043402010-02-05 08:26:50 -08001168 return doGetShareMethodAvailable("ums");
1169 }
1170
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001171 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001172 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001173 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001174
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001175 // TODO: Add support for multiple share methods
1176
1177 /*
1178 * If the volume is mounted and we're enabling then unmount it
1179 */
1180 String path = Environment.getExternalStorageDirectory().getPath();
1181 String vs = getVolumeState(path);
1182 String method = "ums";
1183 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1184 // Override for isUsbMassStorageEnabled()
1185 setUmsEnabling(enable);
1186 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1187 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1188 // Clear override
1189 setUmsEnabling(false);
1190 }
1191 /*
1192 * If we disabled UMS then mount the volume
1193 */
1194 if (!enable) {
1195 doShareUnshareVolume(path, method, enable);
1196 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001197 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001198 " after disabling share method " + method);
1199 /*
1200 * Even though the mount failed, the unshare didn't so don't indicate an error.
1201 * The mountVolume() call will have set the storage state and sent the necessary
1202 * broadcasts.
1203 */
1204 }
1205 }
San Mehatb1043402010-02-05 08:26:50 -08001206 }
1207
1208 public boolean isUsbMassStorageEnabled() {
1209 waitForReady();
1210 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
San Mehat4270e1e2010-01-29 05:32:19 -08001212
San Mehat7fd0fee2009-12-17 07:12:23 -08001213 /**
1214 * @return state of the volume at the specified mount point
1215 */
San Mehat4270e1e2010-01-29 05:32:19 -08001216 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001217 /*
1218 * XXX: Until we have multiple volume discovery, just hardwire
1219 * this to /sdcard
1220 */
1221 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001222 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001223 throw new IllegalArgumentException();
1224 }
1225
1226 return mLegacyState;
1227 }
1228
San Mehat4270e1e2010-01-29 05:32:19 -08001229 public int mountVolume(String path) {
1230 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001231
San Mehat207e5382010-02-04 20:46:54 -08001232 waitForReady();
1233 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001236 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001237 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001238 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001240 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001241 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001242 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1243 Environment.MEDIA_REMOVED.equals(volState) ||
1244 Environment.MEDIA_SHARED.equals(volState) ||
1245 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1246 // Media already unmounted or cannot be unmounted.
1247 // TODO return valid return code when adding observer call back.
1248 return;
1249 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001250 UnmountCallBack ucb = new UnmountCallBack(path, force);
1251 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 }
1253
San Mehat4270e1e2010-01-29 05:32:19 -08001254 public int formatVolume(String path) {
1255 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001256 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001257
San Mehat207e5382010-02-04 20:46:54 -08001258 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
1260
San Mehatc1b4ce92010-02-16 17:13:03 -08001261 public int []getStorageUsers(String path) {
1262 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1263 waitForReady();
1264 try {
1265 String[] r = mConnector.doListCommand(
1266 String.format("storage users %s", path),
1267 VoldResponseCode.StorageUsersListResult);
1268 // FMT: <pid> <process name>
1269 int[] data = new int[r.length];
1270 for (int i = 0; i < r.length; i++) {
1271 String []tok = r[i].split(" ");
1272 try {
1273 data[i] = Integer.parseInt(tok[0]);
1274 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001275 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001276 return new int[0];
1277 }
1278 }
1279 return data;
1280 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001281 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001282 return new int[0];
1283 }
1284 }
1285
San Mehatb1043402010-02-05 08:26:50 -08001286 private void warnOnNotMounted() {
1287 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001288 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001289 }
1290 }
1291
San Mehat4270e1e2010-01-29 05:32:19 -08001292 public String[] getSecureContainerList() {
1293 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001294 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001295 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001296
San Mehat4270e1e2010-01-29 05:32:19 -08001297 try {
1298 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1299 } catch (NativeDaemonConnectorException e) {
1300 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302 }
San Mehat36972292010-01-06 11:06:32 -08001303
San Mehat4270e1e2010-01-29 05:32:19 -08001304 public int createSecureContainer(String id, int sizeMb, String fstype,
1305 String key, int ownerUid) {
1306 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001307 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001308 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001309
San Mehatb1043402010-02-05 08:26:50 -08001310 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001311 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1312 try {
1313 mConnector.doCommand(cmd);
1314 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001315 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001316 }
San Mehata181b212010-02-11 06:50:20 -08001317
1318 if (rc == StorageResultCode.OperationSucceeded) {
1319 synchronized (mAsecMountSet) {
1320 mAsecMountSet.add(id);
1321 }
1322 }
San Mehat4270e1e2010-01-29 05:32:19 -08001323 return rc;
San Mehat36972292010-01-06 11:06:32 -08001324 }
1325
San Mehat4270e1e2010-01-29 05:32:19 -08001326 public int finalizeSecureContainer(String id) {
1327 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001328 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001329
San Mehatb1043402010-02-05 08:26:50 -08001330 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001331 try {
1332 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001333 /*
1334 * Finalization does a remount, so no need
1335 * to update mAsecMountSet
1336 */
San Mehat4270e1e2010-01-29 05:32:19 -08001337 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001338 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001339 }
San Mehat4270e1e2010-01-29 05:32:19 -08001340 return rc;
San Mehat36972292010-01-06 11:06:32 -08001341 }
1342
San Mehatd9709982010-02-18 11:43:03 -08001343 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001344 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001345 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001346 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001347
Kenny Rootaa485402010-09-14 14:49:41 -07001348 /*
1349 * Force a GC to make sure AssetManagers in other threads of the
1350 * system_server are cleaned up. We have to do this since AssetManager
1351 * instances are kept as a WeakReference and it's possible we have files
1352 * open on the external storage.
1353 */
1354 Runtime.getRuntime().gc();
1355
San Mehatb1043402010-02-05 08:26:50 -08001356 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001357 try {
San Mehatd9709982010-02-18 11:43:03 -08001358 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001359 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001360 int code = e.getCode();
1361 if (code == VoldResponseCode.OpFailedStorageBusy) {
1362 rc = StorageResultCode.OperationFailedStorageBusy;
1363 } else {
1364 rc = StorageResultCode.OperationFailedInternalError;
1365 }
San Mehat02735bc2010-01-26 15:18:08 -08001366 }
San Mehata181b212010-02-11 06:50:20 -08001367
1368 if (rc == StorageResultCode.OperationSucceeded) {
1369 synchronized (mAsecMountSet) {
1370 if (mAsecMountSet.contains(id)) {
1371 mAsecMountSet.remove(id);
1372 }
1373 }
1374 }
1375
San Mehat4270e1e2010-01-29 05:32:19 -08001376 return rc;
San Mehat36972292010-01-06 11:06:32 -08001377 }
1378
San Mehat4270e1e2010-01-29 05:32:19 -08001379 public int mountSecureContainer(String id, String key, int ownerUid) {
1380 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001381 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001382 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001383
San Mehata181b212010-02-11 06:50:20 -08001384 synchronized (mAsecMountSet) {
1385 if (mAsecMountSet.contains(id)) {
1386 return StorageResultCode.OperationFailedStorageMounted;
1387 }
1388 }
1389
San Mehatb1043402010-02-05 08:26:50 -08001390 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001391 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1392 try {
1393 mConnector.doCommand(cmd);
1394 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001395 int code = e.getCode();
1396 if (code != VoldResponseCode.OpFailedStorageBusy) {
1397 rc = StorageResultCode.OperationFailedInternalError;
1398 }
San Mehat02735bc2010-01-26 15:18:08 -08001399 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001400
1401 if (rc == StorageResultCode.OperationSucceeded) {
1402 synchronized (mAsecMountSet) {
1403 mAsecMountSet.add(id);
1404 }
1405 }
San Mehat4270e1e2010-01-29 05:32:19 -08001406 return rc;
San Mehat36972292010-01-06 11:06:32 -08001407 }
1408
San Mehatd9709982010-02-18 11:43:03 -08001409 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001410 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001411 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001412 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001413
San Mehat6cdd9c02010-02-09 14:45:20 -08001414 synchronized (mAsecMountSet) {
1415 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001416 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001417 }
1418 }
1419
Kenny Rootaa485402010-09-14 14:49:41 -07001420 /*
1421 * Force a GC to make sure AssetManagers in other threads of the
1422 * system_server are cleaned up. We have to do this since AssetManager
1423 * instances are kept as a WeakReference and it's possible we have files
1424 * open on the external storage.
1425 */
1426 Runtime.getRuntime().gc();
1427
San Mehatb1043402010-02-05 08:26:50 -08001428 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001429 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001430 try {
1431 mConnector.doCommand(cmd);
1432 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001433 int code = e.getCode();
1434 if (code == VoldResponseCode.OpFailedStorageBusy) {
1435 rc = StorageResultCode.OperationFailedStorageBusy;
1436 } else {
1437 rc = StorageResultCode.OperationFailedInternalError;
1438 }
San Mehat02735bc2010-01-26 15:18:08 -08001439 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001440
1441 if (rc == StorageResultCode.OperationSucceeded) {
1442 synchronized (mAsecMountSet) {
1443 mAsecMountSet.remove(id);
1444 }
1445 }
San Mehat4270e1e2010-01-29 05:32:19 -08001446 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001447 }
1448
San Mehat6cdd9c02010-02-09 14:45:20 -08001449 public boolean isSecureContainerMounted(String id) {
1450 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1451 waitForReady();
1452 warnOnNotMounted();
1453
1454 synchronized (mAsecMountSet) {
1455 return mAsecMountSet.contains(id);
1456 }
1457 }
1458
San Mehat4270e1e2010-01-29 05:32:19 -08001459 public int renameSecureContainer(String oldId, String newId) {
1460 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001461 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001462 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001463
San Mehata181b212010-02-11 06:50:20 -08001464 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001465 /*
1466 * Because a mounted container has active internal state which cannot be
1467 * changed while active, we must ensure both ids are not currently mounted.
1468 */
1469 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001470 return StorageResultCode.OperationFailedStorageMounted;
1471 }
1472 }
1473
San Mehatb1043402010-02-05 08:26:50 -08001474 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001475 String cmd = String.format("asec rename %s %s", oldId, newId);
1476 try {
1477 mConnector.doCommand(cmd);
1478 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001479 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001480 }
San Mehata181b212010-02-11 06:50:20 -08001481
San Mehat4270e1e2010-01-29 05:32:19 -08001482 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001483 }
1484
San Mehat4270e1e2010-01-29 05:32:19 -08001485 public String getSecureContainerPath(String id) {
1486 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001487 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001488 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001489
San Mehat2d66cef2010-03-23 11:12:52 -07001490 try {
1491 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1492 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001493 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001494 if (code != VoldResponseCode.AsecPathResult) {
1495 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1496 }
1497 return tok[1];
1498 } catch (NativeDaemonConnectorException e) {
1499 int code = e.getCode();
1500 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1501 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001502 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001503 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001504 }
1505 }
San Mehat22dd86e2010-01-12 12:21:18 -08001506 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001507
1508 public void finishMediaUpdate() {
1509 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1510 }
Kenny Root02c87302010-07-01 08:10:18 -07001511
Kenny Roota02b8b02010-08-05 16:14:17 -07001512 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1513 if (callerUid == android.os.Process.SYSTEM_UID) {
1514 return true;
1515 }
1516
Kenny Root02c87302010-07-01 08:10:18 -07001517 if (packageName == null) {
1518 return false;
1519 }
1520
1521 final int packageUid = mPms.getPackageUid(packageName);
1522
1523 if (DEBUG_OBB) {
1524 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1525 packageUid + ", callerUid = " + callerUid);
1526 }
1527
1528 return callerUid == packageUid;
1529 }
1530
1531 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001532 if (filename == null) {
1533 throw new IllegalArgumentException("filename cannot be null");
1534 }
1535
Kenny Root02c87302010-07-01 08:10:18 -07001536 waitForReady();
1537 warnOnNotMounted();
1538
Kenny Root02c87302010-07-01 08:10:18 -07001539 try {
1540 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1541 String []tok = rsp.get(0).split(" ");
1542 int code = Integer.parseInt(tok[0]);
1543 if (code != VoldResponseCode.AsecPathResult) {
1544 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1545 }
1546 return tok[1];
1547 } catch (NativeDaemonConnectorException e) {
1548 int code = e.getCode();
1549 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001550 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001551 } else {
1552 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1553 }
1554 }
1555 }
1556
1557 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001558 if (filename == null) {
1559 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001560 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001561
1562 synchronized (mObbMounts) {
1563 return mObbPathToStateMap.containsKey(filename);
1564 }
Kenny Root02c87302010-07-01 08:10:18 -07001565 }
1566
Kenny Rootaf9d6672010-10-08 09:21:39 -07001567 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001568 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001569 if (filename == null) {
1570 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001571 }
1572
1573 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001574 throw new IllegalArgumentException("token cannot be null");
1575 }
1576
Kenny Rootaf9d6672010-10-08 09:21:39 -07001577 final int callerUid = Binder.getCallingUid();
1578 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1579 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001580 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1581
1582 if (DEBUG_OBB)
1583 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001584 }
1585
Kenny Rootaf9d6672010-10-08 09:21:39 -07001586 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1587 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001588 if (filename == null) {
1589 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001590 }
1591
Kenny Rootaf9d6672010-10-08 09:21:39 -07001592 final int callerUid = Binder.getCallingUid();
1593 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1594 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001595 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001596
Kenny Roota02b8b02010-08-05 16:14:17 -07001597 if (DEBUG_OBB)
1598 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1599 }
1600
Kenny Rootaf9d6672010-10-08 09:21:39 -07001601 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1602 final IBinder binder = obbState.getBinder();
1603 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001604
Kenny Rootaf9d6672010-10-08 09:21:39 -07001605 if (obbStates == null) {
1606 obbStates = new ArrayList<ObbState>();
1607 mObbMounts.put(binder, obbStates);
1608 } else {
1609 for (final ObbState o : obbStates) {
1610 if (o.filename.equals(obbState.filename)) {
1611 throw new IllegalStateException("Attempt to add ObbState twice. "
1612 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001613 }
1614 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001615 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001616
1617 obbStates.add(obbState);
1618 try {
1619 obbState.link();
1620 } catch (RemoteException e) {
1621 /*
1622 * The binder died before we could link it, so clean up our state
1623 * and return failure.
1624 */
1625 obbStates.remove(obbState);
1626 if (obbStates.isEmpty()) {
1627 mObbMounts.remove(binder);
1628 }
1629
1630 // Rethrow the error so mountObb can get it
1631 throw e;
1632 }
1633
1634 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001635 }
1636
Kenny Rootaf9d6672010-10-08 09:21:39 -07001637 private void removeObbStateLocked(ObbState obbState) {
1638 final IBinder binder = obbState.getBinder();
1639 final List<ObbState> obbStates = mObbMounts.get(binder);
1640 if (obbStates != null) {
1641 if (obbStates.remove(obbState)) {
1642 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001643 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001644 if (obbStates.isEmpty()) {
1645 mObbMounts.remove(binder);
1646 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001647 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001648
Kenny Rootaf9d6672010-10-08 09:21:39 -07001649 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001650 }
1651
Kenny Roota02b8b02010-08-05 16:14:17 -07001652 private class ObbActionHandler extends Handler {
1653 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001654 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001655
1656 ObbActionHandler(Looper l) {
1657 super(l);
1658 }
1659
1660 @Override
1661 public void handleMessage(Message msg) {
1662 switch (msg.what) {
1663 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001664 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001665
1666 if (DEBUG_OBB)
1667 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1668
1669 // If a bind was already initiated we don't really
1670 // need to do anything. The pending install
1671 // will be processed later on.
1672 if (!mBound) {
1673 // If this is the only one pending we might
1674 // have to bind to the service again.
1675 if (!connectToService()) {
1676 Slog.e(TAG, "Failed to bind to media container service");
1677 action.handleError();
1678 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001679 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001680 }
Kenny Root735de3b2010-09-30 14:11:39 -07001681
Kenny Root735de3b2010-09-30 14:11:39 -07001682 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001683 break;
1684 }
1685 case OBB_MCS_BOUND: {
1686 if (DEBUG_OBB)
1687 Slog.i(TAG, "OBB_MCS_BOUND");
1688 if (msg.obj != null) {
1689 mContainerService = (IMediaContainerService) msg.obj;
1690 }
1691 if (mContainerService == null) {
1692 // Something seriously wrong. Bail out
1693 Slog.e(TAG, "Cannot bind to media container service");
1694 for (ObbAction action : mActions) {
1695 // Indicate service bind error
1696 action.handleError();
1697 }
1698 mActions.clear();
1699 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001700 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001701 if (action != null) {
1702 action.execute(this);
1703 }
1704 } else {
1705 // Should never happen ideally.
1706 Slog.w(TAG, "Empty queue");
1707 }
1708 break;
1709 }
1710 case OBB_MCS_RECONNECT: {
1711 if (DEBUG_OBB)
1712 Slog.i(TAG, "OBB_MCS_RECONNECT");
1713 if (mActions.size() > 0) {
1714 if (mBound) {
1715 disconnectService();
1716 }
1717 if (!connectToService()) {
1718 Slog.e(TAG, "Failed to bind to media container service");
1719 for (ObbAction action : mActions) {
1720 // Indicate service bind error
1721 action.handleError();
1722 }
1723 mActions.clear();
1724 }
1725 }
1726 break;
1727 }
1728 case OBB_MCS_UNBIND: {
1729 if (DEBUG_OBB)
1730 Slog.i(TAG, "OBB_MCS_UNBIND");
1731
1732 // Delete pending install
1733 if (mActions.size() > 0) {
1734 mActions.remove(0);
1735 }
1736 if (mActions.size() == 0) {
1737 if (mBound) {
1738 disconnectService();
1739 }
1740 } else {
1741 // There are more pending requests in queue.
1742 // Just post MCS_BOUND message to trigger processing
1743 // of next pending install.
1744 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1745 }
1746 break;
1747 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001748 case OBB_FLUSH_MOUNT_STATE: {
1749 final String path = (String) msg.obj;
1750
1751 if (DEBUG_OBB)
1752 Slog.i(TAG, "Flushing all OBB state for path " + path);
1753
1754 synchronized (mObbMounts) {
1755 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1756
1757 final Iterator<Entry<String, ObbState>> i =
1758 mObbPathToStateMap.entrySet().iterator();
1759 while (i.hasNext()) {
1760 final Entry<String, ObbState> obbEntry = i.next();
1761
1762 /*
1763 * If this entry's source file is in the volume path
1764 * that got unmounted, remove it because it's no
1765 * longer valid.
1766 */
1767 if (obbEntry.getKey().startsWith(path)) {
1768 obbStatesToRemove.add(obbEntry.getValue());
1769 }
1770 }
1771
1772 for (final ObbState obbState : obbStatesToRemove) {
1773 if (DEBUG_OBB)
1774 Slog.i(TAG, "Removing state for " + obbState.filename);
1775
1776 removeObbStateLocked(obbState);
1777
1778 try {
1779 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1780 OnObbStateChangeListener.UNMOUNTED);
1781 } catch (RemoteException e) {
1782 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1783 + obbState.filename);
1784 }
1785 }
1786 }
1787 break;
1788 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001789 }
1790 }
1791
1792 private boolean connectToService() {
1793 if (DEBUG_OBB)
1794 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1795
1796 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1797 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1798 mBound = true;
1799 return true;
1800 }
1801 return false;
1802 }
1803
1804 private void disconnectService() {
1805 mContainerService = null;
1806 mBound = false;
1807 mContext.unbindService(mDefContainerConn);
1808 }
1809 }
1810
1811 abstract class ObbAction {
1812 private static final int MAX_RETRIES = 3;
1813 private int mRetries;
1814
1815 ObbState mObbState;
1816
1817 ObbAction(ObbState obbState) {
1818 mObbState = obbState;
1819 }
1820
1821 public void execute(ObbActionHandler handler) {
1822 try {
1823 if (DEBUG_OBB)
1824 Slog.i(TAG, "Starting to execute action: " + this.toString());
1825 mRetries++;
1826 if (mRetries > MAX_RETRIES) {
1827 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001828 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001829 handleError();
1830 return;
1831 } else {
1832 handleExecute();
1833 if (DEBUG_OBB)
1834 Slog.i(TAG, "Posting install MCS_UNBIND");
1835 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1836 }
1837 } catch (RemoteException e) {
1838 if (DEBUG_OBB)
1839 Slog.i(TAG, "Posting install MCS_RECONNECT");
1840 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1841 } catch (Exception e) {
1842 if (DEBUG_OBB)
1843 Slog.d(TAG, "Error handling OBB action", e);
1844 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001845 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001846 }
1847 }
1848
Kenny Root05105f72010-09-22 17:29:43 -07001849 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001850 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001851
1852 protected ObbInfo getObbInfo() throws IOException {
1853 ObbInfo obbInfo;
1854 try {
1855 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1856 } catch (RemoteException e) {
1857 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1858 + mObbState.filename);
1859 obbInfo = null;
1860 }
1861 if (obbInfo == null) {
1862 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1863 }
1864 return obbInfo;
1865 }
1866
Kenny Rootaf9d6672010-10-08 09:21:39 -07001867 protected void sendNewStatusOrIgnore(int status) {
1868 if (mObbState == null || mObbState.token == null) {
1869 return;
1870 }
1871
Kenny Root38cf8862010-09-26 14:18:51 -07001872 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001873 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07001874 } catch (RemoteException e) {
1875 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1876 }
1877 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001878 }
1879
1880 class MountObbAction extends ObbAction {
1881 private String mKey;
1882
1883 MountObbAction(ObbState obbState, String key) {
1884 super(obbState);
1885 mKey = key;
1886 }
1887
Kenny Root735de3b2010-09-30 14:11:39 -07001888 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001889 waitForReady();
1890 warnOnNotMounted();
1891
Kenny Root38cf8862010-09-26 14:18:51 -07001892 final ObbInfo obbInfo = getObbInfo();
1893
Kenny Roota02b8b02010-08-05 16:14:17 -07001894 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001895 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
1896 + " which is owned by " + obbInfo.packageName);
1897 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
1898 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001899 }
1900
Kenny Rootaf9d6672010-10-08 09:21:39 -07001901 final boolean isMounted;
1902 synchronized (mObbMounts) {
1903 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
1904 }
1905 if (isMounted) {
1906 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
1907 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
1908 return;
1909 }
1910
1911 /*
1912 * The filename passed in might not be the canonical name, so just
1913 * set the filename to the canonicalized version.
1914 */
1915 mObbState.filename = obbInfo.filename;
1916
1917 final String hashedKey;
1918 if (mKey == null) {
1919 hashedKey = "none";
1920 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001921 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07001922 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
1923
1924 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
1925 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
1926 SecretKey key = factory.generateSecret(ks);
1927 BigInteger bi = new BigInteger(key.getEncoded());
1928 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001929 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07001930 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
1931 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
1932 return;
1933 } catch (InvalidKeySpecException e) {
1934 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
1935 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07001936 return;
1937 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001938 }
Kenny Root38cf8862010-09-26 14:18:51 -07001939
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940 int rc = StorageResultCode.OperationSucceeded;
1941 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
1942 mObbState.callerUid);
1943 try {
1944 mConnector.doCommand(cmd);
1945 } catch (NativeDaemonConnectorException e) {
1946 int code = e.getCode();
1947 if (code != VoldResponseCode.OpFailedStorageBusy) {
1948 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07001949 }
1950 }
1951
Kenny Rootaf9d6672010-10-08 09:21:39 -07001952 if (rc == StorageResultCode.OperationSucceeded) {
1953 if (DEBUG_OBB)
1954 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
1955
1956 synchronized (mObbMounts) {
1957 addObbStateLocked(mObbState);
1958 }
1959
1960 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001961 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001962 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001963
Kenny Rootaf9d6672010-10-08 09:21:39 -07001964 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07001965 }
1966 }
1967
Kenny Roota02b8b02010-08-05 16:14:17 -07001968 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001969 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07001970 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001971
1972 @Override
1973 public String toString() {
1974 StringBuilder sb = new StringBuilder();
1975 sb.append("MountObbAction{");
1976 sb.append("filename=");
1977 sb.append(mObbState.filename);
1978 sb.append(",callerUid=");
1979 sb.append(mObbState.callerUid);
1980 sb.append(",token=");
1981 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001982 sb.append(",binder=");
1983 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 sb.append('}');
1985 return sb.toString();
1986 }
1987 }
1988
1989 class UnmountObbAction extends ObbAction {
1990 private boolean mForceUnmount;
1991
1992 UnmountObbAction(ObbState obbState, boolean force) {
1993 super(obbState);
1994 mForceUnmount = force;
1995 }
1996
Kenny Root38cf8862010-09-26 14:18:51 -07001997 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001998 waitForReady();
1999 warnOnNotMounted();
2000
Kenny Root38cf8862010-09-26 14:18:51 -07002001 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002002
Kenny Rootaf9d6672010-10-08 09:21:39 -07002003 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002004 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002005 obbState = mObbPathToStateMap.get(obbInfo.filename);
2006 }
Kenny Root38cf8862010-09-26 14:18:51 -07002007
Kenny Rootaf9d6672010-10-08 09:21:39 -07002008 if (obbState == null) {
2009 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2010 return;
2011 }
2012
2013 if (obbState.callerUid != mObbState.callerUid) {
2014 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2015 + " (owned by " + obbInfo.packageName + ")");
2016 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2017 return;
2018 }
2019
2020 mObbState.filename = obbInfo.filename;
2021
2022 int rc = StorageResultCode.OperationSucceeded;
2023 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2024 (mForceUnmount ? " force" : ""));
2025 try {
2026 mConnector.doCommand(cmd);
2027 } catch (NativeDaemonConnectorException e) {
2028 int code = e.getCode();
2029 if (code == VoldResponseCode.OpFailedStorageBusy) {
2030 rc = StorageResultCode.OperationFailedStorageBusy;
2031 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2032 // If it's not mounted then we've already won.
2033 rc = StorageResultCode.OperationSucceeded;
2034 } else {
2035 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002036 }
2037 }
2038
Kenny Rootaf9d6672010-10-08 09:21:39 -07002039 if (rc == StorageResultCode.OperationSucceeded) {
2040 synchronized (mObbMounts) {
2041 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002042 }
2043
Kenny Rootaf9d6672010-10-08 09:21:39 -07002044 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002045 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002046 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2047 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002048 }
2049 }
2050
2051 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002052 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002053 }
2054
2055 @Override
2056 public String toString() {
2057 StringBuilder sb = new StringBuilder();
2058 sb.append("UnmountObbAction{");
2059 sb.append("filename=");
2060 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2061 sb.append(",force=");
2062 sb.append(mForceUnmount);
2063 sb.append(",callerUid=");
2064 sb.append(mObbState.callerUid);
2065 sb.append(",token=");
2066 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002067 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002068 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002069 sb.append('}');
2070 return sb.toString();
2071 }
Kenny Root02c87302010-07-01 08:10:18 -07002072 }
Kenny Root38cf8862010-09-26 14:18:51 -07002073
2074 @Override
2075 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2076 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2077 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2078 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2079 + " without permission " + android.Manifest.permission.DUMP);
2080 return;
2081 }
2082
Kenny Root38cf8862010-09-26 14:18:51 -07002083 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002084 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002085
Kenny Rootaf9d6672010-10-08 09:21:39 -07002086 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2087 while (binders.hasNext()) {
2088 Entry<IBinder, List<ObbState>> e = binders.next();
2089 pw.print(" Key="); pw.println(e.getKey().toString());
2090 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002091 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002092 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002093 }
2094 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002095
2096 pw.println("");
2097 pw.println(" mObbPathToStateMap:");
2098 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2099 while (maps.hasNext()) {
2100 final Entry<String, ObbState> e = maps.next();
2101 pw.print(" "); pw.print(e.getKey());
2102 pw.print(" -> "); pw.println(e.getValue().toString());
2103 }
Kenny Root38cf8862010-09-26 14:18:51 -07002104 }
2105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106}
2107