blob: c18ccc8c1548278371f550d75fedb08dd2e73dc0 [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;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070021import com.android.server.pm.PackageManagerService;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080022
Jason parks8888c592011-01-20 22:46:41 -060023import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070025import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070029import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070033import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070034import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080035import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040036import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040038import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080040import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080041import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080042import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070044import android.os.storage.IMountService;
45import android.os.storage.IMountServiceListener;
46import android.os.storage.IMountShutdownObserver;
47import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070048import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070049import android.os.storage.StorageResultCode;
Jason parksf7b3cd42011-01-27 09:28:25 -060050import android.text.TextUtils;
San Mehata5078592010-03-25 09:36:54 -070051import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070052
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070054import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070055import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070056import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070057import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070058import java.security.spec.InvalidKeySpecException;
59import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080060import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070061import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080062import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070064import java.util.LinkedList;
65import java.util.List;
66import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070067import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070068import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Kenny Root3b1abba2010-10-13 15:00:07 -070070import javax.crypto.SecretKey;
71import javax.crypto.SecretKeyFactory;
72import javax.crypto.spec.PBEKeySpec;
73
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074/**
San Mehatb1043402010-02-05 08:26:50 -080075 * MountService implements back-end services for platform storage
76 * management.
77 * @hide - Applications should use android.os.storage.StorageManager
78 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 */
Jason parks5af0b912010-11-29 09:05:25 -060080class MountService extends IMountService.Stub implements INativeDaemonConnectorCallbacks {
81
San Mehatb1043402010-02-05 08:26:50 -080082 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080083 private static final boolean DEBUG_UNMOUNT = false;
84 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080085 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private static final String TAG = "MountService";
88
Kenny Root305bcbf2010-09-03 07:56:38 -070089 private static final String VOLD_TAG = "VoldConnector";
90
Kenny Rootcf0b38c2011-03-22 14:17:59 -070091 /** Maximum number of ASEC containers allowed to be mounted. */
92 private static final int MAX_CONTAINERS = 250;
93
San Mehat4270e1e2010-01-29 05:32:19 -080094 /*
95 * Internal vold volume state constants
96 */
San Mehat7fd0fee2009-12-17 07:12:23 -080097 class VolumeState {
98 public static final int Init = -1;
99 public static final int NoMedia = 0;
100 public static final int Idle = 1;
101 public static final int Pending = 2;
102 public static final int Checking = 3;
103 public static final int Mounted = 4;
104 public static final int Unmounting = 5;
105 public static final int Formatting = 6;
106 public static final int Shared = 7;
107 public static final int SharedMnt = 8;
108 }
109
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * Internal vold response code constants
112 */
San Mehat22dd86e2010-01-12 12:21:18 -0800113 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800114 /*
115 * 100 series - Requestion action was initiated; expect another reply
116 * before proceeding with a new command.
117 */
San Mehat22dd86e2010-01-12 12:21:18 -0800118 public static final int VolumeListResult = 110;
119 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800120 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800121
San Mehat4270e1e2010-01-29 05:32:19 -0800122 /*
123 * 200 series - Requestion action has been successfully completed.
124 */
125 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800126 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800127 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800128
San Mehat4270e1e2010-01-29 05:32:19 -0800129 /*
130 * 400 series - Command was accepted, but the requested action
131 * did not take place.
132 */
133 public static final int OpFailedNoMedia = 401;
134 public static final int OpFailedMediaBlank = 402;
135 public static final int OpFailedMediaCorrupt = 403;
136 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800137 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700138 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800139
140 /*
141 * 600 series - Unsolicited broadcasts.
142 */
San Mehat22dd86e2010-01-12 12:21:18 -0800143 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800144 public static final int ShareAvailabilityChange = 620;
145 public static final int VolumeDiskInserted = 630;
146 public static final int VolumeDiskRemoved = 631;
147 public static final int VolumeBadRemoval = 632;
148 }
149
San Mehat4270e1e2010-01-29 05:32:19 -0800150 private Context mContext;
151 private NativeDaemonConnector mConnector;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400152 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
153 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800154 private PackageManagerService mPms;
155 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800156 // Used as a lock for methods that register/unregister listeners.
157 final private ArrayList<MountServiceBinderListener> mListeners =
158 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800159 private boolean mBooted = false;
160 private boolean mReady = false;
161 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400162 // true if we should fake MEDIA_MOUNTED state for external storage
163 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800164
San Mehat6cdd9c02010-02-09 14:45:20 -0800165 /**
166 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800167 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800168 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800169 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800170
Kenny Root02c87302010-07-01 08:10:18 -0700171 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700172 * The size of the crypto algorithm key in bits for OBB files. Currently
173 * Twofish is used which takes 128-bit keys.
174 */
175 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
176
177 /**
178 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
179 * 1024 is reasonably secure and not too slow.
180 */
181 private static final int PBKDF2_HASH_ROUNDS = 1024;
182
183 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700184 * Mounted OBB tracking information. Used to track the current state of all
185 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700186 */
Kenny Root735de3b2010-09-30 14:11:39 -0700187 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700188 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
189
190 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700191 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700192 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700193 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700194 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700195 this.token = token;
196 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700197 }
198
199 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700200 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700201
202 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700203 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700204
Kenny Rootaf9d6672010-10-08 09:21:39 -0700205 // Token of remote Binder caller
206 final IObbActionListener token;
207
208 // Identifier to pass back to the token
209 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700210
Kenny Root735de3b2010-09-30 14:11:39 -0700211 public IBinder getBinder() {
212 return token.asBinder();
213 }
214
Kenny Roota02b8b02010-08-05 16:14:17 -0700215 @Override
216 public void binderDied() {
217 ObbAction action = new UnmountObbAction(this, true);
218 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700219 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700220
Kenny Root5919ac62010-10-05 09:49:40 -0700221 public void link() throws RemoteException {
222 getBinder().linkToDeath(this, 0);
223 }
224
225 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700226 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700227 }
Kenny Root38cf8862010-09-26 14:18:51 -0700228
229 @Override
230 public String toString() {
231 StringBuilder sb = new StringBuilder("ObbState{");
232 sb.append("filename=");
233 sb.append(filename);
234 sb.append(",token=");
235 sb.append(token.toString());
236 sb.append(",callerUid=");
237 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700238 sb.append('}');
239 return sb.toString();
240 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700241 }
242
243 // OBB Action Handler
244 final private ObbActionHandler mObbActionHandler;
245
246 // OBB action handler messages
247 private static final int OBB_RUN_ACTION = 1;
248 private static final int OBB_MCS_BOUND = 2;
249 private static final int OBB_MCS_UNBIND = 3;
250 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700251 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700252
253 /*
254 * Default Container Service information
255 */
256 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
257 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
258
259 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
260
261 class DefaultContainerConnection implements ServiceConnection {
262 public void onServiceConnected(ComponentName name, IBinder service) {
263 if (DEBUG_OBB)
264 Slog.i(TAG, "onServiceConnected");
265 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
266 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
267 }
268
269 public void onServiceDisconnected(ComponentName name) {
270 if (DEBUG_OBB)
271 Slog.i(TAG, "onServiceDisconnected");
272 }
273 };
274
275 // Used in the ObbActionHandler
276 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700277
278 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800279 private static final int H_UNMOUNT_PM_UPDATE = 1;
280 private static final int H_UNMOUNT_PM_DONE = 2;
281 private static final int H_UNMOUNT_MS = 3;
282 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
283 private static final int MAX_UNMOUNT_RETRIES = 4;
284
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800285 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700286 final String path;
287 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800288 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800289
290 UnmountCallBack(String path, boolean force) {
291 retries = 0;
292 this.path = path;
293 this.force = force;
294 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800295
296 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700297 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800298 doUnmountVolume(path, true);
299 }
300 }
301
302 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700303 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800304
305 UmsEnableCallBack(String path, String method, boolean force) {
306 super(path, force);
307 this.method = method;
308 }
309
310 @Override
311 void handleFinished() {
312 super.handleFinished();
313 doShareUnshareVolume(path, method, true);
314 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800315 }
316
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800317 class ShutdownCallBack extends UnmountCallBack {
318 IMountShutdownObserver observer;
319 ShutdownCallBack(String path, IMountShutdownObserver observer) {
320 super(path, true);
321 this.observer = observer;
322 }
323
324 @Override
325 void handleFinished() {
326 int ret = doUnmountVolume(path, true);
327 if (observer != null) {
328 try {
329 observer.onShutDownComplete(ret);
330 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700331 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800332 }
333 }
334 }
335 }
336
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400337 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700339 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800340
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400341 MountServiceHandler(Looper l) {
342 super(l);
343 }
344
Jason parks5af0b912010-11-29 09:05:25 -0600345 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 public void handleMessage(Message msg) {
347 switch (msg.what) {
348 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700349 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
351 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700352 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800353 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700354 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700355 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700356 mUpdatingStatus = true;
357 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800358 }
359 break;
360 }
361 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700362 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700363 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700364 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800365 int size = mForceUnmounts.size();
366 int sizeArr[] = new int[size];
367 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700368 // Kill processes holding references first
369 ActivityManagerService ams = (ActivityManagerService)
370 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800371 for (int i = 0; i < size; i++) {
372 UnmountCallBack ucb = mForceUnmounts.get(i);
373 String path = ucb.path;
374 boolean done = false;
375 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800376 done = true;
377 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800378 int pids[] = getStorageUsers(path);
379 if (pids == null || pids.length == 0) {
380 done = true;
381 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800382 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800383 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700384 // Confirm if file references have been freed.
385 pids = getStorageUsers(path);
386 if (pids == null || pids.length == 0) {
387 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800388 }
389 }
390 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700391 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
392 // Retry again
393 Slog.i(TAG, "Retrying to kill storage users again");
394 mHandler.sendMessageDelayed(
395 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
396 ucb.retries++),
397 RETRY_UNMOUNT_DELAY);
398 } else {
399 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
400 Slog.i(TAG, "Failed to unmount media inspite of " +
401 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
402 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403 sizeArr[sizeArrN++] = i;
404 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
405 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800406 }
407 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800408 // Remove already processed elements from list.
409 for (int i = (sizeArrN-1); i >= 0; i--) {
410 mForceUnmounts.remove(sizeArr[i]);
411 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 break;
413 }
414 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800416 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800417 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800418 break;
419 }
420 }
421 }
422 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400423 final private HandlerThread mHandlerThread;
424 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800425
San Mehat207e5382010-02-04 20:46:54 -0800426 private void waitForReady() {
427 while (mReady == false) {
428 for (int retries = 5; retries > 0; retries--) {
429 if (mReady) {
430 return;
431 }
432 SystemClock.sleep(1000);
433 }
San Mehata5078592010-03-25 09:36:54 -0700434 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800435 }
San Mehat1f6301e2010-01-07 22:40:27 -0800436 }
Kenny Root02c87302010-07-01 08:10:18 -0700437
San Mehat207e5382010-02-04 20:46:54 -0800438 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600439 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800441 String action = intent.getAction();
442
443 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800444 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800445
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800446 /*
447 * In the simulator, we need to broadcast a volume mounted event
448 * to make the media scanner run.
449 */
450 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400451 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
452 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800453 return;
454 }
San Mehatfafb0412010-02-18 19:40:04 -0800455 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600456 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800457 public void run() {
458 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400459 // it is not safe to call vold with mVolumeStates locked
460 // so we make a copy of the paths and states and process them
461 // outside the lock
462 String[] paths, states;
463 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400464 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400465 Set<String> keys = mVolumeStates.keySet();
466 count = keys.size();
467 paths = (String[])keys.toArray(new String[count]);
468 states = new String[count];
469 for (int i = 0; i < count; i++) {
470 states[i] = mVolumeStates.get(paths[i]);
471 }
472 }
San Mehat6a254402010-03-22 10:21:00 -0700473
Mike Lockwood84338c42011-04-05 10:05:47 -0400474 for (int i = 0; i < count; i++) {
475 String path = paths[i];
476 String state = states[i];
477
478 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
479 int rc = doMountVolume(path);
480 if (rc != StorageResultCode.OperationSucceeded) {
481 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
482 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400483 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400484 } else if (state.equals(Environment.MEDIA_SHARED)) {
485 /*
486 * Bootstrap UMS enabled state since vold indicates
487 * the volume is shared (runtime restart while ums enabled)
488 */
489 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
490 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800491 }
492 }
San Mehat6a254402010-03-22 10:21:00 -0700493
Mike Lockwood80e0a412011-04-05 10:21:51 -0400494 /* notify external storage has mounted to trigger media scanner */
495 if (mEmulateExternalStorage) {
496 notifyVolumeStateChange(null,
497 Environment.getExternalStorageDirectory().getPath(),
498 VolumeState.NoMedia, VolumeState.Mounted);
499 }
500
San Mehat6a965af22010-02-24 17:47:30 -0800501 /*
San Mehat6a254402010-03-22 10:21:00 -0700502 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800503 * now that we're up.
504 */
505 if (mSendUmsConnectedOnBoot) {
506 sendUmsIntent(true);
507 mSendUmsConnectedOnBoot = false;
508 }
San Mehatfafb0412010-02-18 19:40:04 -0800509 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700510 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800511 }
San Mehat207e5382010-02-04 20:46:54 -0800512 }
San Mehatfafb0412010-02-18 19:40:04 -0800513 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 }
515 }
516 };
San Mehat4270e1e2010-01-29 05:32:19 -0800517 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
518 final IMountServiceListener mListener;
519
520 MountServiceBinderListener(IMountServiceListener listener) {
521 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700522
San Mehat91c77612010-01-07 10:39:41 -0800523 }
524
San Mehat4270e1e2010-01-29 05:32:19 -0800525 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700526 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700527 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800528 mListeners.remove(this);
529 mListener.asBinder().unlinkToDeath(this, 0);
530 }
531 }
532 }
533
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800534 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800535 // TODO: Add support for multiple share methods
536 if (!method.equals("ums")) {
537 throw new IllegalArgumentException(String.format("Method %s not supported", method));
538 }
539
San Mehat4270e1e2010-01-29 05:32:19 -0800540 try {
541 mConnector.doCommand(String.format(
542 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
543 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700544 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800545 }
San Mehat4270e1e2010-01-29 05:32:19 -0800546 }
547
San Mehat207e5382010-02-04 20:46:54 -0800548 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400549 String oldState;
550 synchronized(mVolumeStates) {
551 oldState = mVolumeStates.put(path, state);
552 }
553 if (state.equals(oldState)) {
554 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
555 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800556 return;
557 }
San Mehatb1043402010-02-05 08:26:50 -0800558
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400559 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700560
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400561 if (path.equals(mExternalStoragePath)) {
562 // Update state on PackageManager, but only of real events
563 if (!mEmulateExternalStorage) {
564 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
565 mPms.updateExternalMediaStatus(false, false);
566
567 /*
568 * Some OBBs might have been unmounted when this volume was
569 * unmounted, so send a message to the handler to let it know to
570 * remove those from the list of mounted OBBS.
571 */
572 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
573 OBB_FLUSH_MOUNT_STATE, path));
574 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
575 mPms.updateExternalMediaStatus(true, false);
576 }
Mike Lockwood03559752010-07-19 18:25:03 -0400577 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800578 }
San Mehat4270e1e2010-01-29 05:32:19 -0800579 synchronized (mListeners) {
580 for (int i = mListeners.size() -1; i >= 0; i--) {
581 MountServiceBinderListener bl = mListeners.get(i);
582 try {
San Mehatb1043402010-02-05 08:26:50 -0800583 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800584 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700585 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800586 mListeners.remove(i);
587 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700588 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800589 }
590 }
591 }
592 }
593
594 /**
595 *
596 * Callback from NativeDaemonConnector
597 */
598 public void onDaemonConnected() {
599 /*
600 * Since we'll be calling back into the NativeDaemonConnector,
601 * we need to do our work in a new thread.
602 */
603 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600604 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800605 public void run() {
606 /**
607 * Determine media state and UMS detection status
608 */
San Mehat4270e1e2010-01-29 05:32:19 -0800609 try {
610 String[] vols = mConnector.doListCommand(
611 "volume list", VoldResponseCode.VolumeListResult);
612 for (String volstr : vols) {
613 String[] tok = volstr.split(" ");
614 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400615 String path = tok[1];
616 String state = Environment.MEDIA_REMOVED;
617
San Mehat4270e1e2010-01-29 05:32:19 -0800618 int st = Integer.parseInt(tok[2]);
619 if (st == VolumeState.NoMedia) {
620 state = Environment.MEDIA_REMOVED;
621 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800622 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800623 } else if (st == VolumeState.Mounted) {
624 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700625 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800626 } else if (st == VolumeState.Shared) {
627 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700628 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800629 } else {
630 throw new Exception(String.format("Unexpected state %d", st));
631 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400632
633 if (state != null) {
634 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
635 updatePublicVolumeState(path, state);
636 }
San Mehat4270e1e2010-01-29 05:32:19 -0800637 }
638 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700639 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400640 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800641 }
642
643 try {
San Mehat207e5382010-02-04 20:46:54 -0800644 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800645 notifyShareAvailabilityChange("ums", avail);
646 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700647 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800648 }
San Mehat207e5382010-02-04 20:46:54 -0800649 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600650 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800651 * the hounds!
652 */
653 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800654 }
655 }.start();
656 }
657
658 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800659 * Callback from NativeDaemonConnector
660 */
661 public boolean onEvent(int code, String raw, String[] cooked) {
662 Intent in = null;
663
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800664 if (DEBUG_EVENTS) {
665 StringBuilder builder = new StringBuilder();
666 builder.append("onEvent::");
667 builder.append(" raw= " + raw);
668 if (cooked != null) {
669 builder.append(" cooked = " );
670 for (String str : cooked) {
671 builder.append(" " + str);
672 }
673 }
San Mehata5078592010-03-25 09:36:54 -0700674 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800675 }
San Mehat4270e1e2010-01-29 05:32:19 -0800676 if (code == VoldResponseCode.VolumeStateChange) {
677 /*
678 * One of the volumes we're managing has changed state.
679 * Format: "NNN Volume <label> <path> state changed
680 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
681 */
682 notifyVolumeStateChange(
683 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
684 Integer.parseInt(cooked[10]));
685 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
686 // FMT: NNN Share method <method> now <available|unavailable>
687 boolean avail = false;
688 if (cooked[5].equals("available")) {
689 avail = true;
690 }
691 notifyShareAvailabilityChange(cooked[3], avail);
692 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
693 (code == VoldResponseCode.VolumeDiskRemoved) ||
694 (code == VoldResponseCode.VolumeBadRemoval)) {
695 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
696 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
697 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
698 final String label = cooked[2];
699 final String path = cooked[3];
700 int major = -1;
701 int minor = -1;
702
703 try {
704 String devComp = cooked[6].substring(1, cooked[6].length() -1);
705 String[] devTok = devComp.split(":");
706 major = Integer.parseInt(devTok[0]);
707 minor = Integer.parseInt(devTok[1]);
708 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700709 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800710 }
711
San Mehat4270e1e2010-01-29 05:32:19 -0800712 if (code == VoldResponseCode.VolumeDiskInserted) {
713 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600714 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800715 public void run() {
716 try {
717 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800718 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700719 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800720 }
721 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700722 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724 }
725 }.start();
726 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
727 /*
728 * This event gets trumped if we're already in BAD_REMOVAL state
729 */
730 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
731 return true;
732 }
733 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700734 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800735 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
736 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
737 mContext.sendBroadcast(in);
738
San Mehata5078592010-03-25 09:36:54 -0700739 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800740 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
741 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
742 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700743 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800744 /* Send the media unmounted event first */
745 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
746 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
747 mContext.sendBroadcast(in);
748
San Mehata5078592010-03-25 09:36:54 -0700749 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800750 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
751 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
752 } else {
San Mehata5078592010-03-25 09:36:54 -0700753 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800754 }
755 } else {
756 return false;
757 }
758
759 if (in != null) {
760 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400761 }
762 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800763 }
764
San Mehat207e5382010-02-04 20:46:54 -0800765 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800766 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700767 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800768
769 Intent in = null;
770
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500771 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700772 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500773 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
774 Uri.parse("file://" + path)));
775 }
776
San Mehat4270e1e2010-01-29 05:32:19 -0800777 if (newState == VolumeState.Init) {
778 } else if (newState == VolumeState.NoMedia) {
779 // NoMedia is handled via Disk Remove events
780 } else if (newState == VolumeState.Idle) {
781 /*
782 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
783 * if we're in the process of enabling UMS
784 */
785 if (!vs.equals(
786 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
787 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800788 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700789 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800790 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
791 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
792 }
793 } else if (newState == VolumeState.Pending) {
794 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700795 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800796 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
797 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
798 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700799 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800800 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800801 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
802 in.putExtra("read-only", false);
803 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800804 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
805 } else if (newState == VolumeState.Formatting) {
806 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700807 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800808 /* Send the media unmounted event first */
809 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
810 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
811 mContext.sendBroadcast(in);
812
San Mehata5078592010-03-25 09:36:54 -0700813 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800814 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
815 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700816 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800817 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700818 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800819 return;
820 } else {
San Mehata5078592010-03-25 09:36:54 -0700821 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800822 }
823
824 if (in != null) {
825 mContext.sendBroadcast(in);
826 }
827 }
828
San Mehat207e5382010-02-04 20:46:54 -0800829 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700830 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700831 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700832 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700833 } catch (NativeDaemonConnectorException ex) {
834 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
835 return false;
836 }
San Mehat207e5382010-02-04 20:46:54 -0800837
838 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700839 String[] tok = line.split(" ");
840 if (tok.length < 3) {
841 Slog.e(TAG, "Malformed response to share status " + method);
842 return false;
843 }
844
San Mehat207e5382010-02-04 20:46:54 -0800845 int code;
846 try {
847 code = Integer.parseInt(tok[0]);
848 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700849 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800850 return false;
851 }
852 if (code == VoldResponseCode.ShareStatusResult) {
853 if (tok[2].equals("available"))
854 return true;
855 return false;
856 } else {
San Mehata5078592010-03-25 09:36:54 -0700857 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800858 return false;
859 }
860 }
San Mehata5078592010-03-25 09:36:54 -0700861 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800862 return false;
863 }
864
865 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800866 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800867
San Mehata5078592010-03-25 09:36:54 -0700868 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800869 try {
870 mConnector.doCommand(String.format("volume mount %s", path));
871 } catch (NativeDaemonConnectorException e) {
872 /*
873 * Mount failed for some reason
874 */
875 Intent in = null;
876 int code = e.getCode();
877 if (code == VoldResponseCode.OpFailedNoMedia) {
878 /*
879 * Attempt to mount but no media inserted
880 */
San Mehatb1043402010-02-05 08:26:50 -0800881 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800882 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700883 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800884 /*
885 * Media is blank or does not contain a supported filesystem
886 */
887 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
888 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800889 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800890 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700891 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800892 /*
893 * Volume consistency check failed
894 */
895 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
896 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800897 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800898 } else {
San Mehatb1043402010-02-05 08:26:50 -0800899 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800900 }
901
902 /*
903 * Send broadcast intent (if required for the failure)
904 */
905 if (in != null) {
906 mContext.sendBroadcast(in);
907 }
908 }
909
910 return rc;
911 }
912
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800913 /*
914 * If force is not set, we do not unmount if there are
915 * processes holding references to the volume about to be unmounted.
916 * If force is set, all the processes holding references need to be
917 * killed via the ActivityManager before actually unmounting the volume.
918 * This might even take a while and might be retried after timed delays
919 * to make sure we dont end up in an instable state and kill some core
920 * processes.
921 */
San Mehatd9709982010-02-18 11:43:03 -0800922 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800923 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800924 return VoldResponseCode.OpFailedVolNotMounted;
925 }
Kenny Rootaa485402010-09-14 14:49:41 -0700926
927 /*
928 * Force a GC to make sure AssetManagers in other threads of the
929 * system_server are cleaned up. We have to do this since AssetManager
930 * instances are kept as a WeakReference and it's possible we have files
931 * open on the external storage.
932 */
933 Runtime.getRuntime().gc();
934
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800935 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700936 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800937 try {
San Mehatd9709982010-02-18 11:43:03 -0800938 mConnector.doCommand(String.format(
939 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700940 // We unmounted the volume. None of the asec containers are available now.
941 synchronized (mAsecMountSet) {
942 mAsecMountSet.clear();
943 }
San Mehatb1043402010-02-05 08:26:50 -0800944 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800945 } catch (NativeDaemonConnectorException e) {
946 // Don't worry about mismatch in PackageManager since the
947 // call back will handle the status changes any way.
948 int code = e.getCode();
949 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800950 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800951 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
952 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800953 } else {
San Mehatb1043402010-02-05 08:26:50 -0800954 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800955 }
956 }
957 }
958
959 private int doFormatVolume(String path) {
960 try {
961 String cmd = String.format("volume format %s", path);
962 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800963 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800964 } catch (NativeDaemonConnectorException e) {
965 int code = e.getCode();
966 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800967 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800968 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800969 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800970 } else {
San Mehatb1043402010-02-05 08:26:50 -0800971 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800972 }
973 }
974 }
975
San Mehatb1043402010-02-05 08:26:50 -0800976 private boolean doGetVolumeShared(String path, String method) {
977 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700978 ArrayList<String> rsp;
979
980 try {
981 rsp = mConnector.doCommand(cmd);
982 } catch (NativeDaemonConnectorException ex) {
983 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
984 return false;
985 }
San Mehatb1043402010-02-05 08:26:50 -0800986
987 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700988 String[] tok = line.split(" ");
989 if (tok.length < 3) {
990 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
991 return false;
992 }
993
San Mehatb1043402010-02-05 08:26:50 -0800994 int code;
995 try {
996 code = Integer.parseInt(tok[0]);
997 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700998 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800999 return false;
1000 }
1001 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -07001002 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -08001003 } else {
San Mehata5078592010-03-25 09:36:54 -07001004 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -08001005 return false;
1006 }
1007 }
San Mehata5078592010-03-25 09:36:54 -07001008 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001009 return false;
1010 }
1011
San Mehat207e5382010-02-04 20:46:54 -08001012 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001013 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001014 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001015 return;
1016 }
1017
1018 synchronized (mListeners) {
1019 for (int i = mListeners.size() -1; i >= 0; i--) {
1020 MountServiceBinderListener bl = mListeners.get(i);
1021 try {
San Mehatb1043402010-02-05 08:26:50 -08001022 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001023 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001024 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001025 mListeners.remove(i);
1026 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001027 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001028 }
1029 }
1030 }
1031
San Mehat207e5382010-02-04 20:46:54 -08001032 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001033 sendUmsIntent(avail);
1034 } else {
1035 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001036 }
San Mehat2fe718a2010-03-11 12:01:49 -08001037
1038 final String path = Environment.getExternalStorageDirectory().getPath();
1039 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1040 /*
1041 * USB mass storage disconnected while enabled
1042 */
1043 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001044 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001045 public void run() {
1046 try {
1047 int rc;
San Mehata5078592010-03-25 09:36:54 -07001048 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001049 doShareUnshareVolume(path, "ums", false);
1050 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001051 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001052 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1053 path, rc));
1054 }
1055 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001056 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001057 }
1058 }
1059 }.start();
1060 }
San Mehat4270e1e2010-01-29 05:32:19 -08001061 }
1062
San Mehat6a965af22010-02-24 17:47:30 -08001063 private void sendUmsIntent(boolean c) {
1064 mContext.sendBroadcast(
1065 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1066 }
1067
San Mehat207e5382010-02-04 20:46:54 -08001068 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001069 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1070 throw new SecurityException(String.format("Requires %s permission", perm));
1071 }
1072 }
1073
1074 /**
San Mehat207e5382010-02-04 20:46:54 -08001075 * Constructs a new MountService instance
1076 *
1077 * @param context Binder context for this service
1078 */
1079 public MountService(Context context) {
1080 mContext = context;
1081
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001082 mExternalStoragePath = Environment.getExternalStorageDirectory().getPath();
Mike Lockwood03559752010-07-19 18:25:03 -04001083 mEmulateExternalStorage = context.getResources().getBoolean(
1084 com.android.internal.R.bool.config_emulateExternalStorage);
1085 if (mEmulateExternalStorage) {
1086 Slog.d(TAG, "using emulated external storage");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001087 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
Mike Lockwood03559752010-07-19 18:25:03 -04001088 }
1089
San Mehat207e5382010-02-04 20:46:54 -08001090 // XXX: This will go away soon in favor of IMountServiceObserver
1091 mPms = (PackageManagerService) ServiceManager.getService("package");
1092
1093 mContext.registerReceiver(mBroadcastReceiver,
1094 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1095
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001096 mHandlerThread = new HandlerThread("MountService");
1097 mHandlerThread.start();
1098 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1099
Kenny Roota02b8b02010-08-05 16:14:17 -07001100 // Add OBB Action Handler to MountService thread.
1101 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1102
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001103 /*
1104 * Vold does not run in the simulator, so pretend the connector thread
1105 * ran and did its thing.
1106 */
1107 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1108 mReady = true;
1109 mUmsEnabling = true;
1110 return;
1111 }
1112
Kenny Root305bcbf2010-09-03 07:56:38 -07001113 /*
1114 * Create the connection to vold with a maximum queue of twice the
1115 * amount of containers we'd ever expect to have. This keeps an
1116 * "asec list" from blocking a thread repeatedly.
1117 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001118 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001119 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001120 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001121 thread.start();
1122 }
1123
1124 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001125 * Exposed API calls below here
1126 */
1127
1128 public void registerListener(IMountServiceListener listener) {
1129 synchronized (mListeners) {
1130 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1131 try {
1132 listener.asBinder().linkToDeath(bl, 0);
1133 mListeners.add(bl);
1134 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001135 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001136 }
1137 }
1138 }
1139
1140 public void unregisterListener(IMountServiceListener listener) {
1141 synchronized (mListeners) {
1142 for(MountServiceBinderListener bl : mListeners) {
1143 if (bl.mListener == listener) {
1144 mListeners.remove(mListeners.indexOf(bl));
1145 return;
1146 }
1147 }
1148 }
1149 }
1150
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001151 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001152 validatePermission(android.Manifest.permission.SHUTDOWN);
1153
San Mehata5078592010-03-25 09:36:54 -07001154 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001155 synchronized (mVolumeStates) {
1156 for (String path : mVolumeStates.keySet()) {
1157 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001158
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001159 if (state.equals(Environment.MEDIA_SHARED)) {
1160 /*
1161 * If the media is currently shared, unshare it.
1162 * XXX: This is still dangerous!. We should not
1163 * be rebooting at *all* if UMS is enabled, since
1164 * the UMS host could have dirty FAT cache entries
1165 * yet to flush.
1166 */
1167 setUsbMassStorageEnabled(false);
1168 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1169 /*
1170 * If the media is being checked, then we need to wait for
1171 * it to complete before being able to proceed.
1172 */
1173 // XXX: @hackbod - Should we disable the ANR timer here?
1174 int retries = 30;
1175 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1176 try {
1177 Thread.sleep(1000);
1178 } catch (InterruptedException iex) {
1179 Slog.e(TAG, "Interrupted while waiting for media", iex);
1180 break;
1181 }
1182 state = Environment.getExternalStorageState();
1183 }
1184 if (retries == 0) {
1185 Slog.e(TAG, "Timed out waiting for media to check");
1186 }
San Mehat91c77612010-01-07 10:39:41 -08001187 }
San Mehat91c77612010-01-07 10:39:41 -08001188
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001189 if (state.equals(Environment.MEDIA_MOUNTED)) {
1190 // Post a unmount message.
1191 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1192 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1193 } else if (observer != null) {
1194 /*
1195 * Observer is waiting for onShutDownComplete when we are done.
1196 * Since nothing will be done send notification directly so shutdown
1197 * sequence can continue.
1198 */
1199 try {
1200 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1201 } catch (RemoteException e) {
1202 Slog.w(TAG, "RemoteException when shutting down");
1203 }
1204 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001205 }
San Mehat4270e1e2010-01-29 05:32:19 -08001206 }
1207 }
1208
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001209 private boolean getUmsEnabling() {
1210 synchronized (mListeners) {
1211 return mUmsEnabling;
1212 }
1213 }
1214
1215 private void setUmsEnabling(boolean enable) {
1216 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001217 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001218 }
1219 }
1220
San Mehatb1043402010-02-05 08:26:50 -08001221 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001222 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001223
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001224 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001225 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001226 }
San Mehatb1043402010-02-05 08:26:50 -08001227 return doGetShareMethodAvailable("ums");
1228 }
1229
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001230 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001231 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001232 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001233
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001234 // TODO: Add support for multiple share methods
1235
1236 /*
1237 * If the volume is mounted and we're enabling then unmount it
1238 */
1239 String path = Environment.getExternalStorageDirectory().getPath();
1240 String vs = getVolumeState(path);
1241 String method = "ums";
1242 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1243 // Override for isUsbMassStorageEnabled()
1244 setUmsEnabling(enable);
1245 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1246 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1247 // Clear override
1248 setUmsEnabling(false);
1249 }
1250 /*
1251 * If we disabled UMS then mount the volume
1252 */
1253 if (!enable) {
1254 doShareUnshareVolume(path, method, enable);
1255 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001256 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001257 " after disabling share method " + method);
1258 /*
1259 * Even though the mount failed, the unshare didn't so don't indicate an error.
1260 * The mountVolume() call will have set the storage state and sent the necessary
1261 * broadcasts.
1262 */
1263 }
1264 }
San Mehatb1043402010-02-05 08:26:50 -08001265 }
1266
1267 public boolean isUsbMassStorageEnabled() {
1268 waitForReady();
1269 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001271
San Mehat7fd0fee2009-12-17 07:12:23 -08001272 /**
1273 * @return state of the volume at the specified mount point
1274 */
San Mehat4270e1e2010-01-29 05:32:19 -08001275 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001276 synchronized (mVolumeStates) {
1277 String state = mVolumeStates.get(mountPoint);
1278 if (state == null) {
1279 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1280 throw new IllegalArgumentException();
1281 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001282
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001283 return state;
1284 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001285 }
1286
Kenny Roote1ff2142010-10-12 11:20:01 -07001287 public boolean isExternalStorageEmulated() {
1288 return mEmulateExternalStorage;
1289 }
1290
San Mehat4270e1e2010-01-29 05:32:19 -08001291 public int mountVolume(String path) {
1292 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001293
San Mehat207e5382010-02-04 20:46:54 -08001294 waitForReady();
1295 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001298 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001299 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001300 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001302 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001303 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001304 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1305 Environment.MEDIA_REMOVED.equals(volState) ||
1306 Environment.MEDIA_SHARED.equals(volState) ||
1307 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1308 // Media already unmounted or cannot be unmounted.
1309 // TODO return valid return code when adding observer call back.
1310 return;
1311 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001312 UnmountCallBack ucb = new UnmountCallBack(path, force);
1313 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315
San Mehat4270e1e2010-01-29 05:32:19 -08001316 public int formatVolume(String path) {
1317 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001318 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001319
San Mehat207e5382010-02-04 20:46:54 -08001320 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322
San Mehatc1b4ce92010-02-16 17:13:03 -08001323 public int []getStorageUsers(String path) {
1324 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1325 waitForReady();
1326 try {
1327 String[] r = mConnector.doListCommand(
1328 String.format("storage users %s", path),
1329 VoldResponseCode.StorageUsersListResult);
1330 // FMT: <pid> <process name>
1331 int[] data = new int[r.length];
1332 for (int i = 0; i < r.length; i++) {
1333 String []tok = r[i].split(" ");
1334 try {
1335 data[i] = Integer.parseInt(tok[0]);
1336 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001337 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001338 return new int[0];
1339 }
1340 }
1341 return data;
1342 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001343 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001344 return new int[0];
1345 }
1346 }
1347
San Mehatb1043402010-02-05 08:26:50 -08001348 private void warnOnNotMounted() {
1349 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001350 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001351 }
1352 }
1353
San Mehat4270e1e2010-01-29 05:32:19 -08001354 public String[] getSecureContainerList() {
1355 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001356 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001357 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001358
San Mehat4270e1e2010-01-29 05:32:19 -08001359 try {
1360 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1361 } catch (NativeDaemonConnectorException e) {
1362 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 }
San Mehat36972292010-01-06 11:06:32 -08001365
San Mehat4270e1e2010-01-29 05:32:19 -08001366 public int createSecureContainer(String id, int sizeMb, String fstype,
1367 String key, int ownerUid) {
1368 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001369 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001370 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001371
San Mehatb1043402010-02-05 08:26:50 -08001372 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001373 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1374 try {
1375 mConnector.doCommand(cmd);
1376 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001377 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001378 }
San Mehata181b212010-02-11 06:50:20 -08001379
1380 if (rc == StorageResultCode.OperationSucceeded) {
1381 synchronized (mAsecMountSet) {
1382 mAsecMountSet.add(id);
1383 }
1384 }
San Mehat4270e1e2010-01-29 05:32:19 -08001385 return rc;
San Mehat36972292010-01-06 11:06:32 -08001386 }
1387
San Mehat4270e1e2010-01-29 05:32:19 -08001388 public int finalizeSecureContainer(String id) {
1389 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001390 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001391
San Mehatb1043402010-02-05 08:26:50 -08001392 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001393 try {
1394 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001395 /*
1396 * Finalization does a remount, so no need
1397 * to update mAsecMountSet
1398 */
San Mehat4270e1e2010-01-29 05:32:19 -08001399 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001400 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001401 }
San Mehat4270e1e2010-01-29 05:32:19 -08001402 return rc;
San Mehat36972292010-01-06 11:06:32 -08001403 }
1404
San Mehatd9709982010-02-18 11:43:03 -08001405 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001406 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001407 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001408 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001409
Kenny Rootaa485402010-09-14 14:49:41 -07001410 /*
1411 * Force a GC to make sure AssetManagers in other threads of the
1412 * system_server are cleaned up. We have to do this since AssetManager
1413 * instances are kept as a WeakReference and it's possible we have files
1414 * open on the external storage.
1415 */
1416 Runtime.getRuntime().gc();
1417
San Mehatb1043402010-02-05 08:26:50 -08001418 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001419 try {
San Mehatd9709982010-02-18 11:43:03 -08001420 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001421 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001422 int code = e.getCode();
1423 if (code == VoldResponseCode.OpFailedStorageBusy) {
1424 rc = StorageResultCode.OperationFailedStorageBusy;
1425 } else {
1426 rc = StorageResultCode.OperationFailedInternalError;
1427 }
San Mehat02735bc2010-01-26 15:18:08 -08001428 }
San Mehata181b212010-02-11 06:50:20 -08001429
1430 if (rc == StorageResultCode.OperationSucceeded) {
1431 synchronized (mAsecMountSet) {
1432 if (mAsecMountSet.contains(id)) {
1433 mAsecMountSet.remove(id);
1434 }
1435 }
1436 }
1437
San Mehat4270e1e2010-01-29 05:32:19 -08001438 return rc;
San Mehat36972292010-01-06 11:06:32 -08001439 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001440
San Mehat4270e1e2010-01-29 05:32:19 -08001441 public int mountSecureContainer(String id, String key, int ownerUid) {
1442 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001443 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001444 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001445
San Mehata181b212010-02-11 06:50:20 -08001446 synchronized (mAsecMountSet) {
1447 if (mAsecMountSet.contains(id)) {
1448 return StorageResultCode.OperationFailedStorageMounted;
1449 }
1450 }
1451
San Mehatb1043402010-02-05 08:26:50 -08001452 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001453 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1454 try {
1455 mConnector.doCommand(cmd);
1456 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001457 int code = e.getCode();
1458 if (code != VoldResponseCode.OpFailedStorageBusy) {
1459 rc = StorageResultCode.OperationFailedInternalError;
1460 }
San Mehat02735bc2010-01-26 15:18:08 -08001461 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001462
1463 if (rc == StorageResultCode.OperationSucceeded) {
1464 synchronized (mAsecMountSet) {
1465 mAsecMountSet.add(id);
1466 }
1467 }
San Mehat4270e1e2010-01-29 05:32:19 -08001468 return rc;
San Mehat36972292010-01-06 11:06:32 -08001469 }
1470
San Mehatd9709982010-02-18 11:43:03 -08001471 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001472 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001473 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001474 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001475
San Mehat6cdd9c02010-02-09 14:45:20 -08001476 synchronized (mAsecMountSet) {
1477 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001478 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001479 }
1480 }
1481
Kenny Rootaa485402010-09-14 14:49:41 -07001482 /*
1483 * Force a GC to make sure AssetManagers in other threads of the
1484 * system_server are cleaned up. We have to do this since AssetManager
1485 * instances are kept as a WeakReference and it's possible we have files
1486 * open on the external storage.
1487 */
1488 Runtime.getRuntime().gc();
1489
San Mehatb1043402010-02-05 08:26:50 -08001490 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001491 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001492 try {
1493 mConnector.doCommand(cmd);
1494 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001495 int code = e.getCode();
1496 if (code == VoldResponseCode.OpFailedStorageBusy) {
1497 rc = StorageResultCode.OperationFailedStorageBusy;
1498 } else {
1499 rc = StorageResultCode.OperationFailedInternalError;
1500 }
San Mehat02735bc2010-01-26 15:18:08 -08001501 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001502
1503 if (rc == StorageResultCode.OperationSucceeded) {
1504 synchronized (mAsecMountSet) {
1505 mAsecMountSet.remove(id);
1506 }
1507 }
San Mehat4270e1e2010-01-29 05:32:19 -08001508 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001509 }
1510
San Mehat6cdd9c02010-02-09 14:45:20 -08001511 public boolean isSecureContainerMounted(String id) {
1512 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1513 waitForReady();
1514 warnOnNotMounted();
1515
1516 synchronized (mAsecMountSet) {
1517 return mAsecMountSet.contains(id);
1518 }
1519 }
1520
San Mehat4270e1e2010-01-29 05:32:19 -08001521 public int renameSecureContainer(String oldId, String newId) {
1522 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001523 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001524 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001525
San Mehata181b212010-02-11 06:50:20 -08001526 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001527 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001528 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001529 * changed while active, we must ensure both ids are not currently mounted.
1530 */
1531 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001532 return StorageResultCode.OperationFailedStorageMounted;
1533 }
1534 }
1535
San Mehatb1043402010-02-05 08:26:50 -08001536 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001537 String cmd = String.format("asec rename %s %s", oldId, newId);
1538 try {
1539 mConnector.doCommand(cmd);
1540 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001541 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001542 }
San Mehata181b212010-02-11 06:50:20 -08001543
San Mehat4270e1e2010-01-29 05:32:19 -08001544 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001545 }
1546
San Mehat4270e1e2010-01-29 05:32:19 -08001547 public String getSecureContainerPath(String id) {
1548 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001549 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001550 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001551
San Mehat2d66cef2010-03-23 11:12:52 -07001552 try {
1553 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1554 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001555 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001556 if (code != VoldResponseCode.AsecPathResult) {
1557 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1558 }
1559 return tok[1];
1560 } catch (NativeDaemonConnectorException e) {
1561 int code = e.getCode();
1562 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001563 Slog.i(TAG, String.format("Container '%s' not found", id));
1564 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001565 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001566 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001567 }
1568 }
San Mehat22dd86e2010-01-12 12:21:18 -08001569 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001570
1571 public void finishMediaUpdate() {
1572 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1573 }
Kenny Root02c87302010-07-01 08:10:18 -07001574
Kenny Roota02b8b02010-08-05 16:14:17 -07001575 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1576 if (callerUid == android.os.Process.SYSTEM_UID) {
1577 return true;
1578 }
1579
Kenny Root02c87302010-07-01 08:10:18 -07001580 if (packageName == null) {
1581 return false;
1582 }
1583
1584 final int packageUid = mPms.getPackageUid(packageName);
1585
1586 if (DEBUG_OBB) {
1587 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1588 packageUid + ", callerUid = " + callerUid);
1589 }
1590
1591 return callerUid == packageUid;
1592 }
1593
1594 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001595 if (filename == null) {
1596 throw new IllegalArgumentException("filename cannot be null");
1597 }
1598
Kenny Root02c87302010-07-01 08:10:18 -07001599 waitForReady();
1600 warnOnNotMounted();
1601
Kenny Root02c87302010-07-01 08:10:18 -07001602 try {
1603 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1604 String []tok = rsp.get(0).split(" ");
1605 int code = Integer.parseInt(tok[0]);
1606 if (code != VoldResponseCode.AsecPathResult) {
1607 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1608 }
1609 return tok[1];
1610 } catch (NativeDaemonConnectorException e) {
1611 int code = e.getCode();
1612 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001613 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001614 } else {
1615 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1616 }
1617 }
1618 }
1619
1620 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001621 if (filename == null) {
1622 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001623 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001624
1625 synchronized (mObbMounts) {
1626 return mObbPathToStateMap.containsKey(filename);
1627 }
Kenny Root02c87302010-07-01 08:10:18 -07001628 }
1629
Kenny Rootaf9d6672010-10-08 09:21:39 -07001630 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001631 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001632 if (filename == null) {
1633 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001634 }
1635
1636 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001637 throw new IllegalArgumentException("token cannot be null");
1638 }
1639
Kenny Rootaf9d6672010-10-08 09:21:39 -07001640 final int callerUid = Binder.getCallingUid();
1641 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1642 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001643 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1644
1645 if (DEBUG_OBB)
1646 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001647 }
1648
Kenny Rootaf9d6672010-10-08 09:21:39 -07001649 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1650 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001651 if (filename == null) {
1652 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001653 }
1654
Kenny Rootaf9d6672010-10-08 09:21:39 -07001655 final int callerUid = Binder.getCallingUid();
1656 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1657 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001658 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001659
Kenny Roota02b8b02010-08-05 16:14:17 -07001660 if (DEBUG_OBB)
1661 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1662 }
1663
Jason parks5af0b912010-11-29 09:05:25 -06001664 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001665 if (TextUtils.isEmpty(password)) {
1666 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001667 }
1668
Jason parks8888c592011-01-20 22:46:41 -06001669 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1670 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001671
1672 waitForReady();
1673
1674 if (DEBUG_EVENTS) {
1675 Slog.i(TAG, "decrypting storage...");
1676 }
1677
1678 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001679 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001680 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001681
Jason parksf7b3cd42011-01-27 09:28:25 -06001682 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001683 return -1;
1684 }
1685
Jason parksf7b3cd42011-01-27 09:28:25 -06001686 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001687
1688 if (code == 0) {
1689 // Decrypt was successful. Post a delayed message before restarting in order
1690 // to let the UI to clear itself
1691 mHandler.postDelayed(new Runnable() {
1692 public void run() {
1693 mConnector.doCommand(String.format("cryptfs restart"));
1694 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001695 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001696 }
1697
1698 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001699 } catch (NativeDaemonConnectorException e) {
1700 // Decryption failed
1701 return e.getCode();
1702 }
Jason parks5af0b912010-11-29 09:05:25 -06001703 }
1704
Jason parks56aa5322011-01-07 09:01:15 -06001705 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001706 if (TextUtils.isEmpty(password)) {
1707 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001708 }
1709
Jason parks8888c592011-01-20 22:46:41 -06001710 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1711 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001712
1713 waitForReady();
1714
1715 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001716 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001717 }
1718
1719 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001720 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001721 } catch (NativeDaemonConnectorException e) {
1722 // Encryption failed
1723 return e.getCode();
1724 }
1725
1726 return 0;
1727 }
1728
Jason parksf7b3cd42011-01-27 09:28:25 -06001729 public int changeEncryptionPassword(String password) {
1730 if (TextUtils.isEmpty(password)) {
1731 throw new IllegalArgumentException("password cannot be empty");
1732 }
1733
1734 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1735 "no permission to access the crypt keeper");
1736
1737 waitForReady();
1738
1739 if (DEBUG_EVENTS) {
1740 Slog.i(TAG, "changing encryption password...");
1741 }
1742
1743 try {
1744 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1745
1746 String[] tokens = response.get(0).split(" ");
1747
1748 if (tokens == null || tokens.length != 2) {
1749 return -1;
1750 }
1751
1752 return Integer.parseInt(tokens[1]);
1753 } catch (NativeDaemonConnectorException e) {
1754 // Encryption failed
1755 return e.getCode();
1756 }
1757 }
1758
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001759 public String[] getVolumeList() {
1760 synchronized(mVolumeStates) {
1761 Set<String> volumes = mVolumeStates.keySet();
1762 String[] result = new String[volumes.size()];
1763 int i = 0;
1764 for (String volume : volumes) {
1765 result[i++] = volume;
1766 }
1767 return result;
1768 }
1769 }
1770
Kenny Rootaf9d6672010-10-08 09:21:39 -07001771 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1772 final IBinder binder = obbState.getBinder();
1773 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001774
Kenny Rootaf9d6672010-10-08 09:21:39 -07001775 if (obbStates == null) {
1776 obbStates = new ArrayList<ObbState>();
1777 mObbMounts.put(binder, obbStates);
1778 } else {
1779 for (final ObbState o : obbStates) {
1780 if (o.filename.equals(obbState.filename)) {
1781 throw new IllegalStateException("Attempt to add ObbState twice. "
1782 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001783 }
1784 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001785 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001786
1787 obbStates.add(obbState);
1788 try {
1789 obbState.link();
1790 } catch (RemoteException e) {
1791 /*
1792 * The binder died before we could link it, so clean up our state
1793 * and return failure.
1794 */
1795 obbStates.remove(obbState);
1796 if (obbStates.isEmpty()) {
1797 mObbMounts.remove(binder);
1798 }
1799
1800 // Rethrow the error so mountObb can get it
1801 throw e;
1802 }
1803
1804 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001805 }
1806
Kenny Rootaf9d6672010-10-08 09:21:39 -07001807 private void removeObbStateLocked(ObbState obbState) {
1808 final IBinder binder = obbState.getBinder();
1809 final List<ObbState> obbStates = mObbMounts.get(binder);
1810 if (obbStates != null) {
1811 if (obbStates.remove(obbState)) {
1812 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001813 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001814 if (obbStates.isEmpty()) {
1815 mObbMounts.remove(binder);
1816 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001817 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001818
Kenny Rootaf9d6672010-10-08 09:21:39 -07001819 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001820 }
1821
Kenny Roota02b8b02010-08-05 16:14:17 -07001822 private class ObbActionHandler extends Handler {
1823 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001824 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001825
1826 ObbActionHandler(Looper l) {
1827 super(l);
1828 }
1829
1830 @Override
1831 public void handleMessage(Message msg) {
1832 switch (msg.what) {
1833 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001834 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001835
1836 if (DEBUG_OBB)
1837 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1838
1839 // If a bind was already initiated we don't really
1840 // need to do anything. The pending install
1841 // will be processed later on.
1842 if (!mBound) {
1843 // If this is the only one pending we might
1844 // have to bind to the service again.
1845 if (!connectToService()) {
1846 Slog.e(TAG, "Failed to bind to media container service");
1847 action.handleError();
1848 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001849 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001850 }
Kenny Root735de3b2010-09-30 14:11:39 -07001851
Kenny Root735de3b2010-09-30 14:11:39 -07001852 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001853 break;
1854 }
1855 case OBB_MCS_BOUND: {
1856 if (DEBUG_OBB)
1857 Slog.i(TAG, "OBB_MCS_BOUND");
1858 if (msg.obj != null) {
1859 mContainerService = (IMediaContainerService) msg.obj;
1860 }
1861 if (mContainerService == null) {
1862 // Something seriously wrong. Bail out
1863 Slog.e(TAG, "Cannot bind to media container service");
1864 for (ObbAction action : mActions) {
1865 // Indicate service bind error
1866 action.handleError();
1867 }
1868 mActions.clear();
1869 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001870 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001871 if (action != null) {
1872 action.execute(this);
1873 }
1874 } else {
1875 // Should never happen ideally.
1876 Slog.w(TAG, "Empty queue");
1877 }
1878 break;
1879 }
1880 case OBB_MCS_RECONNECT: {
1881 if (DEBUG_OBB)
1882 Slog.i(TAG, "OBB_MCS_RECONNECT");
1883 if (mActions.size() > 0) {
1884 if (mBound) {
1885 disconnectService();
1886 }
1887 if (!connectToService()) {
1888 Slog.e(TAG, "Failed to bind to media container service");
1889 for (ObbAction action : mActions) {
1890 // Indicate service bind error
1891 action.handleError();
1892 }
1893 mActions.clear();
1894 }
1895 }
1896 break;
1897 }
1898 case OBB_MCS_UNBIND: {
1899 if (DEBUG_OBB)
1900 Slog.i(TAG, "OBB_MCS_UNBIND");
1901
1902 // Delete pending install
1903 if (mActions.size() > 0) {
1904 mActions.remove(0);
1905 }
1906 if (mActions.size() == 0) {
1907 if (mBound) {
1908 disconnectService();
1909 }
1910 } else {
1911 // There are more pending requests in queue.
1912 // Just post MCS_BOUND message to trigger processing
1913 // of next pending install.
1914 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1915 }
1916 break;
1917 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001918 case OBB_FLUSH_MOUNT_STATE: {
1919 final String path = (String) msg.obj;
1920
1921 if (DEBUG_OBB)
1922 Slog.i(TAG, "Flushing all OBB state for path " + path);
1923
1924 synchronized (mObbMounts) {
1925 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1926
1927 final Iterator<Entry<String, ObbState>> i =
1928 mObbPathToStateMap.entrySet().iterator();
1929 while (i.hasNext()) {
1930 final Entry<String, ObbState> obbEntry = i.next();
1931
1932 /*
1933 * If this entry's source file is in the volume path
1934 * that got unmounted, remove it because it's no
1935 * longer valid.
1936 */
1937 if (obbEntry.getKey().startsWith(path)) {
1938 obbStatesToRemove.add(obbEntry.getValue());
1939 }
1940 }
1941
1942 for (final ObbState obbState : obbStatesToRemove) {
1943 if (DEBUG_OBB)
1944 Slog.i(TAG, "Removing state for " + obbState.filename);
1945
1946 removeObbStateLocked(obbState);
1947
1948 try {
1949 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1950 OnObbStateChangeListener.UNMOUNTED);
1951 } catch (RemoteException e) {
1952 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1953 + obbState.filename);
1954 }
1955 }
1956 }
1957 break;
1958 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001959 }
1960 }
1961
1962 private boolean connectToService() {
1963 if (DEBUG_OBB)
1964 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1965
1966 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1967 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1968 mBound = true;
1969 return true;
1970 }
1971 return false;
1972 }
1973
1974 private void disconnectService() {
1975 mContainerService = null;
1976 mBound = false;
1977 mContext.unbindService(mDefContainerConn);
1978 }
1979 }
1980
1981 abstract class ObbAction {
1982 private static final int MAX_RETRIES = 3;
1983 private int mRetries;
1984
1985 ObbState mObbState;
1986
1987 ObbAction(ObbState obbState) {
1988 mObbState = obbState;
1989 }
1990
1991 public void execute(ObbActionHandler handler) {
1992 try {
1993 if (DEBUG_OBB)
1994 Slog.i(TAG, "Starting to execute action: " + this.toString());
1995 mRetries++;
1996 if (mRetries > MAX_RETRIES) {
1997 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001998 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001999 handleError();
2000 return;
2001 } else {
2002 handleExecute();
2003 if (DEBUG_OBB)
2004 Slog.i(TAG, "Posting install MCS_UNBIND");
2005 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2006 }
2007 } catch (RemoteException e) {
2008 if (DEBUG_OBB)
2009 Slog.i(TAG, "Posting install MCS_RECONNECT");
2010 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2011 } catch (Exception e) {
2012 if (DEBUG_OBB)
2013 Slog.d(TAG, "Error handling OBB action", e);
2014 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002015 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002016 }
2017 }
2018
Kenny Root05105f72010-09-22 17:29:43 -07002019 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002020 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002021
2022 protected ObbInfo getObbInfo() throws IOException {
2023 ObbInfo obbInfo;
2024 try {
2025 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2026 } catch (RemoteException e) {
2027 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2028 + mObbState.filename);
2029 obbInfo = null;
2030 }
2031 if (obbInfo == null) {
2032 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2033 }
2034 return obbInfo;
2035 }
2036
Kenny Rootaf9d6672010-10-08 09:21:39 -07002037 protected void sendNewStatusOrIgnore(int status) {
2038 if (mObbState == null || mObbState.token == null) {
2039 return;
2040 }
2041
Kenny Root38cf8862010-09-26 14:18:51 -07002042 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002043 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002044 } catch (RemoteException e) {
2045 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2046 }
2047 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002048 }
2049
2050 class MountObbAction extends ObbAction {
2051 private String mKey;
2052
2053 MountObbAction(ObbState obbState, String key) {
2054 super(obbState);
2055 mKey = key;
2056 }
2057
Jason parks5af0b912010-11-29 09:05:25 -06002058 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002059 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002060 waitForReady();
2061 warnOnNotMounted();
2062
Kenny Root38cf8862010-09-26 14:18:51 -07002063 final ObbInfo obbInfo = getObbInfo();
2064
Kenny Roota02b8b02010-08-05 16:14:17 -07002065 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002066 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2067 + " which is owned by " + obbInfo.packageName);
2068 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2069 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002070 }
2071
Kenny Rootaf9d6672010-10-08 09:21:39 -07002072 final boolean isMounted;
2073 synchronized (mObbMounts) {
2074 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2075 }
2076 if (isMounted) {
2077 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2078 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2079 return;
2080 }
2081
2082 /*
2083 * The filename passed in might not be the canonical name, so just
2084 * set the filename to the canonicalized version.
2085 */
2086 mObbState.filename = obbInfo.filename;
2087
2088 final String hashedKey;
2089 if (mKey == null) {
2090 hashedKey = "none";
2091 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002092 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002093 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2094
2095 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2096 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2097 SecretKey key = factory.generateSecret(ks);
2098 BigInteger bi = new BigInteger(key.getEncoded());
2099 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002100 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002101 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2102 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2103 return;
2104 } catch (InvalidKeySpecException e) {
2105 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2106 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002107 return;
2108 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002109 }
Kenny Root38cf8862010-09-26 14:18:51 -07002110
Kenny Rootaf9d6672010-10-08 09:21:39 -07002111 int rc = StorageResultCode.OperationSucceeded;
2112 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2113 mObbState.callerUid);
2114 try {
2115 mConnector.doCommand(cmd);
2116 } catch (NativeDaemonConnectorException e) {
2117 int code = e.getCode();
2118 if (code != VoldResponseCode.OpFailedStorageBusy) {
2119 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002120 }
2121 }
2122
Kenny Rootaf9d6672010-10-08 09:21:39 -07002123 if (rc == StorageResultCode.OperationSucceeded) {
2124 if (DEBUG_OBB)
2125 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2126
2127 synchronized (mObbMounts) {
2128 addObbStateLocked(mObbState);
2129 }
2130
2131 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002132 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002133 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002134
Kenny Rootaf9d6672010-10-08 09:21:39 -07002135 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002136 }
2137 }
2138
Jason parks5af0b912010-11-29 09:05:25 -06002139 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002140 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002141 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002142 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002143
2144 @Override
2145 public String toString() {
2146 StringBuilder sb = new StringBuilder();
2147 sb.append("MountObbAction{");
2148 sb.append("filename=");
2149 sb.append(mObbState.filename);
2150 sb.append(",callerUid=");
2151 sb.append(mObbState.callerUid);
2152 sb.append(",token=");
2153 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154 sb.append(",binder=");
2155 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002156 sb.append('}');
2157 return sb.toString();
2158 }
2159 }
2160
2161 class UnmountObbAction extends ObbAction {
2162 private boolean mForceUnmount;
2163
2164 UnmountObbAction(ObbState obbState, boolean force) {
2165 super(obbState);
2166 mForceUnmount = force;
2167 }
2168
Jason parks5af0b912010-11-29 09:05:25 -06002169 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002170 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002171 waitForReady();
2172 warnOnNotMounted();
2173
Kenny Root38cf8862010-09-26 14:18:51 -07002174 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002175
Kenny Rootaf9d6672010-10-08 09:21:39 -07002176 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002177 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002178 obbState = mObbPathToStateMap.get(obbInfo.filename);
2179 }
Kenny Root38cf8862010-09-26 14:18:51 -07002180
Kenny Rootaf9d6672010-10-08 09:21:39 -07002181 if (obbState == null) {
2182 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2183 return;
2184 }
2185
2186 if (obbState.callerUid != mObbState.callerUid) {
2187 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2188 + " (owned by " + obbInfo.packageName + ")");
2189 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2190 return;
2191 }
2192
2193 mObbState.filename = obbInfo.filename;
2194
2195 int rc = StorageResultCode.OperationSucceeded;
2196 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2197 (mForceUnmount ? " force" : ""));
2198 try {
2199 mConnector.doCommand(cmd);
2200 } catch (NativeDaemonConnectorException e) {
2201 int code = e.getCode();
2202 if (code == VoldResponseCode.OpFailedStorageBusy) {
2203 rc = StorageResultCode.OperationFailedStorageBusy;
2204 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2205 // If it's not mounted then we've already won.
2206 rc = StorageResultCode.OperationSucceeded;
2207 } else {
2208 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002209 }
2210 }
2211
Kenny Rootaf9d6672010-10-08 09:21:39 -07002212 if (rc == StorageResultCode.OperationSucceeded) {
2213 synchronized (mObbMounts) {
2214 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002215 }
2216
Kenny Rootaf9d6672010-10-08 09:21:39 -07002217 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002218 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002219 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2220 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002221 }
2222 }
2223
Jason parks5af0b912010-11-29 09:05:25 -06002224 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002225 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002226 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002227 }
2228
2229 @Override
2230 public String toString() {
2231 StringBuilder sb = new StringBuilder();
2232 sb.append("UnmountObbAction{");
2233 sb.append("filename=");
2234 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2235 sb.append(",force=");
2236 sb.append(mForceUnmount);
2237 sb.append(",callerUid=");
2238 sb.append(mObbState.callerUid);
2239 sb.append(",token=");
2240 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002241 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002242 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002243 sb.append('}');
2244 return sb.toString();
2245 }
Kenny Root02c87302010-07-01 08:10:18 -07002246 }
Kenny Root38cf8862010-09-26 14:18:51 -07002247
2248 @Override
2249 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2250 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2251 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2252 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2253 + " without permission " + android.Manifest.permission.DUMP);
2254 return;
2255 }
2256
Kenny Root38cf8862010-09-26 14:18:51 -07002257 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002258 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002259
Kenny Rootaf9d6672010-10-08 09:21:39 -07002260 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2261 while (binders.hasNext()) {
2262 Entry<IBinder, List<ObbState>> e = binders.next();
2263 pw.print(" Key="); pw.println(e.getKey().toString());
2264 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002265 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002266 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002267 }
2268 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002269
2270 pw.println("");
2271 pw.println(" mObbPathToStateMap:");
2272 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2273 while (maps.hasNext()) {
2274 final Entry<String, ObbState> e = maps.next();
2275 pw.print(" "); pw.print(e.getKey());
2276 pw.print(" -> "); pw.println(e.getValue().toString());
2277 }
Kenny Root38cf8862010-09-26 14:18:51 -07002278 }
2279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280}
2281