blob: 376d42f74c1504390f874209603ae64ce0ea8608 [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>();
162 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800163 private PackageManagerService mPms;
164 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800165 // Used as a lock for methods that register/unregister listeners.
166 final private ArrayList<MountServiceBinderListener> mListeners =
167 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800168 private boolean mBooted = false;
169 private boolean mReady = false;
170 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400171 // true if we should fake MEDIA_MOUNTED state for external storage
172 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800173
San Mehat6cdd9c02010-02-09 14:45:20 -0800174 /**
175 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800176 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800177 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800178 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800179
Kenny Root02c87302010-07-01 08:10:18 -0700180 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700181 * The size of the crypto algorithm key in bits for OBB files. Currently
182 * Twofish is used which takes 128-bit keys.
183 */
184 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
185
186 /**
187 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
188 * 1024 is reasonably secure and not too slow.
189 */
190 private static final int PBKDF2_HASH_ROUNDS = 1024;
191
192 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700193 * Mounted OBB tracking information. Used to track the current state of all
194 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700195 */
Kenny Root735de3b2010-09-30 14:11:39 -0700196 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700197 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
198
199 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700200 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700201 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700202 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700204 this.token = token;
205 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700206 }
207
208 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700209 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700210
211 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700212 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700213
Kenny Rootaf9d6672010-10-08 09:21:39 -0700214 // Token of remote Binder caller
215 final IObbActionListener token;
216
217 // Identifier to pass back to the token
218 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700219
Kenny Root735de3b2010-09-30 14:11:39 -0700220 public IBinder getBinder() {
221 return token.asBinder();
222 }
223
Kenny Roota02b8b02010-08-05 16:14:17 -0700224 @Override
225 public void binderDied() {
226 ObbAction action = new UnmountObbAction(this, true);
227 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700228 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700229
Kenny Root5919ac62010-10-05 09:49:40 -0700230 public void link() throws RemoteException {
231 getBinder().linkToDeath(this, 0);
232 }
233
234 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700235 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700236 }
Kenny Root38cf8862010-09-26 14:18:51 -0700237
238 @Override
239 public String toString() {
240 StringBuilder sb = new StringBuilder("ObbState{");
241 sb.append("filename=");
242 sb.append(filename);
243 sb.append(",token=");
244 sb.append(token.toString());
245 sb.append(",callerUid=");
246 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700247 sb.append('}');
248 return sb.toString();
249 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700250 }
251
252 // OBB Action Handler
253 final private ObbActionHandler mObbActionHandler;
254
255 // OBB action handler messages
256 private static final int OBB_RUN_ACTION = 1;
257 private static final int OBB_MCS_BOUND = 2;
258 private static final int OBB_MCS_UNBIND = 3;
259 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700260 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700261
262 /*
263 * Default Container Service information
264 */
265 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
266 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
267
268 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
269
270 class DefaultContainerConnection implements ServiceConnection {
271 public void onServiceConnected(ComponentName name, IBinder service) {
272 if (DEBUG_OBB)
273 Slog.i(TAG, "onServiceConnected");
274 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
275 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
276 }
277
278 public void onServiceDisconnected(ComponentName name) {
279 if (DEBUG_OBB)
280 Slog.i(TAG, "onServiceDisconnected");
281 }
282 };
283
284 // Used in the ObbActionHandler
285 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700286
287 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800288 private static final int H_UNMOUNT_PM_UPDATE = 1;
289 private static final int H_UNMOUNT_PM_DONE = 2;
290 private static final int H_UNMOUNT_MS = 3;
291 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
292 private static final int MAX_UNMOUNT_RETRIES = 4;
293
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800294 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700295 final String path;
296 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800297 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800298
299 UnmountCallBack(String path, boolean force) {
300 retries = 0;
301 this.path = path;
302 this.force = force;
303 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800304
305 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700306 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800307 doUnmountVolume(path, true);
308 }
309 }
310
311 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700312 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800313
314 UmsEnableCallBack(String path, String method, boolean force) {
315 super(path, force);
316 this.method = method;
317 }
318
319 @Override
320 void handleFinished() {
321 super.handleFinished();
322 doShareUnshareVolume(path, method, true);
323 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800324 }
325
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800326 class ShutdownCallBack extends UnmountCallBack {
327 IMountShutdownObserver observer;
328 ShutdownCallBack(String path, IMountShutdownObserver observer) {
329 super(path, true);
330 this.observer = observer;
331 }
332
333 @Override
334 void handleFinished() {
335 int ret = doUnmountVolume(path, true);
336 if (observer != null) {
337 try {
338 observer.onShutDownComplete(ret);
339 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700340 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800341 }
342 }
343 }
344 }
345
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400346 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800347 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700348 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800349
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400350 MountServiceHandler(Looper l) {
351 super(l);
352 }
353
Jason parks5af0b912010-11-29 09:05:25 -0600354 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800355 public void handleMessage(Message msg) {
356 switch (msg.what) {
357 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700358 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
360 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700361 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800362 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700363 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700364 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 mUpdatingStatus = true;
366 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800367 }
368 break;
369 }
370 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700371 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700372 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700373 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800374 int size = mForceUnmounts.size();
375 int sizeArr[] = new int[size];
376 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700377 // Kill processes holding references first
378 ActivityManagerService ams = (ActivityManagerService)
379 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 for (int i = 0; i < size; i++) {
381 UnmountCallBack ucb = mForceUnmounts.get(i);
382 String path = ucb.path;
383 boolean done = false;
384 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800385 done = true;
386 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 int pids[] = getStorageUsers(path);
388 if (pids == null || pids.length == 0) {
389 done = true;
390 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800391 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800392 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700393 // Confirm if file references have been freed.
394 pids = getStorageUsers(path);
395 if (pids == null || pids.length == 0) {
396 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800397 }
398 }
399 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700400 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
401 // Retry again
402 Slog.i(TAG, "Retrying to kill storage users again");
403 mHandler.sendMessageDelayed(
404 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
405 ucb.retries++),
406 RETRY_UNMOUNT_DELAY);
407 } else {
408 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
409 Slog.i(TAG, "Failed to unmount media inspite of " +
410 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
411 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800412 sizeArr[sizeArrN++] = i;
413 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
414 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800415 }
416 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800417 // Remove already processed elements from list.
418 for (int i = (sizeArrN-1); i >= 0; i--) {
419 mForceUnmounts.remove(sizeArr[i]);
420 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 break;
422 }
423 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700424 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800425 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800426 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800427 break;
428 }
429 }
430 }
431 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400432 final private HandlerThread mHandlerThread;
433 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800434
San Mehat207e5382010-02-04 20:46:54 -0800435 private void waitForReady() {
436 while (mReady == false) {
437 for (int retries = 5; retries > 0; retries--) {
438 if (mReady) {
439 return;
440 }
441 SystemClock.sleep(1000);
442 }
San Mehata5078592010-03-25 09:36:54 -0700443 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800444 }
San Mehat1f6301e2010-01-07 22:40:27 -0800445 }
Kenny Root02c87302010-07-01 08:10:18 -0700446
San Mehat207e5382010-02-04 20:46:54 -0800447 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600448 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800450 String action = intent.getAction();
451
452 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800453 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800454
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800455 /*
456 * In the simulator, we need to broadcast a volume mounted event
457 * to make the media scanner run.
458 */
459 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400460 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
461 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800462 return;
463 }
San Mehatfafb0412010-02-18 19:40:04 -0800464 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600465 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800466 public void run() {
467 try {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400468 // it is not safe to call vold with mVolumeStates locked
469 // so we make a copy of the paths and states and process them
470 // outside the lock
471 String[] paths, states;
472 int count;
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400473 synchronized (mVolumeStates) {
Mike Lockwoodb9135632011-04-05 10:05:47 -0400474 Set<String> keys = mVolumeStates.keySet();
475 count = keys.size();
476 paths = (String[])keys.toArray(new String[count]);
477 states = new String[count];
478 for (int i = 0; i < count; i++) {
479 states[i] = mVolumeStates.get(paths[i]);
480 }
481 }
San Mehat6a254402010-03-22 10:21:00 -0700482
Mike Lockwoodb9135632011-04-05 10:05:47 -0400483 for (int i = 0; i < count; i++) {
484 String path = paths[i];
485 String state = states[i];
486
487 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
488 int rc = doMountVolume(path);
489 if (rc != StorageResultCode.OperationSucceeded) {
490 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
491 rc));
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400492 }
Mike Lockwoodb9135632011-04-05 10:05:47 -0400493 } else if (state.equals(Environment.MEDIA_SHARED)) {
494 /*
495 * Bootstrap UMS enabled state since vold indicates
496 * the volume is shared (runtime restart while ums enabled)
497 */
498 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
499 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800500 }
501 }
San Mehat6a254402010-03-22 10:21:00 -0700502
Mike Lockwood91dd02c2011-04-05 10:21:51 -0400503 /* notify external storage has mounted to trigger media scanner */
504 if (mEmulateExternalStorage) {
505 notifyVolumeStateChange(null,
506 Environment.getExternalStorageDirectory().getPath(),
507 VolumeState.NoMedia, VolumeState.Mounted);
508 }
509
San Mehat6a965af22010-02-24 17:47:30 -0800510 /*
San Mehat6a254402010-03-22 10:21:00 -0700511 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800512 * now that we're up.
513 */
514 if (mSendUmsConnectedOnBoot) {
515 sendUmsIntent(true);
516 mSendUmsConnectedOnBoot = false;
517 }
San Mehatfafb0412010-02-18 19:40:04 -0800518 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700519 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800520 }
San Mehat207e5382010-02-04 20:46:54 -0800521 }
San Mehatfafb0412010-02-18 19:40:04 -0800522 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 }
524 }
525 };
526
San Mehat4270e1e2010-01-29 05:32:19 -0800527 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
528 final IMountServiceListener mListener;
529
530 MountServiceBinderListener(IMountServiceListener listener) {
531 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700532
San Mehat91c77612010-01-07 10:39:41 -0800533 }
534
San Mehat4270e1e2010-01-29 05:32:19 -0800535 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700536 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700537 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800538 mListeners.remove(this);
539 mListener.asBinder().unlinkToDeath(this, 0);
540 }
541 }
542 }
543
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800544 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800545 // TODO: Add support for multiple share methods
546 if (!method.equals("ums")) {
547 throw new IllegalArgumentException(String.format("Method %s not supported", method));
548 }
549
San Mehat4270e1e2010-01-29 05:32:19 -0800550 try {
551 mConnector.doCommand(String.format(
552 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
553 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700554 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800555 }
San Mehat4270e1e2010-01-29 05:32:19 -0800556 }
557
San Mehat207e5382010-02-04 20:46:54 -0800558 private void updatePublicVolumeState(String path, String state) {
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400559 String oldState;
560 synchronized(mVolumeStates) {
561 oldState = mVolumeStates.put(path, state);
562 }
563 if (state.equals(oldState)) {
564 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
565 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800566 return;
567 }
San Mehatb1043402010-02-05 08:26:50 -0800568
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400569 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700570
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400571 if (path.equals(mExternalStoragePath)) {
572 // Update state on PackageManager, but only of real events
573 if (!mEmulateExternalStorage) {
574 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
575 mPms.updateExternalMediaStatus(false, false);
576
577 /*
578 * Some OBBs might have been unmounted when this volume was
579 * unmounted, so send a message to the handler to let it know to
580 * remove those from the list of mounted OBBS.
581 */
582 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
583 OBB_FLUSH_MOUNT_STATE, path));
584 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
585 mPms.updateExternalMediaStatus(true, false);
586 }
Mike Lockwood03559752010-07-19 18:25:03 -0400587 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800588 }
San Mehat4270e1e2010-01-29 05:32:19 -0800589 synchronized (mListeners) {
590 for (int i = mListeners.size() -1; i >= 0; i--) {
591 MountServiceBinderListener bl = mListeners.get(i);
592 try {
San Mehatb1043402010-02-05 08:26:50 -0800593 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800594 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700595 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800596 mListeners.remove(i);
597 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700598 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800599 }
600 }
601 }
602 }
603
604 /**
605 *
606 * Callback from NativeDaemonConnector
607 */
608 public void onDaemonConnected() {
609 /*
610 * Since we'll be calling back into the NativeDaemonConnector,
611 * we need to do our work in a new thread.
612 */
613 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600614 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800615 public void run() {
616 /**
617 * Determine media state and UMS detection status
618 */
San Mehat4270e1e2010-01-29 05:32:19 -0800619 try {
620 String[] vols = mConnector.doListCommand(
621 "volume list", VoldResponseCode.VolumeListResult);
622 for (String volstr : vols) {
623 String[] tok = volstr.split(" ");
624 // FMT: <label> <mountpoint> <state>
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400625 String path = tok[1];
626 String state = Environment.MEDIA_REMOVED;
627
San Mehat4270e1e2010-01-29 05:32:19 -0800628 int st = Integer.parseInt(tok[2]);
629 if (st == VolumeState.NoMedia) {
630 state = Environment.MEDIA_REMOVED;
631 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800632 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800633 } else if (st == VolumeState.Mounted) {
634 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700635 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800636 } else if (st == VolumeState.Shared) {
637 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700638 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800639 } else {
640 throw new Exception(String.format("Unexpected state %d", st));
641 }
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400642
643 if (state != null) {
644 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
645 updatePublicVolumeState(path, state);
646 }
San Mehat4270e1e2010-01-29 05:32:19 -0800647 }
648 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700649 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwoodf097fc22011-03-23 14:52:34 -0400650 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800651 }
652
653 try {
San Mehat207e5382010-02-04 20:46:54 -0800654 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800655 notifyShareAvailabilityChange("ums", avail);
656 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700657 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800658 }
San Mehat207e5382010-02-04 20:46:54 -0800659 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600660 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800661 * the hounds!
662 */
663 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800664 }
665 }.start();
666 }
667
668 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800669 * Callback from NativeDaemonConnector
670 */
671 public boolean onEvent(int code, String raw, String[] cooked) {
672 Intent in = null;
673
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800674 if (DEBUG_EVENTS) {
675 StringBuilder builder = new StringBuilder();
676 builder.append("onEvent::");
677 builder.append(" raw= " + raw);
678 if (cooked != null) {
679 builder.append(" cooked = " );
680 for (String str : cooked) {
681 builder.append(" " + str);
682 }
683 }
San Mehata5078592010-03-25 09:36:54 -0700684 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800685 }
San Mehat4270e1e2010-01-29 05:32:19 -0800686 if (code == VoldResponseCode.VolumeStateChange) {
687 /*
688 * One of the volumes we're managing has changed state.
689 * Format: "NNN Volume <label> <path> state changed
690 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
691 */
692 notifyVolumeStateChange(
693 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
694 Integer.parseInt(cooked[10]));
695 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
696 // FMT: NNN Share method <method> now <available|unavailable>
697 boolean avail = false;
698 if (cooked[5].equals("available")) {
699 avail = true;
700 }
701 notifyShareAvailabilityChange(cooked[3], avail);
702 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
703 (code == VoldResponseCode.VolumeDiskRemoved) ||
704 (code == VoldResponseCode.VolumeBadRemoval)) {
705 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
706 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
707 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
708 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);
746 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
747 mContext.sendBroadcast(in);
748
San Mehata5078592010-03-25 09:36:54 -0700749 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800750 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
751 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
752 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700753 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800754 /* Send the media unmounted event first */
755 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
756 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
757 mContext.sendBroadcast(in);
758
San Mehata5078592010-03-25 09:36:54 -0700759 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800760 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
761 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
762 } else {
San Mehata5078592010-03-25 09:36:54 -0700763 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800764 }
765 } else {
766 return false;
767 }
768
769 if (in != null) {
770 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400771 }
772 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800773 }
774
San Mehat207e5382010-02-04 20:46:54 -0800775 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800776 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700777 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800778
779 Intent in = null;
780
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500781 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700782 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500783 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
784 Uri.parse("file://" + path)));
785 }
786
San Mehat4270e1e2010-01-29 05:32:19 -0800787 if (newState == VolumeState.Init) {
788 } else if (newState == VolumeState.NoMedia) {
789 // NoMedia is handled via Disk Remove events
790 } else if (newState == VolumeState.Idle) {
791 /*
792 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
793 * if we're in the process of enabling UMS
794 */
795 if (!vs.equals(
796 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
797 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800798 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700799 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800800 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
801 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
802 }
803 } else if (newState == VolumeState.Pending) {
804 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700805 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800806 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
807 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
808 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700809 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800810 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800811 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
812 in.putExtra("read-only", false);
813 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800814 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
815 } else if (newState == VolumeState.Formatting) {
816 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700817 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800818 /* Send the media unmounted event first */
819 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
820 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
821 mContext.sendBroadcast(in);
822
San Mehata5078592010-03-25 09:36:54 -0700823 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800824 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
825 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700826 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800827 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700828 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800829 return;
830 } else {
San Mehata5078592010-03-25 09:36:54 -0700831 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800832 }
833
834 if (in != null) {
835 mContext.sendBroadcast(in);
836 }
837 }
838
San Mehat207e5382010-02-04 20:46:54 -0800839 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700840 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700841 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700842 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700843 } catch (NativeDaemonConnectorException ex) {
844 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
845 return false;
846 }
San Mehat207e5382010-02-04 20:46:54 -0800847
848 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700849 String[] tok = line.split(" ");
850 if (tok.length < 3) {
851 Slog.e(TAG, "Malformed response to share status " + method);
852 return false;
853 }
854
San Mehat207e5382010-02-04 20:46:54 -0800855 int code;
856 try {
857 code = Integer.parseInt(tok[0]);
858 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700859 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800860 return false;
861 }
862 if (code == VoldResponseCode.ShareStatusResult) {
863 if (tok[2].equals("available"))
864 return true;
865 return false;
866 } else {
San Mehata5078592010-03-25 09:36:54 -0700867 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800868 return false;
869 }
870 }
San Mehata5078592010-03-25 09:36:54 -0700871 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800872 return false;
873 }
874
875 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800876 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800877
San Mehata5078592010-03-25 09:36:54 -0700878 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800879 try {
880 mConnector.doCommand(String.format("volume mount %s", path));
881 } catch (NativeDaemonConnectorException e) {
882 /*
883 * Mount failed for some reason
884 */
885 Intent in = null;
886 int code = e.getCode();
887 if (code == VoldResponseCode.OpFailedNoMedia) {
888 /*
889 * Attempt to mount but no media inserted
890 */
San Mehatb1043402010-02-05 08:26:50 -0800891 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800892 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700893 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800894 /*
895 * Media is blank or does not contain a supported filesystem
896 */
897 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
898 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800899 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800900 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700901 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800902 /*
903 * Volume consistency check failed
904 */
905 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
906 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800907 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800908 } else {
San Mehatb1043402010-02-05 08:26:50 -0800909 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800910 }
911
912 /*
913 * Send broadcast intent (if required for the failure)
914 */
915 if (in != null) {
916 mContext.sendBroadcast(in);
917 }
918 }
919
920 return rc;
921 }
922
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800923 /*
924 * If force is not set, we do not unmount if there are
925 * processes holding references to the volume about to be unmounted.
926 * If force is set, all the processes holding references need to be
927 * killed via the ActivityManager before actually unmounting the volume.
928 * This might even take a while and might be retried after timed delays
929 * to make sure we dont end up in an instable state and kill some core
930 * processes.
931 */
San Mehatd9709982010-02-18 11:43:03 -0800932 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800933 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800934 return VoldResponseCode.OpFailedVolNotMounted;
935 }
Kenny Rootaa485402010-09-14 14:49:41 -0700936
937 /*
938 * Force a GC to make sure AssetManagers in other threads of the
939 * system_server are cleaned up. We have to do this since AssetManager
940 * instances are kept as a WeakReference and it's possible we have files
941 * open on the external storage.
942 */
943 Runtime.getRuntime().gc();
944
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800945 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700946 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800947 try {
San Mehatd9709982010-02-18 11:43:03 -0800948 mConnector.doCommand(String.format(
949 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700950 // We unmounted the volume. None of the asec containers are available now.
951 synchronized (mAsecMountSet) {
952 mAsecMountSet.clear();
953 }
San Mehatb1043402010-02-05 08:26:50 -0800954 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800955 } catch (NativeDaemonConnectorException e) {
956 // Don't worry about mismatch in PackageManager since the
957 // call back will handle the status changes any way.
958 int code = e.getCode();
959 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800960 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800961 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
962 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800963 } else {
San Mehatb1043402010-02-05 08:26:50 -0800964 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800965 }
966 }
967 }
968
969 private int doFormatVolume(String path) {
970 try {
971 String cmd = String.format("volume format %s", path);
972 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800973 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800974 } catch (NativeDaemonConnectorException e) {
975 int code = e.getCode();
976 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800977 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800978 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800979 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800980 } else {
San Mehatb1043402010-02-05 08:26:50 -0800981 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800982 }
983 }
984 }
985
San Mehatb1043402010-02-05 08:26:50 -0800986 private boolean doGetVolumeShared(String path, String method) {
987 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700988 ArrayList<String> rsp;
989
990 try {
991 rsp = mConnector.doCommand(cmd);
992 } catch (NativeDaemonConnectorException ex) {
993 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
994 return false;
995 }
San Mehatb1043402010-02-05 08:26:50 -0800996
997 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700998 String[] tok = line.split(" ");
999 if (tok.length < 3) {
1000 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
1001 return false;
1002 }
1003
San Mehatb1043402010-02-05 08:26:50 -08001004 int code;
1005 try {
1006 code = Integer.parseInt(tok[0]);
1007 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001008 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -08001009 return false;
1010 }
1011 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -07001012 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -08001013 } else {
San Mehata5078592010-03-25 09:36:54 -07001014 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -08001015 return false;
1016 }
1017 }
San Mehata5078592010-03-25 09:36:54 -07001018 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001019 return false;
1020 }
1021
San Mehat207e5382010-02-04 20:46:54 -08001022 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001023 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001024 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001025 return;
1026 }
1027
1028 synchronized (mListeners) {
1029 for (int i = mListeners.size() -1; i >= 0; i--) {
1030 MountServiceBinderListener bl = mListeners.get(i);
1031 try {
San Mehatb1043402010-02-05 08:26:50 -08001032 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001033 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001034 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001035 mListeners.remove(i);
1036 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001037 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001038 }
1039 }
1040 }
1041
San Mehat207e5382010-02-04 20:46:54 -08001042 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001043 sendUmsIntent(avail);
1044 } else {
1045 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001046 }
San Mehat2fe718a2010-03-11 12:01:49 -08001047
1048 final String path = Environment.getExternalStorageDirectory().getPath();
1049 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1050 /*
1051 * USB mass storage disconnected while enabled
1052 */
1053 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001054 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001055 public void run() {
1056 try {
1057 int rc;
San Mehata5078592010-03-25 09:36:54 -07001058 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001059 doShareUnshareVolume(path, "ums", false);
1060 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001061 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001062 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1063 path, rc));
1064 }
1065 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001066 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001067 }
1068 }
1069 }.start();
1070 }
San Mehat4270e1e2010-01-29 05:32:19 -08001071 }
1072
San Mehat6a965af22010-02-24 17:47:30 -08001073 private void sendUmsIntent(boolean c) {
1074 mContext.sendBroadcast(
1075 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1076 }
1077
San Mehat207e5382010-02-04 20:46:54 -08001078 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001079 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1080 throw new SecurityException(String.format("Requires %s permission", perm));
1081 }
1082 }
1083
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001084 // Storage list XML tags
1085 private static final String TAG_STORAGE_LIST = "StorageList";
1086 private static final String TAG_STORAGE = "storage";
1087
1088 private void readStorageList(Resources resources) {
1089 int id = com.android.internal.R.xml.storage_list;
1090 XmlResourceParser parser = resources.getXml(id);
1091 AttributeSet attrs = Xml.asAttributeSet(parser);
1092
1093 try {
1094 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1095 while (true) {
1096 XmlUtils.nextElement(parser);
1097
1098 String element = parser.getName();
1099 if (element == null) break;
1100
1101 if (TAG_STORAGE.equals(element)) {
1102 TypedArray a = resources.obtainAttributes(attrs,
1103 com.android.internal.R.styleable.Storage);
1104
1105 CharSequence path = a.getText(
1106 com.android.internal.R.styleable.Storage_mountPoint);
1107 CharSequence description = a.getText(
1108 com.android.internal.R.styleable.Storage_storageDescription);
1109 boolean primary = a.getBoolean(
1110 com.android.internal.R.styleable.Storage_primary, false);
1111 boolean removable = a.getBoolean(
1112 com.android.internal.R.styleable.Storage_removable, false);
1113 boolean emulated = a.getBoolean(
1114 com.android.internal.R.styleable.Storage_emulated, false);
1115 int mtpReserve = a.getInt(
1116 com.android.internal.R.styleable.Storage_mtpReserve, 0);
1117
1118 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1119 " primary: " + primary + " removable: " + removable +
1120 " emulated: " + emulated + " mtpReserve: " + mtpReserve);
1121 if (path == null || description == null) {
1122 Slog.e(TAG, "path or description is null in readStorageList");
1123 } else {
1124 StorageVolume volume = new StorageVolume(path.toString(),
1125 description.toString(), removable, emulated, mtpReserve);
1126 if (primary) {
1127 if (mPrimaryVolume == null) {
1128 mPrimaryVolume = volume;
1129 } else {
1130 Slog.e(TAG, "multiple primary volumes in storage list");
1131 }
1132 }
1133 if (mPrimaryVolume == volume) {
1134 // primay volume must be first
1135 mVolumes.add(0, volume);
1136 } else {
1137 mVolumes.add(volume);
1138 }
1139 }
1140 a.recycle();
1141 }
1142 }
1143 } catch (XmlPullParserException e) {
1144 throw new RuntimeException(e);
1145 } catch (IOException e) {
1146 throw new RuntimeException(e);
1147 } finally {
1148 parser.close();
1149 }
1150 }
1151
San Mehat4270e1e2010-01-29 05:32:19 -08001152 /**
San Mehat207e5382010-02-04 20:46:54 -08001153 * Constructs a new MountService instance
1154 *
1155 * @param context Binder context for this service
1156 */
1157 public MountService(Context context) {
1158 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001159 Resources resources = context.getResources();
1160 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001161
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001162 if (mPrimaryVolume != null) {
1163 mExternalStoragePath = mPrimaryVolume.getPath();
1164 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1165 if (mEmulateExternalStorage) {
1166 Slog.d(TAG, "using emulated external storage");
1167 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1168 }
Mike Lockwood03559752010-07-19 18:25:03 -04001169 }
1170
San Mehat207e5382010-02-04 20:46:54 -08001171 // XXX: This will go away soon in favor of IMountServiceObserver
1172 mPms = (PackageManagerService) ServiceManager.getService("package");
1173
1174 mContext.registerReceiver(mBroadcastReceiver,
1175 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1176
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001177 mHandlerThread = new HandlerThread("MountService");
1178 mHandlerThread.start();
1179 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1180
Kenny Roota02b8b02010-08-05 16:14:17 -07001181 // Add OBB Action Handler to MountService thread.
1182 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1183
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001184 /*
1185 * Vold does not run in the simulator, so pretend the connector thread
1186 * ran and did its thing.
1187 */
1188 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1189 mReady = true;
1190 mUmsEnabling = true;
1191 return;
1192 }
1193
Kenny Root305bcbf2010-09-03 07:56:38 -07001194 /*
1195 * Create the connection to vold with a maximum queue of twice the
1196 * amount of containers we'd ever expect to have. This keeps an
1197 * "asec list" from blocking a thread repeatedly.
1198 */
1199 mConnector = new NativeDaemonConnector(this, "vold",
1200 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001201 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001202 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001203 thread.start();
1204 }
1205
1206 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001207 * Exposed API calls below here
1208 */
1209
1210 public void registerListener(IMountServiceListener listener) {
1211 synchronized (mListeners) {
1212 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1213 try {
1214 listener.asBinder().linkToDeath(bl, 0);
1215 mListeners.add(bl);
1216 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001217 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001218 }
1219 }
1220 }
1221
1222 public void unregisterListener(IMountServiceListener listener) {
1223 synchronized (mListeners) {
1224 for(MountServiceBinderListener bl : mListeners) {
1225 if (bl.mListener == listener) {
1226 mListeners.remove(mListeners.indexOf(bl));
1227 return;
1228 }
1229 }
1230 }
1231 }
1232
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001233 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001234 validatePermission(android.Manifest.permission.SHUTDOWN);
1235
San Mehata5078592010-03-25 09:36:54 -07001236 Slog.i(TAG, "Shutting down");
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001237 synchronized (mVolumeStates) {
1238 for (String path : mVolumeStates.keySet()) {
1239 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001240
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001241 if (state.equals(Environment.MEDIA_SHARED)) {
1242 /*
1243 * If the media is currently shared, unshare it.
1244 * XXX: This is still dangerous!. We should not
1245 * be rebooting at *all* if UMS is enabled, since
1246 * the UMS host could have dirty FAT cache entries
1247 * yet to flush.
1248 */
1249 setUsbMassStorageEnabled(false);
1250 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1251 /*
1252 * If the media is being checked, then we need to wait for
1253 * it to complete before being able to proceed.
1254 */
1255 // XXX: @hackbod - Should we disable the ANR timer here?
1256 int retries = 30;
1257 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1258 try {
1259 Thread.sleep(1000);
1260 } catch (InterruptedException iex) {
1261 Slog.e(TAG, "Interrupted while waiting for media", iex);
1262 break;
1263 }
1264 state = Environment.getExternalStorageState();
1265 }
1266 if (retries == 0) {
1267 Slog.e(TAG, "Timed out waiting for media to check");
1268 }
San Mehat91c77612010-01-07 10:39:41 -08001269 }
San Mehat91c77612010-01-07 10:39:41 -08001270
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001271 if (state.equals(Environment.MEDIA_MOUNTED)) {
1272 // Post a unmount message.
1273 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1274 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1275 } else if (observer != null) {
1276 /*
1277 * Observer is waiting for onShutDownComplete when we are done.
1278 * Since nothing will be done send notification directly so shutdown
1279 * sequence can continue.
1280 */
1281 try {
1282 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1283 } catch (RemoteException e) {
1284 Slog.w(TAG, "RemoteException when shutting down");
1285 }
1286 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001287 }
San Mehat4270e1e2010-01-29 05:32:19 -08001288 }
1289 }
1290
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001291 private boolean getUmsEnabling() {
1292 synchronized (mListeners) {
1293 return mUmsEnabling;
1294 }
1295 }
1296
1297 private void setUmsEnabling(boolean enable) {
1298 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001299 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001300 }
1301 }
1302
San Mehatb1043402010-02-05 08:26:50 -08001303 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001304 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001305
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001306 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001307 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001308 }
San Mehatb1043402010-02-05 08:26:50 -08001309 return doGetShareMethodAvailable("ums");
1310 }
1311
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001312 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001313 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001314 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001315
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001316 // TODO: Add support for multiple share methods
1317
1318 /*
1319 * If the volume is mounted and we're enabling then unmount it
1320 */
1321 String path = Environment.getExternalStorageDirectory().getPath();
1322 String vs = getVolumeState(path);
1323 String method = "ums";
1324 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1325 // Override for isUsbMassStorageEnabled()
1326 setUmsEnabling(enable);
1327 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1328 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1329 // Clear override
1330 setUmsEnabling(false);
1331 }
1332 /*
1333 * If we disabled UMS then mount the volume
1334 */
1335 if (!enable) {
1336 doShareUnshareVolume(path, method, enable);
1337 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001338 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001339 " after disabling share method " + method);
1340 /*
1341 * Even though the mount failed, the unshare didn't so don't indicate an error.
1342 * The mountVolume() call will have set the storage state and sent the necessary
1343 * broadcasts.
1344 */
1345 }
1346 }
San Mehatb1043402010-02-05 08:26:50 -08001347 }
1348
1349 public boolean isUsbMassStorageEnabled() {
1350 waitForReady();
1351 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001353
San Mehat7fd0fee2009-12-17 07:12:23 -08001354 /**
1355 * @return state of the volume at the specified mount point
1356 */
San Mehat4270e1e2010-01-29 05:32:19 -08001357 public String getVolumeState(String mountPoint) {
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001358 synchronized (mVolumeStates) {
1359 String state = mVolumeStates.get(mountPoint);
1360 if (state == null) {
1361 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1362 throw new IllegalArgumentException();
1363 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001364
Mike Lockwoodf097fc22011-03-23 14:52:34 -04001365 return state;
1366 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001367 }
1368
Kenny Roote1ff2142010-10-12 11:20:01 -07001369 public boolean isExternalStorageEmulated() {
1370 return mEmulateExternalStorage;
1371 }
1372
San Mehat4270e1e2010-01-29 05:32:19 -08001373 public int mountVolume(String path) {
1374 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001375
San Mehat207e5382010-02-04 20:46:54 -08001376 waitForReady();
1377 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001380 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001381 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001382 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001384 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001385 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001386 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1387 Environment.MEDIA_REMOVED.equals(volState) ||
1388 Environment.MEDIA_SHARED.equals(volState) ||
1389 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1390 // Media already unmounted or cannot be unmounted.
1391 // TODO return valid return code when adding observer call back.
1392 return;
1393 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001394 UnmountCallBack ucb = new UnmountCallBack(path, force);
1395 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397
San Mehat4270e1e2010-01-29 05:32:19 -08001398 public int formatVolume(String path) {
1399 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001400 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001401
San Mehat207e5382010-02-04 20:46:54 -08001402 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404
San Mehatc1b4ce92010-02-16 17:13:03 -08001405 public int []getStorageUsers(String path) {
1406 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1407 waitForReady();
1408 try {
1409 String[] r = mConnector.doListCommand(
1410 String.format("storage users %s", path),
1411 VoldResponseCode.StorageUsersListResult);
1412 // FMT: <pid> <process name>
1413 int[] data = new int[r.length];
1414 for (int i = 0; i < r.length; i++) {
1415 String []tok = r[i].split(" ");
1416 try {
1417 data[i] = Integer.parseInt(tok[0]);
1418 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001419 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001420 return new int[0];
1421 }
1422 }
1423 return data;
1424 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001425 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001426 return new int[0];
1427 }
1428 }
1429
San Mehatb1043402010-02-05 08:26:50 -08001430 private void warnOnNotMounted() {
1431 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001432 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001433 }
1434 }
1435
San Mehat4270e1e2010-01-29 05:32:19 -08001436 public String[] getSecureContainerList() {
1437 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001438 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001439 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001440
San Mehat4270e1e2010-01-29 05:32:19 -08001441 try {
1442 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1443 } catch (NativeDaemonConnectorException e) {
1444 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446 }
San Mehat36972292010-01-06 11:06:32 -08001447
San Mehat4270e1e2010-01-29 05:32:19 -08001448 public int createSecureContainer(String id, int sizeMb, String fstype,
1449 String key, int ownerUid) {
1450 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001451 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001452 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001453
San Mehatb1043402010-02-05 08:26:50 -08001454 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001455 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1456 try {
1457 mConnector.doCommand(cmd);
1458 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001459 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001460 }
San Mehata181b212010-02-11 06:50:20 -08001461
1462 if (rc == StorageResultCode.OperationSucceeded) {
1463 synchronized (mAsecMountSet) {
1464 mAsecMountSet.add(id);
1465 }
1466 }
San Mehat4270e1e2010-01-29 05:32:19 -08001467 return rc;
San Mehat36972292010-01-06 11:06:32 -08001468 }
1469
San Mehat4270e1e2010-01-29 05:32:19 -08001470 public int finalizeSecureContainer(String id) {
1471 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001472 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001473
San Mehatb1043402010-02-05 08:26:50 -08001474 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001475 try {
1476 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001477 /*
1478 * Finalization does a remount, so no need
1479 * to update mAsecMountSet
1480 */
San Mehat4270e1e2010-01-29 05:32:19 -08001481 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001482 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001483 }
San Mehat4270e1e2010-01-29 05:32:19 -08001484 return rc;
San Mehat36972292010-01-06 11:06:32 -08001485 }
1486
San Mehatd9709982010-02-18 11:43:03 -08001487 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001488 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001489 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001490 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001491
Kenny Rootaa485402010-09-14 14:49:41 -07001492 /*
1493 * Force a GC to make sure AssetManagers in other threads of the
1494 * system_server are cleaned up. We have to do this since AssetManager
1495 * instances are kept as a WeakReference and it's possible we have files
1496 * open on the external storage.
1497 */
1498 Runtime.getRuntime().gc();
1499
San Mehatb1043402010-02-05 08:26:50 -08001500 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001501 try {
San Mehatd9709982010-02-18 11:43:03 -08001502 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001503 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001504 int code = e.getCode();
1505 if (code == VoldResponseCode.OpFailedStorageBusy) {
1506 rc = StorageResultCode.OperationFailedStorageBusy;
1507 } else {
1508 rc = StorageResultCode.OperationFailedInternalError;
1509 }
San Mehat02735bc2010-01-26 15:18:08 -08001510 }
San Mehata181b212010-02-11 06:50:20 -08001511
1512 if (rc == StorageResultCode.OperationSucceeded) {
1513 synchronized (mAsecMountSet) {
1514 if (mAsecMountSet.contains(id)) {
1515 mAsecMountSet.remove(id);
1516 }
1517 }
1518 }
1519
San Mehat4270e1e2010-01-29 05:32:19 -08001520 return rc;
San Mehat36972292010-01-06 11:06:32 -08001521 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001522
San Mehat4270e1e2010-01-29 05:32:19 -08001523 public int mountSecureContainer(String id, String key, int ownerUid) {
1524 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001525 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001526 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001527
San Mehata181b212010-02-11 06:50:20 -08001528 synchronized (mAsecMountSet) {
1529 if (mAsecMountSet.contains(id)) {
1530 return StorageResultCode.OperationFailedStorageMounted;
1531 }
1532 }
1533
San Mehatb1043402010-02-05 08:26:50 -08001534 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001535 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1536 try {
1537 mConnector.doCommand(cmd);
1538 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001539 int code = e.getCode();
1540 if (code != VoldResponseCode.OpFailedStorageBusy) {
1541 rc = StorageResultCode.OperationFailedInternalError;
1542 }
San Mehat02735bc2010-01-26 15:18:08 -08001543 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001544
1545 if (rc == StorageResultCode.OperationSucceeded) {
1546 synchronized (mAsecMountSet) {
1547 mAsecMountSet.add(id);
1548 }
1549 }
San Mehat4270e1e2010-01-29 05:32:19 -08001550 return rc;
San Mehat36972292010-01-06 11:06:32 -08001551 }
1552
San Mehatd9709982010-02-18 11:43:03 -08001553 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001554 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001555 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001556 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001557
San Mehat6cdd9c02010-02-09 14:45:20 -08001558 synchronized (mAsecMountSet) {
1559 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001560 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001561 }
1562 }
1563
Kenny Rootaa485402010-09-14 14:49:41 -07001564 /*
1565 * Force a GC to make sure AssetManagers in other threads of the
1566 * system_server are cleaned up. We have to do this since AssetManager
1567 * instances are kept as a WeakReference and it's possible we have files
1568 * open on the external storage.
1569 */
1570 Runtime.getRuntime().gc();
1571
San Mehatb1043402010-02-05 08:26:50 -08001572 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001573 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001574 try {
1575 mConnector.doCommand(cmd);
1576 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001577 int code = e.getCode();
1578 if (code == VoldResponseCode.OpFailedStorageBusy) {
1579 rc = StorageResultCode.OperationFailedStorageBusy;
1580 } else {
1581 rc = StorageResultCode.OperationFailedInternalError;
1582 }
San Mehat02735bc2010-01-26 15:18:08 -08001583 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001584
1585 if (rc == StorageResultCode.OperationSucceeded) {
1586 synchronized (mAsecMountSet) {
1587 mAsecMountSet.remove(id);
1588 }
1589 }
San Mehat4270e1e2010-01-29 05:32:19 -08001590 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001591 }
1592
San Mehat6cdd9c02010-02-09 14:45:20 -08001593 public boolean isSecureContainerMounted(String id) {
1594 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1595 waitForReady();
1596 warnOnNotMounted();
1597
1598 synchronized (mAsecMountSet) {
1599 return mAsecMountSet.contains(id);
1600 }
1601 }
1602
San Mehat4270e1e2010-01-29 05:32:19 -08001603 public int renameSecureContainer(String oldId, String newId) {
1604 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001605 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001606 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001607
San Mehata181b212010-02-11 06:50:20 -08001608 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001609 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001610 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001611 * changed while active, we must ensure both ids are not currently mounted.
1612 */
1613 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001614 return StorageResultCode.OperationFailedStorageMounted;
1615 }
1616 }
1617
San Mehatb1043402010-02-05 08:26:50 -08001618 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001619 String cmd = String.format("asec rename %s %s", oldId, newId);
1620 try {
1621 mConnector.doCommand(cmd);
1622 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001623 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001624 }
San Mehata181b212010-02-11 06:50:20 -08001625
San Mehat4270e1e2010-01-29 05:32:19 -08001626 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001627 }
1628
San Mehat4270e1e2010-01-29 05:32:19 -08001629 public String getSecureContainerPath(String id) {
1630 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001631 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001632 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001633
San Mehat2d66cef2010-03-23 11:12:52 -07001634 try {
1635 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1636 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001637 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001638 if (code != VoldResponseCode.AsecPathResult) {
1639 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1640 }
1641 return tok[1];
1642 } catch (NativeDaemonConnectorException e) {
1643 int code = e.getCode();
1644 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1645 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001646 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001647 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001648 }
1649 }
San Mehat22dd86e2010-01-12 12:21:18 -08001650 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001651
1652 public void finishMediaUpdate() {
1653 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1654 }
Kenny Root02c87302010-07-01 08:10:18 -07001655
Kenny Roota02b8b02010-08-05 16:14:17 -07001656 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1657 if (callerUid == android.os.Process.SYSTEM_UID) {
1658 return true;
1659 }
1660
Kenny Root02c87302010-07-01 08:10:18 -07001661 if (packageName == null) {
1662 return false;
1663 }
1664
1665 final int packageUid = mPms.getPackageUid(packageName);
1666
1667 if (DEBUG_OBB) {
1668 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1669 packageUid + ", callerUid = " + callerUid);
1670 }
1671
1672 return callerUid == packageUid;
1673 }
1674
1675 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001676 if (filename == null) {
1677 throw new IllegalArgumentException("filename cannot be null");
1678 }
1679
Kenny Root02c87302010-07-01 08:10:18 -07001680 waitForReady();
1681 warnOnNotMounted();
1682
Kenny Root02c87302010-07-01 08:10:18 -07001683 try {
1684 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1685 String []tok = rsp.get(0).split(" ");
1686 int code = Integer.parseInt(tok[0]);
1687 if (code != VoldResponseCode.AsecPathResult) {
1688 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1689 }
1690 return tok[1];
1691 } catch (NativeDaemonConnectorException e) {
1692 int code = e.getCode();
1693 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001694 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001695 } else {
1696 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1697 }
1698 }
1699 }
1700
1701 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001702 if (filename == null) {
1703 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001704 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001705
1706 synchronized (mObbMounts) {
1707 return mObbPathToStateMap.containsKey(filename);
1708 }
Kenny Root02c87302010-07-01 08:10:18 -07001709 }
1710
Kenny Rootaf9d6672010-10-08 09:21:39 -07001711 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001712 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001713 if (filename == null) {
1714 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001715 }
1716
1717 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001718 throw new IllegalArgumentException("token cannot be null");
1719 }
1720
Kenny Rootaf9d6672010-10-08 09:21:39 -07001721 final int callerUid = Binder.getCallingUid();
1722 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1723 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001724 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1725
1726 if (DEBUG_OBB)
1727 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001728 }
1729
Kenny Rootaf9d6672010-10-08 09:21:39 -07001730 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1731 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001732 if (filename == null) {
1733 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001734 }
1735
Kenny Rootaf9d6672010-10-08 09:21:39 -07001736 final int callerUid = Binder.getCallingUid();
1737 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1738 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001739 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001740
Kenny Roota02b8b02010-08-05 16:14:17 -07001741 if (DEBUG_OBB)
1742 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1743 }
1744
Jason parks5af0b912010-11-29 09:05:25 -06001745 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001746 if (TextUtils.isEmpty(password)) {
1747 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001748 }
1749
Jason parks8888c592011-01-20 22:46:41 -06001750 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1751 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001752
1753 waitForReady();
1754
1755 if (DEBUG_EVENTS) {
1756 Slog.i(TAG, "decrypting storage...");
1757 }
1758
1759 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001760 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001761 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001762
Jason parksf7b3cd42011-01-27 09:28:25 -06001763 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001764 return -1;
1765 }
1766
Jason parksf7b3cd42011-01-27 09:28:25 -06001767 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001768
1769 if (code == 0) {
1770 // Decrypt was successful. Post a delayed message before restarting in order
1771 // to let the UI to clear itself
1772 mHandler.postDelayed(new Runnable() {
1773 public void run() {
1774 mConnector.doCommand(String.format("cryptfs restart"));
1775 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001776 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001777 }
1778
1779 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001780 } catch (NativeDaemonConnectorException e) {
1781 // Decryption failed
1782 return e.getCode();
1783 }
Jason parks5af0b912010-11-29 09:05:25 -06001784 }
1785
Jason parks56aa5322011-01-07 09:01:15 -06001786 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001787 if (TextUtils.isEmpty(password)) {
1788 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001789 }
1790
Jason parks8888c592011-01-20 22:46:41 -06001791 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1792 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001793
1794 waitForReady();
1795
1796 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001797 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001798 }
1799
1800 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001801 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001802 } catch (NativeDaemonConnectorException e) {
1803 // Encryption failed
1804 return e.getCode();
1805 }
1806
1807 return 0;
1808 }
1809
Jason parksf7b3cd42011-01-27 09:28:25 -06001810 public int changeEncryptionPassword(String password) {
1811 if (TextUtils.isEmpty(password)) {
1812 throw new IllegalArgumentException("password cannot be empty");
1813 }
1814
1815 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1816 "no permission to access the crypt keeper");
1817
1818 waitForReady();
1819
1820 if (DEBUG_EVENTS) {
1821 Slog.i(TAG, "changing encryption password...");
1822 }
1823
1824 try {
1825 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1826
1827 String[] tokens = response.get(0).split(" ");
1828
1829 if (tokens == null || tokens.length != 2) {
1830 return -1;
1831 }
1832
1833 return Integer.parseInt(tokens[1]);
1834 } catch (NativeDaemonConnectorException e) {
1835 // Encryption failed
1836 return e.getCode();
1837 }
1838 }
1839
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001840 public Parcelable[] getVolumeList() {
1841 synchronized(mVolumes) {
1842 int size = mVolumes.size();
1843 Parcelable[] result = new Parcelable[size];
1844 for (int i = 0; i < size; i++) {
1845 result[i] = mVolumes.get(i);
Mike Lockwoodd967f462011-03-24 08:12:30 -07001846 }
1847 return result;
1848 }
1849 }
1850
Kenny Rootaf9d6672010-10-08 09:21:39 -07001851 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1852 final IBinder binder = obbState.getBinder();
1853 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001854
Kenny Rootaf9d6672010-10-08 09:21:39 -07001855 if (obbStates == null) {
1856 obbStates = new ArrayList<ObbState>();
1857 mObbMounts.put(binder, obbStates);
1858 } else {
1859 for (final ObbState o : obbStates) {
1860 if (o.filename.equals(obbState.filename)) {
1861 throw new IllegalStateException("Attempt to add ObbState twice. "
1862 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001863 }
1864 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001865 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001866
1867 obbStates.add(obbState);
1868 try {
1869 obbState.link();
1870 } catch (RemoteException e) {
1871 /*
1872 * The binder died before we could link it, so clean up our state
1873 * and return failure.
1874 */
1875 obbStates.remove(obbState);
1876 if (obbStates.isEmpty()) {
1877 mObbMounts.remove(binder);
1878 }
1879
1880 // Rethrow the error so mountObb can get it
1881 throw e;
1882 }
1883
1884 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001885 }
1886
Kenny Rootaf9d6672010-10-08 09:21:39 -07001887 private void removeObbStateLocked(ObbState obbState) {
1888 final IBinder binder = obbState.getBinder();
1889 final List<ObbState> obbStates = mObbMounts.get(binder);
1890 if (obbStates != null) {
1891 if (obbStates.remove(obbState)) {
1892 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001893 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001894 if (obbStates.isEmpty()) {
1895 mObbMounts.remove(binder);
1896 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001897 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001898
Kenny Rootaf9d6672010-10-08 09:21:39 -07001899 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001900 }
1901
Kenny Roota02b8b02010-08-05 16:14:17 -07001902 private class ObbActionHandler extends Handler {
1903 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001904 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001905
1906 ObbActionHandler(Looper l) {
1907 super(l);
1908 }
1909
1910 @Override
1911 public void handleMessage(Message msg) {
1912 switch (msg.what) {
1913 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001914 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001915
1916 if (DEBUG_OBB)
1917 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1918
1919 // If a bind was already initiated we don't really
1920 // need to do anything. The pending install
1921 // will be processed later on.
1922 if (!mBound) {
1923 // If this is the only one pending we might
1924 // have to bind to the service again.
1925 if (!connectToService()) {
1926 Slog.e(TAG, "Failed to bind to media container service");
1927 action.handleError();
1928 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001929 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001930 }
Kenny Root735de3b2010-09-30 14:11:39 -07001931
Kenny Root735de3b2010-09-30 14:11:39 -07001932 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001933 break;
1934 }
1935 case OBB_MCS_BOUND: {
1936 if (DEBUG_OBB)
1937 Slog.i(TAG, "OBB_MCS_BOUND");
1938 if (msg.obj != null) {
1939 mContainerService = (IMediaContainerService) msg.obj;
1940 }
1941 if (mContainerService == null) {
1942 // Something seriously wrong. Bail out
1943 Slog.e(TAG, "Cannot bind to media container service");
1944 for (ObbAction action : mActions) {
1945 // Indicate service bind error
1946 action.handleError();
1947 }
1948 mActions.clear();
1949 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001950 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001951 if (action != null) {
1952 action.execute(this);
1953 }
1954 } else {
1955 // Should never happen ideally.
1956 Slog.w(TAG, "Empty queue");
1957 }
1958 break;
1959 }
1960 case OBB_MCS_RECONNECT: {
1961 if (DEBUG_OBB)
1962 Slog.i(TAG, "OBB_MCS_RECONNECT");
1963 if (mActions.size() > 0) {
1964 if (mBound) {
1965 disconnectService();
1966 }
1967 if (!connectToService()) {
1968 Slog.e(TAG, "Failed to bind to media container service");
1969 for (ObbAction action : mActions) {
1970 // Indicate service bind error
1971 action.handleError();
1972 }
1973 mActions.clear();
1974 }
1975 }
1976 break;
1977 }
1978 case OBB_MCS_UNBIND: {
1979 if (DEBUG_OBB)
1980 Slog.i(TAG, "OBB_MCS_UNBIND");
1981
1982 // Delete pending install
1983 if (mActions.size() > 0) {
1984 mActions.remove(0);
1985 }
1986 if (mActions.size() == 0) {
1987 if (mBound) {
1988 disconnectService();
1989 }
1990 } else {
1991 // There are more pending requests in queue.
1992 // Just post MCS_BOUND message to trigger processing
1993 // of next pending install.
1994 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1995 }
1996 break;
1997 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001998 case OBB_FLUSH_MOUNT_STATE: {
1999 final String path = (String) msg.obj;
2000
2001 if (DEBUG_OBB)
2002 Slog.i(TAG, "Flushing all OBB state for path " + path);
2003
2004 synchronized (mObbMounts) {
2005 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2006
2007 final Iterator<Entry<String, ObbState>> i =
2008 mObbPathToStateMap.entrySet().iterator();
2009 while (i.hasNext()) {
2010 final Entry<String, ObbState> obbEntry = i.next();
2011
2012 /*
2013 * If this entry's source file is in the volume path
2014 * that got unmounted, remove it because it's no
2015 * longer valid.
2016 */
2017 if (obbEntry.getKey().startsWith(path)) {
2018 obbStatesToRemove.add(obbEntry.getValue());
2019 }
2020 }
2021
2022 for (final ObbState obbState : obbStatesToRemove) {
2023 if (DEBUG_OBB)
2024 Slog.i(TAG, "Removing state for " + obbState.filename);
2025
2026 removeObbStateLocked(obbState);
2027
2028 try {
2029 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2030 OnObbStateChangeListener.UNMOUNTED);
2031 } catch (RemoteException e) {
2032 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2033 + obbState.filename);
2034 }
2035 }
2036 }
2037 break;
2038 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002039 }
2040 }
2041
2042 private boolean connectToService() {
2043 if (DEBUG_OBB)
2044 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2045
2046 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2047 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2048 mBound = true;
2049 return true;
2050 }
2051 return false;
2052 }
2053
2054 private void disconnectService() {
2055 mContainerService = null;
2056 mBound = false;
2057 mContext.unbindService(mDefContainerConn);
2058 }
2059 }
2060
2061 abstract class ObbAction {
2062 private static final int MAX_RETRIES = 3;
2063 private int mRetries;
2064
2065 ObbState mObbState;
2066
2067 ObbAction(ObbState obbState) {
2068 mObbState = obbState;
2069 }
2070
2071 public void execute(ObbActionHandler handler) {
2072 try {
2073 if (DEBUG_OBB)
2074 Slog.i(TAG, "Starting to execute action: " + this.toString());
2075 mRetries++;
2076 if (mRetries > MAX_RETRIES) {
2077 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002078 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002079 handleError();
2080 return;
2081 } else {
2082 handleExecute();
2083 if (DEBUG_OBB)
2084 Slog.i(TAG, "Posting install MCS_UNBIND");
2085 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2086 }
2087 } catch (RemoteException e) {
2088 if (DEBUG_OBB)
2089 Slog.i(TAG, "Posting install MCS_RECONNECT");
2090 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2091 } catch (Exception e) {
2092 if (DEBUG_OBB)
2093 Slog.d(TAG, "Error handling OBB action", e);
2094 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002095 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002096 }
2097 }
2098
Kenny Root05105f72010-09-22 17:29:43 -07002099 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002100 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002101
2102 protected ObbInfo getObbInfo() throws IOException {
2103 ObbInfo obbInfo;
2104 try {
2105 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2106 } catch (RemoteException e) {
2107 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2108 + mObbState.filename);
2109 obbInfo = null;
2110 }
2111 if (obbInfo == null) {
2112 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2113 }
2114 return obbInfo;
2115 }
2116
Kenny Rootaf9d6672010-10-08 09:21:39 -07002117 protected void sendNewStatusOrIgnore(int status) {
2118 if (mObbState == null || mObbState.token == null) {
2119 return;
2120 }
2121
Kenny Root38cf8862010-09-26 14:18:51 -07002122 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002123 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002124 } catch (RemoteException e) {
2125 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2126 }
2127 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002128 }
2129
2130 class MountObbAction extends ObbAction {
2131 private String mKey;
2132
2133 MountObbAction(ObbState obbState, String key) {
2134 super(obbState);
2135 mKey = key;
2136 }
2137
Jason parks5af0b912010-11-29 09:05:25 -06002138 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002139 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002140 waitForReady();
2141 warnOnNotMounted();
2142
Kenny Root38cf8862010-09-26 14:18:51 -07002143 final ObbInfo obbInfo = getObbInfo();
2144
Kenny Roota02b8b02010-08-05 16:14:17 -07002145 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002146 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2147 + " which is owned by " + obbInfo.packageName);
2148 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2149 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002150 }
2151
Kenny Rootaf9d6672010-10-08 09:21:39 -07002152 final boolean isMounted;
2153 synchronized (mObbMounts) {
2154 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2155 }
2156 if (isMounted) {
2157 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2158 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2159 return;
2160 }
2161
2162 /*
2163 * The filename passed in might not be the canonical name, so just
2164 * set the filename to the canonicalized version.
2165 */
2166 mObbState.filename = obbInfo.filename;
2167
2168 final String hashedKey;
2169 if (mKey == null) {
2170 hashedKey = "none";
2171 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002172 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002173 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2174
2175 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2176 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2177 SecretKey key = factory.generateSecret(ks);
2178 BigInteger bi = new BigInteger(key.getEncoded());
2179 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002180 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002181 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2182 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2183 return;
2184 } catch (InvalidKeySpecException e) {
2185 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2186 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002187 return;
2188 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002189 }
Kenny Root38cf8862010-09-26 14:18:51 -07002190
Kenny Rootaf9d6672010-10-08 09:21:39 -07002191 int rc = StorageResultCode.OperationSucceeded;
2192 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2193 mObbState.callerUid);
2194 try {
2195 mConnector.doCommand(cmd);
2196 } catch (NativeDaemonConnectorException e) {
2197 int code = e.getCode();
2198 if (code != VoldResponseCode.OpFailedStorageBusy) {
2199 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002200 }
2201 }
2202
Kenny Rootaf9d6672010-10-08 09:21:39 -07002203 if (rc == StorageResultCode.OperationSucceeded) {
2204 if (DEBUG_OBB)
2205 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2206
2207 synchronized (mObbMounts) {
2208 addObbStateLocked(mObbState);
2209 }
2210
2211 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002212 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002213 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002214
Kenny Rootaf9d6672010-10-08 09:21:39 -07002215 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002216 }
2217 }
2218
Jason parks5af0b912010-11-29 09:05:25 -06002219 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002220 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002221 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002222 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002223
2224 @Override
2225 public String toString() {
2226 StringBuilder sb = new StringBuilder();
2227 sb.append("MountObbAction{");
2228 sb.append("filename=");
2229 sb.append(mObbState.filename);
2230 sb.append(",callerUid=");
2231 sb.append(mObbState.callerUid);
2232 sb.append(",token=");
2233 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002234 sb.append(",binder=");
2235 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002236 sb.append('}');
2237 return sb.toString();
2238 }
2239 }
2240
2241 class UnmountObbAction extends ObbAction {
2242 private boolean mForceUnmount;
2243
2244 UnmountObbAction(ObbState obbState, boolean force) {
2245 super(obbState);
2246 mForceUnmount = force;
2247 }
2248
Jason parks5af0b912010-11-29 09:05:25 -06002249 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002250 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002251 waitForReady();
2252 warnOnNotMounted();
2253
Kenny Root38cf8862010-09-26 14:18:51 -07002254 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002255
Kenny Rootaf9d6672010-10-08 09:21:39 -07002256 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002257 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002258 obbState = mObbPathToStateMap.get(obbInfo.filename);
2259 }
Kenny Root38cf8862010-09-26 14:18:51 -07002260
Kenny Rootaf9d6672010-10-08 09:21:39 -07002261 if (obbState == null) {
2262 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2263 return;
2264 }
2265
2266 if (obbState.callerUid != mObbState.callerUid) {
2267 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2268 + " (owned by " + obbInfo.packageName + ")");
2269 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2270 return;
2271 }
2272
2273 mObbState.filename = obbInfo.filename;
2274
2275 int rc = StorageResultCode.OperationSucceeded;
2276 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2277 (mForceUnmount ? " force" : ""));
2278 try {
2279 mConnector.doCommand(cmd);
2280 } catch (NativeDaemonConnectorException e) {
2281 int code = e.getCode();
2282 if (code == VoldResponseCode.OpFailedStorageBusy) {
2283 rc = StorageResultCode.OperationFailedStorageBusy;
2284 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2285 // If it's not mounted then we've already won.
2286 rc = StorageResultCode.OperationSucceeded;
2287 } else {
2288 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002289 }
2290 }
2291
Kenny Rootaf9d6672010-10-08 09:21:39 -07002292 if (rc == StorageResultCode.OperationSucceeded) {
2293 synchronized (mObbMounts) {
2294 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002295 }
2296
Kenny Rootaf9d6672010-10-08 09:21:39 -07002297 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002298 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002299 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2300 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002301 }
2302 }
2303
Jason parks5af0b912010-11-29 09:05:25 -06002304 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002305 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002307 }
2308
2309 @Override
2310 public String toString() {
2311 StringBuilder sb = new StringBuilder();
2312 sb.append("UnmountObbAction{");
2313 sb.append("filename=");
2314 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2315 sb.append(",force=");
2316 sb.append(mForceUnmount);
2317 sb.append(",callerUid=");
2318 sb.append(mObbState.callerUid);
2319 sb.append(",token=");
2320 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002321 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002322 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002323 sb.append('}');
2324 return sb.toString();
2325 }
Kenny Root02c87302010-07-01 08:10:18 -07002326 }
Kenny Root38cf8862010-09-26 14:18:51 -07002327
2328 @Override
2329 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2330 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2331 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2332 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2333 + " without permission " + android.Manifest.permission.DUMP);
2334 return;
2335 }
2336
Kenny Root38cf8862010-09-26 14:18:51 -07002337 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002338 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002339
Kenny Rootaf9d6672010-10-08 09:21:39 -07002340 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2341 while (binders.hasNext()) {
2342 Entry<IBinder, List<ObbState>> e = binders.next();
2343 pw.print(" Key="); pw.println(e.getKey().toString());
2344 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002345 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002346 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002347 }
2348 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002349
2350 pw.println("");
2351 pw.println(" mObbPathToStateMap:");
2352 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2353 while (maps.hasNext()) {
2354 final Entry<String, ObbState> e = maps.next();
2355 pw.print(" "); pw.print(e.getKey());
2356 pw.print(" -> "); pw.println(e.getValue().toString());
2357 }
Kenny Root38cf8862010-09-26 14:18:51 -07002358 }
2359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360}
2361