blob: 6c2f8d1c9cb28acc18f0b56f14a1404a3b30fb57 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020import com.android.server.am.ActivityManagerService;
21
Jason parks8888c592011-01-20 22:46:41 -060022import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070047import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.StorageResultCode;
Jason parksf7b3cd42011-01-27 09:28:25 -060049import android.text.TextUtils;
San Mehata5078592010-03-25 09:36:54 -070050import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070051
Kenny Root38cf8862010-09-26 14:18:51 -070052import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070053import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070054import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070055import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070056import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070057import java.security.spec.InvalidKeySpecException;
58import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080059import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080061import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070062import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070063import java.util.LinkedList;
64import java.util.List;
65import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070066import java.util.Map.Entry;
Mike Lockwoode3b498b2011-03-24 08:12:30 -070067import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Kenny Root3b1abba2010-10-13 15:00:07 -070069import javax.crypto.SecretKey;
70import javax.crypto.SecretKeyFactory;
71import javax.crypto.spec.PBEKeySpec;
72
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073/**
San Mehatb1043402010-02-05 08:26:50 -080074 * MountService implements back-end services for platform storage
75 * management.
76 * @hide - Applications should use android.os.storage.StorageManager
77 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 */
Jason parks5af0b912010-11-29 09:05:25 -060079class MountService extends IMountService.Stub implements INativeDaemonConnectorCallbacks {
80
San Mehatb1043402010-02-05 08:26:50 -080081 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080082 private static final boolean DEBUG_UNMOUNT = false;
83 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080084 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 private static final String TAG = "MountService";
87
Kenny Root305bcbf2010-09-03 07:56:38 -070088 private static final String VOLD_TAG = "VoldConnector";
89
San Mehat4270e1e2010-01-29 05:32:19 -080090 /*
91 * Internal vold volume state constants
92 */
San Mehat7fd0fee2009-12-17 07:12:23 -080093 class VolumeState {
94 public static final int Init = -1;
95 public static final int NoMedia = 0;
96 public static final int Idle = 1;
97 public static final int Pending = 2;
98 public static final int Checking = 3;
99 public static final int Mounted = 4;
100 public static final int Unmounting = 5;
101 public static final int Formatting = 6;
102 public static final int Shared = 7;
103 public static final int SharedMnt = 8;
104 }
105
San Mehat4270e1e2010-01-29 05:32:19 -0800106 /*
107 * Internal vold response code constants
108 */
San Mehat22dd86e2010-01-12 12:21:18 -0800109 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * 100 series - Requestion action was initiated; expect another reply
112 * before proceeding with a new command.
113 */
San Mehat22dd86e2010-01-12 12:21:18 -0800114 public static final int VolumeListResult = 110;
115 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800116 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800117
San Mehat4270e1e2010-01-29 05:32:19 -0800118 /*
119 * 200 series - Requestion action has been successfully completed.
120 */
121 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800122 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800123 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800124
San Mehat4270e1e2010-01-29 05:32:19 -0800125 /*
126 * 400 series - Command was accepted, but the requested action
127 * did not take place.
128 */
129 public static final int OpFailedNoMedia = 401;
130 public static final int OpFailedMediaBlank = 402;
131 public static final int OpFailedMediaCorrupt = 403;
132 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800133 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700134 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800135
136 /*
137 * 600 series - Unsolicited broadcasts.
138 */
San Mehat22dd86e2010-01-12 12:21:18 -0800139 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800140 public static final int ShareAvailabilityChange = 620;
141 public static final int VolumeDiskInserted = 630;
142 public static final int VolumeDiskRemoved = 631;
143 public static final int VolumeBadRemoval = 632;
144 }
145
San Mehat4270e1e2010-01-29 05:32:19 -0800146 private Context mContext;
147 private NativeDaemonConnector mConnector;
Mike Lockwood346a2d72011-03-23 14:52:34 -0400148 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
149 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800150 private PackageManagerService mPms;
151 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800152 // Used as a lock for methods that register/unregister listeners.
153 final private ArrayList<MountServiceBinderListener> mListeners =
154 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800155 private boolean mBooted = false;
156 private boolean mReady = false;
157 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400158 // true if we should fake MEDIA_MOUNTED state for external storage
159 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800160
San Mehat6cdd9c02010-02-09 14:45:20 -0800161 /**
162 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800163 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800164 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800165 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800166
Kenny Root02c87302010-07-01 08:10:18 -0700167 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700168 * The size of the crypto algorithm key in bits for OBB files. Currently
169 * Twofish is used which takes 128-bit keys.
170 */
171 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
172
173 /**
174 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
175 * 1024 is reasonably secure and not too slow.
176 */
177 private static final int PBKDF2_HASH_ROUNDS = 1024;
178
179 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700180 * Mounted OBB tracking information. Used to track the current state of all
181 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700182 */
Kenny Root735de3b2010-09-30 14:11:39 -0700183 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700184 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
185
186 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700187 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700188 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700189 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700190 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700191 this.token = token;
192 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700193 }
194
195 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700196 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700197
198 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700199 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700200
Kenny Rootaf9d6672010-10-08 09:21:39 -0700201 // Token of remote Binder caller
202 final IObbActionListener token;
203
204 // Identifier to pass back to the token
205 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700206
Kenny Root735de3b2010-09-30 14:11:39 -0700207 public IBinder getBinder() {
208 return token.asBinder();
209 }
210
Kenny Roota02b8b02010-08-05 16:14:17 -0700211 @Override
212 public void binderDied() {
213 ObbAction action = new UnmountObbAction(this, true);
214 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700215 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700216
Kenny Root5919ac62010-10-05 09:49:40 -0700217 public void link() throws RemoteException {
218 getBinder().linkToDeath(this, 0);
219 }
220
221 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700222 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700223 }
Kenny Root38cf8862010-09-26 14:18:51 -0700224
225 @Override
226 public String toString() {
227 StringBuilder sb = new StringBuilder("ObbState{");
228 sb.append("filename=");
229 sb.append(filename);
230 sb.append(",token=");
231 sb.append(token.toString());
232 sb.append(",callerUid=");
233 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700234 sb.append('}');
235 return sb.toString();
236 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700237 }
238
239 // OBB Action Handler
240 final private ObbActionHandler mObbActionHandler;
241
242 // OBB action handler messages
243 private static final int OBB_RUN_ACTION = 1;
244 private static final int OBB_MCS_BOUND = 2;
245 private static final int OBB_MCS_UNBIND = 3;
246 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700247 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700248
249 /*
250 * Default Container Service information
251 */
252 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
253 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
254
255 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
256
257 class DefaultContainerConnection implements ServiceConnection {
258 public void onServiceConnected(ComponentName name, IBinder service) {
259 if (DEBUG_OBB)
260 Slog.i(TAG, "onServiceConnected");
261 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
262 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
263 }
264
265 public void onServiceDisconnected(ComponentName name) {
266 if (DEBUG_OBB)
267 Slog.i(TAG, "onServiceDisconnected");
268 }
269 };
270
271 // Used in the ObbActionHandler
272 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700273
274 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800275 private static final int H_UNMOUNT_PM_UPDATE = 1;
276 private static final int H_UNMOUNT_PM_DONE = 2;
277 private static final int H_UNMOUNT_MS = 3;
278 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
279 private static final int MAX_UNMOUNT_RETRIES = 4;
280
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800281 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700282 final String path;
283 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800284 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800285
286 UnmountCallBack(String path, boolean force) {
287 retries = 0;
288 this.path = path;
289 this.force = force;
290 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800291
292 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700293 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800294 doUnmountVolume(path, true);
295 }
296 }
297
298 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700299 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800300
301 UmsEnableCallBack(String path, String method, boolean force) {
302 super(path, force);
303 this.method = method;
304 }
305
306 @Override
307 void handleFinished() {
308 super.handleFinished();
309 doShareUnshareVolume(path, method, true);
310 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800311 }
312
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800313 class ShutdownCallBack extends UnmountCallBack {
314 IMountShutdownObserver observer;
315 ShutdownCallBack(String path, IMountShutdownObserver observer) {
316 super(path, true);
317 this.observer = observer;
318 }
319
320 @Override
321 void handleFinished() {
322 int ret = doUnmountVolume(path, true);
323 if (observer != null) {
324 try {
325 observer.onShutDownComplete(ret);
326 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700327 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800328 }
329 }
330 }
331 }
332
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400333 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800334 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700335 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800336
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400337 MountServiceHandler(Looper l) {
338 super(l);
339 }
340
Jason parks5af0b912010-11-29 09:05:25 -0600341 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800342 public void handleMessage(Message msg) {
343 switch (msg.what) {
344 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700345 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
347 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700348 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800349 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700350 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700351 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700352 mUpdatingStatus = true;
353 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354 }
355 break;
356 }
357 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700358 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700359 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700360 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800361 int size = mForceUnmounts.size();
362 int sizeArr[] = new int[size];
363 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700364 // Kill processes holding references first
365 ActivityManagerService ams = (ActivityManagerService)
366 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800367 for (int i = 0; i < size; i++) {
368 UnmountCallBack ucb = mForceUnmounts.get(i);
369 String path = ucb.path;
370 boolean done = false;
371 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 done = true;
373 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800374 int pids[] = getStorageUsers(path);
375 if (pids == null || pids.length == 0) {
376 done = true;
377 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800378 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800379 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700380 // Confirm if file references have been freed.
381 pids = getStorageUsers(path);
382 if (pids == null || pids.length == 0) {
383 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 }
385 }
386 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700387 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
388 // Retry again
389 Slog.i(TAG, "Retrying to kill storage users again");
390 mHandler.sendMessageDelayed(
391 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
392 ucb.retries++),
393 RETRY_UNMOUNT_DELAY);
394 } else {
395 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
396 Slog.i(TAG, "Failed to unmount media inspite of " +
397 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
398 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800399 sizeArr[sizeArrN++] = i;
400 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
401 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402 }
403 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800404 // Remove already processed elements from list.
405 for (int i = (sizeArrN-1); i >= 0; i--) {
406 mForceUnmounts.remove(sizeArr[i]);
407 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800408 break;
409 }
410 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700411 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800413 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800414 break;
415 }
416 }
417 }
418 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400419 final private HandlerThread mHandlerThread;
420 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421
San Mehat207e5382010-02-04 20:46:54 -0800422 private void waitForReady() {
423 while (mReady == false) {
424 for (int retries = 5; retries > 0; retries--) {
425 if (mReady) {
426 return;
427 }
428 SystemClock.sleep(1000);
429 }
San Mehata5078592010-03-25 09:36:54 -0700430 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800431 }
San Mehat1f6301e2010-01-07 22:40:27 -0800432 }
Kenny Root02c87302010-07-01 08:10:18 -0700433
San Mehat207e5382010-02-04 20:46:54 -0800434 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600435 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800437 String action = intent.getAction();
438
439 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800440 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800441
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800442 /*
443 * In the simulator, we need to broadcast a volume mounted event
444 * to make the media scanner run.
445 */
446 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood0aa5d7b2011-04-05 10:05:47 -0400447 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
448 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800449 return;
450 }
San Mehatfafb0412010-02-18 19:40:04 -0800451 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600452 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800453 public void run() {
454 try {
Mike Lockwood0aa5d7b2011-04-05 10:05:47 -0400455 // it is not safe to call vold with mVolumeStates locked
456 // so we make a copy of the paths and states and process them
457 // outside the lock
458 String[] paths, states;
459 int count;
Mike Lockwood346a2d72011-03-23 14:52:34 -0400460 synchronized (mVolumeStates) {
Mike Lockwood0aa5d7b2011-04-05 10:05:47 -0400461 Set<String> keys = mVolumeStates.keySet();
462 count = keys.size();
463 paths = (String[])keys.toArray(new String[count]);
464 states = new String[count];
465 for (int i = 0; i < count; i++) {
466 states[i] = mVolumeStates.get(paths[i]);
467 }
468 }
San Mehat6a254402010-03-22 10:21:00 -0700469
Mike Lockwood0aa5d7b2011-04-05 10:05:47 -0400470 for (int i = 0; i < count; i++) {
471 String path = paths[i];
472 String state = states[i];
473
474 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
475 int rc = doMountVolume(path);
476 if (rc != StorageResultCode.OperationSucceeded) {
477 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
478 rc));
Mike Lockwood346a2d72011-03-23 14:52:34 -0400479 }
Mike Lockwood0aa5d7b2011-04-05 10:05:47 -0400480 } else if (state.equals(Environment.MEDIA_SHARED)) {
481 /*
482 * Bootstrap UMS enabled state since vold indicates
483 * the volume is shared (runtime restart while ums enabled)
484 */
485 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
486 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800487 }
488 }
San Mehat6a254402010-03-22 10:21:00 -0700489
Mike Lockwood10fbba22011-04-05 10:21:51 -0400490 /* notify external storage has mounted to trigger media scanner */
491 if (mEmulateExternalStorage) {
492 notifyVolumeStateChange(null,
493 Environment.getExternalStorageDirectory().getPath(),
494 VolumeState.NoMedia, VolumeState.Mounted);
495 }
496
San Mehat6a965af22010-02-24 17:47:30 -0800497 /*
San Mehat6a254402010-03-22 10:21:00 -0700498 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800499 * now that we're up.
500 */
501 if (mSendUmsConnectedOnBoot) {
502 sendUmsIntent(true);
503 mSendUmsConnectedOnBoot = false;
504 }
San Mehatfafb0412010-02-18 19:40:04 -0800505 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700506 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800507 }
San Mehat207e5382010-02-04 20:46:54 -0800508 }
San Mehatfafb0412010-02-18 19:40:04 -0800509 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 }
511 }
512 };
513
San Mehat4270e1e2010-01-29 05:32:19 -0800514 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
515 final IMountServiceListener mListener;
516
517 MountServiceBinderListener(IMountServiceListener listener) {
518 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700519
San Mehat91c77612010-01-07 10:39:41 -0800520 }
521
San Mehat4270e1e2010-01-29 05:32:19 -0800522 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700523 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700524 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800525 mListeners.remove(this);
526 mListener.asBinder().unlinkToDeath(this, 0);
527 }
528 }
529 }
530
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800531 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800532 // TODO: Add support for multiple share methods
533 if (!method.equals("ums")) {
534 throw new IllegalArgumentException(String.format("Method %s not supported", method));
535 }
536
San Mehat4270e1e2010-01-29 05:32:19 -0800537 try {
538 mConnector.doCommand(String.format(
539 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
540 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700541 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800542 }
San Mehat4270e1e2010-01-29 05:32:19 -0800543 }
544
San Mehat207e5382010-02-04 20:46:54 -0800545 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood346a2d72011-03-23 14:52:34 -0400546 String oldState;
547 synchronized(mVolumeStates) {
548 oldState = mVolumeStates.put(path, state);
549 }
550 if (state.equals(oldState)) {
551 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
552 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800553 return;
554 }
San Mehatb1043402010-02-05 08:26:50 -0800555
Mike Lockwood346a2d72011-03-23 14:52:34 -0400556 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700557
Mike Lockwood346a2d72011-03-23 14:52:34 -0400558 if (path.equals(mExternalStoragePath)) {
559 // Update state on PackageManager, but only of real events
560 if (!mEmulateExternalStorage) {
561 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
562 mPms.updateExternalMediaStatus(false, false);
563
564 /*
565 * Some OBBs might have been unmounted when this volume was
566 * unmounted, so send a message to the handler to let it know to
567 * remove those from the list of mounted OBBS.
568 */
569 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
570 OBB_FLUSH_MOUNT_STATE, path));
571 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
572 mPms.updateExternalMediaStatus(true, false);
573 }
Mike Lockwood03559752010-07-19 18:25:03 -0400574 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800575 }
San Mehat4270e1e2010-01-29 05:32:19 -0800576 synchronized (mListeners) {
577 for (int i = mListeners.size() -1; i >= 0; i--) {
578 MountServiceBinderListener bl = mListeners.get(i);
579 try {
San Mehatb1043402010-02-05 08:26:50 -0800580 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800581 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700582 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800583 mListeners.remove(i);
584 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700585 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800586 }
587 }
588 }
589 }
590
591 /**
592 *
593 * Callback from NativeDaemonConnector
594 */
595 public void onDaemonConnected() {
596 /*
597 * Since we'll be calling back into the NativeDaemonConnector,
598 * we need to do our work in a new thread.
599 */
600 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600601 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800602 public void run() {
603 /**
604 * Determine media state and UMS detection status
605 */
San Mehat4270e1e2010-01-29 05:32:19 -0800606 try {
607 String[] vols = mConnector.doListCommand(
608 "volume list", VoldResponseCode.VolumeListResult);
609 for (String volstr : vols) {
610 String[] tok = volstr.split(" ");
611 // FMT: <label> <mountpoint> <state>
Mike Lockwood346a2d72011-03-23 14:52:34 -0400612 String path = tok[1];
613 String state = Environment.MEDIA_REMOVED;
614
San Mehat4270e1e2010-01-29 05:32:19 -0800615 int st = Integer.parseInt(tok[2]);
616 if (st == VolumeState.NoMedia) {
617 state = Environment.MEDIA_REMOVED;
618 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800619 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800620 } else if (st == VolumeState.Mounted) {
621 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700622 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800623 } else if (st == VolumeState.Shared) {
624 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700625 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800626 } else {
627 throw new Exception(String.format("Unexpected state %d", st));
628 }
Mike Lockwood346a2d72011-03-23 14:52:34 -0400629
630 if (state != null) {
631 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
632 updatePublicVolumeState(path, state);
633 }
San Mehat4270e1e2010-01-29 05:32:19 -0800634 }
635 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700636 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood346a2d72011-03-23 14:52:34 -0400637 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800638 }
639
640 try {
San Mehat207e5382010-02-04 20:46:54 -0800641 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800642 notifyShareAvailabilityChange("ums", avail);
643 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700644 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800645 }
San Mehat207e5382010-02-04 20:46:54 -0800646 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600647 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800648 * the hounds!
649 */
650 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800651 }
652 }.start();
653 }
654
655 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800656 * Callback from NativeDaemonConnector
657 */
658 public boolean onEvent(int code, String raw, String[] cooked) {
659 Intent in = null;
660
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800661 if (DEBUG_EVENTS) {
662 StringBuilder builder = new StringBuilder();
663 builder.append("onEvent::");
664 builder.append(" raw= " + raw);
665 if (cooked != null) {
666 builder.append(" cooked = " );
667 for (String str : cooked) {
668 builder.append(" " + str);
669 }
670 }
San Mehata5078592010-03-25 09:36:54 -0700671 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800672 }
San Mehat4270e1e2010-01-29 05:32:19 -0800673 if (code == VoldResponseCode.VolumeStateChange) {
674 /*
675 * One of the volumes we're managing has changed state.
676 * Format: "NNN Volume <label> <path> state changed
677 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
678 */
679 notifyVolumeStateChange(
680 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
681 Integer.parseInt(cooked[10]));
682 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
683 // FMT: NNN Share method <method> now <available|unavailable>
684 boolean avail = false;
685 if (cooked[5].equals("available")) {
686 avail = true;
687 }
688 notifyShareAvailabilityChange(cooked[3], avail);
689 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
690 (code == VoldResponseCode.VolumeDiskRemoved) ||
691 (code == VoldResponseCode.VolumeBadRemoval)) {
692 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
693 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
694 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
695 final String label = cooked[2];
696 final String path = cooked[3];
697 int major = -1;
698 int minor = -1;
699
700 try {
701 String devComp = cooked[6].substring(1, cooked[6].length() -1);
702 String[] devTok = devComp.split(":");
703 major = Integer.parseInt(devTok[0]);
704 minor = Integer.parseInt(devTok[1]);
705 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700706 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800707 }
708
San Mehat4270e1e2010-01-29 05:32:19 -0800709 if (code == VoldResponseCode.VolumeDiskInserted) {
710 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600711 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800712 public void run() {
713 try {
714 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800715 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700716 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800717 }
718 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700719 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800720 }
721 }
722 }.start();
723 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
724 /*
725 * This event gets trumped if we're already in BAD_REMOVAL state
726 */
727 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
728 return true;
729 }
730 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700731 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800732 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
733 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
734 mContext.sendBroadcast(in);
735
San Mehata5078592010-03-25 09:36:54 -0700736 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800737 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
738 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
739 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700740 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800741 /* Send the media unmounted event first */
742 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
743 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
744 mContext.sendBroadcast(in);
745
San Mehata5078592010-03-25 09:36:54 -0700746 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800747 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
748 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
749 } else {
San Mehata5078592010-03-25 09:36:54 -0700750 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800751 }
752 } else {
753 return false;
754 }
755
756 if (in != null) {
757 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400758 }
759 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800760 }
761
San Mehat207e5382010-02-04 20:46:54 -0800762 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800763 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700764 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800765
766 Intent in = null;
767
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500768 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700769 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500770 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
771 Uri.parse("file://" + path)));
772 }
773
San Mehat4270e1e2010-01-29 05:32:19 -0800774 if (newState == VolumeState.Init) {
775 } else if (newState == VolumeState.NoMedia) {
776 // NoMedia is handled via Disk Remove events
777 } else if (newState == VolumeState.Idle) {
778 /*
779 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
780 * if we're in the process of enabling UMS
781 */
782 if (!vs.equals(
783 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
784 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800785 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700786 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800787 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
788 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
789 }
790 } else if (newState == VolumeState.Pending) {
791 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700792 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800793 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
794 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
795 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700796 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800797 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800798 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
799 in.putExtra("read-only", false);
800 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800801 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
802 } else if (newState == VolumeState.Formatting) {
803 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700804 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800805 /* Send the media unmounted event first */
806 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
807 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
808 mContext.sendBroadcast(in);
809
San Mehata5078592010-03-25 09:36:54 -0700810 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800811 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
812 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700813 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800814 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700815 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800816 return;
817 } else {
San Mehata5078592010-03-25 09:36:54 -0700818 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800819 }
820
821 if (in != null) {
822 mContext.sendBroadcast(in);
823 }
824 }
825
San Mehat207e5382010-02-04 20:46:54 -0800826 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700827 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700828 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700829 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700830 } catch (NativeDaemonConnectorException ex) {
831 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
832 return false;
833 }
San Mehat207e5382010-02-04 20:46:54 -0800834
835 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700836 String[] tok = line.split(" ");
837 if (tok.length < 3) {
838 Slog.e(TAG, "Malformed response to share status " + method);
839 return false;
840 }
841
San Mehat207e5382010-02-04 20:46:54 -0800842 int code;
843 try {
844 code = Integer.parseInt(tok[0]);
845 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700846 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800847 return false;
848 }
849 if (code == VoldResponseCode.ShareStatusResult) {
850 if (tok[2].equals("available"))
851 return true;
852 return false;
853 } else {
San Mehata5078592010-03-25 09:36:54 -0700854 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800855 return false;
856 }
857 }
San Mehata5078592010-03-25 09:36:54 -0700858 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800859 return false;
860 }
861
862 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800863 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800864
San Mehata5078592010-03-25 09:36:54 -0700865 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800866 try {
867 mConnector.doCommand(String.format("volume mount %s", path));
868 } catch (NativeDaemonConnectorException e) {
869 /*
870 * Mount failed for some reason
871 */
872 Intent in = null;
873 int code = e.getCode();
874 if (code == VoldResponseCode.OpFailedNoMedia) {
875 /*
876 * Attempt to mount but no media inserted
877 */
San Mehatb1043402010-02-05 08:26:50 -0800878 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800879 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700880 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800881 /*
882 * Media is blank or does not contain a supported filesystem
883 */
884 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
885 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800886 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800887 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700888 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800889 /*
890 * Volume consistency check failed
891 */
892 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
893 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800894 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800895 } else {
San Mehatb1043402010-02-05 08:26:50 -0800896 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800897 }
898
899 /*
900 * Send broadcast intent (if required for the failure)
901 */
902 if (in != null) {
903 mContext.sendBroadcast(in);
904 }
905 }
906
907 return rc;
908 }
909
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800910 /*
911 * If force is not set, we do not unmount if there are
912 * processes holding references to the volume about to be unmounted.
913 * If force is set, all the processes holding references need to be
914 * killed via the ActivityManager before actually unmounting the volume.
915 * This might even take a while and might be retried after timed delays
916 * to make sure we dont end up in an instable state and kill some core
917 * processes.
918 */
San Mehatd9709982010-02-18 11:43:03 -0800919 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800920 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800921 return VoldResponseCode.OpFailedVolNotMounted;
922 }
Kenny Rootaa485402010-09-14 14:49:41 -0700923
924 /*
925 * Force a GC to make sure AssetManagers in other threads of the
926 * system_server are cleaned up. We have to do this since AssetManager
927 * instances are kept as a WeakReference and it's possible we have files
928 * open on the external storage.
929 */
930 Runtime.getRuntime().gc();
931
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800932 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700933 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800934 try {
San Mehatd9709982010-02-18 11:43:03 -0800935 mConnector.doCommand(String.format(
936 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700937 // We unmounted the volume. None of the asec containers are available now.
938 synchronized (mAsecMountSet) {
939 mAsecMountSet.clear();
940 }
San Mehatb1043402010-02-05 08:26:50 -0800941 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800942 } catch (NativeDaemonConnectorException e) {
943 // Don't worry about mismatch in PackageManager since the
944 // call back will handle the status changes any way.
945 int code = e.getCode();
946 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800947 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800948 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
949 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800950 } else {
San Mehatb1043402010-02-05 08:26:50 -0800951 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800952 }
953 }
954 }
955
956 private int doFormatVolume(String path) {
957 try {
958 String cmd = String.format("volume format %s", path);
959 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800960 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800961 } catch (NativeDaemonConnectorException e) {
962 int code = e.getCode();
963 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800964 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800965 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800966 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800967 } else {
San Mehatb1043402010-02-05 08:26:50 -0800968 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800969 }
970 }
971 }
972
San Mehatb1043402010-02-05 08:26:50 -0800973 private boolean doGetVolumeShared(String path, String method) {
974 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700975 ArrayList<String> rsp;
976
977 try {
978 rsp = mConnector.doCommand(cmd);
979 } catch (NativeDaemonConnectorException ex) {
980 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
981 return false;
982 }
San Mehatb1043402010-02-05 08:26:50 -0800983
984 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700985 String[] tok = line.split(" ");
986 if (tok.length < 3) {
987 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
988 return false;
989 }
990
San Mehatb1043402010-02-05 08:26:50 -0800991 int code;
992 try {
993 code = Integer.parseInt(tok[0]);
994 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700995 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800996 return false;
997 }
998 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700999 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -08001000 } else {
San Mehata5078592010-03-25 09:36:54 -07001001 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -08001002 return false;
1003 }
1004 }
San Mehata5078592010-03-25 09:36:54 -07001005 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001006 return false;
1007 }
1008
San Mehat207e5382010-02-04 20:46:54 -08001009 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001010 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001011 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001012 return;
1013 }
1014
1015 synchronized (mListeners) {
1016 for (int i = mListeners.size() -1; i >= 0; i--) {
1017 MountServiceBinderListener bl = mListeners.get(i);
1018 try {
San Mehatb1043402010-02-05 08:26:50 -08001019 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001020 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001021 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001022 mListeners.remove(i);
1023 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001024 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001025 }
1026 }
1027 }
1028
San Mehat207e5382010-02-04 20:46:54 -08001029 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001030 sendUmsIntent(avail);
1031 } else {
1032 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001033 }
San Mehat2fe718a2010-03-11 12:01:49 -08001034
1035 final String path = Environment.getExternalStorageDirectory().getPath();
1036 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1037 /*
1038 * USB mass storage disconnected while enabled
1039 */
1040 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001041 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001042 public void run() {
1043 try {
1044 int rc;
San Mehata5078592010-03-25 09:36:54 -07001045 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001046 doShareUnshareVolume(path, "ums", false);
1047 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001048 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001049 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1050 path, rc));
1051 }
1052 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001053 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001054 }
1055 }
1056 }.start();
1057 }
San Mehat4270e1e2010-01-29 05:32:19 -08001058 }
1059
San Mehat6a965af22010-02-24 17:47:30 -08001060 private void sendUmsIntent(boolean c) {
1061 mContext.sendBroadcast(
1062 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1063 }
1064
San Mehat207e5382010-02-04 20:46:54 -08001065 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001066 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1067 throw new SecurityException(String.format("Requires %s permission", perm));
1068 }
1069 }
1070
1071 /**
San Mehat207e5382010-02-04 20:46:54 -08001072 * Constructs a new MountService instance
1073 *
1074 * @param context Binder context for this service
1075 */
1076 public MountService(Context context) {
1077 mContext = context;
1078
Mike Lockwood346a2d72011-03-23 14:52:34 -04001079 mExternalStoragePath = Environment.getExternalStorageDirectory().getPath();
Mike Lockwood03559752010-07-19 18:25:03 -04001080 mEmulateExternalStorage = context.getResources().getBoolean(
1081 com.android.internal.R.bool.config_emulateExternalStorage);
1082 if (mEmulateExternalStorage) {
1083 Slog.d(TAG, "using emulated external storage");
Mike Lockwood346a2d72011-03-23 14:52:34 -04001084 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
Mike Lockwood03559752010-07-19 18:25:03 -04001085 }
1086
San Mehat207e5382010-02-04 20:46:54 -08001087 // XXX: This will go away soon in favor of IMountServiceObserver
1088 mPms = (PackageManagerService) ServiceManager.getService("package");
1089
1090 mContext.registerReceiver(mBroadcastReceiver,
1091 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1092
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001093 mHandlerThread = new HandlerThread("MountService");
1094 mHandlerThread.start();
1095 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1096
Kenny Roota02b8b02010-08-05 16:14:17 -07001097 // Add OBB Action Handler to MountService thread.
1098 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1099
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001100 /*
1101 * Vold does not run in the simulator, so pretend the connector thread
1102 * ran and did its thing.
1103 */
1104 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1105 mReady = true;
1106 mUmsEnabling = true;
1107 return;
1108 }
1109
Kenny Root305bcbf2010-09-03 07:56:38 -07001110 /*
1111 * Create the connection to vold with a maximum queue of twice the
1112 * amount of containers we'd ever expect to have. This keeps an
1113 * "asec list" from blocking a thread repeatedly.
1114 */
1115 mConnector = new NativeDaemonConnector(this, "vold",
1116 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001117 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001118 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001119 thread.start();
1120 }
1121
1122 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001123 * Exposed API calls below here
1124 */
1125
1126 public void registerListener(IMountServiceListener listener) {
1127 synchronized (mListeners) {
1128 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1129 try {
1130 listener.asBinder().linkToDeath(bl, 0);
1131 mListeners.add(bl);
1132 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001133 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001134 }
1135 }
1136 }
1137
1138 public void unregisterListener(IMountServiceListener listener) {
1139 synchronized (mListeners) {
1140 for(MountServiceBinderListener bl : mListeners) {
1141 if (bl.mListener == listener) {
1142 mListeners.remove(mListeners.indexOf(bl));
1143 return;
1144 }
1145 }
1146 }
1147 }
1148
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001149 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001150 validatePermission(android.Manifest.permission.SHUTDOWN);
1151
San Mehata5078592010-03-25 09:36:54 -07001152 Slog.i(TAG, "Shutting down");
Mike Lockwood346a2d72011-03-23 14:52:34 -04001153 synchronized (mVolumeStates) {
1154 for (String path : mVolumeStates.keySet()) {
1155 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001156
Mike Lockwood346a2d72011-03-23 14:52:34 -04001157 if (state.equals(Environment.MEDIA_SHARED)) {
1158 /*
1159 * If the media is currently shared, unshare it.
1160 * XXX: This is still dangerous!. We should not
1161 * be rebooting at *all* if UMS is enabled, since
1162 * the UMS host could have dirty FAT cache entries
1163 * yet to flush.
1164 */
1165 setUsbMassStorageEnabled(false);
1166 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1167 /*
1168 * If the media is being checked, then we need to wait for
1169 * it to complete before being able to proceed.
1170 */
1171 // XXX: @hackbod - Should we disable the ANR timer here?
1172 int retries = 30;
1173 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1174 try {
1175 Thread.sleep(1000);
1176 } catch (InterruptedException iex) {
1177 Slog.e(TAG, "Interrupted while waiting for media", iex);
1178 break;
1179 }
1180 state = Environment.getExternalStorageState();
1181 }
1182 if (retries == 0) {
1183 Slog.e(TAG, "Timed out waiting for media to check");
1184 }
San Mehat91c77612010-01-07 10:39:41 -08001185 }
San Mehat91c77612010-01-07 10:39:41 -08001186
Mike Lockwood346a2d72011-03-23 14:52:34 -04001187 if (state.equals(Environment.MEDIA_MOUNTED)) {
1188 // Post a unmount message.
1189 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1190 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1191 } else if (observer != null) {
1192 /*
1193 * Observer is waiting for onShutDownComplete when we are done.
1194 * Since nothing will be done send notification directly so shutdown
1195 * sequence can continue.
1196 */
1197 try {
1198 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1199 } catch (RemoteException e) {
1200 Slog.w(TAG, "RemoteException when shutting down");
1201 }
1202 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001203 }
San Mehat4270e1e2010-01-29 05:32:19 -08001204 }
1205 }
1206
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001207 private boolean getUmsEnabling() {
1208 synchronized (mListeners) {
1209 return mUmsEnabling;
1210 }
1211 }
1212
1213 private void setUmsEnabling(boolean enable) {
1214 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001215 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001216 }
1217 }
1218
San Mehatb1043402010-02-05 08:26:50 -08001219 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001220 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001221
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001222 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001223 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001224 }
San Mehatb1043402010-02-05 08:26:50 -08001225 return doGetShareMethodAvailable("ums");
1226 }
1227
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001228 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001229 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001230 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001231
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001232 // TODO: Add support for multiple share methods
1233
1234 /*
1235 * If the volume is mounted and we're enabling then unmount it
1236 */
1237 String path = Environment.getExternalStorageDirectory().getPath();
1238 String vs = getVolumeState(path);
1239 String method = "ums";
1240 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1241 // Override for isUsbMassStorageEnabled()
1242 setUmsEnabling(enable);
1243 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1244 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1245 // Clear override
1246 setUmsEnabling(false);
1247 }
1248 /*
1249 * If we disabled UMS then mount the volume
1250 */
1251 if (!enable) {
1252 doShareUnshareVolume(path, method, enable);
1253 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001254 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001255 " after disabling share method " + method);
1256 /*
1257 * Even though the mount failed, the unshare didn't so don't indicate an error.
1258 * The mountVolume() call will have set the storage state and sent the necessary
1259 * broadcasts.
1260 */
1261 }
1262 }
San Mehatb1043402010-02-05 08:26:50 -08001263 }
1264
1265 public boolean isUsbMassStorageEnabled() {
1266 waitForReady();
1267 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001269
San Mehat7fd0fee2009-12-17 07:12:23 -08001270 /**
1271 * @return state of the volume at the specified mount point
1272 */
San Mehat4270e1e2010-01-29 05:32:19 -08001273 public String getVolumeState(String mountPoint) {
Mike Lockwood346a2d72011-03-23 14:52:34 -04001274 synchronized (mVolumeStates) {
1275 String state = mVolumeStates.get(mountPoint);
1276 if (state == null) {
1277 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1278 throw new IllegalArgumentException();
1279 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001280
Mike Lockwood346a2d72011-03-23 14:52:34 -04001281 return state;
1282 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001283 }
1284
Kenny Roote1ff2142010-10-12 11:20:01 -07001285 public boolean isExternalStorageEmulated() {
1286 return mEmulateExternalStorage;
1287 }
1288
San Mehat4270e1e2010-01-29 05:32:19 -08001289 public int mountVolume(String path) {
1290 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001291
San Mehat207e5382010-02-04 20:46:54 -08001292 waitForReady();
1293 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001296 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001297 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001298 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001300 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001301 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001302 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1303 Environment.MEDIA_REMOVED.equals(volState) ||
1304 Environment.MEDIA_SHARED.equals(volState) ||
1305 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1306 // Media already unmounted or cannot be unmounted.
1307 // TODO return valid return code when adding observer call back.
1308 return;
1309 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001310 UnmountCallBack ucb = new UnmountCallBack(path, force);
1311 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
1313
San Mehat4270e1e2010-01-29 05:32:19 -08001314 public int formatVolume(String path) {
1315 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001316 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001317
San Mehat207e5382010-02-04 20:46:54 -08001318 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
San Mehatc1b4ce92010-02-16 17:13:03 -08001321 public int []getStorageUsers(String path) {
1322 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1323 waitForReady();
1324 try {
1325 String[] r = mConnector.doListCommand(
1326 String.format("storage users %s", path),
1327 VoldResponseCode.StorageUsersListResult);
1328 // FMT: <pid> <process name>
1329 int[] data = new int[r.length];
1330 for (int i = 0; i < r.length; i++) {
1331 String []tok = r[i].split(" ");
1332 try {
1333 data[i] = Integer.parseInt(tok[0]);
1334 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001335 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001336 return new int[0];
1337 }
1338 }
1339 return data;
1340 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001341 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001342 return new int[0];
1343 }
1344 }
1345
San Mehatb1043402010-02-05 08:26:50 -08001346 private void warnOnNotMounted() {
1347 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001348 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001349 }
1350 }
1351
San Mehat4270e1e2010-01-29 05:32:19 -08001352 public String[] getSecureContainerList() {
1353 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001354 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001355 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001356
San Mehat4270e1e2010-01-29 05:32:19 -08001357 try {
1358 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1359 } catch (NativeDaemonConnectorException e) {
1360 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362 }
San Mehat36972292010-01-06 11:06:32 -08001363
San Mehat4270e1e2010-01-29 05:32:19 -08001364 public int createSecureContainer(String id, int sizeMb, String fstype,
1365 String key, int ownerUid) {
1366 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001367 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001368 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001369
San Mehatb1043402010-02-05 08:26:50 -08001370 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001371 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1372 try {
1373 mConnector.doCommand(cmd);
1374 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001375 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001376 }
San Mehata181b212010-02-11 06:50:20 -08001377
1378 if (rc == StorageResultCode.OperationSucceeded) {
1379 synchronized (mAsecMountSet) {
1380 mAsecMountSet.add(id);
1381 }
1382 }
San Mehat4270e1e2010-01-29 05:32:19 -08001383 return rc;
San Mehat36972292010-01-06 11:06:32 -08001384 }
1385
San Mehat4270e1e2010-01-29 05:32:19 -08001386 public int finalizeSecureContainer(String id) {
1387 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001388 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001389
San Mehatb1043402010-02-05 08:26:50 -08001390 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001391 try {
1392 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001393 /*
1394 * Finalization does a remount, so no need
1395 * to update mAsecMountSet
1396 */
San Mehat4270e1e2010-01-29 05:32:19 -08001397 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001398 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001399 }
San Mehat4270e1e2010-01-29 05:32:19 -08001400 return rc;
San Mehat36972292010-01-06 11:06:32 -08001401 }
1402
San Mehatd9709982010-02-18 11:43:03 -08001403 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001404 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001405 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001406 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001407
Kenny Rootaa485402010-09-14 14:49:41 -07001408 /*
1409 * Force a GC to make sure AssetManagers in other threads of the
1410 * system_server are cleaned up. We have to do this since AssetManager
1411 * instances are kept as a WeakReference and it's possible we have files
1412 * open on the external storage.
1413 */
1414 Runtime.getRuntime().gc();
1415
San Mehatb1043402010-02-05 08:26:50 -08001416 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001417 try {
San Mehatd9709982010-02-18 11:43:03 -08001418 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001419 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001420 int code = e.getCode();
1421 if (code == VoldResponseCode.OpFailedStorageBusy) {
1422 rc = StorageResultCode.OperationFailedStorageBusy;
1423 } else {
1424 rc = StorageResultCode.OperationFailedInternalError;
1425 }
San Mehat02735bc2010-01-26 15:18:08 -08001426 }
San Mehata181b212010-02-11 06:50:20 -08001427
1428 if (rc == StorageResultCode.OperationSucceeded) {
1429 synchronized (mAsecMountSet) {
1430 if (mAsecMountSet.contains(id)) {
1431 mAsecMountSet.remove(id);
1432 }
1433 }
1434 }
1435
San Mehat4270e1e2010-01-29 05:32:19 -08001436 return rc;
San Mehat36972292010-01-06 11:06:32 -08001437 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001438
San Mehat4270e1e2010-01-29 05:32:19 -08001439 public int mountSecureContainer(String id, String key, int ownerUid) {
1440 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001441 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001442 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001443
San Mehata181b212010-02-11 06:50:20 -08001444 synchronized (mAsecMountSet) {
1445 if (mAsecMountSet.contains(id)) {
1446 return StorageResultCode.OperationFailedStorageMounted;
1447 }
1448 }
1449
San Mehatb1043402010-02-05 08:26:50 -08001450 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001451 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1452 try {
1453 mConnector.doCommand(cmd);
1454 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001455 int code = e.getCode();
1456 if (code != VoldResponseCode.OpFailedStorageBusy) {
1457 rc = StorageResultCode.OperationFailedInternalError;
1458 }
San Mehat02735bc2010-01-26 15:18:08 -08001459 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001460
1461 if (rc == StorageResultCode.OperationSucceeded) {
1462 synchronized (mAsecMountSet) {
1463 mAsecMountSet.add(id);
1464 }
1465 }
San Mehat4270e1e2010-01-29 05:32:19 -08001466 return rc;
San Mehat36972292010-01-06 11:06:32 -08001467 }
1468
San Mehatd9709982010-02-18 11:43:03 -08001469 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001470 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001471 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001472 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001473
San Mehat6cdd9c02010-02-09 14:45:20 -08001474 synchronized (mAsecMountSet) {
1475 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001476 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001477 }
1478 }
1479
Kenny Rootaa485402010-09-14 14:49:41 -07001480 /*
1481 * Force a GC to make sure AssetManagers in other threads of the
1482 * system_server are cleaned up. We have to do this since AssetManager
1483 * instances are kept as a WeakReference and it's possible we have files
1484 * open on the external storage.
1485 */
1486 Runtime.getRuntime().gc();
1487
San Mehatb1043402010-02-05 08:26:50 -08001488 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001489 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001490 try {
1491 mConnector.doCommand(cmd);
1492 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001493 int code = e.getCode();
1494 if (code == VoldResponseCode.OpFailedStorageBusy) {
1495 rc = StorageResultCode.OperationFailedStorageBusy;
1496 } else {
1497 rc = StorageResultCode.OperationFailedInternalError;
1498 }
San Mehat02735bc2010-01-26 15:18:08 -08001499 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001500
1501 if (rc == StorageResultCode.OperationSucceeded) {
1502 synchronized (mAsecMountSet) {
1503 mAsecMountSet.remove(id);
1504 }
1505 }
San Mehat4270e1e2010-01-29 05:32:19 -08001506 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001507 }
1508
San Mehat6cdd9c02010-02-09 14:45:20 -08001509 public boolean isSecureContainerMounted(String id) {
1510 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1511 waitForReady();
1512 warnOnNotMounted();
1513
1514 synchronized (mAsecMountSet) {
1515 return mAsecMountSet.contains(id);
1516 }
1517 }
1518
San Mehat4270e1e2010-01-29 05:32:19 -08001519 public int renameSecureContainer(String oldId, String newId) {
1520 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001521 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001522 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001523
San Mehata181b212010-02-11 06:50:20 -08001524 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001525 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001526 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001527 * changed while active, we must ensure both ids are not currently mounted.
1528 */
1529 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001530 return StorageResultCode.OperationFailedStorageMounted;
1531 }
1532 }
1533
San Mehatb1043402010-02-05 08:26:50 -08001534 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001535 String cmd = String.format("asec rename %s %s", oldId, newId);
1536 try {
1537 mConnector.doCommand(cmd);
1538 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001539 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001540 }
San Mehata181b212010-02-11 06:50:20 -08001541
San Mehat4270e1e2010-01-29 05:32:19 -08001542 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001543 }
1544
San Mehat4270e1e2010-01-29 05:32:19 -08001545 public String getSecureContainerPath(String id) {
1546 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001547 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001548 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001549
San Mehat2d66cef2010-03-23 11:12:52 -07001550 try {
1551 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1552 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001553 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001554 if (code != VoldResponseCode.AsecPathResult) {
1555 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1556 }
1557 return tok[1];
1558 } catch (NativeDaemonConnectorException e) {
1559 int code = e.getCode();
1560 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001561 Slog.i(TAG, String.format("Container '%s' not found", id));
1562 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001563 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001564 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001565 }
1566 }
San Mehat22dd86e2010-01-12 12:21:18 -08001567 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001568
1569 public void finishMediaUpdate() {
1570 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1571 }
Kenny Root02c87302010-07-01 08:10:18 -07001572
Kenny Roota02b8b02010-08-05 16:14:17 -07001573 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1574 if (callerUid == android.os.Process.SYSTEM_UID) {
1575 return true;
1576 }
1577
Kenny Root02c87302010-07-01 08:10:18 -07001578 if (packageName == null) {
1579 return false;
1580 }
1581
1582 final int packageUid = mPms.getPackageUid(packageName);
1583
1584 if (DEBUG_OBB) {
1585 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1586 packageUid + ", callerUid = " + callerUid);
1587 }
1588
1589 return callerUid == packageUid;
1590 }
1591
1592 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001593 if (filename == null) {
1594 throw new IllegalArgumentException("filename cannot be null");
1595 }
1596
Kenny Root02c87302010-07-01 08:10:18 -07001597 waitForReady();
1598 warnOnNotMounted();
1599
Kenny Root02c87302010-07-01 08:10:18 -07001600 try {
1601 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1602 String []tok = rsp.get(0).split(" ");
1603 int code = Integer.parseInt(tok[0]);
1604 if (code != VoldResponseCode.AsecPathResult) {
1605 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1606 }
1607 return tok[1];
1608 } catch (NativeDaemonConnectorException e) {
1609 int code = e.getCode();
1610 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001611 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001612 } else {
1613 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1614 }
1615 }
1616 }
1617
1618 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001619 if (filename == null) {
1620 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001621 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001622
1623 synchronized (mObbMounts) {
1624 return mObbPathToStateMap.containsKey(filename);
1625 }
Kenny Root02c87302010-07-01 08:10:18 -07001626 }
1627
Kenny Rootaf9d6672010-10-08 09:21:39 -07001628 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001629 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001630 if (filename == null) {
1631 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001632 }
1633
1634 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001635 throw new IllegalArgumentException("token cannot be null");
1636 }
1637
Kenny Rootaf9d6672010-10-08 09:21:39 -07001638 final int callerUid = Binder.getCallingUid();
1639 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1640 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001641 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1642
1643 if (DEBUG_OBB)
1644 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001645 }
1646
Kenny Rootaf9d6672010-10-08 09:21:39 -07001647 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1648 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001649 if (filename == null) {
1650 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001651 }
1652
Kenny Rootaf9d6672010-10-08 09:21:39 -07001653 final int callerUid = Binder.getCallingUid();
1654 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1655 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001656 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001657
Kenny Roota02b8b02010-08-05 16:14:17 -07001658 if (DEBUG_OBB)
1659 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1660 }
1661
Jason parks5af0b912010-11-29 09:05:25 -06001662 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001663 if (TextUtils.isEmpty(password)) {
1664 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001665 }
1666
Jason parks8888c592011-01-20 22:46:41 -06001667 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1668 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001669
1670 waitForReady();
1671
1672 if (DEBUG_EVENTS) {
1673 Slog.i(TAG, "decrypting storage...");
1674 }
1675
1676 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001677 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001678 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001679
Jason parksf7b3cd42011-01-27 09:28:25 -06001680 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001681 return -1;
1682 }
1683
Jason parksf7b3cd42011-01-27 09:28:25 -06001684 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001685
1686 if (code == 0) {
1687 // Decrypt was successful. Post a delayed message before restarting in order
1688 // to let the UI to clear itself
1689 mHandler.postDelayed(new Runnable() {
1690 public void run() {
1691 mConnector.doCommand(String.format("cryptfs restart"));
1692 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001693 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001694 }
1695
1696 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001697 } catch (NativeDaemonConnectorException e) {
1698 // Decryption failed
1699 return e.getCode();
1700 }
Jason parks5af0b912010-11-29 09:05:25 -06001701 }
1702
Jason parks56aa5322011-01-07 09:01:15 -06001703 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001704 if (TextUtils.isEmpty(password)) {
1705 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001706 }
1707
Jason parks8888c592011-01-20 22:46:41 -06001708 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1709 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001710
1711 waitForReady();
1712
1713 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001714 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001715 }
1716
1717 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001718 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001719 } catch (NativeDaemonConnectorException e) {
1720 // Encryption failed
1721 return e.getCode();
1722 }
1723
1724 return 0;
1725 }
1726
Jason parksf7b3cd42011-01-27 09:28:25 -06001727 public int changeEncryptionPassword(String password) {
1728 if (TextUtils.isEmpty(password)) {
1729 throw new IllegalArgumentException("password cannot be empty");
1730 }
1731
1732 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1733 "no permission to access the crypt keeper");
1734
1735 waitForReady();
1736
1737 if (DEBUG_EVENTS) {
1738 Slog.i(TAG, "changing encryption password...");
1739 }
1740
1741 try {
1742 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1743
1744 String[] tokens = response.get(0).split(" ");
1745
1746 if (tokens == null || tokens.length != 2) {
1747 return -1;
1748 }
1749
1750 return Integer.parseInt(tokens[1]);
1751 } catch (NativeDaemonConnectorException e) {
1752 // Encryption failed
1753 return e.getCode();
1754 }
1755 }
1756
Mike Lockwoode3b498b2011-03-24 08:12:30 -07001757 public String[] getVolumeList() {
1758 synchronized(mVolumeStates) {
1759 Set<String> volumes = mVolumeStates.keySet();
1760 String[] result = new String[volumes.size()];
1761 int i = 0;
1762 for (String volume : volumes) {
1763 result[i++] = volume;
1764 }
1765 return result;
1766 }
1767 }
1768
Kenny Rootaf9d6672010-10-08 09:21:39 -07001769 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1770 final IBinder binder = obbState.getBinder();
1771 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001772
Kenny Rootaf9d6672010-10-08 09:21:39 -07001773 if (obbStates == null) {
1774 obbStates = new ArrayList<ObbState>();
1775 mObbMounts.put(binder, obbStates);
1776 } else {
1777 for (final ObbState o : obbStates) {
1778 if (o.filename.equals(obbState.filename)) {
1779 throw new IllegalStateException("Attempt to add ObbState twice. "
1780 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001781 }
1782 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001783 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001784
1785 obbStates.add(obbState);
1786 try {
1787 obbState.link();
1788 } catch (RemoteException e) {
1789 /*
1790 * The binder died before we could link it, so clean up our state
1791 * and return failure.
1792 */
1793 obbStates.remove(obbState);
1794 if (obbStates.isEmpty()) {
1795 mObbMounts.remove(binder);
1796 }
1797
1798 // Rethrow the error so mountObb can get it
1799 throw e;
1800 }
1801
1802 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001803 }
1804
Kenny Rootaf9d6672010-10-08 09:21:39 -07001805 private void removeObbStateLocked(ObbState obbState) {
1806 final IBinder binder = obbState.getBinder();
1807 final List<ObbState> obbStates = mObbMounts.get(binder);
1808 if (obbStates != null) {
1809 if (obbStates.remove(obbState)) {
1810 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001811 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001812 if (obbStates.isEmpty()) {
1813 mObbMounts.remove(binder);
1814 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001815 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001816
Kenny Rootaf9d6672010-10-08 09:21:39 -07001817 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001818 }
1819
Kenny Roota02b8b02010-08-05 16:14:17 -07001820 private class ObbActionHandler extends Handler {
1821 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001822 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001823
1824 ObbActionHandler(Looper l) {
1825 super(l);
1826 }
1827
1828 @Override
1829 public void handleMessage(Message msg) {
1830 switch (msg.what) {
1831 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001832 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001833
1834 if (DEBUG_OBB)
1835 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1836
1837 // If a bind was already initiated we don't really
1838 // need to do anything. The pending install
1839 // will be processed later on.
1840 if (!mBound) {
1841 // If this is the only one pending we might
1842 // have to bind to the service again.
1843 if (!connectToService()) {
1844 Slog.e(TAG, "Failed to bind to media container service");
1845 action.handleError();
1846 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001847 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001848 }
Kenny Root735de3b2010-09-30 14:11:39 -07001849
Kenny Root735de3b2010-09-30 14:11:39 -07001850 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001851 break;
1852 }
1853 case OBB_MCS_BOUND: {
1854 if (DEBUG_OBB)
1855 Slog.i(TAG, "OBB_MCS_BOUND");
1856 if (msg.obj != null) {
1857 mContainerService = (IMediaContainerService) msg.obj;
1858 }
1859 if (mContainerService == null) {
1860 // Something seriously wrong. Bail out
1861 Slog.e(TAG, "Cannot bind to media container service");
1862 for (ObbAction action : mActions) {
1863 // Indicate service bind error
1864 action.handleError();
1865 }
1866 mActions.clear();
1867 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001868 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001869 if (action != null) {
1870 action.execute(this);
1871 }
1872 } else {
1873 // Should never happen ideally.
1874 Slog.w(TAG, "Empty queue");
1875 }
1876 break;
1877 }
1878 case OBB_MCS_RECONNECT: {
1879 if (DEBUG_OBB)
1880 Slog.i(TAG, "OBB_MCS_RECONNECT");
1881 if (mActions.size() > 0) {
1882 if (mBound) {
1883 disconnectService();
1884 }
1885 if (!connectToService()) {
1886 Slog.e(TAG, "Failed to bind to media container service");
1887 for (ObbAction action : mActions) {
1888 // Indicate service bind error
1889 action.handleError();
1890 }
1891 mActions.clear();
1892 }
1893 }
1894 break;
1895 }
1896 case OBB_MCS_UNBIND: {
1897 if (DEBUG_OBB)
1898 Slog.i(TAG, "OBB_MCS_UNBIND");
1899
1900 // Delete pending install
1901 if (mActions.size() > 0) {
1902 mActions.remove(0);
1903 }
1904 if (mActions.size() == 0) {
1905 if (mBound) {
1906 disconnectService();
1907 }
1908 } else {
1909 // There are more pending requests in queue.
1910 // Just post MCS_BOUND message to trigger processing
1911 // of next pending install.
1912 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1913 }
1914 break;
1915 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001916 case OBB_FLUSH_MOUNT_STATE: {
1917 final String path = (String) msg.obj;
1918
1919 if (DEBUG_OBB)
1920 Slog.i(TAG, "Flushing all OBB state for path " + path);
1921
1922 synchronized (mObbMounts) {
1923 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1924
1925 final Iterator<Entry<String, ObbState>> i =
1926 mObbPathToStateMap.entrySet().iterator();
1927 while (i.hasNext()) {
1928 final Entry<String, ObbState> obbEntry = i.next();
1929
1930 /*
1931 * If this entry's source file is in the volume path
1932 * that got unmounted, remove it because it's no
1933 * longer valid.
1934 */
1935 if (obbEntry.getKey().startsWith(path)) {
1936 obbStatesToRemove.add(obbEntry.getValue());
1937 }
1938 }
1939
1940 for (final ObbState obbState : obbStatesToRemove) {
1941 if (DEBUG_OBB)
1942 Slog.i(TAG, "Removing state for " + obbState.filename);
1943
1944 removeObbStateLocked(obbState);
1945
1946 try {
1947 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1948 OnObbStateChangeListener.UNMOUNTED);
1949 } catch (RemoteException e) {
1950 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1951 + obbState.filename);
1952 }
1953 }
1954 }
1955 break;
1956 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001957 }
1958 }
1959
1960 private boolean connectToService() {
1961 if (DEBUG_OBB)
1962 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1963
1964 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1965 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1966 mBound = true;
1967 return true;
1968 }
1969 return false;
1970 }
1971
1972 private void disconnectService() {
1973 mContainerService = null;
1974 mBound = false;
1975 mContext.unbindService(mDefContainerConn);
1976 }
1977 }
1978
1979 abstract class ObbAction {
1980 private static final int MAX_RETRIES = 3;
1981 private int mRetries;
1982
1983 ObbState mObbState;
1984
1985 ObbAction(ObbState obbState) {
1986 mObbState = obbState;
1987 }
1988
1989 public void execute(ObbActionHandler handler) {
1990 try {
1991 if (DEBUG_OBB)
1992 Slog.i(TAG, "Starting to execute action: " + this.toString());
1993 mRetries++;
1994 if (mRetries > MAX_RETRIES) {
1995 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001996 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001997 handleError();
1998 return;
1999 } else {
2000 handleExecute();
2001 if (DEBUG_OBB)
2002 Slog.i(TAG, "Posting install MCS_UNBIND");
2003 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2004 }
2005 } catch (RemoteException e) {
2006 if (DEBUG_OBB)
2007 Slog.i(TAG, "Posting install MCS_RECONNECT");
2008 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2009 } catch (Exception e) {
2010 if (DEBUG_OBB)
2011 Slog.d(TAG, "Error handling OBB action", e);
2012 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002013 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002014 }
2015 }
2016
Kenny Root05105f72010-09-22 17:29:43 -07002017 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002018 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002019
2020 protected ObbInfo getObbInfo() throws IOException {
2021 ObbInfo obbInfo;
2022 try {
2023 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2024 } catch (RemoteException e) {
2025 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2026 + mObbState.filename);
2027 obbInfo = null;
2028 }
2029 if (obbInfo == null) {
2030 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2031 }
2032 return obbInfo;
2033 }
2034
Kenny Rootaf9d6672010-10-08 09:21:39 -07002035 protected void sendNewStatusOrIgnore(int status) {
2036 if (mObbState == null || mObbState.token == null) {
2037 return;
2038 }
2039
Kenny Root38cf8862010-09-26 14:18:51 -07002040 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002041 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002042 } catch (RemoteException e) {
2043 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2044 }
2045 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002046 }
2047
2048 class MountObbAction extends ObbAction {
2049 private String mKey;
2050
2051 MountObbAction(ObbState obbState, String key) {
2052 super(obbState);
2053 mKey = key;
2054 }
2055
Jason parks5af0b912010-11-29 09:05:25 -06002056 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002057 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002058 waitForReady();
2059 warnOnNotMounted();
2060
Kenny Root38cf8862010-09-26 14:18:51 -07002061 final ObbInfo obbInfo = getObbInfo();
2062
Kenny Roota02b8b02010-08-05 16:14:17 -07002063 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002064 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2065 + " which is owned by " + obbInfo.packageName);
2066 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2067 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002068 }
2069
Kenny Rootaf9d6672010-10-08 09:21:39 -07002070 final boolean isMounted;
2071 synchronized (mObbMounts) {
2072 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2073 }
2074 if (isMounted) {
2075 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2076 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2077 return;
2078 }
2079
2080 /*
2081 * The filename passed in might not be the canonical name, so just
2082 * set the filename to the canonicalized version.
2083 */
2084 mObbState.filename = obbInfo.filename;
2085
2086 final String hashedKey;
2087 if (mKey == null) {
2088 hashedKey = "none";
2089 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002090 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002091 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2092
2093 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2094 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2095 SecretKey key = factory.generateSecret(ks);
2096 BigInteger bi = new BigInteger(key.getEncoded());
2097 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002098 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002099 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2100 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2101 return;
2102 } catch (InvalidKeySpecException e) {
2103 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2104 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002105 return;
2106 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002107 }
Kenny Root38cf8862010-09-26 14:18:51 -07002108
Kenny Rootaf9d6672010-10-08 09:21:39 -07002109 int rc = StorageResultCode.OperationSucceeded;
2110 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2111 mObbState.callerUid);
2112 try {
2113 mConnector.doCommand(cmd);
2114 } catch (NativeDaemonConnectorException e) {
2115 int code = e.getCode();
2116 if (code != VoldResponseCode.OpFailedStorageBusy) {
2117 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002118 }
2119 }
2120
Kenny Rootaf9d6672010-10-08 09:21:39 -07002121 if (rc == StorageResultCode.OperationSucceeded) {
2122 if (DEBUG_OBB)
2123 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2124
2125 synchronized (mObbMounts) {
2126 addObbStateLocked(mObbState);
2127 }
2128
2129 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002130 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002131 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002132
Kenny Rootaf9d6672010-10-08 09:21:39 -07002133 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002134 }
2135 }
2136
Jason parks5af0b912010-11-29 09:05:25 -06002137 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002138 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002139 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002140 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002141
2142 @Override
2143 public String toString() {
2144 StringBuilder sb = new StringBuilder();
2145 sb.append("MountObbAction{");
2146 sb.append("filename=");
2147 sb.append(mObbState.filename);
2148 sb.append(",callerUid=");
2149 sb.append(mObbState.callerUid);
2150 sb.append(",token=");
2151 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002152 sb.append(",binder=");
2153 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002154 sb.append('}');
2155 return sb.toString();
2156 }
2157 }
2158
2159 class UnmountObbAction extends ObbAction {
2160 private boolean mForceUnmount;
2161
2162 UnmountObbAction(ObbState obbState, boolean force) {
2163 super(obbState);
2164 mForceUnmount = force;
2165 }
2166
Jason parks5af0b912010-11-29 09:05:25 -06002167 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002168 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002169 waitForReady();
2170 warnOnNotMounted();
2171
Kenny Root38cf8862010-09-26 14:18:51 -07002172 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002173
Kenny Rootaf9d6672010-10-08 09:21:39 -07002174 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002175 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002176 obbState = mObbPathToStateMap.get(obbInfo.filename);
2177 }
Kenny Root38cf8862010-09-26 14:18:51 -07002178
Kenny Rootaf9d6672010-10-08 09:21:39 -07002179 if (obbState == null) {
2180 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2181 return;
2182 }
2183
2184 if (obbState.callerUid != mObbState.callerUid) {
2185 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2186 + " (owned by " + obbInfo.packageName + ")");
2187 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2188 return;
2189 }
2190
2191 mObbState.filename = obbInfo.filename;
2192
2193 int rc = StorageResultCode.OperationSucceeded;
2194 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2195 (mForceUnmount ? " force" : ""));
2196 try {
2197 mConnector.doCommand(cmd);
2198 } catch (NativeDaemonConnectorException e) {
2199 int code = e.getCode();
2200 if (code == VoldResponseCode.OpFailedStorageBusy) {
2201 rc = StorageResultCode.OperationFailedStorageBusy;
2202 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2203 // If it's not mounted then we've already won.
2204 rc = StorageResultCode.OperationSucceeded;
2205 } else {
2206 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002207 }
2208 }
2209
Kenny Rootaf9d6672010-10-08 09:21:39 -07002210 if (rc == StorageResultCode.OperationSucceeded) {
2211 synchronized (mObbMounts) {
2212 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002213 }
2214
Kenny Rootaf9d6672010-10-08 09:21:39 -07002215 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002216 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002217 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2218 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002219 }
2220 }
2221
Jason parks5af0b912010-11-29 09:05:25 -06002222 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002223 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002224 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002225 }
2226
2227 @Override
2228 public String toString() {
2229 StringBuilder sb = new StringBuilder();
2230 sb.append("UnmountObbAction{");
2231 sb.append("filename=");
2232 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2233 sb.append(",force=");
2234 sb.append(mForceUnmount);
2235 sb.append(",callerUid=");
2236 sb.append(mObbState.callerUid);
2237 sb.append(",token=");
2238 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002239 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002240 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002241 sb.append('}');
2242 return sb.toString();
2243 }
Kenny Root02c87302010-07-01 08:10:18 -07002244 }
Kenny Root38cf8862010-09-26 14:18:51 -07002245
2246 @Override
2247 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2248 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2249 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2250 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2251 + " without permission " + android.Manifest.permission.DUMP);
2252 return;
2253 }
2254
Kenny Root38cf8862010-09-26 14:18:51 -07002255 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002256 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002257
Kenny Rootaf9d6672010-10-08 09:21:39 -07002258 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2259 while (binders.hasNext()) {
2260 Entry<IBinder, List<ObbState>> e = binders.next();
2261 pw.print(" Key="); pw.println(e.getKey().toString());
2262 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002263 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002264 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002265 }
2266 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002267
2268 pw.println("");
2269 pw.println(" mObbPathToStateMap:");
2270 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2271 while (maps.hasNext()) {
2272 final Entry<String, ObbState> e = maps.next();
2273 pw.print(" "); pw.print(e.getKey());
2274 pw.print(" -> "); pw.println(e.getValue().toString());
2275 }
Kenny Root38cf8862010-09-26 14:18:51 -07002276 }
2277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278}
2279