blob: a32e9f5c846777fc7d18a79763ed3506b751f7e2 [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;
Jeff Sharkeydd519fa2011-12-02 14:11:21 -080023import com.android.server.NativeDaemonConnector.Command;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080024
Jason parks8888c592011-01-20 22:46:41 -060025import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070031import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070033import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070034import android.content.res.Resources;
35import android.content.res.TypedArray;
36import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070037import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070039import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070040import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080041import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040044import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080045import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070046import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080047import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080048import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080049import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070051import android.os.storage.IMountService;
52import android.os.storage.IMountServiceListener;
53import android.os.storage.IMountShutdownObserver;
54import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070055import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070056import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060058import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070060import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070061import android.util.Xml;
62
63import org.xmlpull.v1.XmlPullParser;
64import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070065
Kenny Root38cf8862010-09-26 14:18:51 -070066import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070067import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070068import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070069import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070070import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070071import java.security.spec.InvalidKeySpecException;
72import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080073import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070074import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080075import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070076import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070077import java.util.LinkedList;
78import java.util.List;
79import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070080import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070081import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Kenny Root3b1abba2010-10-13 15:00:07 -070083import javax.crypto.SecretKey;
84import javax.crypto.SecretKeyFactory;
85import javax.crypto.spec.PBEKeySpec;
86
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087/**
San Mehatb1043402010-02-05 08:26:50 -080088 * MountService implements back-end services for platform storage
89 * management.
90 * @hide - Applications should use android.os.storage.StorageManager
91 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070093class MountService extends IMountService.Stub
94 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -060095
San Mehatb1043402010-02-05 08:26:50 -080096 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080097 private static final boolean DEBUG_UNMOUNT = false;
98 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080099 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700100
Kenny Root07714d42011-08-17 17:49:28 -0700101 // Disable this since it messes up long-running cryptfs operations.
102 private static final boolean WATCHDOG_ENABLE = false;
103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 private static final String TAG = "MountService";
105
Kenny Root305bcbf2010-09-03 07:56:38 -0700106 private static final String VOLD_TAG = "VoldConnector";
107
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700108 /** Maximum number of ASEC containers allowed to be mounted. */
109 private static final int MAX_CONTAINERS = 250;
110
San Mehat4270e1e2010-01-29 05:32:19 -0800111 /*
112 * Internal vold volume state constants
113 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800114 class VolumeState {
115 public static final int Init = -1;
116 public static final int NoMedia = 0;
117 public static final int Idle = 1;
118 public static final int Pending = 2;
119 public static final int Checking = 3;
120 public static final int Mounted = 4;
121 public static final int Unmounting = 5;
122 public static final int Formatting = 6;
123 public static final int Shared = 7;
124 public static final int SharedMnt = 8;
125 }
126
San Mehat4270e1e2010-01-29 05:32:19 -0800127 /*
128 * Internal vold response code constants
129 */
San Mehat22dd86e2010-01-12 12:21:18 -0800130 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800131 /*
132 * 100 series - Requestion action was initiated; expect another reply
133 * before proceeding with a new command.
134 */
San Mehat22dd86e2010-01-12 12:21:18 -0800135 public static final int VolumeListResult = 110;
136 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800137 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800138
San Mehat4270e1e2010-01-29 05:32:19 -0800139 /*
140 * 200 series - Requestion action has been successfully completed.
141 */
142 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800143 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800144 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800145
San Mehat4270e1e2010-01-29 05:32:19 -0800146 /*
147 * 400 series - Command was accepted, but the requested action
148 * did not take place.
149 */
150 public static final int OpFailedNoMedia = 401;
151 public static final int OpFailedMediaBlank = 402;
152 public static final int OpFailedMediaCorrupt = 403;
153 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800154 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700155 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800156
157 /*
158 * 600 series - Unsolicited broadcasts.
159 */
San Mehat22dd86e2010-01-12 12:21:18 -0800160 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800161 public static final int VolumeDiskInserted = 630;
162 public static final int VolumeDiskRemoved = 631;
163 public static final int VolumeBadRemoval = 632;
164 }
165
San Mehat4270e1e2010-01-29 05:32:19 -0800166 private Context mContext;
167 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700168 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
169 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400170 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400171 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400172 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800173 private PackageManagerService mPms;
174 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700175 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800176 // Used as a lock for methods that register/unregister listeners.
177 final private ArrayList<MountServiceBinderListener> mListeners =
178 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800179 private boolean mBooted = false;
180 private boolean mReady = false;
181 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400182 // true if we should fake MEDIA_MOUNTED state for external storage
183 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800184
San Mehat6cdd9c02010-02-09 14:45:20 -0800185 /**
186 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800187 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800188 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800189 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800190
Kenny Root02c87302010-07-01 08:10:18 -0700191 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700192 * The size of the crypto algorithm key in bits for OBB files. Currently
193 * Twofish is used which takes 128-bit keys.
194 */
195 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
196
197 /**
198 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
199 * 1024 is reasonably secure and not too slow.
200 */
201 private static final int PBKDF2_HASH_ROUNDS = 1024;
202
203 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700204 * Mounted OBB tracking information. Used to track the current state of all
205 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700206 */
Kenny Root735de3b2010-09-30 14:11:39 -0700207 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700208 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
209
210 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700211 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700212 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700213 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700214 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700215 this.token = token;
216 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700217 }
218
219 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700220 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700221
222 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700223 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700224
Kenny Rootaf9d6672010-10-08 09:21:39 -0700225 // Token of remote Binder caller
226 final IObbActionListener token;
227
228 // Identifier to pass back to the token
229 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700230
Kenny Root735de3b2010-09-30 14:11:39 -0700231 public IBinder getBinder() {
232 return token.asBinder();
233 }
234
Kenny Roota02b8b02010-08-05 16:14:17 -0700235 @Override
236 public void binderDied() {
237 ObbAction action = new UnmountObbAction(this, true);
238 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700239 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700240
Kenny Root5919ac62010-10-05 09:49:40 -0700241 public void link() throws RemoteException {
242 getBinder().linkToDeath(this, 0);
243 }
244
245 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700246 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700247 }
Kenny Root38cf8862010-09-26 14:18:51 -0700248
249 @Override
250 public String toString() {
251 StringBuilder sb = new StringBuilder("ObbState{");
252 sb.append("filename=");
253 sb.append(filename);
254 sb.append(",token=");
255 sb.append(token.toString());
256 sb.append(",callerUid=");
257 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700258 sb.append('}');
259 return sb.toString();
260 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700261 }
262
263 // OBB Action Handler
264 final private ObbActionHandler mObbActionHandler;
265
266 // OBB action handler messages
267 private static final int OBB_RUN_ACTION = 1;
268 private static final int OBB_MCS_BOUND = 2;
269 private static final int OBB_MCS_UNBIND = 3;
270 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700271 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700272
273 /*
274 * Default Container Service information
275 */
276 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
277 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
278
279 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
280
281 class DefaultContainerConnection implements ServiceConnection {
282 public void onServiceConnected(ComponentName name, IBinder service) {
283 if (DEBUG_OBB)
284 Slog.i(TAG, "onServiceConnected");
285 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
286 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
287 }
288
289 public void onServiceDisconnected(ComponentName name) {
290 if (DEBUG_OBB)
291 Slog.i(TAG, "onServiceDisconnected");
292 }
293 };
294
295 // Used in the ObbActionHandler
296 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700297
298 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800299 private static final int H_UNMOUNT_PM_UPDATE = 1;
300 private static final int H_UNMOUNT_PM_DONE = 2;
301 private static final int H_UNMOUNT_MS = 3;
302 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
303 private static final int MAX_UNMOUNT_RETRIES = 4;
304
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800305 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700306 final String path;
307 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700308 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800309 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800310
Ben Komalo13c71972011-09-07 16:35:56 -0700311 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800312 retries = 0;
313 this.path = path;
314 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700315 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800316 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800317
318 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700319 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700320 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800321 }
322 }
323
324 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700325 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800326
327 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700328 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800329 this.method = method;
330 }
331
332 @Override
333 void handleFinished() {
334 super.handleFinished();
335 doShareUnshareVolume(path, method, true);
336 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800337 }
338
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800339 class ShutdownCallBack extends UnmountCallBack {
340 IMountShutdownObserver observer;
341 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700342 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800343 this.observer = observer;
344 }
345
346 @Override
347 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700348 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800349 if (observer != null) {
350 try {
351 observer.onShutDownComplete(ret);
352 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700353 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800354 }
355 }
356 }
357 }
358
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400359 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700361 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800362
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400363 MountServiceHandler(Looper l) {
364 super(l);
365 }
366
Jason parks5af0b912010-11-29 09:05:25 -0600367 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800368 public void handleMessage(Message msg) {
369 switch (msg.what) {
370 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700371 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
373 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700374 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800375 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700376 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700377 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700378 mUpdatingStatus = true;
379 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800380 }
381 break;
382 }
383 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700384 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700385 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700386 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 int size = mForceUnmounts.size();
388 int sizeArr[] = new int[size];
389 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700390 // Kill processes holding references first
391 ActivityManagerService ams = (ActivityManagerService)
392 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800393 for (int i = 0; i < size; i++) {
394 UnmountCallBack ucb = mForceUnmounts.get(i);
395 String path = ucb.path;
396 boolean done = false;
397 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800398 done = true;
399 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800400 int pids[] = getStorageUsers(path);
401 if (pids == null || pids.length == 0) {
402 done = true;
403 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800404 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800405 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700406 // Confirm if file references have been freed.
407 pids = getStorageUsers(path);
408 if (pids == null || pids.length == 0) {
409 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800410 }
411 }
412 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700413 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
414 // Retry again
415 Slog.i(TAG, "Retrying to kill storage users again");
416 mHandler.sendMessageDelayed(
417 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
418 ucb.retries++),
419 RETRY_UNMOUNT_DELAY);
420 } else {
421 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
422 Slog.i(TAG, "Failed to unmount media inspite of " +
423 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
424 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800425 sizeArr[sizeArrN++] = i;
426 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
427 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800428 }
429 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800430 // Remove already processed elements from list.
431 for (int i = (sizeArrN-1); i >= 0; i--) {
432 mForceUnmounts.remove(sizeArr[i]);
433 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800434 break;
435 }
436 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700437 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800438 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800439 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800440 break;
441 }
442 }
443 }
444 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400445 final private HandlerThread mHandlerThread;
446 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800447
San Mehat207e5382010-02-04 20:46:54 -0800448 private void waitForReady() {
449 while (mReady == false) {
450 for (int retries = 5; retries > 0; retries--) {
451 if (mReady) {
452 return;
453 }
454 SystemClock.sleep(1000);
455 }
San Mehata5078592010-03-25 09:36:54 -0700456 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800457 }
San Mehat1f6301e2010-01-07 22:40:27 -0800458 }
Kenny Root02c87302010-07-01 08:10:18 -0700459
Ben Komalo444eca22011-09-01 15:17:44 -0700460 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600461 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800463 String action = intent.getAction();
464
465 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800466 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800467
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800468 /*
469 * In the simulator, we need to broadcast a volume mounted event
470 * to make the media scanner run.
471 */
472 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400473 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
474 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800475 return;
476 }
San Mehatfafb0412010-02-18 19:40:04 -0800477 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600478 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800479 public void run() {
480 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400481 // it is not safe to call vold with mVolumeStates locked
482 // so we make a copy of the paths and states and process them
483 // outside the lock
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700484 String[] paths;
485 String[] states;
Mike Lockwood84338c42011-04-05 10:05:47 -0400486 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400487 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400488 Set<String> keys = mVolumeStates.keySet();
489 count = keys.size();
Ben Komalo444eca22011-09-01 15:17:44 -0700490 paths = keys.toArray(new String[count]);
Mike Lockwood84338c42011-04-05 10:05:47 -0400491 states = new String[count];
492 for (int i = 0; i < count; i++) {
493 states[i] = mVolumeStates.get(paths[i]);
494 }
495 }
San Mehat6a254402010-03-22 10:21:00 -0700496
Mike Lockwood84338c42011-04-05 10:05:47 -0400497 for (int i = 0; i < count; i++) {
498 String path = paths[i];
499 String state = states[i];
500
501 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
502 int rc = doMountVolume(path);
503 if (rc != StorageResultCode.OperationSucceeded) {
504 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
505 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400506 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400507 } else if (state.equals(Environment.MEDIA_SHARED)) {
508 /*
509 * Bootstrap UMS enabled state since vold indicates
510 * the volume is shared (runtime restart while ums enabled)
511 */
512 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
513 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800514 }
515 }
San Mehat6a254402010-03-22 10:21:00 -0700516
Mike Lockwood80e0a412011-04-05 10:21:51 -0400517 /* notify external storage has mounted to trigger media scanner */
518 if (mEmulateExternalStorage) {
519 notifyVolumeStateChange(null,
520 Environment.getExternalStorageDirectory().getPath(),
521 VolumeState.NoMedia, VolumeState.Mounted);
522 }
523
San Mehat6a965af22010-02-24 17:47:30 -0800524 /*
San Mehat6a254402010-03-22 10:21:00 -0700525 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800526 * now that we're up.
527 */
528 if (mSendUmsConnectedOnBoot) {
529 sendUmsIntent(true);
530 mSendUmsConnectedOnBoot = false;
531 }
San Mehatfafb0412010-02-18 19:40:04 -0800532 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700533 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800534 }
San Mehat207e5382010-02-04 20:46:54 -0800535 }
San Mehatfafb0412010-02-18 19:40:04 -0800536 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700537 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
538 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
539 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
540 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542 }
543 };
San Mehat4270e1e2010-01-29 05:32:19 -0800544 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
545 final IMountServiceListener mListener;
546
547 MountServiceBinderListener(IMountServiceListener listener) {
548 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700549
San Mehat91c77612010-01-07 10:39:41 -0800550 }
551
San Mehat4270e1e2010-01-29 05:32:19 -0800552 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700553 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700554 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800555 mListeners.remove(this);
556 mListener.asBinder().unlinkToDeath(this, 0);
557 }
558 }
559 }
560
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800561 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800562 // TODO: Add support for multiple share methods
563 if (!method.equals("ums")) {
564 throw new IllegalArgumentException(String.format("Method %s not supported", method));
565 }
566
San Mehat4270e1e2010-01-29 05:32:19 -0800567 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800568 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800569 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700570 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800571 }
San Mehat4270e1e2010-01-29 05:32:19 -0800572 }
573
San Mehat207e5382010-02-04 20:46:54 -0800574 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400575 String oldState;
576 synchronized(mVolumeStates) {
577 oldState = mVolumeStates.put(path, state);
578 }
579 if (state.equals(oldState)) {
580 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
581 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800582 return;
583 }
San Mehatb1043402010-02-05 08:26:50 -0800584
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400585 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700586
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400587 if (path.equals(mExternalStoragePath)) {
588 // Update state on PackageManager, but only of real events
589 if (!mEmulateExternalStorage) {
590 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
591 mPms.updateExternalMediaStatus(false, false);
592
593 /*
594 * Some OBBs might have been unmounted when this volume was
595 * unmounted, so send a message to the handler to let it know to
596 * remove those from the list of mounted OBBS.
597 */
598 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
599 OBB_FLUSH_MOUNT_STATE, path));
600 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
601 mPms.updateExternalMediaStatus(true, false);
602 }
Mike Lockwood03559752010-07-19 18:25:03 -0400603 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800604 }
San Mehat4270e1e2010-01-29 05:32:19 -0800605 synchronized (mListeners) {
606 for (int i = mListeners.size() -1; i >= 0; i--) {
607 MountServiceBinderListener bl = mListeners.get(i);
608 try {
San Mehatb1043402010-02-05 08:26:50 -0800609 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800610 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700611 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800612 mListeners.remove(i);
613 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700614 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800615 }
616 }
617 }
618 }
619
620 /**
621 *
622 * Callback from NativeDaemonConnector
623 */
624 public void onDaemonConnected() {
625 /*
626 * Since we'll be calling back into the NativeDaemonConnector,
627 * we need to do our work in a new thread.
628 */
629 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600630 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800631 public void run() {
632 /**
633 * Determine media state and UMS detection status
634 */
San Mehat4270e1e2010-01-29 05:32:19 -0800635 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800636 final String[] vols = NativeDaemonEvent.filterMessageList(
637 mConnector.executeForList("volume", "list"),
638 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800639 for (String volstr : vols) {
640 String[] tok = volstr.split(" ");
641 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400642 String path = tok[1];
643 String state = Environment.MEDIA_REMOVED;
644
San Mehat4270e1e2010-01-29 05:32:19 -0800645 int st = Integer.parseInt(tok[2]);
646 if (st == VolumeState.NoMedia) {
647 state = Environment.MEDIA_REMOVED;
648 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800649 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800650 } else if (st == VolumeState.Mounted) {
651 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700652 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800653 } else if (st == VolumeState.Shared) {
654 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700655 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800656 } else {
657 throw new Exception(String.format("Unexpected state %d", st));
658 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400659
660 if (state != null) {
661 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
662 updatePublicVolumeState(path, state);
663 }
San Mehat4270e1e2010-01-29 05:32:19 -0800664 }
665 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700666 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400667 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800668 }
669
San Mehat207e5382010-02-04 20:46:54 -0800670 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600671 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800672 * the hounds!
673 */
674 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800675 }
676 }.start();
677 }
678
679 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800680 * Callback from NativeDaemonConnector
681 */
682 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800683 if (DEBUG_EVENTS) {
684 StringBuilder builder = new StringBuilder();
685 builder.append("onEvent::");
686 builder.append(" raw= " + raw);
687 if (cooked != null) {
688 builder.append(" cooked = " );
689 for (String str : cooked) {
690 builder.append(" " + str);
691 }
692 }
San Mehata5078592010-03-25 09:36:54 -0700693 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800694 }
San Mehat4270e1e2010-01-29 05:32:19 -0800695 if (code == VoldResponseCode.VolumeStateChange) {
696 /*
697 * One of the volumes we're managing has changed state.
698 * Format: "NNN Volume <label> <path> state changed
699 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
700 */
701 notifyVolumeStateChange(
702 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
703 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800704 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
705 (code == VoldResponseCode.VolumeDiskRemoved) ||
706 (code == VoldResponseCode.VolumeBadRemoval)) {
707 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
708 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
709 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400710 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800711 final String label = cooked[2];
712 final String path = cooked[3];
713 int major = -1;
714 int minor = -1;
715
716 try {
717 String devComp = cooked[6].substring(1, cooked[6].length() -1);
718 String[] devTok = devComp.split(":");
719 major = Integer.parseInt(devTok[0]);
720 minor = Integer.parseInt(devTok[1]);
721 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700722 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724
San Mehat4270e1e2010-01-29 05:32:19 -0800725 if (code == VoldResponseCode.VolumeDiskInserted) {
726 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600727 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800728 public void run() {
729 try {
730 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800731 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700732 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800733 }
734 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700735 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800736 }
737 }
738 }.start();
739 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
740 /*
741 * This event gets trumped if we're already in BAD_REMOVAL state
742 */
743 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
744 return true;
745 }
746 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700747 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800748 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400749 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800750
San Mehata5078592010-03-25 09:36:54 -0700751 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400753 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800754 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700755 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800756 /* Send the media unmounted event first */
757 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400758 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800759
San Mehata5078592010-03-25 09:36:54 -0700760 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800761 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400762 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800763 } else {
San Mehata5078592010-03-25 09:36:54 -0700764 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800765 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400766
767 if (action != null) {
768 sendStorageIntent(action, path);
769 }
San Mehat4270e1e2010-01-29 05:32:19 -0800770 } else {
771 return false;
772 }
773
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400774 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800775 }
776
San Mehat207e5382010-02-04 20:46:54 -0800777 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800778 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700779 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800780
Mike Lockwooda5250c92011-05-23 13:44:04 -0400781 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800782
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500783 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700784 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400785 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500786 }
787
San Mehat4270e1e2010-01-29 05:32:19 -0800788 if (newState == VolumeState.Init) {
789 } else if (newState == VolumeState.NoMedia) {
790 // NoMedia is handled via Disk Remove events
791 } else if (newState == VolumeState.Idle) {
792 /*
793 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
794 * if we're in the process of enabling UMS
795 */
796 if (!vs.equals(
797 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
798 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800799 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700800 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800801 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400802 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800803 }
804 } else if (newState == VolumeState.Pending) {
805 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700806 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800807 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800809 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700810 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800811 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400812 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800813 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400814 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800815 } else if (newState == VolumeState.Formatting) {
816 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700817 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800818 /* Send the media unmounted event first */
819 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400820 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800821
San Mehata5078592010-03-25 09:36:54 -0700822 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800823 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400824 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700825 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800826 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700827 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800828 return;
829 } else {
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800831 }
832
Mike Lockwooda5250c92011-05-23 13:44:04 -0400833 if (action != null) {
834 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800835 }
836 }
837
San Mehat207e5382010-02-04 20:46:54 -0800838 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800839 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800840
San Mehata5078592010-03-25 09:36:54 -0700841 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800842 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800843 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800844 } catch (NativeDaemonConnectorException e) {
845 /*
846 * Mount failed for some reason
847 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400848 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800849 int code = e.getCode();
850 if (code == VoldResponseCode.OpFailedNoMedia) {
851 /*
852 * Attempt to mount but no media inserted
853 */
San Mehatb1043402010-02-05 08:26:50 -0800854 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800855 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700856 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800857 /*
858 * Media is blank or does not contain a supported filesystem
859 */
860 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400861 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800862 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800863 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700864 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800865 /*
866 * Volume consistency check failed
867 */
868 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400869 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800870 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800871 } else {
San Mehatb1043402010-02-05 08:26:50 -0800872 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800873 }
874
875 /*
876 * Send broadcast intent (if required for the failure)
877 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400878 if (action != null) {
879 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800880 }
881 }
882
883 return rc;
884 }
885
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800886 /*
887 * If force is not set, we do not unmount if there are
888 * processes holding references to the volume about to be unmounted.
889 * If force is set, all the processes holding references need to be
890 * killed via the ActivityManager before actually unmounting the volume.
891 * This might even take a while and might be retried after timed delays
892 * to make sure we dont end up in an instable state and kill some core
893 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700894 * If removeEncryption is set, force is implied, and the system will remove any encryption
895 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800896 */
Ben Komalo13c71972011-09-07 16:35:56 -0700897 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800898 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800899 return VoldResponseCode.OpFailedVolNotMounted;
900 }
Kenny Rootaa485402010-09-14 14:49:41 -0700901
902 /*
903 * Force a GC to make sure AssetManagers in other threads of the
904 * system_server are cleaned up. We have to do this since AssetManager
905 * instances are kept as a WeakReference and it's possible we have files
906 * open on the external storage.
907 */
908 Runtime.getRuntime().gc();
909
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800910 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700911 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800912 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800913 final Command cmd = new Command("volume", "unmount", path);
914 if (removeEncryption) {
915 cmd.appendArg("force_and_revert");
916 } else if (force) {
917 cmd.appendArg("force");
918 }
919 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700920 // We unmounted the volume. None of the asec containers are available now.
921 synchronized (mAsecMountSet) {
922 mAsecMountSet.clear();
923 }
San Mehatb1043402010-02-05 08:26:50 -0800924 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800925 } catch (NativeDaemonConnectorException e) {
926 // Don't worry about mismatch in PackageManager since the
927 // call back will handle the status changes any way.
928 int code = e.getCode();
929 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800930 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800931 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
932 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800933 } else {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800935 }
936 }
937 }
938
939 private int doFormatVolume(String path) {
940 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800941 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -0800942 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800943 } catch (NativeDaemonConnectorException e) {
944 int code = e.getCode();
945 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800946 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800947 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800948 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800949 } else {
San Mehatb1043402010-02-05 08:26:50 -0800950 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800951 }
952 }
953 }
954
San Mehatb1043402010-02-05 08:26:50 -0800955 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800956 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700957 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800958 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700959 } catch (NativeDaemonConnectorException ex) {
960 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
961 return false;
962 }
San Mehatb1043402010-02-05 08:26:50 -0800963
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800964 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
965 return event.getMessage().endsWith("enabled");
966 } else {
967 return false;
San Mehatb1043402010-02-05 08:26:50 -0800968 }
San Mehatb1043402010-02-05 08:26:50 -0800969 }
970
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700971 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800972 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700973 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800974 for (int i = mListeners.size() -1; i >= 0; i--) {
975 MountServiceBinderListener bl = mListeners.get(i);
976 try {
San Mehatb1043402010-02-05 08:26:50 -0800977 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800978 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700979 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800980 mListeners.remove(i);
981 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700982 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800983 }
984 }
985 }
986
San Mehat207e5382010-02-04 20:46:54 -0800987 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800988 sendUmsIntent(avail);
989 } else {
990 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800991 }
San Mehat2fe718a2010-03-11 12:01:49 -0800992
993 final String path = Environment.getExternalStorageDirectory().getPath();
994 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
995 /*
996 * USB mass storage disconnected while enabled
997 */
998 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600999 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001000 public void run() {
1001 try {
1002 int rc;
San Mehata5078592010-03-25 09:36:54 -07001003 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001004 doShareUnshareVolume(path, "ums", false);
1005 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001006 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001007 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1008 path, rc));
1009 }
1010 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001011 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001012 }
1013 }
1014 }.start();
1015 }
San Mehat4270e1e2010-01-29 05:32:19 -08001016 }
1017
Mike Lockwooda5250c92011-05-23 13:44:04 -04001018 private void sendStorageIntent(String action, String path) {
1019 Intent intent = new Intent(action, Uri.parse("file://" + path));
1020 // add StorageVolume extra
1021 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1022 Slog.d(TAG, "sendStorageIntent " + intent);
1023 mContext.sendBroadcast(intent);
1024 }
1025
San Mehat6a965af22010-02-24 17:47:30 -08001026 private void sendUmsIntent(boolean c) {
1027 mContext.sendBroadcast(
1028 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1029 }
1030
San Mehat207e5382010-02-04 20:46:54 -08001031 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001032 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1033 throw new SecurityException(String.format("Requires %s permission", perm));
1034 }
1035 }
1036
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001037 // Storage list XML tags
1038 private static final String TAG_STORAGE_LIST = "StorageList";
1039 private static final String TAG_STORAGE = "storage";
1040
1041 private void readStorageList(Resources resources) {
1042 int id = com.android.internal.R.xml.storage_list;
1043 XmlResourceParser parser = resources.getXml(id);
1044 AttributeSet attrs = Xml.asAttributeSet(parser);
1045
1046 try {
1047 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1048 while (true) {
1049 XmlUtils.nextElement(parser);
1050
1051 String element = parser.getName();
1052 if (element == null) break;
1053
1054 if (TAG_STORAGE.equals(element)) {
1055 TypedArray a = resources.obtainAttributes(attrs,
1056 com.android.internal.R.styleable.Storage);
1057
1058 CharSequence path = a.getText(
1059 com.android.internal.R.styleable.Storage_mountPoint);
1060 CharSequence description = a.getText(
1061 com.android.internal.R.styleable.Storage_storageDescription);
1062 boolean primary = a.getBoolean(
1063 com.android.internal.R.styleable.Storage_primary, false);
1064 boolean removable = a.getBoolean(
1065 com.android.internal.R.styleable.Storage_removable, false);
1066 boolean emulated = a.getBoolean(
1067 com.android.internal.R.styleable.Storage_emulated, false);
1068 int mtpReserve = a.getInt(
1069 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001070 boolean allowMassStorage = a.getBoolean(
1071 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001072 // resource parser does not support longs, so XML value is in megabytes
1073 long maxFileSize = a.getInt(
1074 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001075
1076 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1077 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001078 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001079 " allowMassStorage: " + allowMassStorage +
1080 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001081 if (path == null || description == null) {
1082 Slog.e(TAG, "path or description is null in readStorageList");
1083 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001084 String pathString = path.toString();
1085 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001086 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001087 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001088 if (primary) {
1089 if (mPrimaryVolume == null) {
1090 mPrimaryVolume = volume;
1091 } else {
1092 Slog.e(TAG, "multiple primary volumes in storage list");
1093 }
1094 }
1095 if (mPrimaryVolume == volume) {
1096 // primay volume must be first
1097 mVolumes.add(0, volume);
1098 } else {
1099 mVolumes.add(volume);
1100 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001101 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001102 }
1103 a.recycle();
1104 }
1105 }
1106 } catch (XmlPullParserException e) {
1107 throw new RuntimeException(e);
1108 } catch (IOException e) {
1109 throw new RuntimeException(e);
1110 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001111 // compute storage ID for each volume
1112 int length = mVolumes.size();
1113 for (int i = 0; i < length; i++) {
1114 mVolumes.get(i).setStorageId(i);
1115 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001116 parser.close();
1117 }
1118 }
1119
San Mehat4270e1e2010-01-29 05:32:19 -08001120 /**
San Mehat207e5382010-02-04 20:46:54 -08001121 * Constructs a new MountService instance
1122 *
1123 * @param context Binder context for this service
1124 */
1125 public MountService(Context context) {
1126 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001127 Resources resources = context.getResources();
1128 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001129
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001130 if (mPrimaryVolume != null) {
1131 mExternalStoragePath = mPrimaryVolume.getPath();
1132 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1133 if (mEmulateExternalStorage) {
1134 Slog.d(TAG, "using emulated external storage");
1135 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1136 }
Mike Lockwood03559752010-07-19 18:25:03 -04001137 }
1138
San Mehat207e5382010-02-04 20:46:54 -08001139 // XXX: This will go away soon in favor of IMountServiceObserver
1140 mPms = (PackageManagerService) ServiceManager.getService("package");
1141
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001142 IntentFilter filter = new IntentFilter();
1143 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1144 // don't bother monitoring USB if mass storage is not supported on our primary volume
1145 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1146 filter.addAction(UsbManager.ACTION_USB_STATE);
1147 }
1148 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001149
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001150 mHandlerThread = new HandlerThread("MountService");
1151 mHandlerThread.start();
1152 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1153
Kenny Roota02b8b02010-08-05 16:14:17 -07001154 // Add OBB Action Handler to MountService thread.
1155 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1156
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001157 /*
1158 * Vold does not run in the simulator, so pretend the connector thread
1159 * ran and did its thing.
1160 */
1161 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1162 mReady = true;
1163 mUmsEnabling = true;
1164 return;
1165 }
1166
Kenny Root305bcbf2010-09-03 07:56:38 -07001167 /*
1168 * Create the connection to vold with a maximum queue of twice the
1169 * amount of containers we'd ever expect to have. This keeps an
1170 * "asec list" from blocking a thread repeatedly.
1171 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001172 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001173 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001174 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001175 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001176
Kenny Root07714d42011-08-17 17:49:28 -07001177 // Add ourself to the Watchdog monitors if enabled.
1178 if (WATCHDOG_ENABLE) {
1179 Watchdog.getInstance().addMonitor(this);
1180 }
San Mehat207e5382010-02-04 20:46:54 -08001181 }
1182
1183 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001184 * Exposed API calls below here
1185 */
1186
1187 public void registerListener(IMountServiceListener listener) {
1188 synchronized (mListeners) {
1189 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1190 try {
1191 listener.asBinder().linkToDeath(bl, 0);
1192 mListeners.add(bl);
1193 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001194 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001195 }
1196 }
1197 }
1198
1199 public void unregisterListener(IMountServiceListener listener) {
1200 synchronized (mListeners) {
1201 for(MountServiceBinderListener bl : mListeners) {
1202 if (bl.mListener == listener) {
1203 mListeners.remove(mListeners.indexOf(bl));
1204 return;
1205 }
1206 }
1207 }
1208 }
1209
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001210 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001211 validatePermission(android.Manifest.permission.SHUTDOWN);
1212
San Mehata5078592010-03-25 09:36:54 -07001213 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001214 synchronized (mVolumeStates) {
1215 for (String path : mVolumeStates.keySet()) {
1216 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001217
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001218 if (state.equals(Environment.MEDIA_SHARED)) {
1219 /*
1220 * If the media is currently shared, unshare it.
1221 * XXX: This is still dangerous!. We should not
1222 * be rebooting at *all* if UMS is enabled, since
1223 * the UMS host could have dirty FAT cache entries
1224 * yet to flush.
1225 */
1226 setUsbMassStorageEnabled(false);
1227 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1228 /*
1229 * If the media is being checked, then we need to wait for
1230 * it to complete before being able to proceed.
1231 */
1232 // XXX: @hackbod - Should we disable the ANR timer here?
1233 int retries = 30;
1234 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1235 try {
1236 Thread.sleep(1000);
1237 } catch (InterruptedException iex) {
1238 Slog.e(TAG, "Interrupted while waiting for media", iex);
1239 break;
1240 }
1241 state = Environment.getExternalStorageState();
1242 }
1243 if (retries == 0) {
1244 Slog.e(TAG, "Timed out waiting for media to check");
1245 }
San Mehat91c77612010-01-07 10:39:41 -08001246 }
San Mehat91c77612010-01-07 10:39:41 -08001247
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001248 if (state.equals(Environment.MEDIA_MOUNTED)) {
1249 // Post a unmount message.
1250 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1251 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1252 } else if (observer != null) {
1253 /*
1254 * Observer is waiting for onShutDownComplete when we are done.
1255 * Since nothing will be done send notification directly so shutdown
1256 * sequence can continue.
1257 */
1258 try {
1259 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1260 } catch (RemoteException e) {
1261 Slog.w(TAG, "RemoteException when shutting down");
1262 }
1263 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001264 }
San Mehat4270e1e2010-01-29 05:32:19 -08001265 }
1266 }
1267
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001268 private boolean getUmsEnabling() {
1269 synchronized (mListeners) {
1270 return mUmsEnabling;
1271 }
1272 }
1273
1274 private void setUmsEnabling(boolean enable) {
1275 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001276 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001277 }
1278 }
1279
San Mehatb1043402010-02-05 08:26:50 -08001280 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001281 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001282
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001283 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001284 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001285 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001286 synchronized (mListeners) {
1287 return mUmsAvailable;
1288 }
San Mehatb1043402010-02-05 08:26:50 -08001289 }
1290
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001291 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001292 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001293 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001294
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001295 // TODO: Add support for multiple share methods
1296
1297 /*
1298 * If the volume is mounted and we're enabling then unmount it
1299 */
1300 String path = Environment.getExternalStorageDirectory().getPath();
1301 String vs = getVolumeState(path);
1302 String method = "ums";
1303 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1304 // Override for isUsbMassStorageEnabled()
1305 setUmsEnabling(enable);
1306 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1307 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1308 // Clear override
1309 setUmsEnabling(false);
1310 }
1311 /*
1312 * If we disabled UMS then mount the volume
1313 */
1314 if (!enable) {
1315 doShareUnshareVolume(path, method, enable);
1316 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001317 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001318 " after disabling share method " + method);
1319 /*
1320 * Even though the mount failed, the unshare didn't so don't indicate an error.
1321 * The mountVolume() call will have set the storage state and sent the necessary
1322 * broadcasts.
1323 */
1324 }
1325 }
San Mehatb1043402010-02-05 08:26:50 -08001326 }
1327
1328 public boolean isUsbMassStorageEnabled() {
1329 waitForReady();
1330 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001332
San Mehat7fd0fee2009-12-17 07:12:23 -08001333 /**
1334 * @return state of the volume at the specified mount point
1335 */
San Mehat4270e1e2010-01-29 05:32:19 -08001336 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001337 synchronized (mVolumeStates) {
1338 String state = mVolumeStates.get(mountPoint);
1339 if (state == null) {
1340 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001341 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1342 state = Environment.MEDIA_REMOVED;
1343 } else {
1344 throw new IllegalArgumentException();
1345 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001346 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001347
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001348 return state;
1349 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001350 }
1351
Kenny Roote1ff2142010-10-12 11:20:01 -07001352 public boolean isExternalStorageEmulated() {
1353 return mEmulateExternalStorage;
1354 }
1355
San Mehat4270e1e2010-01-29 05:32:19 -08001356 public int mountVolume(String path) {
1357 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001358
San Mehat207e5382010-02-04 20:46:54 -08001359 waitForReady();
1360 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362
Ben Komalo13c71972011-09-07 16:35:56 -07001363 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001364 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001365 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001367 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001368 if (DEBUG_UNMOUNT) {
1369 Slog.i(TAG, "Unmounting " + path
1370 + " force = " + force
1371 + " removeEncryption = " + removeEncryption);
1372 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001373 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1374 Environment.MEDIA_REMOVED.equals(volState) ||
1375 Environment.MEDIA_SHARED.equals(volState) ||
1376 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1377 // Media already unmounted or cannot be unmounted.
1378 // TODO return valid return code when adding observer call back.
1379 return;
1380 }
Ben Komalo13c71972011-09-07 16:35:56 -07001381 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001382 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
San Mehat4270e1e2010-01-29 05:32:19 -08001385 public int formatVolume(String path) {
1386 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001387 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001388
San Mehat207e5382010-02-04 20:46:54 -08001389 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
1391
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001392 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001393 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1394 waitForReady();
1395 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001396 final String[] r = NativeDaemonEvent.filterMessageList(
1397 mConnector.executeForList("storage", "users", path),
1398 VoldResponseCode.StorageUsersListResult);
1399
San Mehatc1b4ce92010-02-16 17:13:03 -08001400 // FMT: <pid> <process name>
1401 int[] data = new int[r.length];
1402 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001403 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001404 try {
1405 data[i] = Integer.parseInt(tok[0]);
1406 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001407 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001408 return new int[0];
1409 }
1410 }
1411 return data;
1412 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001413 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001414 return new int[0];
1415 }
1416 }
1417
San Mehatb1043402010-02-05 08:26:50 -08001418 private void warnOnNotMounted() {
1419 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001420 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001421 }
1422 }
1423
San Mehat4270e1e2010-01-29 05:32:19 -08001424 public String[] getSecureContainerList() {
1425 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001426 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001427 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001428
San Mehat4270e1e2010-01-29 05:32:19 -08001429 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001430 return NativeDaemonEvent.filterMessageList(
1431 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001432 } 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 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001445 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001446 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001447 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001448 }
San Mehata181b212010-02-11 06:50:20 -08001449
1450 if (rc == StorageResultCode.OperationSucceeded) {
1451 synchronized (mAsecMountSet) {
1452 mAsecMountSet.add(id);
1453 }
1454 }
San Mehat4270e1e2010-01-29 05:32:19 -08001455 return rc;
San Mehat36972292010-01-06 11:06:32 -08001456 }
1457
San Mehat4270e1e2010-01-29 05:32:19 -08001458 public int finalizeSecureContainer(String id) {
1459 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001460 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001461
San Mehatb1043402010-02-05 08:26:50 -08001462 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001463 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001464 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001465 /*
1466 * Finalization does a remount, so no need
1467 * to update mAsecMountSet
1468 */
San Mehat4270e1e2010-01-29 05:32:19 -08001469 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001470 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001471 }
San Mehat4270e1e2010-01-29 05:32:19 -08001472 return rc;
San Mehat36972292010-01-06 11:06:32 -08001473 }
1474
San Mehatd9709982010-02-18 11:43:03 -08001475 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001476 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001477 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001478 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001479
Kenny Rootaa485402010-09-14 14:49:41 -07001480 /*
1481 * Force a GC to make sure AssetManagers in other threads of the
1482 * system_server are cleaned up. We have to do this since AssetManager
1483 * instances are kept as a WeakReference and it's possible we have files
1484 * open on the external storage.
1485 */
1486 Runtime.getRuntime().gc();
1487
San Mehatb1043402010-02-05 08:26:50 -08001488 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001489 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001490 final Command cmd = new Command("asec", "destroy", id);
1491 if (force) {
1492 cmd.appendArg("force");
1493 }
1494 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001495 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001496 int code = e.getCode();
1497 if (code == VoldResponseCode.OpFailedStorageBusy) {
1498 rc = StorageResultCode.OperationFailedStorageBusy;
1499 } else {
1500 rc = StorageResultCode.OperationFailedInternalError;
1501 }
San Mehat02735bc2010-01-26 15:18:08 -08001502 }
San Mehata181b212010-02-11 06:50:20 -08001503
1504 if (rc == StorageResultCode.OperationSucceeded) {
1505 synchronized (mAsecMountSet) {
1506 if (mAsecMountSet.contains(id)) {
1507 mAsecMountSet.remove(id);
1508 }
1509 }
1510 }
1511
San Mehat4270e1e2010-01-29 05:32:19 -08001512 return rc;
San Mehat36972292010-01-06 11:06:32 -08001513 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001514
San Mehat4270e1e2010-01-29 05:32:19 -08001515 public int mountSecureContainer(String id, String key, int ownerUid) {
1516 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001517 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001518 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001519
San Mehata181b212010-02-11 06:50:20 -08001520 synchronized (mAsecMountSet) {
1521 if (mAsecMountSet.contains(id)) {
1522 return StorageResultCode.OperationFailedStorageMounted;
1523 }
1524 }
1525
San Mehatb1043402010-02-05 08:26:50 -08001526 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001527 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001528 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001529 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001530 int code = e.getCode();
1531 if (code != VoldResponseCode.OpFailedStorageBusy) {
1532 rc = StorageResultCode.OperationFailedInternalError;
1533 }
San Mehat02735bc2010-01-26 15:18:08 -08001534 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001535
1536 if (rc == StorageResultCode.OperationSucceeded) {
1537 synchronized (mAsecMountSet) {
1538 mAsecMountSet.add(id);
1539 }
1540 }
San Mehat4270e1e2010-01-29 05:32:19 -08001541 return rc;
San Mehat36972292010-01-06 11:06:32 -08001542 }
1543
San Mehatd9709982010-02-18 11:43:03 -08001544 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001545 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001546 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001547 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001548
San Mehat6cdd9c02010-02-09 14:45:20 -08001549 synchronized (mAsecMountSet) {
1550 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001551 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001552 }
1553 }
1554
Kenny Rootaa485402010-09-14 14:49:41 -07001555 /*
1556 * Force a GC to make sure AssetManagers in other threads of the
1557 * system_server are cleaned up. We have to do this since AssetManager
1558 * instances are kept as a WeakReference and it's possible we have files
1559 * open on the external storage.
1560 */
1561 Runtime.getRuntime().gc();
1562
San Mehatb1043402010-02-05 08:26:50 -08001563 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001564 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001565 final Command cmd = new Command("asec", "unmount", id);
1566 if (force) {
1567 cmd.appendArg("force");
1568 }
1569 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001570 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001571 int code = e.getCode();
1572 if (code == VoldResponseCode.OpFailedStorageBusy) {
1573 rc = StorageResultCode.OperationFailedStorageBusy;
1574 } else {
1575 rc = StorageResultCode.OperationFailedInternalError;
1576 }
San Mehat02735bc2010-01-26 15:18:08 -08001577 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001578
1579 if (rc == StorageResultCode.OperationSucceeded) {
1580 synchronized (mAsecMountSet) {
1581 mAsecMountSet.remove(id);
1582 }
1583 }
San Mehat4270e1e2010-01-29 05:32:19 -08001584 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001585 }
1586
San Mehat6cdd9c02010-02-09 14:45:20 -08001587 public boolean isSecureContainerMounted(String id) {
1588 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1589 waitForReady();
1590 warnOnNotMounted();
1591
1592 synchronized (mAsecMountSet) {
1593 return mAsecMountSet.contains(id);
1594 }
1595 }
1596
San Mehat4270e1e2010-01-29 05:32:19 -08001597 public int renameSecureContainer(String oldId, String newId) {
1598 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001599 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001600 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001601
San Mehata181b212010-02-11 06:50:20 -08001602 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001603 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001604 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001605 * changed while active, we must ensure both ids are not currently mounted.
1606 */
1607 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001608 return StorageResultCode.OperationFailedStorageMounted;
1609 }
1610 }
1611
San Mehatb1043402010-02-05 08:26:50 -08001612 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001613 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001614 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001615 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001616 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001617 }
San Mehata181b212010-02-11 06:50:20 -08001618
San Mehat4270e1e2010-01-29 05:32:19 -08001619 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001620 }
1621
San Mehat4270e1e2010-01-29 05:32:19 -08001622 public String getSecureContainerPath(String id) {
1623 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001624 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001625 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001626
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001627 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001628 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001629 event = mConnector.execute("asec", "path", id);
1630 event.checkCode(VoldResponseCode.AsecPathResult);
1631 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001632 } catch (NativeDaemonConnectorException e) {
1633 int code = e.getCode();
1634 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001635 Slog.i(TAG, String.format("Container '%s' not found", id));
1636 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001637 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001638 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001639 }
1640 }
San Mehat22dd86e2010-01-12 12:21:18 -08001641 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001642
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001643 public String getSecureContainerFilesystemPath(String id) {
1644 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1645 waitForReady();
1646 warnOnNotMounted();
1647
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001648 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001649 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001650 event = mConnector.execute("asec", "fspath", id);
1651 event.checkCode(VoldResponseCode.AsecPathResult);
1652 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001653 } catch (NativeDaemonConnectorException e) {
1654 int code = e.getCode();
1655 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1656 Slog.i(TAG, String.format("Container '%s' not found", id));
1657 return null;
1658 } else {
1659 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1660 }
1661 }
1662 }
1663
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001664 public void finishMediaUpdate() {
1665 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1666 }
Kenny Root02c87302010-07-01 08:10:18 -07001667
Kenny Roota02b8b02010-08-05 16:14:17 -07001668 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1669 if (callerUid == android.os.Process.SYSTEM_UID) {
1670 return true;
1671 }
1672
Kenny Root02c87302010-07-01 08:10:18 -07001673 if (packageName == null) {
1674 return false;
1675 }
1676
1677 final int packageUid = mPms.getPackageUid(packageName);
1678
1679 if (DEBUG_OBB) {
1680 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1681 packageUid + ", callerUid = " + callerUid);
1682 }
1683
1684 return callerUid == packageUid;
1685 }
1686
1687 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001688 if (filename == null) {
1689 throw new IllegalArgumentException("filename cannot be null");
1690 }
1691
Kenny Root02c87302010-07-01 08:10:18 -07001692 waitForReady();
1693 warnOnNotMounted();
1694
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001695 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001696 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001697 event = mConnector.execute("obb", "path", filename);
1698 event.checkCode(VoldResponseCode.AsecPathResult);
1699 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001700 } catch (NativeDaemonConnectorException e) {
1701 int code = e.getCode();
1702 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001703 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001704 } else {
1705 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1706 }
1707 }
1708 }
1709
1710 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001711 if (filename == null) {
1712 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001713 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001714
1715 synchronized (mObbMounts) {
1716 return mObbPathToStateMap.containsKey(filename);
1717 }
Kenny Root02c87302010-07-01 08:10:18 -07001718 }
1719
Kenny Rootaf9d6672010-10-08 09:21:39 -07001720 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001721 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001722 if (filename == null) {
1723 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001724 }
1725
1726 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001727 throw new IllegalArgumentException("token cannot be null");
1728 }
1729
Kenny Rootaf9d6672010-10-08 09:21:39 -07001730 final int callerUid = Binder.getCallingUid();
1731 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1732 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001733 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1734
1735 if (DEBUG_OBB)
1736 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001737 }
1738
Kenny Rootaf9d6672010-10-08 09:21:39 -07001739 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1740 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001741 if (filename == null) {
1742 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001743 }
1744
Kenny Rootaf9d6672010-10-08 09:21:39 -07001745 final int callerUid = Binder.getCallingUid();
1746 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1747 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001748 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001749
Kenny Roota02b8b02010-08-05 16:14:17 -07001750 if (DEBUG_OBB)
1751 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1752 }
1753
Ben Komalo444eca22011-09-01 15:17:44 -07001754 @Override
1755 public int getEncryptionState() {
1756 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1757 "no permission to access the crypt keeper");
1758
1759 waitForReady();
1760
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001761 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001762 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001763 event = mConnector.execute("cryptfs", "cryptocomplete");
1764 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001765 } catch (NumberFormatException e) {
1766 // Bad result - unexpected.
1767 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1768 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1769 } catch (NativeDaemonConnectorException e) {
1770 // Something bad happened.
1771 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1772 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1773 }
1774 }
1775
1776 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001777 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001778 if (TextUtils.isEmpty(password)) {
1779 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001780 }
1781
Jason parks8888c592011-01-20 22:46:41 -06001782 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1783 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001784
1785 waitForReady();
1786
1787 if (DEBUG_EVENTS) {
1788 Slog.i(TAG, "decrypting storage...");
1789 }
1790
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001791 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001792 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001793 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001794
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001795 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001796 if (code == 0) {
1797 // Decrypt was successful. Post a delayed message before restarting in order
1798 // to let the UI to clear itself
1799 mHandler.postDelayed(new Runnable() {
1800 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001801 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001802 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001803 } catch (NativeDaemonConnectorException e) {
1804 Slog.e(TAG, "problem executing in background", e);
1805 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001806 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001807 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001808 }
1809
1810 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001811 } catch (NativeDaemonConnectorException e) {
1812 // Decryption failed
1813 return e.getCode();
1814 }
Jason parks5af0b912010-11-29 09:05:25 -06001815 }
1816
Jason parks56aa5322011-01-07 09:01:15 -06001817 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001818 if (TextUtils.isEmpty(password)) {
1819 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001820 }
1821
Jason parks8888c592011-01-20 22:46:41 -06001822 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1823 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001824
1825 waitForReady();
1826
1827 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001828 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001829 }
1830
1831 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001832 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06001833 } catch (NativeDaemonConnectorException e) {
1834 // Encryption failed
1835 return e.getCode();
1836 }
1837
1838 return 0;
1839 }
1840
Jason parksf7b3cd42011-01-27 09:28:25 -06001841 public int changeEncryptionPassword(String password) {
1842 if (TextUtils.isEmpty(password)) {
1843 throw new IllegalArgumentException("password cannot be empty");
1844 }
1845
1846 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1847 "no permission to access the crypt keeper");
1848
1849 waitForReady();
1850
1851 if (DEBUG_EVENTS) {
1852 Slog.i(TAG, "changing encryption password...");
1853 }
1854
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001855 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06001856 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001857 event = mConnector.execute("cryptfs", "changepw", password);
1858 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06001859 } catch (NativeDaemonConnectorException e) {
1860 // Encryption failed
1861 return e.getCode();
1862 }
1863 }
1864
Christopher Tate32418be2011-10-10 13:51:12 -07001865 /**
1866 * Validate a user-supplied password string with cryptfs
1867 */
1868 @Override
1869 public int verifyEncryptionPassword(String password) throws RemoteException {
1870 // Only the system process is permitted to validate passwords
1871 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1872 throw new SecurityException("no permission to access the crypt keeper");
1873 }
1874
1875 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1876 "no permission to access the crypt keeper");
1877
1878 if (TextUtils.isEmpty(password)) {
1879 throw new IllegalArgumentException("password cannot be empty");
1880 }
1881
1882 waitForReady();
1883
1884 if (DEBUG_EVENTS) {
1885 Slog.i(TAG, "validating encryption password...");
1886 }
1887
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001888 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07001889 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001890 event = mConnector.execute("cryptfs", "verifypw", password);
1891 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
1892 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07001893 } catch (NativeDaemonConnectorException e) {
1894 // Encryption failed
1895 return e.getCode();
1896 }
1897 }
1898
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001899 public Parcelable[] getVolumeList() {
1900 synchronized(mVolumes) {
1901 int size = mVolumes.size();
1902 Parcelable[] result = new Parcelable[size];
1903 for (int i = 0; i < size; i++) {
1904 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001905 }
1906 return result;
1907 }
1908 }
1909
Kenny Rootaf9d6672010-10-08 09:21:39 -07001910 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1911 final IBinder binder = obbState.getBinder();
1912 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001913
Kenny Rootaf9d6672010-10-08 09:21:39 -07001914 if (obbStates == null) {
1915 obbStates = new ArrayList<ObbState>();
1916 mObbMounts.put(binder, obbStates);
1917 } else {
1918 for (final ObbState o : obbStates) {
1919 if (o.filename.equals(obbState.filename)) {
1920 throw new IllegalStateException("Attempt to add ObbState twice. "
1921 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001922 }
1923 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001924 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001925
1926 obbStates.add(obbState);
1927 try {
1928 obbState.link();
1929 } catch (RemoteException e) {
1930 /*
1931 * The binder died before we could link it, so clean up our state
1932 * and return failure.
1933 */
1934 obbStates.remove(obbState);
1935 if (obbStates.isEmpty()) {
1936 mObbMounts.remove(binder);
1937 }
1938
1939 // Rethrow the error so mountObb can get it
1940 throw e;
1941 }
1942
1943 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 }
1945
Kenny Rootaf9d6672010-10-08 09:21:39 -07001946 private void removeObbStateLocked(ObbState obbState) {
1947 final IBinder binder = obbState.getBinder();
1948 final List<ObbState> obbStates = mObbMounts.get(binder);
1949 if (obbStates != null) {
1950 if (obbStates.remove(obbState)) {
1951 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001952 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001953 if (obbStates.isEmpty()) {
1954 mObbMounts.remove(binder);
1955 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001956 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001957
Kenny Rootaf9d6672010-10-08 09:21:39 -07001958 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001959 }
1960
Kenny Roota02b8b02010-08-05 16:14:17 -07001961 private class ObbActionHandler extends Handler {
1962 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001963 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001964
1965 ObbActionHandler(Looper l) {
1966 super(l);
1967 }
1968
1969 @Override
1970 public void handleMessage(Message msg) {
1971 switch (msg.what) {
1972 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001973 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001974
1975 if (DEBUG_OBB)
1976 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1977
1978 // If a bind was already initiated we don't really
1979 // need to do anything. The pending install
1980 // will be processed later on.
1981 if (!mBound) {
1982 // If this is the only one pending we might
1983 // have to bind to the service again.
1984 if (!connectToService()) {
1985 Slog.e(TAG, "Failed to bind to media container service");
1986 action.handleError();
1987 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001988 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001989 }
Kenny Root735de3b2010-09-30 14:11:39 -07001990
Kenny Root735de3b2010-09-30 14:11:39 -07001991 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001992 break;
1993 }
1994 case OBB_MCS_BOUND: {
1995 if (DEBUG_OBB)
1996 Slog.i(TAG, "OBB_MCS_BOUND");
1997 if (msg.obj != null) {
1998 mContainerService = (IMediaContainerService) msg.obj;
1999 }
2000 if (mContainerService == null) {
2001 // Something seriously wrong. Bail out
2002 Slog.e(TAG, "Cannot bind to media container service");
2003 for (ObbAction action : mActions) {
2004 // Indicate service bind error
2005 action.handleError();
2006 }
2007 mActions.clear();
2008 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002009 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002010 if (action != null) {
2011 action.execute(this);
2012 }
2013 } else {
2014 // Should never happen ideally.
2015 Slog.w(TAG, "Empty queue");
2016 }
2017 break;
2018 }
2019 case OBB_MCS_RECONNECT: {
2020 if (DEBUG_OBB)
2021 Slog.i(TAG, "OBB_MCS_RECONNECT");
2022 if (mActions.size() > 0) {
2023 if (mBound) {
2024 disconnectService();
2025 }
2026 if (!connectToService()) {
2027 Slog.e(TAG, "Failed to bind to media container service");
2028 for (ObbAction action : mActions) {
2029 // Indicate service bind error
2030 action.handleError();
2031 }
2032 mActions.clear();
2033 }
2034 }
2035 break;
2036 }
2037 case OBB_MCS_UNBIND: {
2038 if (DEBUG_OBB)
2039 Slog.i(TAG, "OBB_MCS_UNBIND");
2040
2041 // Delete pending install
2042 if (mActions.size() > 0) {
2043 mActions.remove(0);
2044 }
2045 if (mActions.size() == 0) {
2046 if (mBound) {
2047 disconnectService();
2048 }
2049 } else {
2050 // There are more pending requests in queue.
2051 // Just post MCS_BOUND message to trigger processing
2052 // of next pending install.
2053 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2054 }
2055 break;
2056 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002057 case OBB_FLUSH_MOUNT_STATE: {
2058 final String path = (String) msg.obj;
2059
2060 if (DEBUG_OBB)
2061 Slog.i(TAG, "Flushing all OBB state for path " + path);
2062
2063 synchronized (mObbMounts) {
2064 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2065
2066 final Iterator<Entry<String, ObbState>> i =
2067 mObbPathToStateMap.entrySet().iterator();
2068 while (i.hasNext()) {
2069 final Entry<String, ObbState> obbEntry = i.next();
2070
2071 /*
2072 * If this entry's source file is in the volume path
2073 * that got unmounted, remove it because it's no
2074 * longer valid.
2075 */
2076 if (obbEntry.getKey().startsWith(path)) {
2077 obbStatesToRemove.add(obbEntry.getValue());
2078 }
2079 }
2080
2081 for (final ObbState obbState : obbStatesToRemove) {
2082 if (DEBUG_OBB)
2083 Slog.i(TAG, "Removing state for " + obbState.filename);
2084
2085 removeObbStateLocked(obbState);
2086
2087 try {
2088 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2089 OnObbStateChangeListener.UNMOUNTED);
2090 } catch (RemoteException e) {
2091 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2092 + obbState.filename);
2093 }
2094 }
2095 }
2096 break;
2097 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002098 }
2099 }
2100
2101 private boolean connectToService() {
2102 if (DEBUG_OBB)
2103 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2104
2105 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2106 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2107 mBound = true;
2108 return true;
2109 }
2110 return false;
2111 }
2112
2113 private void disconnectService() {
2114 mContainerService = null;
2115 mBound = false;
2116 mContext.unbindService(mDefContainerConn);
2117 }
2118 }
2119
2120 abstract class ObbAction {
2121 private static final int MAX_RETRIES = 3;
2122 private int mRetries;
2123
2124 ObbState mObbState;
2125
2126 ObbAction(ObbState obbState) {
2127 mObbState = obbState;
2128 }
2129
2130 public void execute(ObbActionHandler handler) {
2131 try {
2132 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002133 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002134 mRetries++;
2135 if (mRetries > MAX_RETRIES) {
2136 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002137 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002138 handleError();
2139 return;
2140 } else {
2141 handleExecute();
2142 if (DEBUG_OBB)
2143 Slog.i(TAG, "Posting install MCS_UNBIND");
2144 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2145 }
2146 } catch (RemoteException e) {
2147 if (DEBUG_OBB)
2148 Slog.i(TAG, "Posting install MCS_RECONNECT");
2149 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2150 } catch (Exception e) {
2151 if (DEBUG_OBB)
2152 Slog.d(TAG, "Error handling OBB action", e);
2153 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002154 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002155 }
2156 }
2157
Kenny Root05105f72010-09-22 17:29:43 -07002158 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002159 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002160
2161 protected ObbInfo getObbInfo() throws IOException {
2162 ObbInfo obbInfo;
2163 try {
2164 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2165 } catch (RemoteException e) {
2166 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2167 + mObbState.filename);
2168 obbInfo = null;
2169 }
2170 if (obbInfo == null) {
2171 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2172 }
2173 return obbInfo;
2174 }
2175
Kenny Rootaf9d6672010-10-08 09:21:39 -07002176 protected void sendNewStatusOrIgnore(int status) {
2177 if (mObbState == null || mObbState.token == null) {
2178 return;
2179 }
2180
Kenny Root38cf8862010-09-26 14:18:51 -07002181 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002182 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002183 } catch (RemoteException e) {
2184 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2185 }
2186 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002187 }
2188
2189 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002190 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002191
2192 MountObbAction(ObbState obbState, String key) {
2193 super(obbState);
2194 mKey = key;
2195 }
2196
Jason parks5af0b912010-11-29 09:05:25 -06002197 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002198 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002199 waitForReady();
2200 warnOnNotMounted();
2201
Kenny Root38cf8862010-09-26 14:18:51 -07002202 final ObbInfo obbInfo = getObbInfo();
2203
Kenny Roota02b8b02010-08-05 16:14:17 -07002204 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002205 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2206 + " which is owned by " + obbInfo.packageName);
2207 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2208 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002209 }
2210
Kenny Rootaf9d6672010-10-08 09:21:39 -07002211 final boolean isMounted;
2212 synchronized (mObbMounts) {
2213 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2214 }
2215 if (isMounted) {
2216 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2217 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2218 return;
2219 }
2220
2221 /*
2222 * The filename passed in might not be the canonical name, so just
2223 * set the filename to the canonicalized version.
2224 */
2225 mObbState.filename = obbInfo.filename;
2226
2227 final String hashedKey;
2228 if (mKey == null) {
2229 hashedKey = "none";
2230 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002231 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002232 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2233
2234 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2235 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2236 SecretKey key = factory.generateSecret(ks);
2237 BigInteger bi = new BigInteger(key.getEncoded());
2238 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002239 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002240 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2241 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2242 return;
2243 } catch (InvalidKeySpecException e) {
2244 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2245 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002246 return;
2247 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002248 }
Kenny Root38cf8862010-09-26 14:18:51 -07002249
Kenny Rootaf9d6672010-10-08 09:21:39 -07002250 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002251 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002252 mConnector.execute(
2253 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002254 } catch (NativeDaemonConnectorException e) {
2255 int code = e.getCode();
2256 if (code != VoldResponseCode.OpFailedStorageBusy) {
2257 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002258 }
2259 }
2260
Kenny Rootaf9d6672010-10-08 09:21:39 -07002261 if (rc == StorageResultCode.OperationSucceeded) {
2262 if (DEBUG_OBB)
2263 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2264
2265 synchronized (mObbMounts) {
2266 addObbStateLocked(mObbState);
2267 }
2268
2269 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002270 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002271 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002272
Kenny Rootaf9d6672010-10-08 09:21:39 -07002273 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002274 }
2275 }
2276
Jason parks5af0b912010-11-29 09:05:25 -06002277 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002278 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002279 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002280 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002281
2282 @Override
2283 public String toString() {
2284 StringBuilder sb = new StringBuilder();
2285 sb.append("MountObbAction{");
2286 sb.append("filename=");
2287 sb.append(mObbState.filename);
2288 sb.append(",callerUid=");
2289 sb.append(mObbState.callerUid);
2290 sb.append(",token=");
2291 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002292 sb.append(",binder=");
2293 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002294 sb.append('}');
2295 return sb.toString();
2296 }
2297 }
2298
2299 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002300 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002301
2302 UnmountObbAction(ObbState obbState, boolean force) {
2303 super(obbState);
2304 mForceUnmount = force;
2305 }
2306
Jason parks5af0b912010-11-29 09:05:25 -06002307 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002308 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002309 waitForReady();
2310 warnOnNotMounted();
2311
Kenny Root38cf8862010-09-26 14:18:51 -07002312 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002313
Kenny Rootaf9d6672010-10-08 09:21:39 -07002314 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002315 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002316 obbState = mObbPathToStateMap.get(obbInfo.filename);
2317 }
Kenny Root38cf8862010-09-26 14:18:51 -07002318
Kenny Rootaf9d6672010-10-08 09:21:39 -07002319 if (obbState == null) {
2320 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2321 return;
2322 }
2323
2324 if (obbState.callerUid != mObbState.callerUid) {
2325 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2326 + " (owned by " + obbInfo.packageName + ")");
2327 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2328 return;
2329 }
2330
2331 mObbState.filename = obbInfo.filename;
2332
2333 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002334 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002335 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2336 if (mForceUnmount) {
2337 cmd.appendArg("force");
2338 }
2339 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002340 } catch (NativeDaemonConnectorException e) {
2341 int code = e.getCode();
2342 if (code == VoldResponseCode.OpFailedStorageBusy) {
2343 rc = StorageResultCode.OperationFailedStorageBusy;
2344 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2345 // If it's not mounted then we've already won.
2346 rc = StorageResultCode.OperationSucceeded;
2347 } else {
2348 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002349 }
2350 }
2351
Kenny Rootaf9d6672010-10-08 09:21:39 -07002352 if (rc == StorageResultCode.OperationSucceeded) {
2353 synchronized (mObbMounts) {
2354 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002355 }
2356
Kenny Rootaf9d6672010-10-08 09:21:39 -07002357 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002358 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002359 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2360 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002361 }
2362 }
2363
Jason parks5af0b912010-11-29 09:05:25 -06002364 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002365 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002366 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002367 }
2368
2369 @Override
2370 public String toString() {
2371 StringBuilder sb = new StringBuilder();
2372 sb.append("UnmountObbAction{");
2373 sb.append("filename=");
2374 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2375 sb.append(",force=");
2376 sb.append(mForceUnmount);
2377 sb.append(",callerUid=");
2378 sb.append(mObbState.callerUid);
2379 sb.append(",token=");
2380 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002381 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002382 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002383 sb.append('}');
2384 return sb.toString();
2385 }
Kenny Root02c87302010-07-01 08:10:18 -07002386 }
Kenny Root38cf8862010-09-26 14:18:51 -07002387
2388 @Override
2389 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2390 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2391 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2392 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2393 + " without permission " + android.Manifest.permission.DUMP);
2394 return;
2395 }
2396
Kenny Root38cf8862010-09-26 14:18:51 -07002397 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002398 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002399
Kenny Rootaf9d6672010-10-08 09:21:39 -07002400 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2401 while (binders.hasNext()) {
2402 Entry<IBinder, List<ObbState>> e = binders.next();
2403 pw.print(" Key="); pw.println(e.getKey().toString());
2404 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002405 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002406 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002407 }
2408 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409
2410 pw.println("");
2411 pw.println(" mObbPathToStateMap:");
2412 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2413 while (maps.hasNext()) {
2414 final Entry<String, ObbState> e = maps.next();
2415 pw.print(" "); pw.print(e.getKey());
2416 pw.print(" -> "); pw.println(e.getValue().toString());
2417 }
Kenny Root38cf8862010-09-26 14:18:51 -07002418 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002419
2420 pw.println("");
2421
2422 synchronized (mVolumes) {
2423 pw.println(" mVolumes:");
2424
2425 final int N = mVolumes.size();
2426 for (int i = 0; i < N; i++) {
2427 final StorageVolume v = mVolumes.get(i);
2428 pw.print(" ");
2429 pw.println(v.toString());
2430 }
2431 }
Kenny Root38cf8862010-09-26 14:18:51 -07002432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002434 /** {@inheritDoc} */
2435 public void monitor() {
2436 if (mConnector != null) {
2437 mConnector.monitor();
2438 }
2439 }
2440}