blob: 1f2ac2be501caadb13e3417776656aa1a06bec7f [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;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070020import com.android.internal.util.XmlUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
Jason parks8888c592011-01-20 22:46:41 -060023import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070025import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070029import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040039import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070040import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080042import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070043import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080044import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080045import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080046import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.IMountService;
49import android.os.storage.IMountServiceListener;
50import android.os.storage.IMountShutdownObserver;
51import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070052import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070053import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070054import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060055import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070057import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.Xml;
59
60import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070062
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070064import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070065import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070066import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070067import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070068import java.security.spec.InvalidKeySpecException;
69import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080070import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070071import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080072import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070073import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070074import java.util.LinkedList;
75import java.util.List;
76import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.util.Map.Entry;
Mike Lockwoodd967f462011-03-24 08:12:30 -070078import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079
Kenny Root3b1abba2010-10-13 15:00:07 -070080import javax.crypto.SecretKey;
81import javax.crypto.SecretKeyFactory;
82import javax.crypto.spec.PBEKeySpec;
83
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084/**
San Mehatb1043402010-02-05 08:26:50 -080085 * MountService implements back-end services for platform storage
86 * management.
87 * @hide - Applications should use android.os.storage.StorageManager
88 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 */
Jason parks5af0b912010-11-29 09:05:25 -060090class MountService extends IMountService.Stub implements INativeDaemonConnectorCallbacks {
91
San Mehatb1043402010-02-05 08:26:50 -080092 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080093 private static final boolean DEBUG_UNMOUNT = false;
94 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080095 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private static final String TAG = "MountService";
98
Kenny Root305bcbf2010-09-03 07:56:38 -070099 private static final String VOLD_TAG = "VoldConnector";
100
San Mehat4270e1e2010-01-29 05:32:19 -0800101 /*
102 * Internal vold volume state constants
103 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800104 class VolumeState {
105 public static final int Init = -1;
106 public static final int NoMedia = 0;
107 public static final int Idle = 1;
108 public static final int Pending = 2;
109 public static final int Checking = 3;
110 public static final int Mounted = 4;
111 public static final int Unmounting = 5;
112 public static final int Formatting = 6;
113 public static final int Shared = 7;
114 public static final int SharedMnt = 8;
115 }
116
San Mehat4270e1e2010-01-29 05:32:19 -0800117 /*
118 * Internal vold response code constants
119 */
San Mehat22dd86e2010-01-12 12:21:18 -0800120 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800121 /*
122 * 100 series - Requestion action was initiated; expect another reply
123 * before proceeding with a new command.
124 */
San Mehat22dd86e2010-01-12 12:21:18 -0800125 public static final int VolumeListResult = 110;
126 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800127 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800128
San Mehat4270e1e2010-01-29 05:32:19 -0800129 /*
130 * 200 series - Requestion action has been successfully completed.
131 */
132 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800133 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800134 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800135
San Mehat4270e1e2010-01-29 05:32:19 -0800136 /*
137 * 400 series - Command was accepted, but the requested action
138 * did not take place.
139 */
140 public static final int OpFailedNoMedia = 401;
141 public static final int OpFailedMediaBlank = 402;
142 public static final int OpFailedMediaCorrupt = 403;
143 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800144 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700145 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800146
147 /*
148 * 600 series - Unsolicited broadcasts.
149 */
San Mehat22dd86e2010-01-12 12:21:18 -0800150 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800151 public static final int ShareAvailabilityChange = 620;
152 public static final int VolumeDiskInserted = 630;
153 public static final int VolumeDiskRemoved = 631;
154 public static final int VolumeBadRemoval = 632;
155 }
156
San Mehat4270e1e2010-01-29 05:32:19 -0800157 private Context mContext;
158 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700159 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
160 private StorageVolume mPrimaryVolume;
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400161 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400162 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400163 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800164 private PackageManagerService mPms;
165 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800166 // Used as a lock for methods that register/unregister listeners.
167 final private ArrayList<MountServiceBinderListener> mListeners =
168 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800169 private boolean mBooted = false;
170 private boolean mReady = false;
171 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400172 // true if we should fake MEDIA_MOUNTED state for external storage
173 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800174
San Mehat6cdd9c02010-02-09 14:45:20 -0800175 /**
176 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800177 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800178 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800179 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800180
Kenny Root02c87302010-07-01 08:10:18 -0700181 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700182 * The size of the crypto algorithm key in bits for OBB files. Currently
183 * Twofish is used which takes 128-bit keys.
184 */
185 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
186
187 /**
188 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
189 * 1024 is reasonably secure and not too slow.
190 */
191 private static final int PBKDF2_HASH_ROUNDS = 1024;
192
193 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700194 * Mounted OBB tracking information. Used to track the current state of all
195 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700196 */
Kenny Root735de3b2010-09-30 14:11:39 -0700197 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700198 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
199
200 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700201 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700202 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700204 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700205 this.token = token;
206 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700207 }
208
209 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700210 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700211
212 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700213 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700214
Kenny Rootaf9d6672010-10-08 09:21:39 -0700215 // Token of remote Binder caller
216 final IObbActionListener token;
217
218 // Identifier to pass back to the token
219 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700220
Kenny Root735de3b2010-09-30 14:11:39 -0700221 public IBinder getBinder() {
222 return token.asBinder();
223 }
224
Kenny Roota02b8b02010-08-05 16:14:17 -0700225 @Override
226 public void binderDied() {
227 ObbAction action = new UnmountObbAction(this, true);
228 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700229 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700230
Kenny Root5919ac62010-10-05 09:49:40 -0700231 public void link() throws RemoteException {
232 getBinder().linkToDeath(this, 0);
233 }
234
235 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700236 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700237 }
Kenny Root38cf8862010-09-26 14:18:51 -0700238
239 @Override
240 public String toString() {
241 StringBuilder sb = new StringBuilder("ObbState{");
242 sb.append("filename=");
243 sb.append(filename);
244 sb.append(",token=");
245 sb.append(token.toString());
246 sb.append(",callerUid=");
247 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700248 sb.append('}');
249 return sb.toString();
250 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700251 }
252
253 // OBB Action Handler
254 final private ObbActionHandler mObbActionHandler;
255
256 // OBB action handler messages
257 private static final int OBB_RUN_ACTION = 1;
258 private static final int OBB_MCS_BOUND = 2;
259 private static final int OBB_MCS_UNBIND = 3;
260 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700261 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262
263 /*
264 * Default Container Service information
265 */
266 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
267 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
268
269 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
270
271 class DefaultContainerConnection implements ServiceConnection {
272 public void onServiceConnected(ComponentName name, IBinder service) {
273 if (DEBUG_OBB)
274 Slog.i(TAG, "onServiceConnected");
275 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
276 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
277 }
278
279 public void onServiceDisconnected(ComponentName name) {
280 if (DEBUG_OBB)
281 Slog.i(TAG, "onServiceDisconnected");
282 }
283 };
284
285 // Used in the ObbActionHandler
286 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700287
288 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800289 private static final int H_UNMOUNT_PM_UPDATE = 1;
290 private static final int H_UNMOUNT_PM_DONE = 2;
291 private static final int H_UNMOUNT_MS = 3;
292 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
293 private static final int MAX_UNMOUNT_RETRIES = 4;
294
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800295 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700296 final String path;
297 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800298 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800299
300 UnmountCallBack(String path, boolean force) {
301 retries = 0;
302 this.path = path;
303 this.force = force;
304 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800305
306 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700307 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800308 doUnmountVolume(path, true);
309 }
310 }
311
312 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700313 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800314
315 UmsEnableCallBack(String path, String method, boolean force) {
316 super(path, force);
317 this.method = method;
318 }
319
320 @Override
321 void handleFinished() {
322 super.handleFinished();
323 doShareUnshareVolume(path, method, true);
324 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800325 }
326
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800327 class ShutdownCallBack extends UnmountCallBack {
328 IMountShutdownObserver observer;
329 ShutdownCallBack(String path, IMountShutdownObserver observer) {
330 super(path, true);
331 this.observer = observer;
332 }
333
334 @Override
335 void handleFinished() {
336 int ret = doUnmountVolume(path, true);
337 if (observer != null) {
338 try {
339 observer.onShutDownComplete(ret);
340 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700341 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800342 }
343 }
344 }
345 }
346
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400347 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800348 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700349 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800350
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400351 MountServiceHandler(Looper l) {
352 super(l);
353 }
354
Jason parks5af0b912010-11-29 09:05:25 -0600355 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800356 public void handleMessage(Message msg) {
357 switch (msg.what) {
358 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700359 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
361 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700362 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800363 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700364 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700365 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700366 mUpdatingStatus = true;
367 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800368 }
369 break;
370 }
371 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700372 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700373 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700374 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800375 int size = mForceUnmounts.size();
376 int sizeArr[] = new int[size];
377 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700378 // Kill processes holding references first
379 ActivityManagerService ams = (ActivityManagerService)
380 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800381 for (int i = 0; i < size; i++) {
382 UnmountCallBack ucb = mForceUnmounts.get(i);
383 String path = ucb.path;
384 boolean done = false;
385 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800386 done = true;
387 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800388 int pids[] = getStorageUsers(path);
389 if (pids == null || pids.length == 0) {
390 done = true;
391 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800393 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700394 // Confirm if file references have been freed.
395 pids = getStorageUsers(path);
396 if (pids == null || pids.length == 0) {
397 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800398 }
399 }
400 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700401 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
402 // Retry again
403 Slog.i(TAG, "Retrying to kill storage users again");
404 mHandler.sendMessageDelayed(
405 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
406 ucb.retries++),
407 RETRY_UNMOUNT_DELAY);
408 } else {
409 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
410 Slog.i(TAG, "Failed to unmount media inspite of " +
411 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
412 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800413 sizeArr[sizeArrN++] = i;
414 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
415 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800416 }
417 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800418 // Remove already processed elements from list.
419 for (int i = (sizeArrN-1); i >= 0; i--) {
420 mForceUnmounts.remove(sizeArr[i]);
421 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800422 break;
423 }
424 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700425 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800426 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800427 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800428 break;
429 }
430 }
431 }
432 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400433 final private HandlerThread mHandlerThread;
434 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800435
San Mehat207e5382010-02-04 20:46:54 -0800436 private void waitForReady() {
437 while (mReady == false) {
438 for (int retries = 5; retries > 0; retries--) {
439 if (mReady) {
440 return;
441 }
442 SystemClock.sleep(1000);
443 }
San Mehata5078592010-03-25 09:36:54 -0700444 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800445 }
San Mehat1f6301e2010-01-07 22:40:27 -0800446 }
Kenny Root02c87302010-07-01 08:10:18 -0700447
San Mehat207e5382010-02-04 20:46:54 -0800448 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600449 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800451 String action = intent.getAction();
452
453 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800454 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800455
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800456 /*
457 * In the simulator, we need to broadcast a volume mounted event
458 * to make the media scanner run.
459 */
460 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400461 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
462 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800463 return;
464 }
San Mehatfafb0412010-02-18 19:40:04 -0800465 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600466 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800467 public void run() {
468 try {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400469 // it is not safe to call vold with mVolumeStates locked
470 // so we make a copy of the paths and states and process them
471 // outside the lock
472 String[] paths, states;
473 int count;
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400474 synchronized (mVolumeStates) {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400475 Set<String> keys = mVolumeStates.keySet();
476 count = keys.size();
477 paths = (String[])keys.toArray(new String[count]);
478 states = new String[count];
479 for (int i = 0; i < count; i++) {
480 states[i] = mVolumeStates.get(paths[i]);
481 }
482 }
San Mehat6a254402010-03-22 10:21:00 -0700483
Mike Lockwoodb9135632011-04-05 10:05:47 -0400484 for (int i = 0; i < count; i++) {
485 String path = paths[i];
486 String state = states[i];
487
488 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
489 int rc = doMountVolume(path);
490 if (rc != StorageResultCode.OperationSucceeded) {
491 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
492 rc));
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400493 }
Mike Lockwoodb9135632011-04-05 10:05:47 -0400494 } else if (state.equals(Environment.MEDIA_SHARED)) {
495 /*
496 * Bootstrap UMS enabled state since vold indicates
497 * the volume is shared (runtime restart while ums enabled)
498 */
499 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
500 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800501 }
502 }
San Mehat6a254402010-03-22 10:21:00 -0700503
Mike Lockwood91dd02c2011-04-05 10:21:51 -0400504 /* notify external storage has mounted to trigger media scanner */
505 if (mEmulateExternalStorage) {
506 notifyVolumeStateChange(null,
507 Environment.getExternalStorageDirectory().getPath(),
508 VolumeState.NoMedia, VolumeState.Mounted);
509 }
510
San Mehat6a965af22010-02-24 17:47:30 -0800511 /*
San Mehat6a254402010-03-22 10:21:00 -0700512 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800513 * now that we're up.
514 */
515 if (mSendUmsConnectedOnBoot) {
516 sendUmsIntent(true);
517 mSendUmsConnectedOnBoot = false;
518 }
San Mehatfafb0412010-02-18 19:40:04 -0800519 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700520 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800521 }
San Mehat207e5382010-02-04 20:46:54 -0800522 }
San Mehatfafb0412010-02-18 19:40:04 -0800523 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 }
525 }
526 };
527
San Mehat4270e1e2010-01-29 05:32:19 -0800528 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
529 final IMountServiceListener mListener;
530
531 MountServiceBinderListener(IMountServiceListener listener) {
532 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700533
San Mehat91c77612010-01-07 10:39:41 -0800534 }
535
San Mehat4270e1e2010-01-29 05:32:19 -0800536 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700537 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700538 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800539 mListeners.remove(this);
540 mListener.asBinder().unlinkToDeath(this, 0);
541 }
542 }
543 }
544
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800545 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800546 // TODO: Add support for multiple share methods
547 if (!method.equals("ums")) {
548 throw new IllegalArgumentException(String.format("Method %s not supported", method));
549 }
550
San Mehat4270e1e2010-01-29 05:32:19 -0800551 try {
552 mConnector.doCommand(String.format(
553 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
554 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700555 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800556 }
San Mehat4270e1e2010-01-29 05:32:19 -0800557 }
558
San Mehat207e5382010-02-04 20:46:54 -0800559 private void updatePublicVolumeState(String path, String state) {
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400560 String oldState;
561 synchronized(mVolumeStates) {
562 oldState = mVolumeStates.put(path, state);
563 }
564 if (state.equals(oldState)) {
565 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
566 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800567 return;
568 }
San Mehatb1043402010-02-05 08:26:50 -0800569
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400570 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700571
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400572 if (path.equals(mExternalStoragePath)) {
573 // Update state on PackageManager, but only of real events
574 if (!mEmulateExternalStorage) {
575 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
576 mPms.updateExternalMediaStatus(false, false);
577
578 /*
579 * Some OBBs might have been unmounted when this volume was
580 * unmounted, so send a message to the handler to let it know to
581 * remove those from the list of mounted OBBS.
582 */
583 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
584 OBB_FLUSH_MOUNT_STATE, path));
585 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
586 mPms.updateExternalMediaStatus(true, false);
587 }
Mike Lockwood03559752010-07-19 18:25:03 -0400588 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800589 }
San Mehat4270e1e2010-01-29 05:32:19 -0800590 synchronized (mListeners) {
591 for (int i = mListeners.size() -1; i >= 0; i--) {
592 MountServiceBinderListener bl = mListeners.get(i);
593 try {
San Mehatb1043402010-02-05 08:26:50 -0800594 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800595 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700596 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800597 mListeners.remove(i);
598 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700599 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800600 }
601 }
602 }
603 }
604
605 /**
606 *
607 * Callback from NativeDaemonConnector
608 */
609 public void onDaemonConnected() {
610 /*
611 * Since we'll be calling back into the NativeDaemonConnector,
612 * we need to do our work in a new thread.
613 */
614 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600615 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800616 public void run() {
617 /**
618 * Determine media state and UMS detection status
619 */
San Mehat4270e1e2010-01-29 05:32:19 -0800620 try {
621 String[] vols = mConnector.doListCommand(
622 "volume list", VoldResponseCode.VolumeListResult);
623 for (String volstr : vols) {
624 String[] tok = volstr.split(" ");
625 // FMT: <label> <mountpoint> <state>
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400626 String path = tok[1];
627 String state = Environment.MEDIA_REMOVED;
628
San Mehat4270e1e2010-01-29 05:32:19 -0800629 int st = Integer.parseInt(tok[2]);
630 if (st == VolumeState.NoMedia) {
631 state = Environment.MEDIA_REMOVED;
632 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800633 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800634 } else if (st == VolumeState.Mounted) {
635 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700636 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800637 } else if (st == VolumeState.Shared) {
638 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700639 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800640 } else {
641 throw new Exception(String.format("Unexpected state %d", st));
642 }
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400643
644 if (state != null) {
645 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
646 updatePublicVolumeState(path, state);
647 }
San Mehat4270e1e2010-01-29 05:32:19 -0800648 }
649 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700650 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400651 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800652 }
653
654 try {
San Mehat207e5382010-02-04 20:46:54 -0800655 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800656 notifyShareAvailabilityChange("ums", avail);
657 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700658 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800659 }
San Mehat207e5382010-02-04 20:46:54 -0800660 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600661 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800662 * the hounds!
663 */
664 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800665 }
666 }.start();
667 }
668
669 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800670 * Callback from NativeDaemonConnector
671 */
672 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800673 if (DEBUG_EVENTS) {
674 StringBuilder builder = new StringBuilder();
675 builder.append("onEvent::");
676 builder.append(" raw= " + raw);
677 if (cooked != null) {
678 builder.append(" cooked = " );
679 for (String str : cooked) {
680 builder.append(" " + str);
681 }
682 }
San Mehata5078592010-03-25 09:36:54 -0700683 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800684 }
San Mehat4270e1e2010-01-29 05:32:19 -0800685 if (code == VoldResponseCode.VolumeStateChange) {
686 /*
687 * One of the volumes we're managing has changed state.
688 * Format: "NNN Volume <label> <path> state changed
689 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
690 */
691 notifyVolumeStateChange(
692 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
693 Integer.parseInt(cooked[10]));
694 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
695 // FMT: NNN Share method <method> now <available|unavailable>
696 boolean avail = false;
697 if (cooked[5].equals("available")) {
698 avail = true;
699 }
700 notifyShareAvailabilityChange(cooked[3], avail);
701 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
702 (code == VoldResponseCode.VolumeDiskRemoved) ||
703 (code == VoldResponseCode.VolumeBadRemoval)) {
704 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
705 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
706 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400707 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800708 final String label = cooked[2];
709 final String path = cooked[3];
710 int major = -1;
711 int minor = -1;
712
713 try {
714 String devComp = cooked[6].substring(1, cooked[6].length() -1);
715 String[] devTok = devComp.split(":");
716 major = Integer.parseInt(devTok[0]);
717 minor = Integer.parseInt(devTok[1]);
718 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700719 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800720 }
721
San Mehat4270e1e2010-01-29 05:32:19 -0800722 if (code == VoldResponseCode.VolumeDiskInserted) {
723 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600724 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800725 public void run() {
726 try {
727 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800728 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700729 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800730 }
731 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700732 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800733 }
734 }
735 }.start();
736 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
737 /*
738 * This event gets trumped if we're already in BAD_REMOVAL state
739 */
740 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
741 return true;
742 }
743 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700744 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800745 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400746 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800747
San Mehata5078592010-03-25 09:36:54 -0700748 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800749 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400750 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800751 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700752 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800753 /* Send the media unmounted event first */
754 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400755 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800756
San Mehata5078592010-03-25 09:36:54 -0700757 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800758 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400759 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800760 } else {
San Mehata5078592010-03-25 09:36:54 -0700761 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800762 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400763
764 if (action != null) {
765 sendStorageIntent(action, path);
766 }
San Mehat4270e1e2010-01-29 05:32:19 -0800767 } else {
768 return false;
769 }
770
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400771 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800772 }
773
San Mehat207e5382010-02-04 20:46:54 -0800774 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800775 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700776 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800777
Mike Lockwooda5250c92011-05-23 13:44:04 -0400778 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800779
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500780 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700781 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400782 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500783 }
784
San Mehat4270e1e2010-01-29 05:32:19 -0800785 if (newState == VolumeState.Init) {
786 } else if (newState == VolumeState.NoMedia) {
787 // NoMedia is handled via Disk Remove events
788 } else if (newState == VolumeState.Idle) {
789 /*
790 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
791 * if we're in the process of enabling UMS
792 */
793 if (!vs.equals(
794 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
795 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800796 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700797 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800798 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400799 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800800 }
801 } else if (newState == VolumeState.Pending) {
802 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700803 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800804 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400805 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800806 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700807 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800808 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400809 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800810 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400811 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800812 } else if (newState == VolumeState.Formatting) {
813 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700814 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800815 /* Send the media unmounted event first */
816 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400817 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800818
San Mehata5078592010-03-25 09:36:54 -0700819 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800820 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400821 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700822 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800823 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700824 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800825 return;
826 } else {
San Mehata5078592010-03-25 09:36:54 -0700827 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800828 }
829
Mike Lockwooda5250c92011-05-23 13:44:04 -0400830 if (action != null) {
831 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800832 }
833 }
834
San Mehat207e5382010-02-04 20:46:54 -0800835 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700836 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700837 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700838 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700839 } catch (NativeDaemonConnectorException ex) {
840 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
841 return false;
842 }
San Mehat207e5382010-02-04 20:46:54 -0800843
844 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700845 String[] tok = line.split(" ");
846 if (tok.length < 3) {
847 Slog.e(TAG, "Malformed response to share status " + method);
848 return false;
849 }
850
San Mehat207e5382010-02-04 20:46:54 -0800851 int code;
852 try {
853 code = Integer.parseInt(tok[0]);
854 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700855 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800856 return false;
857 }
858 if (code == VoldResponseCode.ShareStatusResult) {
859 if (tok[2].equals("available"))
860 return true;
861 return false;
862 } else {
San Mehata5078592010-03-25 09:36:54 -0700863 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800864 return false;
865 }
866 }
San Mehata5078592010-03-25 09:36:54 -0700867 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800868 return false;
869 }
870
871 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800872 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800873
San Mehata5078592010-03-25 09:36:54 -0700874 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800875 try {
876 mConnector.doCommand(String.format("volume mount %s", path));
877 } catch (NativeDaemonConnectorException e) {
878 /*
879 * Mount failed for some reason
880 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400881 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800882 int code = e.getCode();
883 if (code == VoldResponseCode.OpFailedNoMedia) {
884 /*
885 * Attempt to mount but no media inserted
886 */
San Mehatb1043402010-02-05 08:26:50 -0800887 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800888 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700889 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800890 /*
891 * Media is blank or does not contain a supported filesystem
892 */
893 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400894 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800895 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800896 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700897 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800898 /*
899 * Volume consistency check failed
900 */
901 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400902 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800903 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800904 } else {
San Mehatb1043402010-02-05 08:26:50 -0800905 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800906 }
907
908 /*
909 * Send broadcast intent (if required for the failure)
910 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400911 if (action != null) {
912 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800913 }
914 }
915
916 return rc;
917 }
918
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800919 /*
920 * If force is not set, we do not unmount if there are
921 * processes holding references to the volume about to be unmounted.
922 * If force is set, all the processes holding references need to be
923 * killed via the ActivityManager before actually unmounting the volume.
924 * This might even take a while and might be retried after timed delays
925 * to make sure we dont end up in an instable state and kill some core
926 * processes.
927 */
San Mehatd9709982010-02-18 11:43:03 -0800928 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800929 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800930 return VoldResponseCode.OpFailedVolNotMounted;
931 }
Kenny Rootaa485402010-09-14 14:49:41 -0700932
933 /*
934 * Force a GC to make sure AssetManagers in other threads of the
935 * system_server are cleaned up. We have to do this since AssetManager
936 * instances are kept as a WeakReference and it's possible we have files
937 * open on the external storage.
938 */
939 Runtime.getRuntime().gc();
940
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800941 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700942 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800943 try {
San Mehatd9709982010-02-18 11:43:03 -0800944 mConnector.doCommand(String.format(
945 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700946 // We unmounted the volume. None of the asec containers are available now.
947 synchronized (mAsecMountSet) {
948 mAsecMountSet.clear();
949 }
San Mehatb1043402010-02-05 08:26:50 -0800950 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800951 } catch (NativeDaemonConnectorException e) {
952 // Don't worry about mismatch in PackageManager since the
953 // call back will handle the status changes any way.
954 int code = e.getCode();
955 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800956 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800957 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
958 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800959 } else {
San Mehatb1043402010-02-05 08:26:50 -0800960 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800961 }
962 }
963 }
964
965 private int doFormatVolume(String path) {
966 try {
967 String cmd = String.format("volume format %s", path);
968 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800969 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800970 } catch (NativeDaemonConnectorException e) {
971 int code = e.getCode();
972 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800973 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800974 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800975 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800976 } else {
San Mehatb1043402010-02-05 08:26:50 -0800977 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800978 }
979 }
980 }
981
San Mehatb1043402010-02-05 08:26:50 -0800982 private boolean doGetVolumeShared(String path, String method) {
983 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700984 ArrayList<String> rsp;
985
986 try {
987 rsp = mConnector.doCommand(cmd);
988 } catch (NativeDaemonConnectorException ex) {
989 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
990 return false;
991 }
San Mehatb1043402010-02-05 08:26:50 -0800992
993 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700994 String[] tok = line.split(" ");
995 if (tok.length < 3) {
996 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
997 return false;
998 }
999
San Mehatb1043402010-02-05 08:26:50 -08001000 int code;
1001 try {
1002 code = Integer.parseInt(tok[0]);
1003 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001004 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -08001005 return false;
1006 }
1007 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -07001008 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -08001009 } else {
San Mehata5078592010-03-25 09:36:54 -07001010 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -08001011 return false;
1012 }
1013 }
San Mehata5078592010-03-25 09:36:54 -07001014 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001015 return false;
1016 }
1017
San Mehat207e5382010-02-04 20:46:54 -08001018 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001019 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001020 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001021 return;
1022 }
1023
1024 synchronized (mListeners) {
1025 for (int i = mListeners.size() -1; i >= 0; i--) {
1026 MountServiceBinderListener bl = mListeners.get(i);
1027 try {
San Mehatb1043402010-02-05 08:26:50 -08001028 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001029 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001030 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001031 mListeners.remove(i);
1032 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001033 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001034 }
1035 }
1036 }
1037
San Mehat207e5382010-02-04 20:46:54 -08001038 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001039 sendUmsIntent(avail);
1040 } else {
1041 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001042 }
San Mehat2fe718a2010-03-11 12:01:49 -08001043
1044 final String path = Environment.getExternalStorageDirectory().getPath();
1045 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1046 /*
1047 * USB mass storage disconnected while enabled
1048 */
1049 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001050 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001051 public void run() {
1052 try {
1053 int rc;
San Mehata5078592010-03-25 09:36:54 -07001054 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001055 doShareUnshareVolume(path, "ums", false);
1056 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001057 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001058 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1059 path, rc));
1060 }
1061 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001062 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001063 }
1064 }
1065 }.start();
1066 }
San Mehat4270e1e2010-01-29 05:32:19 -08001067 }
1068
Mike Lockwooda5250c92011-05-23 13:44:04 -04001069 private void sendStorageIntent(String action, String path) {
1070 Intent intent = new Intent(action, Uri.parse("file://" + path));
1071 // add StorageVolume extra
1072 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1073 Slog.d(TAG, "sendStorageIntent " + intent);
1074 mContext.sendBroadcast(intent);
1075 }
1076
San Mehat6a965af22010-02-24 17:47:30 -08001077 private void sendUmsIntent(boolean c) {
1078 mContext.sendBroadcast(
1079 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1080 }
1081
San Mehat207e5382010-02-04 20:46:54 -08001082 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001083 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1084 throw new SecurityException(String.format("Requires %s permission", perm));
1085 }
1086 }
1087
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001088 // Storage list XML tags
1089 private static final String TAG_STORAGE_LIST = "StorageList";
1090 private static final String TAG_STORAGE = "storage";
1091
1092 private void readStorageList(Resources resources) {
1093 int id = com.android.internal.R.xml.storage_list;
1094 XmlResourceParser parser = resources.getXml(id);
1095 AttributeSet attrs = Xml.asAttributeSet(parser);
1096
1097 try {
1098 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1099 while (true) {
1100 XmlUtils.nextElement(parser);
1101
1102 String element = parser.getName();
1103 if (element == null) break;
1104
1105 if (TAG_STORAGE.equals(element)) {
1106 TypedArray a = resources.obtainAttributes(attrs,
1107 com.android.internal.R.styleable.Storage);
1108
1109 CharSequence path = a.getText(
1110 com.android.internal.R.styleable.Storage_mountPoint);
1111 CharSequence description = a.getText(
1112 com.android.internal.R.styleable.Storage_storageDescription);
1113 boolean primary = a.getBoolean(
1114 com.android.internal.R.styleable.Storage_primary, false);
1115 boolean removable = a.getBoolean(
1116 com.android.internal.R.styleable.Storage_removable, false);
1117 boolean emulated = a.getBoolean(
1118 com.android.internal.R.styleable.Storage_emulated, false);
1119 int mtpReserve = a.getInt(
1120 com.android.internal.R.styleable.Storage_mtpReserve, 0);
1121
1122 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1123 " primary: " + primary + " removable: " + removable +
1124 " emulated: " + emulated + " mtpReserve: " + mtpReserve);
1125 if (path == null || description == null) {
1126 Slog.e(TAG, "path or description is null in readStorageList");
1127 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001128 String pathString = path.toString();
1129 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001130 description.toString(), removable, emulated, mtpReserve);
1131 if (primary) {
1132 if (mPrimaryVolume == null) {
1133 mPrimaryVolume = volume;
1134 } else {
1135 Slog.e(TAG, "multiple primary volumes in storage list");
1136 }
1137 }
1138 if (mPrimaryVolume == volume) {
1139 // primay volume must be first
1140 mVolumes.add(0, volume);
1141 } else {
1142 mVolumes.add(volume);
1143 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001144 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001145 }
1146 a.recycle();
1147 }
1148 }
1149 } catch (XmlPullParserException e) {
1150 throw new RuntimeException(e);
1151 } catch (IOException e) {
1152 throw new RuntimeException(e);
1153 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001154 // compute storage ID for each volume
1155 int length = mVolumes.size();
1156 for (int i = 0; i < length; i++) {
1157 mVolumes.get(i).setStorageId(i);
1158 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001159 parser.close();
1160 }
1161 }
1162
San Mehat4270e1e2010-01-29 05:32:19 -08001163 /**
San Mehat207e5382010-02-04 20:46:54 -08001164 * Constructs a new MountService instance
1165 *
1166 * @param context Binder context for this service
1167 */
1168 public MountService(Context context) {
1169 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001170 Resources resources = context.getResources();
1171 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001172
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001173 if (mPrimaryVolume != null) {
1174 mExternalStoragePath = mPrimaryVolume.getPath();
1175 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1176 if (mEmulateExternalStorage) {
1177 Slog.d(TAG, "using emulated external storage");
1178 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1179 }
Mike Lockwood03559752010-07-19 18:25:03 -04001180 }
1181
San Mehat207e5382010-02-04 20:46:54 -08001182 // XXX: This will go away soon in favor of IMountServiceObserver
1183 mPms = (PackageManagerService) ServiceManager.getService("package");
1184
1185 mContext.registerReceiver(mBroadcastReceiver,
1186 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1187
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001188 mHandlerThread = new HandlerThread("MountService");
1189 mHandlerThread.start();
1190 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1191
Kenny Roota02b8b02010-08-05 16:14:17 -07001192 // Add OBB Action Handler to MountService thread.
1193 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1194
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001195 /*
1196 * Vold does not run in the simulator, so pretend the connector thread
1197 * ran and did its thing.
1198 */
1199 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1200 mReady = true;
1201 mUmsEnabling = true;
1202 return;
1203 }
1204
Kenny Root305bcbf2010-09-03 07:56:38 -07001205 /*
1206 * Create the connection to vold with a maximum queue of twice the
1207 * amount of containers we'd ever expect to have. This keeps an
1208 * "asec list" from blocking a thread repeatedly.
1209 */
1210 mConnector = new NativeDaemonConnector(this, "vold",
1211 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001212 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001213 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001214 thread.start();
1215 }
1216
1217 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001218 * Exposed API calls below here
1219 */
1220
1221 public void registerListener(IMountServiceListener listener) {
1222 synchronized (mListeners) {
1223 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1224 try {
1225 listener.asBinder().linkToDeath(bl, 0);
1226 mListeners.add(bl);
1227 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001228 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001229 }
1230 }
1231 }
1232
1233 public void unregisterListener(IMountServiceListener listener) {
1234 synchronized (mListeners) {
1235 for(MountServiceBinderListener bl : mListeners) {
1236 if (bl.mListener == listener) {
1237 mListeners.remove(mListeners.indexOf(bl));
1238 return;
1239 }
1240 }
1241 }
1242 }
1243
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001244 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001245 validatePermission(android.Manifest.permission.SHUTDOWN);
1246
San Mehata5078592010-03-25 09:36:54 -07001247 Slog.i(TAG, "Shutting down");
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001248 synchronized (mVolumeStates) {
1249 for (String path : mVolumeStates.keySet()) {
1250 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001251
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001252 if (state.equals(Environment.MEDIA_SHARED)) {
1253 /*
1254 * If the media is currently shared, unshare it.
1255 * XXX: This is still dangerous!. We should not
1256 * be rebooting at *all* if UMS is enabled, since
1257 * the UMS host could have dirty FAT cache entries
1258 * yet to flush.
1259 */
1260 setUsbMassStorageEnabled(false);
1261 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1262 /*
1263 * If the media is being checked, then we need to wait for
1264 * it to complete before being able to proceed.
1265 */
1266 // XXX: @hackbod - Should we disable the ANR timer here?
1267 int retries = 30;
1268 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1269 try {
1270 Thread.sleep(1000);
1271 } catch (InterruptedException iex) {
1272 Slog.e(TAG, "Interrupted while waiting for media", iex);
1273 break;
1274 }
1275 state = Environment.getExternalStorageState();
1276 }
1277 if (retries == 0) {
1278 Slog.e(TAG, "Timed out waiting for media to check");
1279 }
San Mehat91c77612010-01-07 10:39:41 -08001280 }
San Mehat91c77612010-01-07 10:39:41 -08001281
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001282 if (state.equals(Environment.MEDIA_MOUNTED)) {
1283 // Post a unmount message.
1284 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1285 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1286 } else if (observer != null) {
1287 /*
1288 * Observer is waiting for onShutDownComplete when we are done.
1289 * Since nothing will be done send notification directly so shutdown
1290 * sequence can continue.
1291 */
1292 try {
1293 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1294 } catch (RemoteException e) {
1295 Slog.w(TAG, "RemoteException when shutting down");
1296 }
1297 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001298 }
San Mehat4270e1e2010-01-29 05:32:19 -08001299 }
1300 }
1301
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001302 private boolean getUmsEnabling() {
1303 synchronized (mListeners) {
1304 return mUmsEnabling;
1305 }
1306 }
1307
1308 private void setUmsEnabling(boolean enable) {
1309 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001310 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001311 }
1312 }
1313
San Mehatb1043402010-02-05 08:26:50 -08001314 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001315 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001316
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001317 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001318 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001319 }
San Mehatb1043402010-02-05 08:26:50 -08001320 return doGetShareMethodAvailable("ums");
1321 }
1322
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001323 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001324 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001325 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001326
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001327 // TODO: Add support for multiple share methods
1328
1329 /*
1330 * If the volume is mounted and we're enabling then unmount it
1331 */
1332 String path = Environment.getExternalStorageDirectory().getPath();
1333 String vs = getVolumeState(path);
1334 String method = "ums";
1335 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1336 // Override for isUsbMassStorageEnabled()
1337 setUmsEnabling(enable);
1338 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1339 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1340 // Clear override
1341 setUmsEnabling(false);
1342 }
1343 /*
1344 * If we disabled UMS then mount the volume
1345 */
1346 if (!enable) {
1347 doShareUnshareVolume(path, method, enable);
1348 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001349 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001350 " after disabling share method " + method);
1351 /*
1352 * Even though the mount failed, the unshare didn't so don't indicate an error.
1353 * The mountVolume() call will have set the storage state and sent the necessary
1354 * broadcasts.
1355 */
1356 }
1357 }
San Mehatb1043402010-02-05 08:26:50 -08001358 }
1359
1360 public boolean isUsbMassStorageEnabled() {
1361 waitForReady();
1362 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001364
San Mehat7fd0fee2009-12-17 07:12:23 -08001365 /**
1366 * @return state of the volume at the specified mount point
1367 */
San Mehat4270e1e2010-01-29 05:32:19 -08001368 public String getVolumeState(String mountPoint) {
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001369 synchronized (mVolumeStates) {
1370 String state = mVolumeStates.get(mountPoint);
1371 if (state == null) {
1372 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1373 throw new IllegalArgumentException();
1374 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001375
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001376 return state;
1377 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001378 }
1379
Kenny Roote1ff2142010-10-12 11:20:01 -07001380 public boolean isExternalStorageEmulated() {
1381 return mEmulateExternalStorage;
1382 }
1383
San Mehat4270e1e2010-01-29 05:32:19 -08001384 public int mountVolume(String path) {
1385 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001386
San Mehat207e5382010-02-04 20:46:54 -08001387 waitForReady();
1388 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001391 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001392 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001393 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001395 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001396 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001397 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1398 Environment.MEDIA_REMOVED.equals(volState) ||
1399 Environment.MEDIA_SHARED.equals(volState) ||
1400 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1401 // Media already unmounted or cannot be unmounted.
1402 // TODO return valid return code when adding observer call back.
1403 return;
1404 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001405 UnmountCallBack ucb = new UnmountCallBack(path, force);
1406 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408
San Mehat4270e1e2010-01-29 05:32:19 -08001409 public int formatVolume(String path) {
1410 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001411 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001412
San Mehat207e5382010-02-04 20:46:54 -08001413 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
San Mehatc1b4ce92010-02-16 17:13:03 -08001416 public int []getStorageUsers(String path) {
1417 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1418 waitForReady();
1419 try {
1420 String[] r = mConnector.doListCommand(
1421 String.format("storage users %s", path),
1422 VoldResponseCode.StorageUsersListResult);
1423 // FMT: <pid> <process name>
1424 int[] data = new int[r.length];
1425 for (int i = 0; i < r.length; i++) {
1426 String []tok = r[i].split(" ");
1427 try {
1428 data[i] = Integer.parseInt(tok[0]);
1429 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001430 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001431 return new int[0];
1432 }
1433 }
1434 return data;
1435 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001436 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001437 return new int[0];
1438 }
1439 }
1440
San Mehatb1043402010-02-05 08:26:50 -08001441 private void warnOnNotMounted() {
1442 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001443 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001444 }
1445 }
1446
San Mehat4270e1e2010-01-29 05:32:19 -08001447 public String[] getSecureContainerList() {
1448 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001449 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001450 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001451
San Mehat4270e1e2010-01-29 05:32:19 -08001452 try {
1453 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1454 } catch (NativeDaemonConnectorException e) {
1455 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457 }
San Mehat36972292010-01-06 11:06:32 -08001458
San Mehat4270e1e2010-01-29 05:32:19 -08001459 public int createSecureContainer(String id, int sizeMb, String fstype,
1460 String key, int ownerUid) {
1461 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001462 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001463 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001464
San Mehatb1043402010-02-05 08:26:50 -08001465 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001466 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1467 try {
1468 mConnector.doCommand(cmd);
1469 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001470 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001471 }
San Mehata181b212010-02-11 06:50:20 -08001472
1473 if (rc == StorageResultCode.OperationSucceeded) {
1474 synchronized (mAsecMountSet) {
1475 mAsecMountSet.add(id);
1476 }
1477 }
San Mehat4270e1e2010-01-29 05:32:19 -08001478 return rc;
San Mehat36972292010-01-06 11:06:32 -08001479 }
1480
San Mehat4270e1e2010-01-29 05:32:19 -08001481 public int finalizeSecureContainer(String id) {
1482 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001483 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001484
San Mehatb1043402010-02-05 08:26:50 -08001485 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001486 try {
1487 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001488 /*
1489 * Finalization does a remount, so no need
1490 * to update mAsecMountSet
1491 */
San Mehat4270e1e2010-01-29 05:32:19 -08001492 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001493 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001494 }
San Mehat4270e1e2010-01-29 05:32:19 -08001495 return rc;
San Mehat36972292010-01-06 11:06:32 -08001496 }
1497
San Mehatd9709982010-02-18 11:43:03 -08001498 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001499 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001500 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001501 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001502
Kenny Rootaa485402010-09-14 14:49:41 -07001503 /*
1504 * Force a GC to make sure AssetManagers in other threads of the
1505 * system_server are cleaned up. We have to do this since AssetManager
1506 * instances are kept as a WeakReference and it's possible we have files
1507 * open on the external storage.
1508 */
1509 Runtime.getRuntime().gc();
1510
San Mehatb1043402010-02-05 08:26:50 -08001511 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001512 try {
San Mehatd9709982010-02-18 11:43:03 -08001513 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001514 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001515 int code = e.getCode();
1516 if (code == VoldResponseCode.OpFailedStorageBusy) {
1517 rc = StorageResultCode.OperationFailedStorageBusy;
1518 } else {
1519 rc = StorageResultCode.OperationFailedInternalError;
1520 }
San Mehat02735bc2010-01-26 15:18:08 -08001521 }
San Mehata181b212010-02-11 06:50:20 -08001522
1523 if (rc == StorageResultCode.OperationSucceeded) {
1524 synchronized (mAsecMountSet) {
1525 if (mAsecMountSet.contains(id)) {
1526 mAsecMountSet.remove(id);
1527 }
1528 }
1529 }
1530
San Mehat4270e1e2010-01-29 05:32:19 -08001531 return rc;
San Mehat36972292010-01-06 11:06:32 -08001532 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001533
San Mehat4270e1e2010-01-29 05:32:19 -08001534 public int mountSecureContainer(String id, String key, int ownerUid) {
1535 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001536 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001537 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001538
San Mehata181b212010-02-11 06:50:20 -08001539 synchronized (mAsecMountSet) {
1540 if (mAsecMountSet.contains(id)) {
1541 return StorageResultCode.OperationFailedStorageMounted;
1542 }
1543 }
1544
San Mehatb1043402010-02-05 08:26:50 -08001545 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001546 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1547 try {
1548 mConnector.doCommand(cmd);
1549 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001550 int code = e.getCode();
1551 if (code != VoldResponseCode.OpFailedStorageBusy) {
1552 rc = StorageResultCode.OperationFailedInternalError;
1553 }
San Mehat02735bc2010-01-26 15:18:08 -08001554 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001555
1556 if (rc == StorageResultCode.OperationSucceeded) {
1557 synchronized (mAsecMountSet) {
1558 mAsecMountSet.add(id);
1559 }
1560 }
San Mehat4270e1e2010-01-29 05:32:19 -08001561 return rc;
San Mehat36972292010-01-06 11:06:32 -08001562 }
1563
San Mehatd9709982010-02-18 11:43:03 -08001564 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001565 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001566 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001567 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001568
San Mehat6cdd9c02010-02-09 14:45:20 -08001569 synchronized (mAsecMountSet) {
1570 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001571 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001572 }
1573 }
1574
Kenny Rootaa485402010-09-14 14:49:41 -07001575 /*
1576 * Force a GC to make sure AssetManagers in other threads of the
1577 * system_server are cleaned up. We have to do this since AssetManager
1578 * instances are kept as a WeakReference and it's possible we have files
1579 * open on the external storage.
1580 */
1581 Runtime.getRuntime().gc();
1582
San Mehatb1043402010-02-05 08:26:50 -08001583 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001584 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001585 try {
1586 mConnector.doCommand(cmd);
1587 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001588 int code = e.getCode();
1589 if (code == VoldResponseCode.OpFailedStorageBusy) {
1590 rc = StorageResultCode.OperationFailedStorageBusy;
1591 } else {
1592 rc = StorageResultCode.OperationFailedInternalError;
1593 }
San Mehat02735bc2010-01-26 15:18:08 -08001594 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001595
1596 if (rc == StorageResultCode.OperationSucceeded) {
1597 synchronized (mAsecMountSet) {
1598 mAsecMountSet.remove(id);
1599 }
1600 }
San Mehat4270e1e2010-01-29 05:32:19 -08001601 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001602 }
1603
San Mehat6cdd9c02010-02-09 14:45:20 -08001604 public boolean isSecureContainerMounted(String id) {
1605 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1606 waitForReady();
1607 warnOnNotMounted();
1608
1609 synchronized (mAsecMountSet) {
1610 return mAsecMountSet.contains(id);
1611 }
1612 }
1613
San Mehat4270e1e2010-01-29 05:32:19 -08001614 public int renameSecureContainer(String oldId, String newId) {
1615 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001616 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001617 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001618
San Mehata181b212010-02-11 06:50:20 -08001619 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001620 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001621 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001622 * changed while active, we must ensure both ids are not currently mounted.
1623 */
1624 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001625 return StorageResultCode.OperationFailedStorageMounted;
1626 }
1627 }
1628
San Mehatb1043402010-02-05 08:26:50 -08001629 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001630 String cmd = String.format("asec rename %s %s", oldId, newId);
1631 try {
1632 mConnector.doCommand(cmd);
1633 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001634 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001635 }
San Mehata181b212010-02-11 06:50:20 -08001636
San Mehat4270e1e2010-01-29 05:32:19 -08001637 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001638 }
1639
San Mehat4270e1e2010-01-29 05:32:19 -08001640 public String getSecureContainerPath(String id) {
1641 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001642 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001643 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001644
San Mehat2d66cef2010-03-23 11:12:52 -07001645 try {
1646 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1647 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001648 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001649 if (code != VoldResponseCode.AsecPathResult) {
1650 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1651 }
1652 return tok[1];
1653 } catch (NativeDaemonConnectorException e) {
1654 int code = e.getCode();
1655 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1656 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001657 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001658 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001659 }
1660 }
San Mehat22dd86e2010-01-12 12:21:18 -08001661 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001662
1663 public void finishMediaUpdate() {
1664 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1665 }
Kenny Root02c87302010-07-01 08:10:18 -07001666
Kenny Roota02b8b02010-08-05 16:14:17 -07001667 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1668 if (callerUid == android.os.Process.SYSTEM_UID) {
1669 return true;
1670 }
1671
Kenny Root02c87302010-07-01 08:10:18 -07001672 if (packageName == null) {
1673 return false;
1674 }
1675
1676 final int packageUid = mPms.getPackageUid(packageName);
1677
1678 if (DEBUG_OBB) {
1679 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1680 packageUid + ", callerUid = " + callerUid);
1681 }
1682
1683 return callerUid == packageUid;
1684 }
1685
1686 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001687 if (filename == null) {
1688 throw new IllegalArgumentException("filename cannot be null");
1689 }
1690
Kenny Root02c87302010-07-01 08:10:18 -07001691 waitForReady();
1692 warnOnNotMounted();
1693
Kenny Root02c87302010-07-01 08:10:18 -07001694 try {
1695 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1696 String []tok = rsp.get(0).split(" ");
1697 int code = Integer.parseInt(tok[0]);
1698 if (code != VoldResponseCode.AsecPathResult) {
1699 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1700 }
1701 return tok[1];
1702 } catch (NativeDaemonConnectorException e) {
1703 int code = e.getCode();
1704 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001705 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001706 } else {
1707 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1708 }
1709 }
1710 }
1711
1712 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001713 if (filename == null) {
1714 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001715 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001716
1717 synchronized (mObbMounts) {
1718 return mObbPathToStateMap.containsKey(filename);
1719 }
Kenny Root02c87302010-07-01 08:10:18 -07001720 }
1721
Kenny Rootaf9d6672010-10-08 09:21:39 -07001722 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001723 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001724 if (filename == null) {
1725 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001726 }
1727
1728 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001729 throw new IllegalArgumentException("token cannot be null");
1730 }
1731
Kenny Rootaf9d6672010-10-08 09:21:39 -07001732 final int callerUid = Binder.getCallingUid();
1733 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1734 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001735 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1736
1737 if (DEBUG_OBB)
1738 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001739 }
1740
Kenny Rootaf9d6672010-10-08 09:21:39 -07001741 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1742 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001743 if (filename == null) {
1744 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001745 }
1746
Kenny Rootaf9d6672010-10-08 09:21:39 -07001747 final int callerUid = Binder.getCallingUid();
1748 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1749 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001750 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001751
Kenny Roota02b8b02010-08-05 16:14:17 -07001752 if (DEBUG_OBB)
1753 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1754 }
1755
Jason parks5af0b912010-11-29 09:05:25 -06001756 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001757 if (TextUtils.isEmpty(password)) {
1758 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001759 }
1760
Jason parks8888c592011-01-20 22:46:41 -06001761 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1762 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001763
1764 waitForReady();
1765
1766 if (DEBUG_EVENTS) {
1767 Slog.i(TAG, "decrypting storage...");
1768 }
1769
1770 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001771 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001772 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001773
Jason parksf7b3cd42011-01-27 09:28:25 -06001774 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001775 return -1;
1776 }
1777
Jason parksf7b3cd42011-01-27 09:28:25 -06001778 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001779
1780 if (code == 0) {
1781 // Decrypt was successful. Post a delayed message before restarting in order
1782 // to let the UI to clear itself
1783 mHandler.postDelayed(new Runnable() {
1784 public void run() {
1785 mConnector.doCommand(String.format("cryptfs restart"));
1786 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001787 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001788 }
1789
1790 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001791 } catch (NativeDaemonConnectorException e) {
1792 // Decryption failed
1793 return e.getCode();
1794 }
Jason parks5af0b912010-11-29 09:05:25 -06001795 }
1796
Jason parks56aa5322011-01-07 09:01:15 -06001797 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001798 if (TextUtils.isEmpty(password)) {
1799 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001800 }
1801
Jason parks8888c592011-01-20 22:46:41 -06001802 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1803 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001804
1805 waitForReady();
1806
1807 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001808 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001809 }
1810
1811 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001812 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001813 } catch (NativeDaemonConnectorException e) {
1814 // Encryption failed
1815 return e.getCode();
1816 }
1817
1818 return 0;
1819 }
1820
Jason parksf7b3cd42011-01-27 09:28:25 -06001821 public int changeEncryptionPassword(String password) {
1822 if (TextUtils.isEmpty(password)) {
1823 throw new IllegalArgumentException("password cannot be empty");
1824 }
1825
1826 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1827 "no permission to access the crypt keeper");
1828
1829 waitForReady();
1830
1831 if (DEBUG_EVENTS) {
1832 Slog.i(TAG, "changing encryption password...");
1833 }
1834
1835 try {
1836 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1837
1838 String[] tokens = response.get(0).split(" ");
1839
1840 if (tokens == null || tokens.length != 2) {
1841 return -1;
1842 }
1843
1844 return Integer.parseInt(tokens[1]);
1845 } catch (NativeDaemonConnectorException e) {
1846 // Encryption failed
1847 return e.getCode();
1848 }
1849 }
1850
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001851 public Parcelable[] getVolumeList() {
1852 synchronized(mVolumes) {
1853 int size = mVolumes.size();
1854 Parcelable[] result = new Parcelable[size];
1855 for (int i = 0; i < size; i++) {
1856 result[i] = mVolumes.get(i);
Mike Lockwoodd967f462011-03-24 08:12:30 -07001857 }
1858 return result;
1859 }
1860 }
1861
Kenny Rootaf9d6672010-10-08 09:21:39 -07001862 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1863 final IBinder binder = obbState.getBinder();
1864 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001865
Kenny Rootaf9d6672010-10-08 09:21:39 -07001866 if (obbStates == null) {
1867 obbStates = new ArrayList<ObbState>();
1868 mObbMounts.put(binder, obbStates);
1869 } else {
1870 for (final ObbState o : obbStates) {
1871 if (o.filename.equals(obbState.filename)) {
1872 throw new IllegalStateException("Attempt to add ObbState twice. "
1873 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001874 }
1875 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001876 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001877
1878 obbStates.add(obbState);
1879 try {
1880 obbState.link();
1881 } catch (RemoteException e) {
1882 /*
1883 * The binder died before we could link it, so clean up our state
1884 * and return failure.
1885 */
1886 obbStates.remove(obbState);
1887 if (obbStates.isEmpty()) {
1888 mObbMounts.remove(binder);
1889 }
1890
1891 // Rethrow the error so mountObb can get it
1892 throw e;
1893 }
1894
1895 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001896 }
1897
Kenny Rootaf9d6672010-10-08 09:21:39 -07001898 private void removeObbStateLocked(ObbState obbState) {
1899 final IBinder binder = obbState.getBinder();
1900 final List<ObbState> obbStates = mObbMounts.get(binder);
1901 if (obbStates != null) {
1902 if (obbStates.remove(obbState)) {
1903 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001904 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001905 if (obbStates.isEmpty()) {
1906 mObbMounts.remove(binder);
1907 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001908 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001909
Kenny Rootaf9d6672010-10-08 09:21:39 -07001910 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001911 }
1912
Kenny Roota02b8b02010-08-05 16:14:17 -07001913 private class ObbActionHandler extends Handler {
1914 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001915 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001916
1917 ObbActionHandler(Looper l) {
1918 super(l);
1919 }
1920
1921 @Override
1922 public void handleMessage(Message msg) {
1923 switch (msg.what) {
1924 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001925 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001926
1927 if (DEBUG_OBB)
1928 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1929
1930 // If a bind was already initiated we don't really
1931 // need to do anything. The pending install
1932 // will be processed later on.
1933 if (!mBound) {
1934 // If this is the only one pending we might
1935 // have to bind to the service again.
1936 if (!connectToService()) {
1937 Slog.e(TAG, "Failed to bind to media container service");
1938 action.handleError();
1939 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001940 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001941 }
Kenny Root735de3b2010-09-30 14:11:39 -07001942
Kenny Root735de3b2010-09-30 14:11:39 -07001943 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 break;
1945 }
1946 case OBB_MCS_BOUND: {
1947 if (DEBUG_OBB)
1948 Slog.i(TAG, "OBB_MCS_BOUND");
1949 if (msg.obj != null) {
1950 mContainerService = (IMediaContainerService) msg.obj;
1951 }
1952 if (mContainerService == null) {
1953 // Something seriously wrong. Bail out
1954 Slog.e(TAG, "Cannot bind to media container service");
1955 for (ObbAction action : mActions) {
1956 // Indicate service bind error
1957 action.handleError();
1958 }
1959 mActions.clear();
1960 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001961 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001962 if (action != null) {
1963 action.execute(this);
1964 }
1965 } else {
1966 // Should never happen ideally.
1967 Slog.w(TAG, "Empty queue");
1968 }
1969 break;
1970 }
1971 case OBB_MCS_RECONNECT: {
1972 if (DEBUG_OBB)
1973 Slog.i(TAG, "OBB_MCS_RECONNECT");
1974 if (mActions.size() > 0) {
1975 if (mBound) {
1976 disconnectService();
1977 }
1978 if (!connectToService()) {
1979 Slog.e(TAG, "Failed to bind to media container service");
1980 for (ObbAction action : mActions) {
1981 // Indicate service bind error
1982 action.handleError();
1983 }
1984 mActions.clear();
1985 }
1986 }
1987 break;
1988 }
1989 case OBB_MCS_UNBIND: {
1990 if (DEBUG_OBB)
1991 Slog.i(TAG, "OBB_MCS_UNBIND");
1992
1993 // Delete pending install
1994 if (mActions.size() > 0) {
1995 mActions.remove(0);
1996 }
1997 if (mActions.size() == 0) {
1998 if (mBound) {
1999 disconnectService();
2000 }
2001 } else {
2002 // There are more pending requests in queue.
2003 // Just post MCS_BOUND message to trigger processing
2004 // of next pending install.
2005 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2006 }
2007 break;
2008 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002009 case OBB_FLUSH_MOUNT_STATE: {
2010 final String path = (String) msg.obj;
2011
2012 if (DEBUG_OBB)
2013 Slog.i(TAG, "Flushing all OBB state for path " + path);
2014
2015 synchronized (mObbMounts) {
2016 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2017
2018 final Iterator<Entry<String, ObbState>> i =
2019 mObbPathToStateMap.entrySet().iterator();
2020 while (i.hasNext()) {
2021 final Entry<String, ObbState> obbEntry = i.next();
2022
2023 /*
2024 * If this entry's source file is in the volume path
2025 * that got unmounted, remove it because it's no
2026 * longer valid.
2027 */
2028 if (obbEntry.getKey().startsWith(path)) {
2029 obbStatesToRemove.add(obbEntry.getValue());
2030 }
2031 }
2032
2033 for (final ObbState obbState : obbStatesToRemove) {
2034 if (DEBUG_OBB)
2035 Slog.i(TAG, "Removing state for " + obbState.filename);
2036
2037 removeObbStateLocked(obbState);
2038
2039 try {
2040 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2041 OnObbStateChangeListener.UNMOUNTED);
2042 } catch (RemoteException e) {
2043 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2044 + obbState.filename);
2045 }
2046 }
2047 }
2048 break;
2049 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002050 }
2051 }
2052
2053 private boolean connectToService() {
2054 if (DEBUG_OBB)
2055 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2056
2057 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2058 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2059 mBound = true;
2060 return true;
2061 }
2062 return false;
2063 }
2064
2065 private void disconnectService() {
2066 mContainerService = null;
2067 mBound = false;
2068 mContext.unbindService(mDefContainerConn);
2069 }
2070 }
2071
2072 abstract class ObbAction {
2073 private static final int MAX_RETRIES = 3;
2074 private int mRetries;
2075
2076 ObbState mObbState;
2077
2078 ObbAction(ObbState obbState) {
2079 mObbState = obbState;
2080 }
2081
2082 public void execute(ObbActionHandler handler) {
2083 try {
2084 if (DEBUG_OBB)
2085 Slog.i(TAG, "Starting to execute action: " + this.toString());
2086 mRetries++;
2087 if (mRetries > MAX_RETRIES) {
2088 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002089 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002090 handleError();
2091 return;
2092 } else {
2093 handleExecute();
2094 if (DEBUG_OBB)
2095 Slog.i(TAG, "Posting install MCS_UNBIND");
2096 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2097 }
2098 } catch (RemoteException e) {
2099 if (DEBUG_OBB)
2100 Slog.i(TAG, "Posting install MCS_RECONNECT");
2101 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2102 } catch (Exception e) {
2103 if (DEBUG_OBB)
2104 Slog.d(TAG, "Error handling OBB action", e);
2105 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002106 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002107 }
2108 }
2109
Kenny Root05105f72010-09-22 17:29:43 -07002110 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002111 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002112
2113 protected ObbInfo getObbInfo() throws IOException {
2114 ObbInfo obbInfo;
2115 try {
2116 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2117 } catch (RemoteException e) {
2118 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2119 + mObbState.filename);
2120 obbInfo = null;
2121 }
2122 if (obbInfo == null) {
2123 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2124 }
2125 return obbInfo;
2126 }
2127
Kenny Rootaf9d6672010-10-08 09:21:39 -07002128 protected void sendNewStatusOrIgnore(int status) {
2129 if (mObbState == null || mObbState.token == null) {
2130 return;
2131 }
2132
Kenny Root38cf8862010-09-26 14:18:51 -07002133 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002134 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002135 } catch (RemoteException e) {
2136 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2137 }
2138 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002139 }
2140
2141 class MountObbAction extends ObbAction {
2142 private String mKey;
2143
2144 MountObbAction(ObbState obbState, String key) {
2145 super(obbState);
2146 mKey = key;
2147 }
2148
Jason parks5af0b912010-11-29 09:05:25 -06002149 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002150 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002151 waitForReady();
2152 warnOnNotMounted();
2153
Kenny Root38cf8862010-09-26 14:18:51 -07002154 final ObbInfo obbInfo = getObbInfo();
2155
Kenny Roota02b8b02010-08-05 16:14:17 -07002156 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002157 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2158 + " which is owned by " + obbInfo.packageName);
2159 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2160 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002161 }
2162
Kenny Rootaf9d6672010-10-08 09:21:39 -07002163 final boolean isMounted;
2164 synchronized (mObbMounts) {
2165 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2166 }
2167 if (isMounted) {
2168 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2169 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2170 return;
2171 }
2172
2173 /*
2174 * The filename passed in might not be the canonical name, so just
2175 * set the filename to the canonicalized version.
2176 */
2177 mObbState.filename = obbInfo.filename;
2178
2179 final String hashedKey;
2180 if (mKey == null) {
2181 hashedKey = "none";
2182 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002183 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002184 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2185
2186 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2187 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2188 SecretKey key = factory.generateSecret(ks);
2189 BigInteger bi = new BigInteger(key.getEncoded());
2190 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002191 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002192 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2193 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2194 return;
2195 } catch (InvalidKeySpecException e) {
2196 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2197 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002198 return;
2199 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002200 }
Kenny Root38cf8862010-09-26 14:18:51 -07002201
Kenny Rootaf9d6672010-10-08 09:21:39 -07002202 int rc = StorageResultCode.OperationSucceeded;
2203 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2204 mObbState.callerUid);
2205 try {
2206 mConnector.doCommand(cmd);
2207 } catch (NativeDaemonConnectorException e) {
2208 int code = e.getCode();
2209 if (code != VoldResponseCode.OpFailedStorageBusy) {
2210 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002211 }
2212 }
2213
Kenny Rootaf9d6672010-10-08 09:21:39 -07002214 if (rc == StorageResultCode.OperationSucceeded) {
2215 if (DEBUG_OBB)
2216 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2217
2218 synchronized (mObbMounts) {
2219 addObbStateLocked(mObbState);
2220 }
2221
2222 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002223 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002224 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002225
Kenny Rootaf9d6672010-10-08 09:21:39 -07002226 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002227 }
2228 }
2229
Jason parks5af0b912010-11-29 09:05:25 -06002230 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002231 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002232 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002233 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002234
2235 @Override
2236 public String toString() {
2237 StringBuilder sb = new StringBuilder();
2238 sb.append("MountObbAction{");
2239 sb.append("filename=");
2240 sb.append(mObbState.filename);
2241 sb.append(",callerUid=");
2242 sb.append(mObbState.callerUid);
2243 sb.append(",token=");
2244 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002245 sb.append(",binder=");
2246 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002247 sb.append('}');
2248 return sb.toString();
2249 }
2250 }
2251
2252 class UnmountObbAction extends ObbAction {
2253 private boolean mForceUnmount;
2254
2255 UnmountObbAction(ObbState obbState, boolean force) {
2256 super(obbState);
2257 mForceUnmount = force;
2258 }
2259
Jason parks5af0b912010-11-29 09:05:25 -06002260 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002261 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002262 waitForReady();
2263 warnOnNotMounted();
2264
Kenny Root38cf8862010-09-26 14:18:51 -07002265 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002266
Kenny Rootaf9d6672010-10-08 09:21:39 -07002267 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002268 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002269 obbState = mObbPathToStateMap.get(obbInfo.filename);
2270 }
Kenny Root38cf8862010-09-26 14:18:51 -07002271
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272 if (obbState == null) {
2273 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2274 return;
2275 }
2276
2277 if (obbState.callerUid != mObbState.callerUid) {
2278 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2279 + " (owned by " + obbInfo.packageName + ")");
2280 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2281 return;
2282 }
2283
2284 mObbState.filename = obbInfo.filename;
2285
2286 int rc = StorageResultCode.OperationSucceeded;
2287 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2288 (mForceUnmount ? " force" : ""));
2289 try {
2290 mConnector.doCommand(cmd);
2291 } catch (NativeDaemonConnectorException e) {
2292 int code = e.getCode();
2293 if (code == VoldResponseCode.OpFailedStorageBusy) {
2294 rc = StorageResultCode.OperationFailedStorageBusy;
2295 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2296 // If it's not mounted then we've already won.
2297 rc = StorageResultCode.OperationSucceeded;
2298 } else {
2299 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002300 }
2301 }
2302
Kenny Rootaf9d6672010-10-08 09:21:39 -07002303 if (rc == StorageResultCode.OperationSucceeded) {
2304 synchronized (mObbMounts) {
2305 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002306 }
2307
Kenny Rootaf9d6672010-10-08 09:21:39 -07002308 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002309 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002310 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2311 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002312 }
2313 }
2314
Jason parks5af0b912010-11-29 09:05:25 -06002315 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002316 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002318 }
2319
2320 @Override
2321 public String toString() {
2322 StringBuilder sb = new StringBuilder();
2323 sb.append("UnmountObbAction{");
2324 sb.append("filename=");
2325 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2326 sb.append(",force=");
2327 sb.append(mForceUnmount);
2328 sb.append(",callerUid=");
2329 sb.append(mObbState.callerUid);
2330 sb.append(",token=");
2331 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002332 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002333 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002334 sb.append('}');
2335 return sb.toString();
2336 }
Kenny Root02c87302010-07-01 08:10:18 -07002337 }
Kenny Root38cf8862010-09-26 14:18:51 -07002338
2339 @Override
2340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2341 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2342 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2343 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2344 + " without permission " + android.Manifest.permission.DUMP);
2345 return;
2346 }
2347
Kenny Root38cf8862010-09-26 14:18:51 -07002348 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002349 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002350
Kenny Rootaf9d6672010-10-08 09:21:39 -07002351 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2352 while (binders.hasNext()) {
2353 Entry<IBinder, List<ObbState>> e = binders.next();
2354 pw.print(" Key="); pw.println(e.getKey().toString());
2355 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002356 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002357 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002358 }
2359 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002360
2361 pw.println("");
2362 pw.println(" mObbPathToStateMap:");
2363 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2364 while (maps.hasNext()) {
2365 final Entry<String, ObbState> e = maps.next();
2366 pw.print(" "); pw.print(e.getKey());
2367 pw.print(" -> "); pw.println(e.getValue().toString());
2368 }
Kenny Root38cf8862010-09-26 14:18:51 -07002369 }
2370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371}
2372