blob: fd0320198998bfdcd6fcd30b00ac07a940531f69 [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;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070022import com.android.server.pm.PackageManagerService;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080023
Jason parks8888c592011-01-20 22:46:41 -060024import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070026import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070030import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070033import android.content.res.Resources;
34import android.content.res.TypedArray;
35import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070036import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070038import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070039import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070045import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080046import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080047import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080048import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
62import org.xmlpull.v1.XmlPullParser;
63import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070064
Kenny Root38cf8862010-09-26 14:18:51 -070065import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070066import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070067import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070068import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070069import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070070import java.security.spec.InvalidKeySpecException;
71import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080072import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070073import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080074import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070076import java.util.LinkedList;
77import java.util.List;
78import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070080import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Kenny Root3b1abba2010-10-13 15:00:07 -070082import javax.crypto.SecretKey;
83import javax.crypto.SecretKeyFactory;
84import javax.crypto.spec.PBEKeySpec;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086/**
San Mehatb1043402010-02-05 08:26:50 -080087 * MountService implements back-end services for platform storage
88 * management.
89 * @hide - Applications should use android.os.storage.StorageManager
90 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070092class MountService extends IMountService.Stub
93 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -060094
San Mehatb1043402010-02-05 08:26:50 -080095 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080096 private static final boolean DEBUG_UNMOUNT = false;
97 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080098 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private static final String TAG = "MountService";
101
Kenny Root305bcbf2010-09-03 07:56:38 -0700102 private static final String VOLD_TAG = "VoldConnector";
103
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700104 /** Maximum number of ASEC containers allowed to be mounted. */
105 private static final int MAX_CONTAINERS = 250;
106
San Mehat4270e1e2010-01-29 05:32:19 -0800107 /*
108 * Internal vold volume state constants
109 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800110 class VolumeState {
111 public static final int Init = -1;
112 public static final int NoMedia = 0;
113 public static final int Idle = 1;
114 public static final int Pending = 2;
115 public static final int Checking = 3;
116 public static final int Mounted = 4;
117 public static final int Unmounting = 5;
118 public static final int Formatting = 6;
119 public static final int Shared = 7;
120 public static final int SharedMnt = 8;
121 }
122
San Mehat4270e1e2010-01-29 05:32:19 -0800123 /*
124 * Internal vold response code constants
125 */
San Mehat22dd86e2010-01-12 12:21:18 -0800126 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800127 /*
128 * 100 series - Requestion action was initiated; expect another reply
129 * before proceeding with a new command.
130 */
San Mehat22dd86e2010-01-12 12:21:18 -0800131 public static final int VolumeListResult = 110;
132 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800133 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800134
San Mehat4270e1e2010-01-29 05:32:19 -0800135 /*
136 * 200 series - Requestion action has been successfully completed.
137 */
138 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800139 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800140 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800141
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * 400 series - Command was accepted, but the requested action
144 * did not take place.
145 */
146 public static final int OpFailedNoMedia = 401;
147 public static final int OpFailedMediaBlank = 402;
148 public static final int OpFailedMediaCorrupt = 403;
149 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800150 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700151 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800152
153 /*
154 * 600 series - Unsolicited broadcasts.
155 */
San Mehat22dd86e2010-01-12 12:21:18 -0800156 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800157 public static final int VolumeDiskInserted = 630;
158 public static final int VolumeDiskRemoved = 631;
159 public static final int VolumeBadRemoval = 632;
160 }
161
San Mehat4270e1e2010-01-29 05:32:19 -0800162 private Context mContext;
163 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700164 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
165 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400166 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400167 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400168 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800169 private PackageManagerService mPms;
170 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700171 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800172 // Used as a lock for methods that register/unregister listeners.
173 final private ArrayList<MountServiceBinderListener> mListeners =
174 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800175 private boolean mBooted = false;
176 private boolean mReady = false;
177 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400178 // true if we should fake MEDIA_MOUNTED state for external storage
179 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800180
San Mehat6cdd9c02010-02-09 14:45:20 -0800181 /**
182 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800183 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800184 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800185 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800186
Kenny Root02c87302010-07-01 08:10:18 -0700187 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700188 * The size of the crypto algorithm key in bits for OBB files. Currently
189 * Twofish is used which takes 128-bit keys.
190 */
191 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
192
193 /**
194 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
195 * 1024 is reasonably secure and not too slow.
196 */
197 private static final int PBKDF2_HASH_ROUNDS = 1024;
198
199 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700200 * Mounted OBB tracking information. Used to track the current state of all
201 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700202 */
Kenny Root735de3b2010-09-30 14:11:39 -0700203 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700204 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
205
206 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700207 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700208 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700209 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700210 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700211 this.token = token;
212 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700213 }
214
215 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700216 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700217
218 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700219 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700220
Kenny Rootaf9d6672010-10-08 09:21:39 -0700221 // Token of remote Binder caller
222 final IObbActionListener token;
223
224 // Identifier to pass back to the token
225 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700226
Kenny Root735de3b2010-09-30 14:11:39 -0700227 public IBinder getBinder() {
228 return token.asBinder();
229 }
230
Kenny Roota02b8b02010-08-05 16:14:17 -0700231 @Override
232 public void binderDied() {
233 ObbAction action = new UnmountObbAction(this, true);
234 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700235 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700236
Kenny Root5919ac62010-10-05 09:49:40 -0700237 public void link() throws RemoteException {
238 getBinder().linkToDeath(this, 0);
239 }
240
241 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700242 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700243 }
Kenny Root38cf8862010-09-26 14:18:51 -0700244
245 @Override
246 public String toString() {
247 StringBuilder sb = new StringBuilder("ObbState{");
248 sb.append("filename=");
249 sb.append(filename);
250 sb.append(",token=");
251 sb.append(token.toString());
252 sb.append(",callerUid=");
253 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700254 sb.append('}');
255 return sb.toString();
256 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700257 }
258
259 // OBB Action Handler
260 final private ObbActionHandler mObbActionHandler;
261
262 // OBB action handler messages
263 private static final int OBB_RUN_ACTION = 1;
264 private static final int OBB_MCS_BOUND = 2;
265 private static final int OBB_MCS_UNBIND = 3;
266 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700267 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
269 /*
270 * Default Container Service information
271 */
272 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
273 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
274
275 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
276
277 class DefaultContainerConnection implements ServiceConnection {
278 public void onServiceConnected(ComponentName name, IBinder service) {
279 if (DEBUG_OBB)
280 Slog.i(TAG, "onServiceConnected");
281 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
282 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
283 }
284
285 public void onServiceDisconnected(ComponentName name) {
286 if (DEBUG_OBB)
287 Slog.i(TAG, "onServiceDisconnected");
288 }
289 };
290
291 // Used in the ObbActionHandler
292 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700293
294 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800295 private static final int H_UNMOUNT_PM_UPDATE = 1;
296 private static final int H_UNMOUNT_PM_DONE = 2;
297 private static final int H_UNMOUNT_MS = 3;
298 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
299 private static final int MAX_UNMOUNT_RETRIES = 4;
300
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800301 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700302 final String path;
303 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800304 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800305
306 UnmountCallBack(String path, boolean force) {
307 retries = 0;
308 this.path = path;
309 this.force = force;
310 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800311
312 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700313 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800314 doUnmountVolume(path, true);
315 }
316 }
317
318 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700319 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800320
321 UmsEnableCallBack(String path, String method, boolean force) {
322 super(path, force);
323 this.method = method;
324 }
325
326 @Override
327 void handleFinished() {
328 super.handleFinished();
329 doShareUnshareVolume(path, method, true);
330 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800331 }
332
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800333 class ShutdownCallBack extends UnmountCallBack {
334 IMountShutdownObserver observer;
335 ShutdownCallBack(String path, IMountShutdownObserver observer) {
336 super(path, true);
337 this.observer = observer;
338 }
339
340 @Override
341 void handleFinished() {
342 int ret = doUnmountVolume(path, true);
343 if (observer != null) {
344 try {
345 observer.onShutDownComplete(ret);
346 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700347 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800348 }
349 }
350 }
351 }
352
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400353 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700355 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800356
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400357 MountServiceHandler(Looper l) {
358 super(l);
359 }
360
Jason parks5af0b912010-11-29 09:05:25 -0600361 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800362 public void handleMessage(Message msg) {
363 switch (msg.what) {
364 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700365 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800366 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
367 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700368 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800369 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700370 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700371 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700372 mUpdatingStatus = true;
373 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800374 }
375 break;
376 }
377 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700378 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700379 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700380 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800381 int size = mForceUnmounts.size();
382 int sizeArr[] = new int[size];
383 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700384 // Kill processes holding references first
385 ActivityManagerService ams = (ActivityManagerService)
386 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 for (int i = 0; i < size; i++) {
388 UnmountCallBack ucb = mForceUnmounts.get(i);
389 String path = ucb.path;
390 boolean done = false;
391 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800392 done = true;
393 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800394 int pids[] = getStorageUsers(path);
395 if (pids == null || pids.length == 0) {
396 done = true;
397 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800398 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800399 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700400 // Confirm if file references have been freed.
401 pids = getStorageUsers(path);
402 if (pids == null || pids.length == 0) {
403 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800404 }
405 }
406 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700407 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
408 // Retry again
409 Slog.i(TAG, "Retrying to kill storage users again");
410 mHandler.sendMessageDelayed(
411 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
412 ucb.retries++),
413 RETRY_UNMOUNT_DELAY);
414 } else {
415 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
416 Slog.i(TAG, "Failed to unmount media inspite of " +
417 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
418 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 sizeArr[sizeArrN++] = i;
420 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
421 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800422 }
423 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800424 // Remove already processed elements from list.
425 for (int i = (sizeArrN-1); i >= 0; i--) {
426 mForceUnmounts.remove(sizeArr[i]);
427 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800428 break;
429 }
430 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700431 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800432 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800433 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800434 break;
435 }
436 }
437 }
438 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400439 final private HandlerThread mHandlerThread;
440 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800441
San Mehat207e5382010-02-04 20:46:54 -0800442 private void waitForReady() {
443 while (mReady == false) {
444 for (int retries = 5; retries > 0; retries--) {
445 if (mReady) {
446 return;
447 }
448 SystemClock.sleep(1000);
449 }
San Mehata5078592010-03-25 09:36:54 -0700450 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800451 }
San Mehat1f6301e2010-01-07 22:40:27 -0800452 }
Kenny Root02c87302010-07-01 08:10:18 -0700453
San Mehat207e5382010-02-04 20:46:54 -0800454 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600455 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800457 String action = intent.getAction();
458
459 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800460 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800461
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800462 /*
463 * In the simulator, we need to broadcast a volume mounted event
464 * to make the media scanner run.
465 */
466 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400467 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
468 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800469 return;
470 }
San Mehatfafb0412010-02-18 19:40:04 -0800471 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600472 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800473 public void run() {
474 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400475 // it is not safe to call vold with mVolumeStates locked
476 // so we make a copy of the paths and states and process them
477 // outside the lock
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700478 String[] paths;
479 String[] states;
Mike Lockwood84338c42011-04-05 10:05:47 -0400480 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400481 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400482 Set<String> keys = mVolumeStates.keySet();
483 count = keys.size();
484 paths = (String[])keys.toArray(new String[count]);
485 states = new String[count];
486 for (int i = 0; i < count; i++) {
487 states[i] = mVolumeStates.get(paths[i]);
488 }
489 }
San Mehat6a254402010-03-22 10:21:00 -0700490
Mike Lockwood84338c42011-04-05 10:05:47 -0400491 for (int i = 0; i < count; i++) {
492 String path = paths[i];
493 String state = states[i];
494
495 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
496 int rc = doMountVolume(path);
497 if (rc != StorageResultCode.OperationSucceeded) {
498 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
499 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400500 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400501 } else if (state.equals(Environment.MEDIA_SHARED)) {
502 /*
503 * Bootstrap UMS enabled state since vold indicates
504 * the volume is shared (runtime restart while ums enabled)
505 */
506 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
507 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800508 }
509 }
San Mehat6a254402010-03-22 10:21:00 -0700510
Mike Lockwood80e0a412011-04-05 10:21:51 -0400511 /* notify external storage has mounted to trigger media scanner */
512 if (mEmulateExternalStorage) {
513 notifyVolumeStateChange(null,
514 Environment.getExternalStorageDirectory().getPath(),
515 VolumeState.NoMedia, VolumeState.Mounted);
516 }
517
San Mehat6a965af22010-02-24 17:47:30 -0800518 /*
San Mehat6a254402010-03-22 10:21:00 -0700519 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800520 * now that we're up.
521 */
522 if (mSendUmsConnectedOnBoot) {
523 sendUmsIntent(true);
524 mSendUmsConnectedOnBoot = false;
525 }
San Mehatfafb0412010-02-18 19:40:04 -0800526 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700527 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800528 }
San Mehat207e5382010-02-04 20:46:54 -0800529 }
San Mehatfafb0412010-02-18 19:40:04 -0800530 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700531 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
532 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
533 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
534 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 }
536 }
537 };
San Mehat4270e1e2010-01-29 05:32:19 -0800538 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
539 final IMountServiceListener mListener;
540
541 MountServiceBinderListener(IMountServiceListener listener) {
542 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700543
San Mehat91c77612010-01-07 10:39:41 -0800544 }
545
San Mehat4270e1e2010-01-29 05:32:19 -0800546 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700547 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700548 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800549 mListeners.remove(this);
550 mListener.asBinder().unlinkToDeath(this, 0);
551 }
552 }
553 }
554
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800555 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800556 // TODO: Add support for multiple share methods
557 if (!method.equals("ums")) {
558 throw new IllegalArgumentException(String.format("Method %s not supported", method));
559 }
560
San Mehat4270e1e2010-01-29 05:32:19 -0800561 try {
562 mConnector.doCommand(String.format(
563 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
564 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700565 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800566 }
San Mehat4270e1e2010-01-29 05:32:19 -0800567 }
568
San Mehat207e5382010-02-04 20:46:54 -0800569 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400570 String oldState;
571 synchronized(mVolumeStates) {
572 oldState = mVolumeStates.put(path, state);
573 }
574 if (state.equals(oldState)) {
575 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
576 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800577 return;
578 }
San Mehatb1043402010-02-05 08:26:50 -0800579
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400580 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700581
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400582 if (path.equals(mExternalStoragePath)) {
583 // Update state on PackageManager, but only of real events
584 if (!mEmulateExternalStorage) {
585 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
586 mPms.updateExternalMediaStatus(false, false);
587
588 /*
589 * Some OBBs might have been unmounted when this volume was
590 * unmounted, so send a message to the handler to let it know to
591 * remove those from the list of mounted OBBS.
592 */
593 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
594 OBB_FLUSH_MOUNT_STATE, path));
595 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
596 mPms.updateExternalMediaStatus(true, false);
597 }
Mike Lockwood03559752010-07-19 18:25:03 -0400598 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800599 }
San Mehat4270e1e2010-01-29 05:32:19 -0800600 synchronized (mListeners) {
601 for (int i = mListeners.size() -1; i >= 0; i--) {
602 MountServiceBinderListener bl = mListeners.get(i);
603 try {
San Mehatb1043402010-02-05 08:26:50 -0800604 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800605 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700606 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800607 mListeners.remove(i);
608 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700609 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800610 }
611 }
612 }
613 }
614
615 /**
616 *
617 * Callback from NativeDaemonConnector
618 */
619 public void onDaemonConnected() {
620 /*
621 * Since we'll be calling back into the NativeDaemonConnector,
622 * we need to do our work in a new thread.
623 */
624 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600625 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800626 public void run() {
627 /**
628 * Determine media state and UMS detection status
629 */
San Mehat4270e1e2010-01-29 05:32:19 -0800630 try {
631 String[] vols = mConnector.doListCommand(
632 "volume list", VoldResponseCode.VolumeListResult);
633 for (String volstr : vols) {
634 String[] tok = volstr.split(" ");
635 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400636 String path = tok[1];
637 String state = Environment.MEDIA_REMOVED;
638
San Mehat4270e1e2010-01-29 05:32:19 -0800639 int st = Integer.parseInt(tok[2]);
640 if (st == VolumeState.NoMedia) {
641 state = Environment.MEDIA_REMOVED;
642 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800643 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800644 } else if (st == VolumeState.Mounted) {
645 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700646 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800647 } else if (st == VolumeState.Shared) {
648 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700649 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800650 } else {
651 throw new Exception(String.format("Unexpected state %d", st));
652 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400653
654 if (state != null) {
655 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
656 updatePublicVolumeState(path, state);
657 }
San Mehat4270e1e2010-01-29 05:32:19 -0800658 }
659 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700660 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400661 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800662 }
663
San Mehat207e5382010-02-04 20:46:54 -0800664 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600665 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800666 * the hounds!
667 */
668 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800669 }
670 }.start();
671 }
672
673 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800674 * Callback from NativeDaemonConnector
675 */
676 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800677 if (DEBUG_EVENTS) {
678 StringBuilder builder = new StringBuilder();
679 builder.append("onEvent::");
680 builder.append(" raw= " + raw);
681 if (cooked != null) {
682 builder.append(" cooked = " );
683 for (String str : cooked) {
684 builder.append(" " + str);
685 }
686 }
San Mehata5078592010-03-25 09:36:54 -0700687 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800688 }
San Mehat4270e1e2010-01-29 05:32:19 -0800689 if (code == VoldResponseCode.VolumeStateChange) {
690 /*
691 * One of the volumes we're managing has changed state.
692 * Format: "NNN Volume <label> <path> state changed
693 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
694 */
695 notifyVolumeStateChange(
696 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
697 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800698 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
699 (code == VoldResponseCode.VolumeDiskRemoved) ||
700 (code == VoldResponseCode.VolumeBadRemoval)) {
701 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
702 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
703 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400704 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800705 final String label = cooked[2];
706 final String path = cooked[3];
707 int major = -1;
708 int minor = -1;
709
710 try {
711 String devComp = cooked[6].substring(1, cooked[6].length() -1);
712 String[] devTok = devComp.split(":");
713 major = Integer.parseInt(devTok[0]);
714 minor = Integer.parseInt(devTok[1]);
715 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700716 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800717 }
718
San Mehat4270e1e2010-01-29 05:32:19 -0800719 if (code == VoldResponseCode.VolumeDiskInserted) {
720 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600721 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800722 public void run() {
723 try {
724 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800725 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700726 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800727 }
728 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700729 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800730 }
731 }
732 }.start();
733 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
734 /*
735 * This event gets trumped if we're already in BAD_REMOVAL state
736 */
737 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
738 return true;
739 }
740 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700741 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800742 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400743 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800744
San Mehata5078592010-03-25 09:36:54 -0700745 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800746 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400747 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800748 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700749 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800750 /* Send the media unmounted event first */
751 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400752 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800753
San Mehata5078592010-03-25 09:36:54 -0700754 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800755 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400756 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800757 } else {
San Mehata5078592010-03-25 09:36:54 -0700758 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800759 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400760
761 if (action != null) {
762 sendStorageIntent(action, path);
763 }
San Mehat4270e1e2010-01-29 05:32:19 -0800764 } else {
765 return false;
766 }
767
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400768 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800769 }
770
San Mehat207e5382010-02-04 20:46:54 -0800771 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800772 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700773 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800774
Mike Lockwooda5250c92011-05-23 13:44:04 -0400775 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800776
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500777 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700778 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400779 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500780 }
781
San Mehat4270e1e2010-01-29 05:32:19 -0800782 if (newState == VolumeState.Init) {
783 } else if (newState == VolumeState.NoMedia) {
784 // NoMedia is handled via Disk Remove events
785 } else if (newState == VolumeState.Idle) {
786 /*
787 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
788 * if we're in the process of enabling UMS
789 */
790 if (!vs.equals(
791 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
792 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800793 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700794 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800795 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400796 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800797 }
798 } else if (newState == VolumeState.Pending) {
799 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700800 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800801 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400802 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800803 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700804 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800805 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400806 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800807 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800809 } else if (newState == VolumeState.Formatting) {
810 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700811 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800812 /* Send the media unmounted event first */
813 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400814 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800815
San Mehata5078592010-03-25 09:36:54 -0700816 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800817 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400818 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700819 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800820 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700821 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800822 return;
823 } else {
San Mehata5078592010-03-25 09:36:54 -0700824 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800825 }
826
Mike Lockwooda5250c92011-05-23 13:44:04 -0400827 if (action != null) {
828 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800829 }
830 }
831
San Mehat207e5382010-02-04 20:46:54 -0800832 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800833 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800834
San Mehata5078592010-03-25 09:36:54 -0700835 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800836 try {
837 mConnector.doCommand(String.format("volume mount %s", path));
838 } catch (NativeDaemonConnectorException e) {
839 /*
840 * Mount failed for some reason
841 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400842 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800843 int code = e.getCode();
844 if (code == VoldResponseCode.OpFailedNoMedia) {
845 /*
846 * Attempt to mount but no media inserted
847 */
San Mehatb1043402010-02-05 08:26:50 -0800848 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800849 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700850 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800851 /*
852 * Media is blank or does not contain a supported filesystem
853 */
854 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400855 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800856 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800857 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800859 /*
860 * Volume consistency check failed
861 */
862 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400863 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800864 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800865 } else {
San Mehatb1043402010-02-05 08:26:50 -0800866 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800867 }
868
869 /*
870 * Send broadcast intent (if required for the failure)
871 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400872 if (action != null) {
873 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800874 }
875 }
876
877 return rc;
878 }
879
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800880 /*
881 * If force is not set, we do not unmount if there are
882 * processes holding references to the volume about to be unmounted.
883 * If force is set, all the processes holding references need to be
884 * killed via the ActivityManager before actually unmounting the volume.
885 * This might even take a while and might be retried after timed delays
886 * to make sure we dont end up in an instable state and kill some core
887 * processes.
888 */
San Mehatd9709982010-02-18 11:43:03 -0800889 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800890 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800891 return VoldResponseCode.OpFailedVolNotMounted;
892 }
Kenny Rootaa485402010-09-14 14:49:41 -0700893
894 /*
895 * Force a GC to make sure AssetManagers in other threads of the
896 * system_server are cleaned up. We have to do this since AssetManager
897 * instances are kept as a WeakReference and it's possible we have files
898 * open on the external storage.
899 */
900 Runtime.getRuntime().gc();
901
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800902 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700903 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800904 try {
San Mehatd9709982010-02-18 11:43:03 -0800905 mConnector.doCommand(String.format(
906 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700907 // We unmounted the volume. None of the asec containers are available now.
908 synchronized (mAsecMountSet) {
909 mAsecMountSet.clear();
910 }
San Mehatb1043402010-02-05 08:26:50 -0800911 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800912 } catch (NativeDaemonConnectorException e) {
913 // Don't worry about mismatch in PackageManager since the
914 // call back will handle the status changes any way.
915 int code = e.getCode();
916 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800917 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800918 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
919 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800920 } else {
San Mehatb1043402010-02-05 08:26:50 -0800921 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800922 }
923 }
924 }
925
926 private int doFormatVolume(String path) {
927 try {
928 String cmd = String.format("volume format %s", path);
929 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800930 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800931 } catch (NativeDaemonConnectorException e) {
932 int code = e.getCode();
933 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800935 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800936 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800937 } else {
San Mehatb1043402010-02-05 08:26:50 -0800938 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800939 }
940 }
941 }
942
San Mehatb1043402010-02-05 08:26:50 -0800943 private boolean doGetVolumeShared(String path, String method) {
944 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700945 ArrayList<String> rsp;
946
947 try {
948 rsp = mConnector.doCommand(cmd);
949 } catch (NativeDaemonConnectorException ex) {
950 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
951 return false;
952 }
San Mehatb1043402010-02-05 08:26:50 -0800953
954 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700955 String[] tok = line.split(" ");
956 if (tok.length < 3) {
957 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
958 return false;
959 }
960
San Mehatb1043402010-02-05 08:26:50 -0800961 int code;
962 try {
963 code = Integer.parseInt(tok[0]);
964 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700965 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800966 return false;
967 }
968 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700969 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800970 } else {
San Mehata5078592010-03-25 09:36:54 -0700971 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800972 return false;
973 }
974 }
San Mehata5078592010-03-25 09:36:54 -0700975 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800976 return false;
977 }
978
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700979 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800980 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700981 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800982 for (int i = mListeners.size() -1; i >= 0; i--) {
983 MountServiceBinderListener bl = mListeners.get(i);
984 try {
San Mehatb1043402010-02-05 08:26:50 -0800985 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800986 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700987 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800988 mListeners.remove(i);
989 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700990 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800991 }
992 }
993 }
994
San Mehat207e5382010-02-04 20:46:54 -0800995 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800996 sendUmsIntent(avail);
997 } else {
998 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800999 }
San Mehat2fe718a2010-03-11 12:01:49 -08001000
1001 final String path = Environment.getExternalStorageDirectory().getPath();
1002 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1003 /*
1004 * USB mass storage disconnected while enabled
1005 */
1006 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001007 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001008 public void run() {
1009 try {
1010 int rc;
San Mehata5078592010-03-25 09:36:54 -07001011 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001012 doShareUnshareVolume(path, "ums", false);
1013 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001014 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001015 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1016 path, rc));
1017 }
1018 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001019 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001020 }
1021 }
1022 }.start();
1023 }
San Mehat4270e1e2010-01-29 05:32:19 -08001024 }
1025
Mike Lockwooda5250c92011-05-23 13:44:04 -04001026 private void sendStorageIntent(String action, String path) {
1027 Intent intent = new Intent(action, Uri.parse("file://" + path));
1028 // add StorageVolume extra
1029 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1030 Slog.d(TAG, "sendStorageIntent " + intent);
1031 mContext.sendBroadcast(intent);
1032 }
1033
San Mehat6a965af22010-02-24 17:47:30 -08001034 private void sendUmsIntent(boolean c) {
1035 mContext.sendBroadcast(
1036 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1037 }
1038
San Mehat207e5382010-02-04 20:46:54 -08001039 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001040 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1041 throw new SecurityException(String.format("Requires %s permission", perm));
1042 }
1043 }
1044
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001045 // Storage list XML tags
1046 private static final String TAG_STORAGE_LIST = "StorageList";
1047 private static final String TAG_STORAGE = "storage";
1048
1049 private void readStorageList(Resources resources) {
1050 int id = com.android.internal.R.xml.storage_list;
1051 XmlResourceParser parser = resources.getXml(id);
1052 AttributeSet attrs = Xml.asAttributeSet(parser);
1053
1054 try {
1055 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1056 while (true) {
1057 XmlUtils.nextElement(parser);
1058
1059 String element = parser.getName();
1060 if (element == null) break;
1061
1062 if (TAG_STORAGE.equals(element)) {
1063 TypedArray a = resources.obtainAttributes(attrs,
1064 com.android.internal.R.styleable.Storage);
1065
1066 CharSequence path = a.getText(
1067 com.android.internal.R.styleable.Storage_mountPoint);
1068 CharSequence description = a.getText(
1069 com.android.internal.R.styleable.Storage_storageDescription);
1070 boolean primary = a.getBoolean(
1071 com.android.internal.R.styleable.Storage_primary, false);
1072 boolean removable = a.getBoolean(
1073 com.android.internal.R.styleable.Storage_removable, false);
1074 boolean emulated = a.getBoolean(
1075 com.android.internal.R.styleable.Storage_emulated, false);
1076 int mtpReserve = a.getInt(
1077 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001078 boolean allowMassStorage = a.getBoolean(
1079 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001080 // resource parser does not support longs, so XML value is in megabytes
1081 long maxFileSize = a.getInt(
1082 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001083
1084 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1085 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001086 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001087 " allowMassStorage: " + allowMassStorage +
1088 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001089 if (path == null || description == null) {
1090 Slog.e(TAG, "path or description is null in readStorageList");
1091 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001092 String pathString = path.toString();
1093 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001094 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001095 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001096 if (primary) {
1097 if (mPrimaryVolume == null) {
1098 mPrimaryVolume = volume;
1099 } else {
1100 Slog.e(TAG, "multiple primary volumes in storage list");
1101 }
1102 }
1103 if (mPrimaryVolume == volume) {
1104 // primay volume must be first
1105 mVolumes.add(0, volume);
1106 } else {
1107 mVolumes.add(volume);
1108 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001109 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001110 }
1111 a.recycle();
1112 }
1113 }
1114 } catch (XmlPullParserException e) {
1115 throw new RuntimeException(e);
1116 } catch (IOException e) {
1117 throw new RuntimeException(e);
1118 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001119 // compute storage ID for each volume
1120 int length = mVolumes.size();
1121 for (int i = 0; i < length; i++) {
1122 mVolumes.get(i).setStorageId(i);
1123 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001124 parser.close();
1125 }
1126 }
1127
San Mehat4270e1e2010-01-29 05:32:19 -08001128 /**
San Mehat207e5382010-02-04 20:46:54 -08001129 * Constructs a new MountService instance
1130 *
1131 * @param context Binder context for this service
1132 */
1133 public MountService(Context context) {
1134 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001135 Resources resources = context.getResources();
1136 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001137
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001138 if (mPrimaryVolume != null) {
1139 mExternalStoragePath = mPrimaryVolume.getPath();
1140 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1141 if (mEmulateExternalStorage) {
1142 Slog.d(TAG, "using emulated external storage");
1143 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1144 }
Mike Lockwood03559752010-07-19 18:25:03 -04001145 }
1146
San Mehat207e5382010-02-04 20:46:54 -08001147 // XXX: This will go away soon in favor of IMountServiceObserver
1148 mPms = (PackageManagerService) ServiceManager.getService("package");
1149
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001150 IntentFilter filter = new IntentFilter();
1151 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1152 // don't bother monitoring USB if mass storage is not supported on our primary volume
1153 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1154 filter.addAction(UsbManager.ACTION_USB_STATE);
1155 }
1156 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001157
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001158 mHandlerThread = new HandlerThread("MountService");
1159 mHandlerThread.start();
1160 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1161
Kenny Roota02b8b02010-08-05 16:14:17 -07001162 // Add OBB Action Handler to MountService thread.
1163 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1164
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001165 /*
1166 * Vold does not run in the simulator, so pretend the connector thread
1167 * ran and did its thing.
1168 */
1169 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1170 mReady = true;
1171 mUmsEnabling = true;
1172 return;
1173 }
1174
Kenny Root305bcbf2010-09-03 07:56:38 -07001175 /*
1176 * Create the connection to vold with a maximum queue of twice the
1177 * amount of containers we'd ever expect to have. This keeps an
1178 * "asec list" from blocking a thread repeatedly.
1179 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001180 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001181 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001182 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001183 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001184
1185 // Add ourself to the Watchdog monitors.
1186 Watchdog.getInstance().addMonitor(this);
San Mehat207e5382010-02-04 20:46:54 -08001187 }
1188
1189 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001190 * Exposed API calls below here
1191 */
1192
1193 public void registerListener(IMountServiceListener listener) {
1194 synchronized (mListeners) {
1195 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1196 try {
1197 listener.asBinder().linkToDeath(bl, 0);
1198 mListeners.add(bl);
1199 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001200 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001201 }
1202 }
1203 }
1204
1205 public void unregisterListener(IMountServiceListener listener) {
1206 synchronized (mListeners) {
1207 for(MountServiceBinderListener bl : mListeners) {
1208 if (bl.mListener == listener) {
1209 mListeners.remove(mListeners.indexOf(bl));
1210 return;
1211 }
1212 }
1213 }
1214 }
1215
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001216 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001217 validatePermission(android.Manifest.permission.SHUTDOWN);
1218
San Mehata5078592010-03-25 09:36:54 -07001219 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001220 synchronized (mVolumeStates) {
1221 for (String path : mVolumeStates.keySet()) {
1222 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001223
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001224 if (state.equals(Environment.MEDIA_SHARED)) {
1225 /*
1226 * If the media is currently shared, unshare it.
1227 * XXX: This is still dangerous!. We should not
1228 * be rebooting at *all* if UMS is enabled, since
1229 * the UMS host could have dirty FAT cache entries
1230 * yet to flush.
1231 */
1232 setUsbMassStorageEnabled(false);
1233 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1234 /*
1235 * If the media is being checked, then we need to wait for
1236 * it to complete before being able to proceed.
1237 */
1238 // XXX: @hackbod - Should we disable the ANR timer here?
1239 int retries = 30;
1240 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1241 try {
1242 Thread.sleep(1000);
1243 } catch (InterruptedException iex) {
1244 Slog.e(TAG, "Interrupted while waiting for media", iex);
1245 break;
1246 }
1247 state = Environment.getExternalStorageState();
1248 }
1249 if (retries == 0) {
1250 Slog.e(TAG, "Timed out waiting for media to check");
1251 }
San Mehat91c77612010-01-07 10:39:41 -08001252 }
San Mehat91c77612010-01-07 10:39:41 -08001253
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001254 if (state.equals(Environment.MEDIA_MOUNTED)) {
1255 // Post a unmount message.
1256 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1257 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1258 } else if (observer != null) {
1259 /*
1260 * Observer is waiting for onShutDownComplete when we are done.
1261 * Since nothing will be done send notification directly so shutdown
1262 * sequence can continue.
1263 */
1264 try {
1265 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1266 } catch (RemoteException e) {
1267 Slog.w(TAG, "RemoteException when shutting down");
1268 }
1269 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001270 }
San Mehat4270e1e2010-01-29 05:32:19 -08001271 }
1272 }
1273
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001274 private boolean getUmsEnabling() {
1275 synchronized (mListeners) {
1276 return mUmsEnabling;
1277 }
1278 }
1279
1280 private void setUmsEnabling(boolean enable) {
1281 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001282 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001283 }
1284 }
1285
San Mehatb1043402010-02-05 08:26:50 -08001286 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001287 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001288
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001289 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001290 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001291 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001292 synchronized (mListeners) {
1293 return mUmsAvailable;
1294 }
San Mehatb1043402010-02-05 08:26:50 -08001295 }
1296
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001297 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001298 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001299 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001300
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001301 // TODO: Add support for multiple share methods
1302
1303 /*
1304 * If the volume is mounted and we're enabling then unmount it
1305 */
1306 String path = Environment.getExternalStorageDirectory().getPath();
1307 String vs = getVolumeState(path);
1308 String method = "ums";
1309 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1310 // Override for isUsbMassStorageEnabled()
1311 setUmsEnabling(enable);
1312 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1313 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1314 // Clear override
1315 setUmsEnabling(false);
1316 }
1317 /*
1318 * If we disabled UMS then mount the volume
1319 */
1320 if (!enable) {
1321 doShareUnshareVolume(path, method, enable);
1322 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001323 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001324 " after disabling share method " + method);
1325 /*
1326 * Even though the mount failed, the unshare didn't so don't indicate an error.
1327 * The mountVolume() call will have set the storage state and sent the necessary
1328 * broadcasts.
1329 */
1330 }
1331 }
San Mehatb1043402010-02-05 08:26:50 -08001332 }
1333
1334 public boolean isUsbMassStorageEnabled() {
1335 waitForReady();
1336 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001338
San Mehat7fd0fee2009-12-17 07:12:23 -08001339 /**
1340 * @return state of the volume at the specified mount point
1341 */
San Mehat4270e1e2010-01-29 05:32:19 -08001342 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001343 synchronized (mVolumeStates) {
1344 String state = mVolumeStates.get(mountPoint);
1345 if (state == null) {
1346 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001347 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1348 state = Environment.MEDIA_REMOVED;
1349 } else {
1350 throw new IllegalArgumentException();
1351 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001352 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001353
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001354 return state;
1355 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001356 }
1357
Kenny Roote1ff2142010-10-12 11:20:01 -07001358 public boolean isExternalStorageEmulated() {
1359 return mEmulateExternalStorage;
1360 }
1361
San Mehat4270e1e2010-01-29 05:32:19 -08001362 public int mountVolume(String path) {
1363 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001364
San Mehat207e5382010-02-04 20:46:54 -08001365 waitForReady();
1366 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001369 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001370 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001371 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001373 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001374 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001375 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1376 Environment.MEDIA_REMOVED.equals(volState) ||
1377 Environment.MEDIA_SHARED.equals(volState) ||
1378 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1379 // Media already unmounted or cannot be unmounted.
1380 // TODO return valid return code when adding observer call back.
1381 return;
1382 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001383 UnmountCallBack ucb = new UnmountCallBack(path, force);
1384 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386
San Mehat4270e1e2010-01-29 05:32:19 -08001387 public int formatVolume(String path) {
1388 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001389 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001390
San Mehat207e5382010-02-04 20:46:54 -08001391 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001394 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001395 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1396 waitForReady();
1397 try {
1398 String[] r = mConnector.doListCommand(
1399 String.format("storage users %s", path),
1400 VoldResponseCode.StorageUsersListResult);
1401 // FMT: <pid> <process name>
1402 int[] data = new int[r.length];
1403 for (int i = 0; i < r.length; i++) {
1404 String []tok = r[i].split(" ");
1405 try {
1406 data[i] = Integer.parseInt(tok[0]);
1407 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001408 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001409 return new int[0];
1410 }
1411 }
1412 return data;
1413 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001414 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001415 return new int[0];
1416 }
1417 }
1418
San Mehatb1043402010-02-05 08:26:50 -08001419 private void warnOnNotMounted() {
1420 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001421 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001422 }
1423 }
1424
San Mehat4270e1e2010-01-29 05:32:19 -08001425 public String[] getSecureContainerList() {
1426 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001427 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001428 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001429
San Mehat4270e1e2010-01-29 05:32:19 -08001430 try {
1431 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1432 } catch (NativeDaemonConnectorException e) {
1433 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 }
San Mehat36972292010-01-06 11:06:32 -08001436
San Mehat4270e1e2010-01-29 05:32:19 -08001437 public int createSecureContainer(String id, int sizeMb, String fstype,
1438 String key, int ownerUid) {
1439 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001440 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001441 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001442
San Mehatb1043402010-02-05 08:26:50 -08001443 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001444 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1445 try {
1446 mConnector.doCommand(cmd);
1447 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001448 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001449 }
San Mehata181b212010-02-11 06:50:20 -08001450
1451 if (rc == StorageResultCode.OperationSucceeded) {
1452 synchronized (mAsecMountSet) {
1453 mAsecMountSet.add(id);
1454 }
1455 }
San Mehat4270e1e2010-01-29 05:32:19 -08001456 return rc;
San Mehat36972292010-01-06 11:06:32 -08001457 }
1458
San Mehat4270e1e2010-01-29 05:32:19 -08001459 public int finalizeSecureContainer(String id) {
1460 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001461 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001462
San Mehatb1043402010-02-05 08:26:50 -08001463 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001464 try {
1465 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001466 /*
1467 * Finalization does a remount, so no need
1468 * to update mAsecMountSet
1469 */
San Mehat4270e1e2010-01-29 05:32:19 -08001470 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001471 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001472 }
San Mehat4270e1e2010-01-29 05:32:19 -08001473 return rc;
San Mehat36972292010-01-06 11:06:32 -08001474 }
1475
San Mehatd9709982010-02-18 11:43:03 -08001476 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001477 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001478 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001479 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001480
Kenny Rootaa485402010-09-14 14:49:41 -07001481 /*
1482 * Force a GC to make sure AssetManagers in other threads of the
1483 * system_server are cleaned up. We have to do this since AssetManager
1484 * instances are kept as a WeakReference and it's possible we have files
1485 * open on the external storage.
1486 */
1487 Runtime.getRuntime().gc();
1488
San Mehatb1043402010-02-05 08:26:50 -08001489 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001490 try {
San Mehatd9709982010-02-18 11:43:03 -08001491 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001492 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001493 int code = e.getCode();
1494 if (code == VoldResponseCode.OpFailedStorageBusy) {
1495 rc = StorageResultCode.OperationFailedStorageBusy;
1496 } else {
1497 rc = StorageResultCode.OperationFailedInternalError;
1498 }
San Mehat02735bc2010-01-26 15:18:08 -08001499 }
San Mehata181b212010-02-11 06:50:20 -08001500
1501 if (rc == StorageResultCode.OperationSucceeded) {
1502 synchronized (mAsecMountSet) {
1503 if (mAsecMountSet.contains(id)) {
1504 mAsecMountSet.remove(id);
1505 }
1506 }
1507 }
1508
San Mehat4270e1e2010-01-29 05:32:19 -08001509 return rc;
San Mehat36972292010-01-06 11:06:32 -08001510 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001511
San Mehat4270e1e2010-01-29 05:32:19 -08001512 public int mountSecureContainer(String id, String key, int ownerUid) {
1513 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001514 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001515 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001516
San Mehata181b212010-02-11 06:50:20 -08001517 synchronized (mAsecMountSet) {
1518 if (mAsecMountSet.contains(id)) {
1519 return StorageResultCode.OperationFailedStorageMounted;
1520 }
1521 }
1522
San Mehatb1043402010-02-05 08:26:50 -08001523 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001524 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1525 try {
1526 mConnector.doCommand(cmd);
1527 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001528 int code = e.getCode();
1529 if (code != VoldResponseCode.OpFailedStorageBusy) {
1530 rc = StorageResultCode.OperationFailedInternalError;
1531 }
San Mehat02735bc2010-01-26 15:18:08 -08001532 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001533
1534 if (rc == StorageResultCode.OperationSucceeded) {
1535 synchronized (mAsecMountSet) {
1536 mAsecMountSet.add(id);
1537 }
1538 }
San Mehat4270e1e2010-01-29 05:32:19 -08001539 return rc;
San Mehat36972292010-01-06 11:06:32 -08001540 }
1541
San Mehatd9709982010-02-18 11:43:03 -08001542 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001543 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001544 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001545 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001546
San Mehat6cdd9c02010-02-09 14:45:20 -08001547 synchronized (mAsecMountSet) {
1548 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001549 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001550 }
1551 }
1552
Kenny Rootaa485402010-09-14 14:49:41 -07001553 /*
1554 * Force a GC to make sure AssetManagers in other threads of the
1555 * system_server are cleaned up. We have to do this since AssetManager
1556 * instances are kept as a WeakReference and it's possible we have files
1557 * open on the external storage.
1558 */
1559 Runtime.getRuntime().gc();
1560
San Mehatb1043402010-02-05 08:26:50 -08001561 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001562 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001563 try {
1564 mConnector.doCommand(cmd);
1565 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001566 int code = e.getCode();
1567 if (code == VoldResponseCode.OpFailedStorageBusy) {
1568 rc = StorageResultCode.OperationFailedStorageBusy;
1569 } else {
1570 rc = StorageResultCode.OperationFailedInternalError;
1571 }
San Mehat02735bc2010-01-26 15:18:08 -08001572 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001573
1574 if (rc == StorageResultCode.OperationSucceeded) {
1575 synchronized (mAsecMountSet) {
1576 mAsecMountSet.remove(id);
1577 }
1578 }
San Mehat4270e1e2010-01-29 05:32:19 -08001579 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001580 }
1581
San Mehat6cdd9c02010-02-09 14:45:20 -08001582 public boolean isSecureContainerMounted(String id) {
1583 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1584 waitForReady();
1585 warnOnNotMounted();
1586
1587 synchronized (mAsecMountSet) {
1588 return mAsecMountSet.contains(id);
1589 }
1590 }
1591
San Mehat4270e1e2010-01-29 05:32:19 -08001592 public int renameSecureContainer(String oldId, String newId) {
1593 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001594 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001595 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001596
San Mehata181b212010-02-11 06:50:20 -08001597 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001598 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001599 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001600 * changed while active, we must ensure both ids are not currently mounted.
1601 */
1602 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001603 return StorageResultCode.OperationFailedStorageMounted;
1604 }
1605 }
1606
San Mehatb1043402010-02-05 08:26:50 -08001607 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001608 String cmd = String.format("asec rename %s %s", oldId, newId);
1609 try {
1610 mConnector.doCommand(cmd);
1611 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001612 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001613 }
San Mehata181b212010-02-11 06:50:20 -08001614
San Mehat4270e1e2010-01-29 05:32:19 -08001615 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001616 }
1617
San Mehat4270e1e2010-01-29 05:32:19 -08001618 public String getSecureContainerPath(String id) {
1619 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001620 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001621 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001622
San Mehat2d66cef2010-03-23 11:12:52 -07001623 try {
1624 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1625 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001626 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001627 if (code != VoldResponseCode.AsecPathResult) {
1628 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1629 }
1630 return tok[1];
1631 } catch (NativeDaemonConnectorException e) {
1632 int code = e.getCode();
1633 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001634 Slog.i(TAG, String.format("Container '%s' not found", id));
1635 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001636 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001637 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001638 }
1639 }
San Mehat22dd86e2010-01-12 12:21:18 -08001640 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001641
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001642 public String getSecureContainerFilesystemPath(String id) {
1643 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1644 waitForReady();
1645 warnOnNotMounted();
1646
1647 try {
1648 ArrayList<String> rsp = mConnector.doCommand(String.format("asec fspath %s", id));
1649 String []tok = rsp.get(0).split(" ");
1650 int code = Integer.parseInt(tok[0]);
1651 if (code != VoldResponseCode.AsecPathResult) {
1652 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1653 }
1654 return tok[1];
1655 } catch (NativeDaemonConnectorException e) {
1656 int code = e.getCode();
1657 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1658 Slog.i(TAG, String.format("Container '%s' not found", id));
1659 return null;
1660 } else {
1661 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1662 }
1663 }
1664 }
1665
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001666 public void finishMediaUpdate() {
1667 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1668 }
Kenny Root02c87302010-07-01 08:10:18 -07001669
Kenny Roota02b8b02010-08-05 16:14:17 -07001670 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1671 if (callerUid == android.os.Process.SYSTEM_UID) {
1672 return true;
1673 }
1674
Kenny Root02c87302010-07-01 08:10:18 -07001675 if (packageName == null) {
1676 return false;
1677 }
1678
1679 final int packageUid = mPms.getPackageUid(packageName);
1680
1681 if (DEBUG_OBB) {
1682 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1683 packageUid + ", callerUid = " + callerUid);
1684 }
1685
1686 return callerUid == packageUid;
1687 }
1688
1689 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001690 if (filename == null) {
1691 throw new IllegalArgumentException("filename cannot be null");
1692 }
1693
Kenny Root02c87302010-07-01 08:10:18 -07001694 waitForReady();
1695 warnOnNotMounted();
1696
Kenny Root02c87302010-07-01 08:10:18 -07001697 try {
1698 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1699 String []tok = rsp.get(0).split(" ");
1700 int code = Integer.parseInt(tok[0]);
1701 if (code != VoldResponseCode.AsecPathResult) {
1702 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1703 }
1704 return tok[1];
1705 } catch (NativeDaemonConnectorException e) {
1706 int code = e.getCode();
1707 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001708 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001709 } else {
1710 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1711 }
1712 }
1713 }
1714
1715 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001716 if (filename == null) {
1717 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001718 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001719
1720 synchronized (mObbMounts) {
1721 return mObbPathToStateMap.containsKey(filename);
1722 }
Kenny Root02c87302010-07-01 08:10:18 -07001723 }
1724
Kenny Rootaf9d6672010-10-08 09:21:39 -07001725 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001726 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001727 if (filename == null) {
1728 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001729 }
1730
1731 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001732 throw new IllegalArgumentException("token cannot be null");
1733 }
1734
Kenny Rootaf9d6672010-10-08 09:21:39 -07001735 final int callerUid = Binder.getCallingUid();
1736 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1737 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001738 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1739
1740 if (DEBUG_OBB)
1741 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001742 }
1743
Kenny Rootaf9d6672010-10-08 09:21:39 -07001744 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1745 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001746 if (filename == null) {
1747 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001748 }
1749
Kenny Rootaf9d6672010-10-08 09:21:39 -07001750 final int callerUid = Binder.getCallingUid();
1751 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1752 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001753 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001754
Kenny Roota02b8b02010-08-05 16:14:17 -07001755 if (DEBUG_OBB)
1756 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1757 }
1758
Jason parks5af0b912010-11-29 09:05:25 -06001759 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001760 if (TextUtils.isEmpty(password)) {
1761 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001762 }
1763
Jason parks8888c592011-01-20 22:46:41 -06001764 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1765 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001766
1767 waitForReady();
1768
1769 if (DEBUG_EVENTS) {
1770 Slog.i(TAG, "decrypting storage...");
1771 }
1772
1773 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001774 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001775 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001776
Jason parksf7b3cd42011-01-27 09:28:25 -06001777 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001778 return -1;
1779 }
1780
Jason parksf7b3cd42011-01-27 09:28:25 -06001781 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001782
1783 if (code == 0) {
1784 // Decrypt was successful. Post a delayed message before restarting in order
1785 // to let the UI to clear itself
1786 mHandler.postDelayed(new Runnable() {
1787 public void run() {
1788 mConnector.doCommand(String.format("cryptfs restart"));
1789 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001790 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001791 }
1792
1793 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001794 } catch (NativeDaemonConnectorException e) {
1795 // Decryption failed
1796 return e.getCode();
1797 }
Jason parks5af0b912010-11-29 09:05:25 -06001798 }
1799
Jason parks56aa5322011-01-07 09:01:15 -06001800 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001801 if (TextUtils.isEmpty(password)) {
1802 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001803 }
1804
Jason parks8888c592011-01-20 22:46:41 -06001805 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1806 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001807
1808 waitForReady();
1809
1810 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001811 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001812 }
1813
1814 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001815 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001816 } catch (NativeDaemonConnectorException e) {
1817 // Encryption failed
1818 return e.getCode();
1819 }
1820
1821 return 0;
1822 }
1823
Jason parksf7b3cd42011-01-27 09:28:25 -06001824 public int changeEncryptionPassword(String password) {
1825 if (TextUtils.isEmpty(password)) {
1826 throw new IllegalArgumentException("password cannot be empty");
1827 }
1828
1829 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1830 "no permission to access the crypt keeper");
1831
1832 waitForReady();
1833
1834 if (DEBUG_EVENTS) {
1835 Slog.i(TAG, "changing encryption password...");
1836 }
1837
1838 try {
1839 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1840
1841 String[] tokens = response.get(0).split(" ");
1842
1843 if (tokens == null || tokens.length != 2) {
1844 return -1;
1845 }
1846
1847 return Integer.parseInt(tokens[1]);
1848 } catch (NativeDaemonConnectorException e) {
1849 // Encryption failed
1850 return e.getCode();
1851 }
1852 }
1853
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001854 public Parcelable[] getVolumeList() {
1855 synchronized(mVolumes) {
1856 int size = mVolumes.size();
1857 Parcelable[] result = new Parcelable[size];
1858 for (int i = 0; i < size; i++) {
1859 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001860 }
1861 return result;
1862 }
1863 }
1864
Kenny Rootaf9d6672010-10-08 09:21:39 -07001865 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1866 final IBinder binder = obbState.getBinder();
1867 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001868
Kenny Rootaf9d6672010-10-08 09:21:39 -07001869 if (obbStates == null) {
1870 obbStates = new ArrayList<ObbState>();
1871 mObbMounts.put(binder, obbStates);
1872 } else {
1873 for (final ObbState o : obbStates) {
1874 if (o.filename.equals(obbState.filename)) {
1875 throw new IllegalStateException("Attempt to add ObbState twice. "
1876 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001877 }
1878 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001879 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001880
1881 obbStates.add(obbState);
1882 try {
1883 obbState.link();
1884 } catch (RemoteException e) {
1885 /*
1886 * The binder died before we could link it, so clean up our state
1887 * and return failure.
1888 */
1889 obbStates.remove(obbState);
1890 if (obbStates.isEmpty()) {
1891 mObbMounts.remove(binder);
1892 }
1893
1894 // Rethrow the error so mountObb can get it
1895 throw e;
1896 }
1897
1898 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001899 }
1900
Kenny Rootaf9d6672010-10-08 09:21:39 -07001901 private void removeObbStateLocked(ObbState obbState) {
1902 final IBinder binder = obbState.getBinder();
1903 final List<ObbState> obbStates = mObbMounts.get(binder);
1904 if (obbStates != null) {
1905 if (obbStates.remove(obbState)) {
1906 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001907 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001908 if (obbStates.isEmpty()) {
1909 mObbMounts.remove(binder);
1910 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001911 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001912
Kenny Rootaf9d6672010-10-08 09:21:39 -07001913 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001914 }
1915
Kenny Roota02b8b02010-08-05 16:14:17 -07001916 private class ObbActionHandler extends Handler {
1917 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001918 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001919
1920 ObbActionHandler(Looper l) {
1921 super(l);
1922 }
1923
1924 @Override
1925 public void handleMessage(Message msg) {
1926 switch (msg.what) {
1927 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001928 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001929
1930 if (DEBUG_OBB)
1931 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1932
1933 // If a bind was already initiated we don't really
1934 // need to do anything. The pending install
1935 // will be processed later on.
1936 if (!mBound) {
1937 // If this is the only one pending we might
1938 // have to bind to the service again.
1939 if (!connectToService()) {
1940 Slog.e(TAG, "Failed to bind to media container service");
1941 action.handleError();
1942 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001943 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 }
Kenny Root735de3b2010-09-30 14:11:39 -07001945
Kenny Root735de3b2010-09-30 14:11:39 -07001946 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001947 break;
1948 }
1949 case OBB_MCS_BOUND: {
1950 if (DEBUG_OBB)
1951 Slog.i(TAG, "OBB_MCS_BOUND");
1952 if (msg.obj != null) {
1953 mContainerService = (IMediaContainerService) msg.obj;
1954 }
1955 if (mContainerService == null) {
1956 // Something seriously wrong. Bail out
1957 Slog.e(TAG, "Cannot bind to media container service");
1958 for (ObbAction action : mActions) {
1959 // Indicate service bind error
1960 action.handleError();
1961 }
1962 mActions.clear();
1963 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001964 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001965 if (action != null) {
1966 action.execute(this);
1967 }
1968 } else {
1969 // Should never happen ideally.
1970 Slog.w(TAG, "Empty queue");
1971 }
1972 break;
1973 }
1974 case OBB_MCS_RECONNECT: {
1975 if (DEBUG_OBB)
1976 Slog.i(TAG, "OBB_MCS_RECONNECT");
1977 if (mActions.size() > 0) {
1978 if (mBound) {
1979 disconnectService();
1980 }
1981 if (!connectToService()) {
1982 Slog.e(TAG, "Failed to bind to media container service");
1983 for (ObbAction action : mActions) {
1984 // Indicate service bind error
1985 action.handleError();
1986 }
1987 mActions.clear();
1988 }
1989 }
1990 break;
1991 }
1992 case OBB_MCS_UNBIND: {
1993 if (DEBUG_OBB)
1994 Slog.i(TAG, "OBB_MCS_UNBIND");
1995
1996 // Delete pending install
1997 if (mActions.size() > 0) {
1998 mActions.remove(0);
1999 }
2000 if (mActions.size() == 0) {
2001 if (mBound) {
2002 disconnectService();
2003 }
2004 } else {
2005 // There are more pending requests in queue.
2006 // Just post MCS_BOUND message to trigger processing
2007 // of next pending install.
2008 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2009 }
2010 break;
2011 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002012 case OBB_FLUSH_MOUNT_STATE: {
2013 final String path = (String) msg.obj;
2014
2015 if (DEBUG_OBB)
2016 Slog.i(TAG, "Flushing all OBB state for path " + path);
2017
2018 synchronized (mObbMounts) {
2019 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2020
2021 final Iterator<Entry<String, ObbState>> i =
2022 mObbPathToStateMap.entrySet().iterator();
2023 while (i.hasNext()) {
2024 final Entry<String, ObbState> obbEntry = i.next();
2025
2026 /*
2027 * If this entry's source file is in the volume path
2028 * that got unmounted, remove it because it's no
2029 * longer valid.
2030 */
2031 if (obbEntry.getKey().startsWith(path)) {
2032 obbStatesToRemove.add(obbEntry.getValue());
2033 }
2034 }
2035
2036 for (final ObbState obbState : obbStatesToRemove) {
2037 if (DEBUG_OBB)
2038 Slog.i(TAG, "Removing state for " + obbState.filename);
2039
2040 removeObbStateLocked(obbState);
2041
2042 try {
2043 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2044 OnObbStateChangeListener.UNMOUNTED);
2045 } catch (RemoteException e) {
2046 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2047 + obbState.filename);
2048 }
2049 }
2050 }
2051 break;
2052 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002053 }
2054 }
2055
2056 private boolean connectToService() {
2057 if (DEBUG_OBB)
2058 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2059
2060 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2061 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2062 mBound = true;
2063 return true;
2064 }
2065 return false;
2066 }
2067
2068 private void disconnectService() {
2069 mContainerService = null;
2070 mBound = false;
2071 mContext.unbindService(mDefContainerConn);
2072 }
2073 }
2074
2075 abstract class ObbAction {
2076 private static final int MAX_RETRIES = 3;
2077 private int mRetries;
2078
2079 ObbState mObbState;
2080
2081 ObbAction(ObbState obbState) {
2082 mObbState = obbState;
2083 }
2084
2085 public void execute(ObbActionHandler handler) {
2086 try {
2087 if (DEBUG_OBB)
2088 Slog.i(TAG, "Starting to execute action: " + this.toString());
2089 mRetries++;
2090 if (mRetries > MAX_RETRIES) {
2091 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002092 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002093 handleError();
2094 return;
2095 } else {
2096 handleExecute();
2097 if (DEBUG_OBB)
2098 Slog.i(TAG, "Posting install MCS_UNBIND");
2099 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2100 }
2101 } catch (RemoteException e) {
2102 if (DEBUG_OBB)
2103 Slog.i(TAG, "Posting install MCS_RECONNECT");
2104 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2105 } catch (Exception e) {
2106 if (DEBUG_OBB)
2107 Slog.d(TAG, "Error handling OBB action", e);
2108 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002109 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002110 }
2111 }
2112
Kenny Root05105f72010-09-22 17:29:43 -07002113 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002114 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002115
2116 protected ObbInfo getObbInfo() throws IOException {
2117 ObbInfo obbInfo;
2118 try {
2119 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2120 } catch (RemoteException e) {
2121 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2122 + mObbState.filename);
2123 obbInfo = null;
2124 }
2125 if (obbInfo == null) {
2126 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2127 }
2128 return obbInfo;
2129 }
2130
Kenny Rootaf9d6672010-10-08 09:21:39 -07002131 protected void sendNewStatusOrIgnore(int status) {
2132 if (mObbState == null || mObbState.token == null) {
2133 return;
2134 }
2135
Kenny Root38cf8862010-09-26 14:18:51 -07002136 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002137 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002138 } catch (RemoteException e) {
2139 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2140 }
2141 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002142 }
2143
2144 class MountObbAction extends ObbAction {
2145 private String mKey;
2146
2147 MountObbAction(ObbState obbState, String key) {
2148 super(obbState);
2149 mKey = key;
2150 }
2151
Jason parks5af0b912010-11-29 09:05:25 -06002152 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002153 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154 waitForReady();
2155 warnOnNotMounted();
2156
Kenny Root38cf8862010-09-26 14:18:51 -07002157 final ObbInfo obbInfo = getObbInfo();
2158
Kenny Roota02b8b02010-08-05 16:14:17 -07002159 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002160 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2161 + " which is owned by " + obbInfo.packageName);
2162 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2163 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002164 }
2165
Kenny Rootaf9d6672010-10-08 09:21:39 -07002166 final boolean isMounted;
2167 synchronized (mObbMounts) {
2168 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2169 }
2170 if (isMounted) {
2171 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2172 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2173 return;
2174 }
2175
2176 /*
2177 * The filename passed in might not be the canonical name, so just
2178 * set the filename to the canonicalized version.
2179 */
2180 mObbState.filename = obbInfo.filename;
2181
2182 final String hashedKey;
2183 if (mKey == null) {
2184 hashedKey = "none";
2185 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002186 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002187 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2188
2189 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2190 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2191 SecretKey key = factory.generateSecret(ks);
2192 BigInteger bi = new BigInteger(key.getEncoded());
2193 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002194 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002195 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2196 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2197 return;
2198 } catch (InvalidKeySpecException e) {
2199 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2200 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002201 return;
2202 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002203 }
Kenny Root38cf8862010-09-26 14:18:51 -07002204
Kenny Rootaf9d6672010-10-08 09:21:39 -07002205 int rc = StorageResultCode.OperationSucceeded;
2206 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2207 mObbState.callerUid);
2208 try {
2209 mConnector.doCommand(cmd);
2210 } catch (NativeDaemonConnectorException e) {
2211 int code = e.getCode();
2212 if (code != VoldResponseCode.OpFailedStorageBusy) {
2213 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002214 }
2215 }
2216
Kenny Rootaf9d6672010-10-08 09:21:39 -07002217 if (rc == StorageResultCode.OperationSucceeded) {
2218 if (DEBUG_OBB)
2219 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2220
2221 synchronized (mObbMounts) {
2222 addObbStateLocked(mObbState);
2223 }
2224
2225 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002226 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002227 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002228
Kenny Rootaf9d6672010-10-08 09:21:39 -07002229 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002230 }
2231 }
2232
Jason parks5af0b912010-11-29 09:05:25 -06002233 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002234 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002235 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002236 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002237
2238 @Override
2239 public String toString() {
2240 StringBuilder sb = new StringBuilder();
2241 sb.append("MountObbAction{");
2242 sb.append("filename=");
2243 sb.append(mObbState.filename);
2244 sb.append(",callerUid=");
2245 sb.append(mObbState.callerUid);
2246 sb.append(",token=");
2247 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002248 sb.append(",binder=");
2249 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002250 sb.append('}');
2251 return sb.toString();
2252 }
2253 }
2254
2255 class UnmountObbAction extends ObbAction {
2256 private boolean mForceUnmount;
2257
2258 UnmountObbAction(ObbState obbState, boolean force) {
2259 super(obbState);
2260 mForceUnmount = force;
2261 }
2262
Jason parks5af0b912010-11-29 09:05:25 -06002263 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002264 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002265 waitForReady();
2266 warnOnNotMounted();
2267
Kenny Root38cf8862010-09-26 14:18:51 -07002268 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002269
Kenny Rootaf9d6672010-10-08 09:21:39 -07002270 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002271 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272 obbState = mObbPathToStateMap.get(obbInfo.filename);
2273 }
Kenny Root38cf8862010-09-26 14:18:51 -07002274
Kenny Rootaf9d6672010-10-08 09:21:39 -07002275 if (obbState == null) {
2276 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2277 return;
2278 }
2279
2280 if (obbState.callerUid != mObbState.callerUid) {
2281 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2282 + " (owned by " + obbInfo.packageName + ")");
2283 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2284 return;
2285 }
2286
2287 mObbState.filename = obbInfo.filename;
2288
2289 int rc = StorageResultCode.OperationSucceeded;
2290 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2291 (mForceUnmount ? " force" : ""));
2292 try {
2293 mConnector.doCommand(cmd);
2294 } catch (NativeDaemonConnectorException e) {
2295 int code = e.getCode();
2296 if (code == VoldResponseCode.OpFailedStorageBusy) {
2297 rc = StorageResultCode.OperationFailedStorageBusy;
2298 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2299 // If it's not mounted then we've already won.
2300 rc = StorageResultCode.OperationSucceeded;
2301 } else {
2302 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002303 }
2304 }
2305
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 if (rc == StorageResultCode.OperationSucceeded) {
2307 synchronized (mObbMounts) {
2308 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002309 }
2310
Kenny Rootaf9d6672010-10-08 09:21:39 -07002311 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002312 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002313 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2314 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002315 }
2316 }
2317
Jason parks5af0b912010-11-29 09:05:25 -06002318 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002319 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002320 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002321 }
2322
2323 @Override
2324 public String toString() {
2325 StringBuilder sb = new StringBuilder();
2326 sb.append("UnmountObbAction{");
2327 sb.append("filename=");
2328 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2329 sb.append(",force=");
2330 sb.append(mForceUnmount);
2331 sb.append(",callerUid=");
2332 sb.append(mObbState.callerUid);
2333 sb.append(",token=");
2334 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002335 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002336 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002337 sb.append('}');
2338 return sb.toString();
2339 }
Kenny Root02c87302010-07-01 08:10:18 -07002340 }
Kenny Root38cf8862010-09-26 14:18:51 -07002341
2342 @Override
2343 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2344 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2345 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2346 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2347 + " without permission " + android.Manifest.permission.DUMP);
2348 return;
2349 }
2350
Kenny Root38cf8862010-09-26 14:18:51 -07002351 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002352 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002353
Kenny Rootaf9d6672010-10-08 09:21:39 -07002354 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2355 while (binders.hasNext()) {
2356 Entry<IBinder, List<ObbState>> e = binders.next();
2357 pw.print(" Key="); pw.println(e.getKey().toString());
2358 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002359 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002360 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002361 }
2362 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002363
2364 pw.println("");
2365 pw.println(" mObbPathToStateMap:");
2366 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2367 while (maps.hasNext()) {
2368 final Entry<String, ObbState> e = maps.next();
2369 pw.print(" "); pw.print(e.getKey());
2370 pw.print(" -> "); pw.println(e.getValue().toString());
2371 }
Kenny Root38cf8862010-09-26 14:18:51 -07002372 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002373
2374 pw.println("");
2375
2376 synchronized (mVolumes) {
2377 pw.println(" mVolumes:");
2378
2379 final int N = mVolumes.size();
2380 for (int i = 0; i < N; i++) {
2381 final StorageVolume v = mVolumes.get(i);
2382 pw.print(" ");
2383 pw.println(v.toString());
2384 }
2385 }
Kenny Root38cf8862010-09-26 14:18:51 -07002386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002388 /** {@inheritDoc} */
2389 public void monitor() {
2390 if (mConnector != null) {
2391 mConnector.monitor();
2392 }
2393 }
2394}