blob: 3257c26e283971a63c3d75350a2c57ab4f66577f [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
San Mehat6a965af22010-02-24 17:47:30 -0800494 /*
San Mehat6a254402010-03-22 10:21:00 -0700495 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800496 * now that we're up.
497 */
498 if (mSendUmsConnectedOnBoot) {
499 sendUmsIntent(true);
500 mSendUmsConnectedOnBoot = false;
501 }
San Mehatfafb0412010-02-18 19:40:04 -0800502 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700503 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800504 }
San Mehat207e5382010-02-04 20:46:54 -0800505 }
San Mehatfafb0412010-02-18 19:40:04 -0800506 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508 }
509 };
San Mehat4270e1e2010-01-29 05:32:19 -0800510 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
511 final IMountServiceListener mListener;
512
513 MountServiceBinderListener(IMountServiceListener listener) {
514 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700515
San Mehat91c77612010-01-07 10:39:41 -0800516 }
517
San Mehat4270e1e2010-01-29 05:32:19 -0800518 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700519 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700520 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800521 mListeners.remove(this);
522 mListener.asBinder().unlinkToDeath(this, 0);
523 }
524 }
525 }
526
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800527 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800528 // TODO: Add support for multiple share methods
529 if (!method.equals("ums")) {
530 throw new IllegalArgumentException(String.format("Method %s not supported", method));
531 }
532
San Mehat4270e1e2010-01-29 05:32:19 -0800533 try {
534 mConnector.doCommand(String.format(
535 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
536 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700537 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800538 }
San Mehat4270e1e2010-01-29 05:32:19 -0800539 }
540
San Mehat207e5382010-02-04 20:46:54 -0800541 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400542 String oldState;
543 synchronized(mVolumeStates) {
544 oldState = mVolumeStates.put(path, state);
545 }
546 if (state.equals(oldState)) {
547 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
548 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800549 return;
550 }
San Mehatb1043402010-02-05 08:26:50 -0800551
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400552 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700553
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400554 if (path.equals(mExternalStoragePath)) {
555 // Update state on PackageManager, but only of real events
556 if (!mEmulateExternalStorage) {
557 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
558 mPms.updateExternalMediaStatus(false, false);
559
560 /*
561 * Some OBBs might have been unmounted when this volume was
562 * unmounted, so send a message to the handler to let it know to
563 * remove those from the list of mounted OBBS.
564 */
565 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
566 OBB_FLUSH_MOUNT_STATE, path));
567 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
568 mPms.updateExternalMediaStatus(true, false);
569 }
Mike Lockwood03559752010-07-19 18:25:03 -0400570 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800571 }
San Mehat4270e1e2010-01-29 05:32:19 -0800572 synchronized (mListeners) {
573 for (int i = mListeners.size() -1; i >= 0; i--) {
574 MountServiceBinderListener bl = mListeners.get(i);
575 try {
San Mehatb1043402010-02-05 08:26:50 -0800576 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800577 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700578 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800579 mListeners.remove(i);
580 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700581 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800582 }
583 }
584 }
585 }
586
587 /**
588 *
589 * Callback from NativeDaemonConnector
590 */
591 public void onDaemonConnected() {
592 /*
593 * Since we'll be calling back into the NativeDaemonConnector,
594 * we need to do our work in a new thread.
595 */
596 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600597 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800598 public void run() {
599 /**
600 * Determine media state and UMS detection status
601 */
San Mehat4270e1e2010-01-29 05:32:19 -0800602 try {
603 String[] vols = mConnector.doListCommand(
604 "volume list", VoldResponseCode.VolumeListResult);
605 for (String volstr : vols) {
606 String[] tok = volstr.split(" ");
607 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400608 String path = tok[1];
609 String state = Environment.MEDIA_REMOVED;
610
San Mehat4270e1e2010-01-29 05:32:19 -0800611 int st = Integer.parseInt(tok[2]);
612 if (st == VolumeState.NoMedia) {
613 state = Environment.MEDIA_REMOVED;
614 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800615 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800616 } else if (st == VolumeState.Mounted) {
617 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700618 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800619 } else if (st == VolumeState.Shared) {
620 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700621 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800622 } else {
623 throw new Exception(String.format("Unexpected state %d", st));
624 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400625
626 if (state != null) {
627 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
628 updatePublicVolumeState(path, state);
629 }
San Mehat4270e1e2010-01-29 05:32:19 -0800630 }
631 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700632 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400633 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800634 }
635
636 try {
San Mehat207e5382010-02-04 20:46:54 -0800637 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800638 notifyShareAvailabilityChange("ums", avail);
639 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700640 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800641 }
San Mehat207e5382010-02-04 20:46:54 -0800642 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600643 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800644 * the hounds!
645 */
646 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800647 }
648 }.start();
649 }
650
651 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800652 * Callback from NativeDaemonConnector
653 */
654 public boolean onEvent(int code, String raw, String[] cooked) {
655 Intent in = null;
656
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800657 if (DEBUG_EVENTS) {
658 StringBuilder builder = new StringBuilder();
659 builder.append("onEvent::");
660 builder.append(" raw= " + raw);
661 if (cooked != null) {
662 builder.append(" cooked = " );
663 for (String str : cooked) {
664 builder.append(" " + str);
665 }
666 }
San Mehata5078592010-03-25 09:36:54 -0700667 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800668 }
San Mehat4270e1e2010-01-29 05:32:19 -0800669 if (code == VoldResponseCode.VolumeStateChange) {
670 /*
671 * One of the volumes we're managing has changed state.
672 * Format: "NNN Volume <label> <path> state changed
673 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
674 */
675 notifyVolumeStateChange(
676 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
677 Integer.parseInt(cooked[10]));
678 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
679 // FMT: NNN Share method <method> now <available|unavailable>
680 boolean avail = false;
681 if (cooked[5].equals("available")) {
682 avail = true;
683 }
684 notifyShareAvailabilityChange(cooked[3], avail);
685 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
686 (code == VoldResponseCode.VolumeDiskRemoved) ||
687 (code == VoldResponseCode.VolumeBadRemoval)) {
688 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
689 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
690 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
691 final String label = cooked[2];
692 final String path = cooked[3];
693 int major = -1;
694 int minor = -1;
695
696 try {
697 String devComp = cooked[6].substring(1, cooked[6].length() -1);
698 String[] devTok = devComp.split(":");
699 major = Integer.parseInt(devTok[0]);
700 minor = Integer.parseInt(devTok[1]);
701 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700702 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800703 }
704
San Mehat4270e1e2010-01-29 05:32:19 -0800705 if (code == VoldResponseCode.VolumeDiskInserted) {
706 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600707 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800708 public void run() {
709 try {
710 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800711 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700712 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800713 }
714 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700715 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800716 }
717 }
718 }.start();
719 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
720 /*
721 * This event gets trumped if we're already in BAD_REMOVAL state
722 */
723 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
724 return true;
725 }
726 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700727 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800728 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
729 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
730 mContext.sendBroadcast(in);
731
San Mehata5078592010-03-25 09:36:54 -0700732 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800733 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
734 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
735 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700736 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800737 /* Send the media unmounted event first */
738 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
739 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
740 mContext.sendBroadcast(in);
741
San Mehata5078592010-03-25 09:36:54 -0700742 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800743 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
744 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
745 } else {
San Mehata5078592010-03-25 09:36:54 -0700746 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800747 }
748 } else {
749 return false;
750 }
751
752 if (in != null) {
753 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400754 }
755 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800756 }
757
San Mehat207e5382010-02-04 20:46:54 -0800758 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800759 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700760 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800761
762 Intent in = null;
763
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500764 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700765 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500766 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
767 Uri.parse("file://" + path)));
768 }
769
San Mehat4270e1e2010-01-29 05:32:19 -0800770 if (newState == VolumeState.Init) {
771 } else if (newState == VolumeState.NoMedia) {
772 // NoMedia is handled via Disk Remove events
773 } else if (newState == VolumeState.Idle) {
774 /*
775 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
776 * if we're in the process of enabling UMS
777 */
778 if (!vs.equals(
779 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
780 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800781 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700782 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800783 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
784 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
785 }
786 } else if (newState == VolumeState.Pending) {
787 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700788 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800789 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
790 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
791 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700792 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800793 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800794 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
795 in.putExtra("read-only", false);
796 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800797 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
798 } else if (newState == VolumeState.Formatting) {
799 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700800 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800801 /* Send the media unmounted event first */
802 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
803 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
804 mContext.sendBroadcast(in);
805
San Mehata5078592010-03-25 09:36:54 -0700806 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800807 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
808 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700809 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800810 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700811 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800812 return;
813 } else {
San Mehata5078592010-03-25 09:36:54 -0700814 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800815 }
816
817 if (in != null) {
818 mContext.sendBroadcast(in);
819 }
820 }
821
San Mehat207e5382010-02-04 20:46:54 -0800822 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700823 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700824 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700825 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700826 } catch (NativeDaemonConnectorException ex) {
827 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
828 return false;
829 }
San Mehat207e5382010-02-04 20:46:54 -0800830
831 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700832 String[] tok = line.split(" ");
833 if (tok.length < 3) {
834 Slog.e(TAG, "Malformed response to share status " + method);
835 return false;
836 }
837
San Mehat207e5382010-02-04 20:46:54 -0800838 int code;
839 try {
840 code = Integer.parseInt(tok[0]);
841 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700842 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800843 return false;
844 }
845 if (code == VoldResponseCode.ShareStatusResult) {
846 if (tok[2].equals("available"))
847 return true;
848 return false;
849 } else {
San Mehata5078592010-03-25 09:36:54 -0700850 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800851 return false;
852 }
853 }
San Mehata5078592010-03-25 09:36:54 -0700854 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800855 return false;
856 }
857
858 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800859 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800860
San Mehata5078592010-03-25 09:36:54 -0700861 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800862 try {
863 mConnector.doCommand(String.format("volume mount %s", path));
864 } catch (NativeDaemonConnectorException e) {
865 /*
866 * Mount failed for some reason
867 */
868 Intent in = null;
869 int code = e.getCode();
870 if (code == VoldResponseCode.OpFailedNoMedia) {
871 /*
872 * Attempt to mount but no media inserted
873 */
San Mehatb1043402010-02-05 08:26:50 -0800874 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800875 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700876 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800877 /*
878 * Media is blank or does not contain a supported filesystem
879 */
880 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
881 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800882 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800883 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700884 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800885 /*
886 * Volume consistency check failed
887 */
888 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
889 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800890 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800891 } else {
San Mehatb1043402010-02-05 08:26:50 -0800892 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800893 }
894
895 /*
896 * Send broadcast intent (if required for the failure)
897 */
898 if (in != null) {
899 mContext.sendBroadcast(in);
900 }
901 }
902
903 return rc;
904 }
905
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800906 /*
907 * If force is not set, we do not unmount if there are
908 * processes holding references to the volume about to be unmounted.
909 * If force is set, all the processes holding references need to be
910 * killed via the ActivityManager before actually unmounting the volume.
911 * This might even take a while and might be retried after timed delays
912 * to make sure we dont end up in an instable state and kill some core
913 * processes.
914 */
San Mehatd9709982010-02-18 11:43:03 -0800915 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800916 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800917 return VoldResponseCode.OpFailedVolNotMounted;
918 }
Kenny Rootaa485402010-09-14 14:49:41 -0700919
920 /*
921 * Force a GC to make sure AssetManagers in other threads of the
922 * system_server are cleaned up. We have to do this since AssetManager
923 * instances are kept as a WeakReference and it's possible we have files
924 * open on the external storage.
925 */
926 Runtime.getRuntime().gc();
927
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800928 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700929 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800930 try {
San Mehatd9709982010-02-18 11:43:03 -0800931 mConnector.doCommand(String.format(
932 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700933 // We unmounted the volume. None of the asec containers are available now.
934 synchronized (mAsecMountSet) {
935 mAsecMountSet.clear();
936 }
San Mehatb1043402010-02-05 08:26:50 -0800937 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800938 } catch (NativeDaemonConnectorException e) {
939 // Don't worry about mismatch in PackageManager since the
940 // call back will handle the status changes any way.
941 int code = e.getCode();
942 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800943 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800944 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
945 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800946 } else {
San Mehatb1043402010-02-05 08:26:50 -0800947 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800948 }
949 }
950 }
951
952 private int doFormatVolume(String path) {
953 try {
954 String cmd = String.format("volume format %s", path);
955 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800956 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800957 } catch (NativeDaemonConnectorException e) {
958 int code = e.getCode();
959 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800960 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800961 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800962 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800963 } else {
San Mehatb1043402010-02-05 08:26:50 -0800964 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800965 }
966 }
967 }
968
San Mehatb1043402010-02-05 08:26:50 -0800969 private boolean doGetVolumeShared(String path, String method) {
970 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700971 ArrayList<String> rsp;
972
973 try {
974 rsp = mConnector.doCommand(cmd);
975 } catch (NativeDaemonConnectorException ex) {
976 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
977 return false;
978 }
San Mehatb1043402010-02-05 08:26:50 -0800979
980 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700981 String[] tok = line.split(" ");
982 if (tok.length < 3) {
983 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
984 return false;
985 }
986
San Mehatb1043402010-02-05 08:26:50 -0800987 int code;
988 try {
989 code = Integer.parseInt(tok[0]);
990 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700991 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800992 return false;
993 }
994 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700995 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800996 } else {
San Mehata5078592010-03-25 09:36:54 -0700997 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800998 return false;
999 }
1000 }
San Mehata5078592010-03-25 09:36:54 -07001001 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001002 return false;
1003 }
1004
San Mehat207e5382010-02-04 20:46:54 -08001005 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001006 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001007 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001008 return;
1009 }
1010
1011 synchronized (mListeners) {
1012 for (int i = mListeners.size() -1; i >= 0; i--) {
1013 MountServiceBinderListener bl = mListeners.get(i);
1014 try {
San Mehatb1043402010-02-05 08:26:50 -08001015 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001016 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001017 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001018 mListeners.remove(i);
1019 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001020 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001021 }
1022 }
1023 }
1024
San Mehat207e5382010-02-04 20:46:54 -08001025 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001026 sendUmsIntent(avail);
1027 } else {
1028 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001029 }
San Mehat2fe718a2010-03-11 12:01:49 -08001030
1031 final String path = Environment.getExternalStorageDirectory().getPath();
1032 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1033 /*
1034 * USB mass storage disconnected while enabled
1035 */
1036 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001037 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001038 public void run() {
1039 try {
1040 int rc;
San Mehata5078592010-03-25 09:36:54 -07001041 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001042 doShareUnshareVolume(path, "ums", false);
1043 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001044 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001045 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1046 path, rc));
1047 }
1048 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001049 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001050 }
1051 }
1052 }.start();
1053 }
San Mehat4270e1e2010-01-29 05:32:19 -08001054 }
1055
San Mehat6a965af22010-02-24 17:47:30 -08001056 private void sendUmsIntent(boolean c) {
1057 mContext.sendBroadcast(
1058 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1059 }
1060
San Mehat207e5382010-02-04 20:46:54 -08001061 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001062 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1063 throw new SecurityException(String.format("Requires %s permission", perm));
1064 }
1065 }
1066
1067 /**
San Mehat207e5382010-02-04 20:46:54 -08001068 * Constructs a new MountService instance
1069 *
1070 * @param context Binder context for this service
1071 */
1072 public MountService(Context context) {
1073 mContext = context;
1074
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001075 mExternalStoragePath = Environment.getExternalStorageDirectory().getPath();
Mike Lockwood03559752010-07-19 18:25:03 -04001076 mEmulateExternalStorage = context.getResources().getBoolean(
1077 com.android.internal.R.bool.config_emulateExternalStorage);
1078 if (mEmulateExternalStorage) {
1079 Slog.d(TAG, "using emulated external storage");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001080 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
Mike Lockwood03559752010-07-19 18:25:03 -04001081 }
1082
San Mehat207e5382010-02-04 20:46:54 -08001083 // XXX: This will go away soon in favor of IMountServiceObserver
1084 mPms = (PackageManagerService) ServiceManager.getService("package");
1085
1086 mContext.registerReceiver(mBroadcastReceiver,
1087 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1088
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001089 mHandlerThread = new HandlerThread("MountService");
1090 mHandlerThread.start();
1091 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1092
Kenny Roota02b8b02010-08-05 16:14:17 -07001093 // Add OBB Action Handler to MountService thread.
1094 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1095
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001096 /*
1097 * Vold does not run in the simulator, so pretend the connector thread
1098 * ran and did its thing.
1099 */
1100 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1101 mReady = true;
1102 mUmsEnabling = true;
1103 return;
1104 }
1105
Kenny Root305bcbf2010-09-03 07:56:38 -07001106 /*
1107 * Create the connection to vold with a maximum queue of twice the
1108 * amount of containers we'd ever expect to have. This keeps an
1109 * "asec list" from blocking a thread repeatedly.
1110 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001111 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001112 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001113 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001114 thread.start();
1115 }
1116
1117 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001118 * Exposed API calls below here
1119 */
1120
1121 public void registerListener(IMountServiceListener listener) {
1122 synchronized (mListeners) {
1123 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1124 try {
1125 listener.asBinder().linkToDeath(bl, 0);
1126 mListeners.add(bl);
1127 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001128 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001129 }
1130 }
1131 }
1132
1133 public void unregisterListener(IMountServiceListener listener) {
1134 synchronized (mListeners) {
1135 for(MountServiceBinderListener bl : mListeners) {
1136 if (bl.mListener == listener) {
1137 mListeners.remove(mListeners.indexOf(bl));
1138 return;
1139 }
1140 }
1141 }
1142 }
1143
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001144 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001145 validatePermission(android.Manifest.permission.SHUTDOWN);
1146
San Mehata5078592010-03-25 09:36:54 -07001147 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001148 synchronized (mVolumeStates) {
1149 for (String path : mVolumeStates.keySet()) {
1150 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001151
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001152 if (state.equals(Environment.MEDIA_SHARED)) {
1153 /*
1154 * If the media is currently shared, unshare it.
1155 * XXX: This is still dangerous!. We should not
1156 * be rebooting at *all* if UMS is enabled, since
1157 * the UMS host could have dirty FAT cache entries
1158 * yet to flush.
1159 */
1160 setUsbMassStorageEnabled(false);
1161 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1162 /*
1163 * If the media is being checked, then we need to wait for
1164 * it to complete before being able to proceed.
1165 */
1166 // XXX: @hackbod - Should we disable the ANR timer here?
1167 int retries = 30;
1168 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1169 try {
1170 Thread.sleep(1000);
1171 } catch (InterruptedException iex) {
1172 Slog.e(TAG, "Interrupted while waiting for media", iex);
1173 break;
1174 }
1175 state = Environment.getExternalStorageState();
1176 }
1177 if (retries == 0) {
1178 Slog.e(TAG, "Timed out waiting for media to check");
1179 }
San Mehat91c77612010-01-07 10:39:41 -08001180 }
San Mehat91c77612010-01-07 10:39:41 -08001181
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001182 if (state.equals(Environment.MEDIA_MOUNTED)) {
1183 // Post a unmount message.
1184 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1185 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1186 } else if (observer != null) {
1187 /*
1188 * Observer is waiting for onShutDownComplete when we are done.
1189 * Since nothing will be done send notification directly so shutdown
1190 * sequence can continue.
1191 */
1192 try {
1193 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1194 } catch (RemoteException e) {
1195 Slog.w(TAG, "RemoteException when shutting down");
1196 }
1197 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001198 }
San Mehat4270e1e2010-01-29 05:32:19 -08001199 }
1200 }
1201
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001202 private boolean getUmsEnabling() {
1203 synchronized (mListeners) {
1204 return mUmsEnabling;
1205 }
1206 }
1207
1208 private void setUmsEnabling(boolean enable) {
1209 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001210 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001211 }
1212 }
1213
San Mehatb1043402010-02-05 08:26:50 -08001214 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001215 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001216
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001217 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001218 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001219 }
San Mehatb1043402010-02-05 08:26:50 -08001220 return doGetShareMethodAvailable("ums");
1221 }
1222
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001223 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001224 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001225 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001226
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001227 // TODO: Add support for multiple share methods
1228
1229 /*
1230 * If the volume is mounted and we're enabling then unmount it
1231 */
1232 String path = Environment.getExternalStorageDirectory().getPath();
1233 String vs = getVolumeState(path);
1234 String method = "ums";
1235 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1236 // Override for isUsbMassStorageEnabled()
1237 setUmsEnabling(enable);
1238 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1239 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1240 // Clear override
1241 setUmsEnabling(false);
1242 }
1243 /*
1244 * If we disabled UMS then mount the volume
1245 */
1246 if (!enable) {
1247 doShareUnshareVolume(path, method, enable);
1248 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001249 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001250 " after disabling share method " + method);
1251 /*
1252 * Even though the mount failed, the unshare didn't so don't indicate an error.
1253 * The mountVolume() call will have set the storage state and sent the necessary
1254 * broadcasts.
1255 */
1256 }
1257 }
San Mehatb1043402010-02-05 08:26:50 -08001258 }
1259
1260 public boolean isUsbMassStorageEnabled() {
1261 waitForReady();
1262 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001264
San Mehat7fd0fee2009-12-17 07:12:23 -08001265 /**
1266 * @return state of the volume at the specified mount point
1267 */
San Mehat4270e1e2010-01-29 05:32:19 -08001268 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001269 synchronized (mVolumeStates) {
1270 String state = mVolumeStates.get(mountPoint);
1271 if (state == null) {
1272 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1273 throw new IllegalArgumentException();
1274 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001275
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001276 return state;
1277 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001278 }
1279
Kenny Roote1ff2142010-10-12 11:20:01 -07001280 public boolean isExternalStorageEmulated() {
1281 return mEmulateExternalStorage;
1282 }
1283
San Mehat4270e1e2010-01-29 05:32:19 -08001284 public int mountVolume(String path) {
1285 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001286
San Mehat207e5382010-02-04 20:46:54 -08001287 waitForReady();
1288 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
1290
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001291 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001292 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001293 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001295 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001296 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001297 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1298 Environment.MEDIA_REMOVED.equals(volState) ||
1299 Environment.MEDIA_SHARED.equals(volState) ||
1300 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1301 // Media already unmounted or cannot be unmounted.
1302 // TODO return valid return code when adding observer call back.
1303 return;
1304 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001305 UnmountCallBack ucb = new UnmountCallBack(path, force);
1306 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308
San Mehat4270e1e2010-01-29 05:32:19 -08001309 public int formatVolume(String path) {
1310 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001311 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001312
San Mehat207e5382010-02-04 20:46:54 -08001313 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315
San Mehatc1b4ce92010-02-16 17:13:03 -08001316 public int []getStorageUsers(String path) {
1317 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1318 waitForReady();
1319 try {
1320 String[] r = mConnector.doListCommand(
1321 String.format("storage users %s", path),
1322 VoldResponseCode.StorageUsersListResult);
1323 // FMT: <pid> <process name>
1324 int[] data = new int[r.length];
1325 for (int i = 0; i < r.length; i++) {
1326 String []tok = r[i].split(" ");
1327 try {
1328 data[i] = Integer.parseInt(tok[0]);
1329 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001330 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001331 return new int[0];
1332 }
1333 }
1334 return data;
1335 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001336 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001337 return new int[0];
1338 }
1339 }
1340
San Mehatb1043402010-02-05 08:26:50 -08001341 private void warnOnNotMounted() {
1342 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001343 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001344 }
1345 }
1346
San Mehat4270e1e2010-01-29 05:32:19 -08001347 public String[] getSecureContainerList() {
1348 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001349 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001350 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001351
San Mehat4270e1e2010-01-29 05:32:19 -08001352 try {
1353 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1354 } catch (NativeDaemonConnectorException e) {
1355 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 }
San Mehat36972292010-01-06 11:06:32 -08001358
San Mehat4270e1e2010-01-29 05:32:19 -08001359 public int createSecureContainer(String id, int sizeMb, String fstype,
1360 String key, int ownerUid) {
1361 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001362 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001363 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001364
San Mehatb1043402010-02-05 08:26:50 -08001365 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001366 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1367 try {
1368 mConnector.doCommand(cmd);
1369 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001370 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001371 }
San Mehata181b212010-02-11 06:50:20 -08001372
1373 if (rc == StorageResultCode.OperationSucceeded) {
1374 synchronized (mAsecMountSet) {
1375 mAsecMountSet.add(id);
1376 }
1377 }
San Mehat4270e1e2010-01-29 05:32:19 -08001378 return rc;
San Mehat36972292010-01-06 11:06:32 -08001379 }
1380
San Mehat4270e1e2010-01-29 05:32:19 -08001381 public int finalizeSecureContainer(String id) {
1382 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001383 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001384
San Mehatb1043402010-02-05 08:26:50 -08001385 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001386 try {
1387 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001388 /*
1389 * Finalization does a remount, so no need
1390 * to update mAsecMountSet
1391 */
San Mehat4270e1e2010-01-29 05:32:19 -08001392 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001393 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001394 }
San Mehat4270e1e2010-01-29 05:32:19 -08001395 return rc;
San Mehat36972292010-01-06 11:06:32 -08001396 }
1397
San Mehatd9709982010-02-18 11:43:03 -08001398 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001399 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001400 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001401 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001402
Kenny Rootaa485402010-09-14 14:49:41 -07001403 /*
1404 * Force a GC to make sure AssetManagers in other threads of the
1405 * system_server are cleaned up. We have to do this since AssetManager
1406 * instances are kept as a WeakReference and it's possible we have files
1407 * open on the external storage.
1408 */
1409 Runtime.getRuntime().gc();
1410
San Mehatb1043402010-02-05 08:26:50 -08001411 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001412 try {
San Mehatd9709982010-02-18 11:43:03 -08001413 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001414 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001415 int code = e.getCode();
1416 if (code == VoldResponseCode.OpFailedStorageBusy) {
1417 rc = StorageResultCode.OperationFailedStorageBusy;
1418 } else {
1419 rc = StorageResultCode.OperationFailedInternalError;
1420 }
San Mehat02735bc2010-01-26 15:18:08 -08001421 }
San Mehata181b212010-02-11 06:50:20 -08001422
1423 if (rc == StorageResultCode.OperationSucceeded) {
1424 synchronized (mAsecMountSet) {
1425 if (mAsecMountSet.contains(id)) {
1426 mAsecMountSet.remove(id);
1427 }
1428 }
1429 }
1430
San Mehat4270e1e2010-01-29 05:32:19 -08001431 return rc;
San Mehat36972292010-01-06 11:06:32 -08001432 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001433
San Mehat4270e1e2010-01-29 05:32:19 -08001434 public int mountSecureContainer(String id, String key, int ownerUid) {
1435 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001436 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001437 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001438
San Mehata181b212010-02-11 06:50:20 -08001439 synchronized (mAsecMountSet) {
1440 if (mAsecMountSet.contains(id)) {
1441 return StorageResultCode.OperationFailedStorageMounted;
1442 }
1443 }
1444
San Mehatb1043402010-02-05 08:26:50 -08001445 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001446 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1447 try {
1448 mConnector.doCommand(cmd);
1449 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001450 int code = e.getCode();
1451 if (code != VoldResponseCode.OpFailedStorageBusy) {
1452 rc = StorageResultCode.OperationFailedInternalError;
1453 }
San Mehat02735bc2010-01-26 15:18:08 -08001454 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001455
1456 if (rc == StorageResultCode.OperationSucceeded) {
1457 synchronized (mAsecMountSet) {
1458 mAsecMountSet.add(id);
1459 }
1460 }
San Mehat4270e1e2010-01-29 05:32:19 -08001461 return rc;
San Mehat36972292010-01-06 11:06:32 -08001462 }
1463
San Mehatd9709982010-02-18 11:43:03 -08001464 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001465 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001466 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001467 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001468
San Mehat6cdd9c02010-02-09 14:45:20 -08001469 synchronized (mAsecMountSet) {
1470 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001471 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001472 }
1473 }
1474
Kenny Rootaa485402010-09-14 14:49:41 -07001475 /*
1476 * Force a GC to make sure AssetManagers in other threads of the
1477 * system_server are cleaned up. We have to do this since AssetManager
1478 * instances are kept as a WeakReference and it's possible we have files
1479 * open on the external storage.
1480 */
1481 Runtime.getRuntime().gc();
1482
San Mehatb1043402010-02-05 08:26:50 -08001483 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001484 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001485 try {
1486 mConnector.doCommand(cmd);
1487 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001488 int code = e.getCode();
1489 if (code == VoldResponseCode.OpFailedStorageBusy) {
1490 rc = StorageResultCode.OperationFailedStorageBusy;
1491 } else {
1492 rc = StorageResultCode.OperationFailedInternalError;
1493 }
San Mehat02735bc2010-01-26 15:18:08 -08001494 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001495
1496 if (rc == StorageResultCode.OperationSucceeded) {
1497 synchronized (mAsecMountSet) {
1498 mAsecMountSet.remove(id);
1499 }
1500 }
San Mehat4270e1e2010-01-29 05:32:19 -08001501 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001502 }
1503
San Mehat6cdd9c02010-02-09 14:45:20 -08001504 public boolean isSecureContainerMounted(String id) {
1505 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1506 waitForReady();
1507 warnOnNotMounted();
1508
1509 synchronized (mAsecMountSet) {
1510 return mAsecMountSet.contains(id);
1511 }
1512 }
1513
San Mehat4270e1e2010-01-29 05:32:19 -08001514 public int renameSecureContainer(String oldId, String newId) {
1515 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001516 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001517 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001518
San Mehata181b212010-02-11 06:50:20 -08001519 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001520 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001521 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001522 * changed while active, we must ensure both ids are not currently mounted.
1523 */
1524 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001525 return StorageResultCode.OperationFailedStorageMounted;
1526 }
1527 }
1528
San Mehatb1043402010-02-05 08:26:50 -08001529 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001530 String cmd = String.format("asec rename %s %s", oldId, newId);
1531 try {
1532 mConnector.doCommand(cmd);
1533 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001534 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001535 }
San Mehata181b212010-02-11 06:50:20 -08001536
San Mehat4270e1e2010-01-29 05:32:19 -08001537 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001538 }
1539
San Mehat4270e1e2010-01-29 05:32:19 -08001540 public String getSecureContainerPath(String id) {
1541 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001542 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001543 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001544
San Mehat2d66cef2010-03-23 11:12:52 -07001545 try {
1546 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1547 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001548 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001549 if (code != VoldResponseCode.AsecPathResult) {
1550 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1551 }
1552 return tok[1];
1553 } catch (NativeDaemonConnectorException e) {
1554 int code = e.getCode();
1555 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001556 Slog.i(TAG, String.format("Container '%s' not found", id));
1557 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001558 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001559 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001560 }
1561 }
San Mehat22dd86e2010-01-12 12:21:18 -08001562 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001563
1564 public void finishMediaUpdate() {
1565 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1566 }
Kenny Root02c87302010-07-01 08:10:18 -07001567
Kenny Roota02b8b02010-08-05 16:14:17 -07001568 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1569 if (callerUid == android.os.Process.SYSTEM_UID) {
1570 return true;
1571 }
1572
Kenny Root02c87302010-07-01 08:10:18 -07001573 if (packageName == null) {
1574 return false;
1575 }
1576
1577 final int packageUid = mPms.getPackageUid(packageName);
1578
1579 if (DEBUG_OBB) {
1580 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1581 packageUid + ", callerUid = " + callerUid);
1582 }
1583
1584 return callerUid == packageUid;
1585 }
1586
1587 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001588 if (filename == null) {
1589 throw new IllegalArgumentException("filename cannot be null");
1590 }
1591
Kenny Root02c87302010-07-01 08:10:18 -07001592 waitForReady();
1593 warnOnNotMounted();
1594
Kenny Root02c87302010-07-01 08:10:18 -07001595 try {
1596 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1597 String []tok = rsp.get(0).split(" ");
1598 int code = Integer.parseInt(tok[0]);
1599 if (code != VoldResponseCode.AsecPathResult) {
1600 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1601 }
1602 return tok[1];
1603 } catch (NativeDaemonConnectorException e) {
1604 int code = e.getCode();
1605 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001606 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001607 } else {
1608 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1609 }
1610 }
1611 }
1612
1613 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001614 if (filename == null) {
1615 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001616 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001617
1618 synchronized (mObbMounts) {
1619 return mObbPathToStateMap.containsKey(filename);
1620 }
Kenny Root02c87302010-07-01 08:10:18 -07001621 }
1622
Kenny Rootaf9d6672010-10-08 09:21:39 -07001623 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001624 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001625 if (filename == null) {
1626 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001627 }
1628
1629 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001630 throw new IllegalArgumentException("token cannot be null");
1631 }
1632
Kenny Rootaf9d6672010-10-08 09:21:39 -07001633 final int callerUid = Binder.getCallingUid();
1634 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1635 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001636 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1637
1638 if (DEBUG_OBB)
1639 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001640 }
1641
Kenny Rootaf9d6672010-10-08 09:21:39 -07001642 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1643 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001644 if (filename == null) {
1645 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001646 }
1647
Kenny Rootaf9d6672010-10-08 09:21:39 -07001648 final int callerUid = Binder.getCallingUid();
1649 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1650 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001651 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001652
Kenny Roota02b8b02010-08-05 16:14:17 -07001653 if (DEBUG_OBB)
1654 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1655 }
1656
Jason parks5af0b912010-11-29 09:05:25 -06001657 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001658 if (TextUtils.isEmpty(password)) {
1659 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001660 }
1661
Jason parks8888c592011-01-20 22:46:41 -06001662 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1663 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001664
1665 waitForReady();
1666
1667 if (DEBUG_EVENTS) {
1668 Slog.i(TAG, "decrypting storage...");
1669 }
1670
1671 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001672 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001673 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001674
Jason parksf7b3cd42011-01-27 09:28:25 -06001675 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001676 return -1;
1677 }
1678
Jason parksf7b3cd42011-01-27 09:28:25 -06001679 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001680
1681 if (code == 0) {
1682 // Decrypt was successful. Post a delayed message before restarting in order
1683 // to let the UI to clear itself
1684 mHandler.postDelayed(new Runnable() {
1685 public void run() {
1686 mConnector.doCommand(String.format("cryptfs restart"));
1687 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001688 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001689 }
1690
1691 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001692 } catch (NativeDaemonConnectorException e) {
1693 // Decryption failed
1694 return e.getCode();
1695 }
Jason parks5af0b912010-11-29 09:05:25 -06001696 }
1697
Jason parks56aa5322011-01-07 09:01:15 -06001698 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001699 if (TextUtils.isEmpty(password)) {
1700 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001701 }
1702
Jason parks8888c592011-01-20 22:46:41 -06001703 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1704 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001705
1706 waitForReady();
1707
1708 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001709 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001710 }
1711
1712 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001713 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001714 } catch (NativeDaemonConnectorException e) {
1715 // Encryption failed
1716 return e.getCode();
1717 }
1718
1719 return 0;
1720 }
1721
Jason parksf7b3cd42011-01-27 09:28:25 -06001722 public int changeEncryptionPassword(String password) {
1723 if (TextUtils.isEmpty(password)) {
1724 throw new IllegalArgumentException("password cannot be empty");
1725 }
1726
1727 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1728 "no permission to access the crypt keeper");
1729
1730 waitForReady();
1731
1732 if (DEBUG_EVENTS) {
1733 Slog.i(TAG, "changing encryption password...");
1734 }
1735
1736 try {
1737 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1738
1739 String[] tokens = response.get(0).split(" ");
1740
1741 if (tokens == null || tokens.length != 2) {
1742 return -1;
1743 }
1744
1745 return Integer.parseInt(tokens[1]);
1746 } catch (NativeDaemonConnectorException e) {
1747 // Encryption failed
1748 return e.getCode();
1749 }
1750 }
1751
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001752 public String[] getVolumeList() {
1753 synchronized(mVolumeStates) {
1754 Set<String> volumes = mVolumeStates.keySet();
1755 String[] result = new String[volumes.size()];
1756 int i = 0;
1757 for (String volume : volumes) {
1758 result[i++] = volume;
1759 }
1760 return result;
1761 }
1762 }
1763
Kenny Rootaf9d6672010-10-08 09:21:39 -07001764 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1765 final IBinder binder = obbState.getBinder();
1766 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001767
Kenny Rootaf9d6672010-10-08 09:21:39 -07001768 if (obbStates == null) {
1769 obbStates = new ArrayList<ObbState>();
1770 mObbMounts.put(binder, obbStates);
1771 } else {
1772 for (final ObbState o : obbStates) {
1773 if (o.filename.equals(obbState.filename)) {
1774 throw new IllegalStateException("Attempt to add ObbState twice. "
1775 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001776 }
1777 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001778 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001779
1780 obbStates.add(obbState);
1781 try {
1782 obbState.link();
1783 } catch (RemoteException e) {
1784 /*
1785 * The binder died before we could link it, so clean up our state
1786 * and return failure.
1787 */
1788 obbStates.remove(obbState);
1789 if (obbStates.isEmpty()) {
1790 mObbMounts.remove(binder);
1791 }
1792
1793 // Rethrow the error so mountObb can get it
1794 throw e;
1795 }
1796
1797 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001798 }
1799
Kenny Rootaf9d6672010-10-08 09:21:39 -07001800 private void removeObbStateLocked(ObbState obbState) {
1801 final IBinder binder = obbState.getBinder();
1802 final List<ObbState> obbStates = mObbMounts.get(binder);
1803 if (obbStates != null) {
1804 if (obbStates.remove(obbState)) {
1805 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001806 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001807 if (obbStates.isEmpty()) {
1808 mObbMounts.remove(binder);
1809 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001810 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001811
Kenny Rootaf9d6672010-10-08 09:21:39 -07001812 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001813 }
1814
Kenny Roota02b8b02010-08-05 16:14:17 -07001815 private class ObbActionHandler extends Handler {
1816 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001817 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001818
1819 ObbActionHandler(Looper l) {
1820 super(l);
1821 }
1822
1823 @Override
1824 public void handleMessage(Message msg) {
1825 switch (msg.what) {
1826 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001827 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001828
1829 if (DEBUG_OBB)
1830 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1831
1832 // If a bind was already initiated we don't really
1833 // need to do anything. The pending install
1834 // will be processed later on.
1835 if (!mBound) {
1836 // If this is the only one pending we might
1837 // have to bind to the service again.
1838 if (!connectToService()) {
1839 Slog.e(TAG, "Failed to bind to media container service");
1840 action.handleError();
1841 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001842 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001843 }
Kenny Root735de3b2010-09-30 14:11:39 -07001844
Kenny Root735de3b2010-09-30 14:11:39 -07001845 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001846 break;
1847 }
1848 case OBB_MCS_BOUND: {
1849 if (DEBUG_OBB)
1850 Slog.i(TAG, "OBB_MCS_BOUND");
1851 if (msg.obj != null) {
1852 mContainerService = (IMediaContainerService) msg.obj;
1853 }
1854 if (mContainerService == null) {
1855 // Something seriously wrong. Bail out
1856 Slog.e(TAG, "Cannot bind to media container service");
1857 for (ObbAction action : mActions) {
1858 // Indicate service bind error
1859 action.handleError();
1860 }
1861 mActions.clear();
1862 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001863 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001864 if (action != null) {
1865 action.execute(this);
1866 }
1867 } else {
1868 // Should never happen ideally.
1869 Slog.w(TAG, "Empty queue");
1870 }
1871 break;
1872 }
1873 case OBB_MCS_RECONNECT: {
1874 if (DEBUG_OBB)
1875 Slog.i(TAG, "OBB_MCS_RECONNECT");
1876 if (mActions.size() > 0) {
1877 if (mBound) {
1878 disconnectService();
1879 }
1880 if (!connectToService()) {
1881 Slog.e(TAG, "Failed to bind to media container service");
1882 for (ObbAction action : mActions) {
1883 // Indicate service bind error
1884 action.handleError();
1885 }
1886 mActions.clear();
1887 }
1888 }
1889 break;
1890 }
1891 case OBB_MCS_UNBIND: {
1892 if (DEBUG_OBB)
1893 Slog.i(TAG, "OBB_MCS_UNBIND");
1894
1895 // Delete pending install
1896 if (mActions.size() > 0) {
1897 mActions.remove(0);
1898 }
1899 if (mActions.size() == 0) {
1900 if (mBound) {
1901 disconnectService();
1902 }
1903 } else {
1904 // There are more pending requests in queue.
1905 // Just post MCS_BOUND message to trigger processing
1906 // of next pending install.
1907 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1908 }
1909 break;
1910 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001911 case OBB_FLUSH_MOUNT_STATE: {
1912 final String path = (String) msg.obj;
1913
1914 if (DEBUG_OBB)
1915 Slog.i(TAG, "Flushing all OBB state for path " + path);
1916
1917 synchronized (mObbMounts) {
1918 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1919
1920 final Iterator<Entry<String, ObbState>> i =
1921 mObbPathToStateMap.entrySet().iterator();
1922 while (i.hasNext()) {
1923 final Entry<String, ObbState> obbEntry = i.next();
1924
1925 /*
1926 * If this entry's source file is in the volume path
1927 * that got unmounted, remove it because it's no
1928 * longer valid.
1929 */
1930 if (obbEntry.getKey().startsWith(path)) {
1931 obbStatesToRemove.add(obbEntry.getValue());
1932 }
1933 }
1934
1935 for (final ObbState obbState : obbStatesToRemove) {
1936 if (DEBUG_OBB)
1937 Slog.i(TAG, "Removing state for " + obbState.filename);
1938
1939 removeObbStateLocked(obbState);
1940
1941 try {
1942 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1943 OnObbStateChangeListener.UNMOUNTED);
1944 } catch (RemoteException e) {
1945 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1946 + obbState.filename);
1947 }
1948 }
1949 }
1950 break;
1951 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001952 }
1953 }
1954
1955 private boolean connectToService() {
1956 if (DEBUG_OBB)
1957 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1958
1959 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1960 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1961 mBound = true;
1962 return true;
1963 }
1964 return false;
1965 }
1966
1967 private void disconnectService() {
1968 mContainerService = null;
1969 mBound = false;
1970 mContext.unbindService(mDefContainerConn);
1971 }
1972 }
1973
1974 abstract class ObbAction {
1975 private static final int MAX_RETRIES = 3;
1976 private int mRetries;
1977
1978 ObbState mObbState;
1979
1980 ObbAction(ObbState obbState) {
1981 mObbState = obbState;
1982 }
1983
1984 public void execute(ObbActionHandler handler) {
1985 try {
1986 if (DEBUG_OBB)
1987 Slog.i(TAG, "Starting to execute action: " + this.toString());
1988 mRetries++;
1989 if (mRetries > MAX_RETRIES) {
1990 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001991 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001992 handleError();
1993 return;
1994 } else {
1995 handleExecute();
1996 if (DEBUG_OBB)
1997 Slog.i(TAG, "Posting install MCS_UNBIND");
1998 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1999 }
2000 } catch (RemoteException e) {
2001 if (DEBUG_OBB)
2002 Slog.i(TAG, "Posting install MCS_RECONNECT");
2003 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2004 } catch (Exception e) {
2005 if (DEBUG_OBB)
2006 Slog.d(TAG, "Error handling OBB action", e);
2007 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002008 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002009 }
2010 }
2011
Kenny Root05105f72010-09-22 17:29:43 -07002012 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002013 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002014
2015 protected ObbInfo getObbInfo() throws IOException {
2016 ObbInfo obbInfo;
2017 try {
2018 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2019 } catch (RemoteException e) {
2020 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2021 + mObbState.filename);
2022 obbInfo = null;
2023 }
2024 if (obbInfo == null) {
2025 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2026 }
2027 return obbInfo;
2028 }
2029
Kenny Rootaf9d6672010-10-08 09:21:39 -07002030 protected void sendNewStatusOrIgnore(int status) {
2031 if (mObbState == null || mObbState.token == null) {
2032 return;
2033 }
2034
Kenny Root38cf8862010-09-26 14:18:51 -07002035 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002036 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002037 } catch (RemoteException e) {
2038 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2039 }
2040 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002041 }
2042
2043 class MountObbAction extends ObbAction {
2044 private String mKey;
2045
2046 MountObbAction(ObbState obbState, String key) {
2047 super(obbState);
2048 mKey = key;
2049 }
2050
Jason parks5af0b912010-11-29 09:05:25 -06002051 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002052 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002053 waitForReady();
2054 warnOnNotMounted();
2055
Kenny Root38cf8862010-09-26 14:18:51 -07002056 final ObbInfo obbInfo = getObbInfo();
2057
Kenny Roota02b8b02010-08-05 16:14:17 -07002058 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002059 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2060 + " which is owned by " + obbInfo.packageName);
2061 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2062 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002063 }
2064
Kenny Rootaf9d6672010-10-08 09:21:39 -07002065 final boolean isMounted;
2066 synchronized (mObbMounts) {
2067 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2068 }
2069 if (isMounted) {
2070 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2071 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2072 return;
2073 }
2074
2075 /*
2076 * The filename passed in might not be the canonical name, so just
2077 * set the filename to the canonicalized version.
2078 */
2079 mObbState.filename = obbInfo.filename;
2080
2081 final String hashedKey;
2082 if (mKey == null) {
2083 hashedKey = "none";
2084 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002085 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002086 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2087
2088 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2089 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2090 SecretKey key = factory.generateSecret(ks);
2091 BigInteger bi = new BigInteger(key.getEncoded());
2092 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002093 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002094 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2095 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2096 return;
2097 } catch (InvalidKeySpecException e) {
2098 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2099 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002100 return;
2101 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002102 }
Kenny Root38cf8862010-09-26 14:18:51 -07002103
Kenny Rootaf9d6672010-10-08 09:21:39 -07002104 int rc = StorageResultCode.OperationSucceeded;
2105 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2106 mObbState.callerUid);
2107 try {
2108 mConnector.doCommand(cmd);
2109 } catch (NativeDaemonConnectorException e) {
2110 int code = e.getCode();
2111 if (code != VoldResponseCode.OpFailedStorageBusy) {
2112 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002113 }
2114 }
2115
Kenny Rootaf9d6672010-10-08 09:21:39 -07002116 if (rc == StorageResultCode.OperationSucceeded) {
2117 if (DEBUG_OBB)
2118 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2119
2120 synchronized (mObbMounts) {
2121 addObbStateLocked(mObbState);
2122 }
2123
2124 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002125 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002126 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002127
Kenny Rootaf9d6672010-10-08 09:21:39 -07002128 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002129 }
2130 }
2131
Jason parks5af0b912010-11-29 09:05:25 -06002132 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002133 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002134 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002135 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002136
2137 @Override
2138 public String toString() {
2139 StringBuilder sb = new StringBuilder();
2140 sb.append("MountObbAction{");
2141 sb.append("filename=");
2142 sb.append(mObbState.filename);
2143 sb.append(",callerUid=");
2144 sb.append(mObbState.callerUid);
2145 sb.append(",token=");
2146 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002147 sb.append(",binder=");
2148 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002149 sb.append('}');
2150 return sb.toString();
2151 }
2152 }
2153
2154 class UnmountObbAction extends ObbAction {
2155 private boolean mForceUnmount;
2156
2157 UnmountObbAction(ObbState obbState, boolean force) {
2158 super(obbState);
2159 mForceUnmount = force;
2160 }
2161
Jason parks5af0b912010-11-29 09:05:25 -06002162 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002163 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002164 waitForReady();
2165 warnOnNotMounted();
2166
Kenny Root38cf8862010-09-26 14:18:51 -07002167 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002168
Kenny Rootaf9d6672010-10-08 09:21:39 -07002169 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002170 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002171 obbState = mObbPathToStateMap.get(obbInfo.filename);
2172 }
Kenny Root38cf8862010-09-26 14:18:51 -07002173
Kenny Rootaf9d6672010-10-08 09:21:39 -07002174 if (obbState == null) {
2175 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2176 return;
2177 }
2178
2179 if (obbState.callerUid != mObbState.callerUid) {
2180 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2181 + " (owned by " + obbInfo.packageName + ")");
2182 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2183 return;
2184 }
2185
2186 mObbState.filename = obbInfo.filename;
2187
2188 int rc = StorageResultCode.OperationSucceeded;
2189 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2190 (mForceUnmount ? " force" : ""));
2191 try {
2192 mConnector.doCommand(cmd);
2193 } catch (NativeDaemonConnectorException e) {
2194 int code = e.getCode();
2195 if (code == VoldResponseCode.OpFailedStorageBusy) {
2196 rc = StorageResultCode.OperationFailedStorageBusy;
2197 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2198 // If it's not mounted then we've already won.
2199 rc = StorageResultCode.OperationSucceeded;
2200 } else {
2201 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002202 }
2203 }
2204
Kenny Rootaf9d6672010-10-08 09:21:39 -07002205 if (rc == StorageResultCode.OperationSucceeded) {
2206 synchronized (mObbMounts) {
2207 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002208 }
2209
Kenny Rootaf9d6672010-10-08 09:21:39 -07002210 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002211 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002212 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2213 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002214 }
2215 }
2216
Jason parks5af0b912010-11-29 09:05:25 -06002217 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002218 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002219 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002220 }
2221
2222 @Override
2223 public String toString() {
2224 StringBuilder sb = new StringBuilder();
2225 sb.append("UnmountObbAction{");
2226 sb.append("filename=");
2227 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2228 sb.append(",force=");
2229 sb.append(mForceUnmount);
2230 sb.append(",callerUid=");
2231 sb.append(mObbState.callerUid);
2232 sb.append(",token=");
2233 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002234 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002235 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002236 sb.append('}');
2237 return sb.toString();
2238 }
Kenny Root02c87302010-07-01 08:10:18 -07002239 }
Kenny Root38cf8862010-09-26 14:18:51 -07002240
2241 @Override
2242 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2243 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2244 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2245 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2246 + " without permission " + android.Manifest.permission.DUMP);
2247 return;
2248 }
2249
Kenny Root38cf8862010-09-26 14:18:51 -07002250 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002251 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002252
Kenny Rootaf9d6672010-10-08 09:21:39 -07002253 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2254 while (binders.hasNext()) {
2255 Entry<IBinder, List<ObbState>> e = binders.next();
2256 pw.print(" Key="); pw.println(e.getKey().toString());
2257 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002258 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002259 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002260 }
2261 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002262
2263 pw.println("");
2264 pw.println(" mObbPathToStateMap:");
2265 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2266 while (maps.hasNext()) {
2267 final Entry<String, ObbState> e = maps.next();
2268 pw.print(" "); pw.print(e.getKey());
2269 pw.print(" -> "); pw.println(e.getValue().toString());
2270 }
Kenny Root38cf8862010-09-26 14:18:51 -07002271 }
2272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273}
2274