blob: 510bdb2a12edf9ec707176415d51aa762bbc1894 [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;
Amith Yamasani483f3b02012-03-13 16:08:00 -070051import android.os.UserId;
Kenny Roota02b8b02010-08-05 16:14:17 -070052import android.os.storage.IMountService;
53import android.os.storage.IMountServiceListener;
54import android.os.storage.IMountShutdownObserver;
55import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070056import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060059import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070061import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070062import android.util.Xml;
63
64import org.xmlpull.v1.XmlPullParser;
65import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070066
Kenny Root38cf8862010-09-26 14:18:51 -070067import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070068import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070069import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070070import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070071import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070072import java.security.spec.InvalidKeySpecException;
73import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080074import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070075import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080076import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070078import java.util.LinkedList;
79import java.util.List;
80import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070081import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070082import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Kenny Root3b1abba2010-10-13 15:00:07 -070084import javax.crypto.SecretKey;
85import javax.crypto.SecretKeyFactory;
86import javax.crypto.spec.PBEKeySpec;
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088/**
San Mehatb1043402010-02-05 08:26:50 -080089 * MountService implements back-end services for platform storage
90 * management.
91 * @hide - Applications should use android.os.storage.StorageManager
92 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070094class MountService extends IMountService.Stub
95 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -060096
San Mehatb1043402010-02-05 08:26:50 -080097 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080098 private static final boolean DEBUG_UNMOUNT = false;
99 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800100 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700101
Kenny Root07714d42011-08-17 17:49:28 -0700102 // Disable this since it messes up long-running cryptfs operations.
103 private static final boolean WATCHDOG_ENABLE = false;
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private static final String TAG = "MountService";
106
Kenny Root305bcbf2010-09-03 07:56:38 -0700107 private static final String VOLD_TAG = "VoldConnector";
108
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700109 /** Maximum number of ASEC containers allowed to be mounted. */
110 private static final int MAX_CONTAINERS = 250;
111
San Mehat4270e1e2010-01-29 05:32:19 -0800112 /*
113 * Internal vold volume state constants
114 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800115 class VolumeState {
116 public static final int Init = -1;
117 public static final int NoMedia = 0;
118 public static final int Idle = 1;
119 public static final int Pending = 2;
120 public static final int Checking = 3;
121 public static final int Mounted = 4;
122 public static final int Unmounting = 5;
123 public static final int Formatting = 6;
124 public static final int Shared = 7;
125 public static final int SharedMnt = 8;
126 }
127
San Mehat4270e1e2010-01-29 05:32:19 -0800128 /*
129 * Internal vold response code constants
130 */
San Mehat22dd86e2010-01-12 12:21:18 -0800131 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800132 /*
133 * 100 series - Requestion action was initiated; expect another reply
134 * before proceeding with a new command.
135 */
San Mehat22dd86e2010-01-12 12:21:18 -0800136 public static final int VolumeListResult = 110;
137 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800138 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 /*
141 * 200 series - Requestion action has been successfully completed.
142 */
143 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800144 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800145 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800146
San Mehat4270e1e2010-01-29 05:32:19 -0800147 /*
148 * 400 series - Command was accepted, but the requested action
149 * did not take place.
150 */
151 public static final int OpFailedNoMedia = 401;
152 public static final int OpFailedMediaBlank = 402;
153 public static final int OpFailedMediaCorrupt = 403;
154 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800155 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700156 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800157
158 /*
159 * 600 series - Unsolicited broadcasts.
160 */
San Mehat22dd86e2010-01-12 12:21:18 -0800161 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800162 public static final int VolumeDiskInserted = 630;
163 public static final int VolumeDiskRemoved = 631;
164 public static final int VolumeBadRemoval = 632;
165 }
166
San Mehat4270e1e2010-01-29 05:32:19 -0800167 private Context mContext;
168 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700169 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
170 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400171 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400172 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400173 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800174 private PackageManagerService mPms;
175 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700176 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800177 // Used as a lock for methods that register/unregister listeners.
178 final private ArrayList<MountServiceBinderListener> mListeners =
179 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800180 private boolean mBooted = false;
181 private boolean mReady = false;
182 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400183 // true if we should fake MEDIA_MOUNTED state for external storage
184 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800185
San Mehat6cdd9c02010-02-09 14:45:20 -0800186 /**
187 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800188 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800189 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800190 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800191
Kenny Root02c87302010-07-01 08:10:18 -0700192 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700193 * The size of the crypto algorithm key in bits for OBB files. Currently
194 * Twofish is used which takes 128-bit keys.
195 */
196 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
197
198 /**
199 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
200 * 1024 is reasonably secure and not too slow.
201 */
202 private static final int PBKDF2_HASH_ROUNDS = 1024;
203
204 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700205 * Mounted OBB tracking information. Used to track the current state of all
206 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700207 */
Kenny Root735de3b2010-09-30 14:11:39 -0700208 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700209 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
210
211 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700212 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700213 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700214 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700215 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700216 this.token = token;
217 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700218 }
219
220 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700221 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700222
223 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700224 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700225
Kenny Rootaf9d6672010-10-08 09:21:39 -0700226 // Token of remote Binder caller
227 final IObbActionListener token;
228
229 // Identifier to pass back to the token
230 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700231
Kenny Root735de3b2010-09-30 14:11:39 -0700232 public IBinder getBinder() {
233 return token.asBinder();
234 }
235
Kenny Roota02b8b02010-08-05 16:14:17 -0700236 @Override
237 public void binderDied() {
238 ObbAction action = new UnmountObbAction(this, true);
239 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700240 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700241
Kenny Root5919ac62010-10-05 09:49:40 -0700242 public void link() throws RemoteException {
243 getBinder().linkToDeath(this, 0);
244 }
245
246 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700247 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700248 }
Kenny Root38cf8862010-09-26 14:18:51 -0700249
250 @Override
251 public String toString() {
252 StringBuilder sb = new StringBuilder("ObbState{");
253 sb.append("filename=");
254 sb.append(filename);
255 sb.append(",token=");
256 sb.append(token.toString());
257 sb.append(",callerUid=");
258 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700259 sb.append('}');
260 return sb.toString();
261 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700262 }
263
264 // OBB Action Handler
265 final private ObbActionHandler mObbActionHandler;
266
267 // OBB action handler messages
268 private static final int OBB_RUN_ACTION = 1;
269 private static final int OBB_MCS_BOUND = 2;
270 private static final int OBB_MCS_UNBIND = 3;
271 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700272 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700273
274 /*
275 * Default Container Service information
276 */
277 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
278 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
279
280 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
281
282 class DefaultContainerConnection implements ServiceConnection {
283 public void onServiceConnected(ComponentName name, IBinder service) {
284 if (DEBUG_OBB)
285 Slog.i(TAG, "onServiceConnected");
286 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
287 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
288 }
289
290 public void onServiceDisconnected(ComponentName name) {
291 if (DEBUG_OBB)
292 Slog.i(TAG, "onServiceDisconnected");
293 }
294 };
295
296 // Used in the ObbActionHandler
297 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700298
299 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800300 private static final int H_UNMOUNT_PM_UPDATE = 1;
301 private static final int H_UNMOUNT_PM_DONE = 2;
302 private static final int H_UNMOUNT_MS = 3;
303 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
304 private static final int MAX_UNMOUNT_RETRIES = 4;
305
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800306 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700307 final String path;
308 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700309 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800310 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800311
Ben Komalo13c71972011-09-07 16:35:56 -0700312 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800313 retries = 0;
314 this.path = path;
315 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700316 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800317 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800318
319 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700320 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700321 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800322 }
323 }
324
325 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700326 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800327
328 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700329 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800330 this.method = method;
331 }
332
333 @Override
334 void handleFinished() {
335 super.handleFinished();
336 doShareUnshareVolume(path, method, true);
337 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 }
339
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800340 class ShutdownCallBack extends UnmountCallBack {
341 IMountShutdownObserver observer;
342 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700343 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800344 this.observer = observer;
345 }
346
347 @Override
348 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700349 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800350 if (observer != null) {
351 try {
352 observer.onShutDownComplete(ret);
353 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700354 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800355 }
356 }
357 }
358 }
359
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400360 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800361 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700362 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800363
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400364 MountServiceHandler(Looper l) {
365 super(l);
366 }
367
Jason parks5af0b912010-11-29 09:05:25 -0600368 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800369 public void handleMessage(Message msg) {
370 switch (msg.what) {
371 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700372 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800373 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
374 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700375 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800376 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700377 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700378 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700379 mUpdatingStatus = true;
380 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800381 }
382 break;
383 }
384 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700385 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700386 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700387 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800388 int size = mForceUnmounts.size();
389 int sizeArr[] = new int[size];
390 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700391 // Kill processes holding references first
392 ActivityManagerService ams = (ActivityManagerService)
393 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800394 for (int i = 0; i < size; i++) {
395 UnmountCallBack ucb = mForceUnmounts.get(i);
396 String path = ucb.path;
397 boolean done = false;
398 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800399 done = true;
400 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800401 int pids[] = getStorageUsers(path);
402 if (pids == null || pids.length == 0) {
403 done = true;
404 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800405 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800406 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700407 // Confirm if file references have been freed.
408 pids = getStorageUsers(path);
409 if (pids == null || pids.length == 0) {
410 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800411 }
412 }
413 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700414 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
415 // Retry again
416 Slog.i(TAG, "Retrying to kill storage users again");
417 mHandler.sendMessageDelayed(
418 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
419 ucb.retries++),
420 RETRY_UNMOUNT_DELAY);
421 } else {
422 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
423 Slog.i(TAG, "Failed to unmount media inspite of " +
424 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
425 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800426 sizeArr[sizeArrN++] = i;
427 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
428 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800429 }
430 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800431 // Remove already processed elements from list.
432 for (int i = (sizeArrN-1); i >= 0; i--) {
433 mForceUnmounts.remove(sizeArr[i]);
434 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800435 break;
436 }
437 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700438 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800440 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800441 break;
442 }
443 }
444 }
445 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400446 final private HandlerThread mHandlerThread;
447 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800448
San Mehat207e5382010-02-04 20:46:54 -0800449 private void waitForReady() {
450 while (mReady == false) {
451 for (int retries = 5; retries > 0; retries--) {
452 if (mReady) {
453 return;
454 }
455 SystemClock.sleep(1000);
456 }
San Mehata5078592010-03-25 09:36:54 -0700457 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800458 }
San Mehat1f6301e2010-01-07 22:40:27 -0800459 }
Kenny Root02c87302010-07-01 08:10:18 -0700460
Ben Komalo444eca22011-09-01 15:17:44 -0700461 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600462 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800464 String action = intent.getAction();
465
466 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800467 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800468
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800469 /*
470 * In the simulator, we need to broadcast a volume mounted event
471 * to make the media scanner run.
472 */
473 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400474 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
475 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800476 return;
477 }
San Mehatfafb0412010-02-18 19:40:04 -0800478 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600479 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800480 public void run() {
481 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400482 // it is not safe to call vold with mVolumeStates locked
483 // so we make a copy of the paths and states and process them
484 // outside the lock
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700485 String[] paths;
486 String[] states;
Mike Lockwood84338c42011-04-05 10:05:47 -0400487 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400488 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400489 Set<String> keys = mVolumeStates.keySet();
490 count = keys.size();
Ben Komalo444eca22011-09-01 15:17:44 -0700491 paths = keys.toArray(new String[count]);
Mike Lockwood84338c42011-04-05 10:05:47 -0400492 states = new String[count];
493 for (int i = 0; i < count; i++) {
494 states[i] = mVolumeStates.get(paths[i]);
495 }
496 }
San Mehat6a254402010-03-22 10:21:00 -0700497
Mike Lockwood84338c42011-04-05 10:05:47 -0400498 for (int i = 0; i < count; i++) {
499 String path = paths[i];
500 String state = states[i];
501
502 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
503 int rc = doMountVolume(path);
504 if (rc != StorageResultCode.OperationSucceeded) {
505 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
506 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400507 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400508 } else if (state.equals(Environment.MEDIA_SHARED)) {
509 /*
510 * Bootstrap UMS enabled state since vold indicates
511 * the volume is shared (runtime restart while ums enabled)
512 */
513 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
514 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800515 }
516 }
San Mehat6a254402010-03-22 10:21:00 -0700517
Mike Lockwood80e0a412011-04-05 10:21:51 -0400518 /* notify external storage has mounted to trigger media scanner */
519 if (mEmulateExternalStorage) {
520 notifyVolumeStateChange(null,
521 Environment.getExternalStorageDirectory().getPath(),
522 VolumeState.NoMedia, VolumeState.Mounted);
523 }
524
San Mehat6a965af22010-02-24 17:47:30 -0800525 /*
San Mehat6a254402010-03-22 10:21:00 -0700526 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800527 * now that we're up.
528 */
529 if (mSendUmsConnectedOnBoot) {
530 sendUmsIntent(true);
531 mSendUmsConnectedOnBoot = false;
532 }
San Mehatfafb0412010-02-18 19:40:04 -0800533 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700534 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800535 }
San Mehat207e5382010-02-04 20:46:54 -0800536 }
San Mehatfafb0412010-02-18 19:40:04 -0800537 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700538 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
539 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
540 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
541 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543 }
544 };
San Mehat4270e1e2010-01-29 05:32:19 -0800545 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
546 final IMountServiceListener mListener;
547
548 MountServiceBinderListener(IMountServiceListener listener) {
549 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700550
San Mehat91c77612010-01-07 10:39:41 -0800551 }
552
San Mehat4270e1e2010-01-29 05:32:19 -0800553 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700554 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700555 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800556 mListeners.remove(this);
557 mListener.asBinder().unlinkToDeath(this, 0);
558 }
559 }
560 }
561
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800562 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800563 // TODO: Add support for multiple share methods
564 if (!method.equals("ums")) {
565 throw new IllegalArgumentException(String.format("Method %s not supported", method));
566 }
567
San Mehat4270e1e2010-01-29 05:32:19 -0800568 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800569 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800570 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700571 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800572 }
San Mehat4270e1e2010-01-29 05:32:19 -0800573 }
574
San Mehat207e5382010-02-04 20:46:54 -0800575 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400576 String oldState;
577 synchronized(mVolumeStates) {
578 oldState = mVolumeStates.put(path, state);
579 }
580 if (state.equals(oldState)) {
581 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
582 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800583 return;
584 }
San Mehatb1043402010-02-05 08:26:50 -0800585
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400586 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700587
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400588 if (path.equals(mExternalStoragePath)) {
589 // Update state on PackageManager, but only of real events
590 if (!mEmulateExternalStorage) {
591 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
592 mPms.updateExternalMediaStatus(false, false);
593
594 /*
595 * Some OBBs might have been unmounted when this volume was
596 * unmounted, so send a message to the handler to let it know to
597 * remove those from the list of mounted OBBS.
598 */
599 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
600 OBB_FLUSH_MOUNT_STATE, path));
601 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
602 mPms.updateExternalMediaStatus(true, false);
603 }
Mike Lockwood03559752010-07-19 18:25:03 -0400604 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800605 }
San Mehat4270e1e2010-01-29 05:32:19 -0800606 synchronized (mListeners) {
607 for (int i = mListeners.size() -1; i >= 0; i--) {
608 MountServiceBinderListener bl = mListeners.get(i);
609 try {
San Mehatb1043402010-02-05 08:26:50 -0800610 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800611 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700612 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800613 mListeners.remove(i);
614 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700615 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800616 }
617 }
618 }
619 }
620
621 /**
622 *
623 * Callback from NativeDaemonConnector
624 */
625 public void onDaemonConnected() {
626 /*
627 * Since we'll be calling back into the NativeDaemonConnector,
628 * we need to do our work in a new thread.
629 */
630 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600631 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800632 public void run() {
633 /**
634 * Determine media state and UMS detection status
635 */
San Mehat4270e1e2010-01-29 05:32:19 -0800636 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800637 final String[] vols = NativeDaemonEvent.filterMessageList(
638 mConnector.executeForList("volume", "list"),
639 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800640 for (String volstr : vols) {
641 String[] tok = volstr.split(" ");
642 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400643 String path = tok[1];
644 String state = Environment.MEDIA_REMOVED;
645
San Mehat4270e1e2010-01-29 05:32:19 -0800646 int st = Integer.parseInt(tok[2]);
647 if (st == VolumeState.NoMedia) {
648 state = Environment.MEDIA_REMOVED;
649 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800650 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800651 } else if (st == VolumeState.Mounted) {
652 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700653 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800654 } else if (st == VolumeState.Shared) {
655 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700656 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800657 } else {
658 throw new Exception(String.format("Unexpected state %d", st));
659 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400660
661 if (state != null) {
662 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
663 updatePublicVolumeState(path, state);
664 }
San Mehat4270e1e2010-01-29 05:32:19 -0800665 }
666 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700667 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400668 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800669 }
670
San Mehat207e5382010-02-04 20:46:54 -0800671 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600672 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800673 * the hounds!
674 */
675 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800676 }
677 }.start();
678 }
679
680 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800681 * Callback from NativeDaemonConnector
682 */
683 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800684 if (DEBUG_EVENTS) {
685 StringBuilder builder = new StringBuilder();
686 builder.append("onEvent::");
687 builder.append(" raw= " + raw);
688 if (cooked != null) {
689 builder.append(" cooked = " );
690 for (String str : cooked) {
691 builder.append(" " + str);
692 }
693 }
San Mehata5078592010-03-25 09:36:54 -0700694 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800695 }
San Mehat4270e1e2010-01-29 05:32:19 -0800696 if (code == VoldResponseCode.VolumeStateChange) {
697 /*
698 * One of the volumes we're managing has changed state.
699 * Format: "NNN Volume <label> <path> state changed
700 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
701 */
702 notifyVolumeStateChange(
703 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
704 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800705 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
706 (code == VoldResponseCode.VolumeDiskRemoved) ||
707 (code == VoldResponseCode.VolumeBadRemoval)) {
708 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
709 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
710 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400711 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800712 final String label = cooked[2];
713 final String path = cooked[3];
714 int major = -1;
715 int minor = -1;
716
717 try {
718 String devComp = cooked[6].substring(1, cooked[6].length() -1);
719 String[] devTok = devComp.split(":");
720 major = Integer.parseInt(devTok[0]);
721 minor = Integer.parseInt(devTok[1]);
722 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700723 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800724 }
725
San Mehat4270e1e2010-01-29 05:32:19 -0800726 if (code == VoldResponseCode.VolumeDiskInserted) {
727 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600728 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800729 public void run() {
730 try {
731 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800732 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700733 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800734 }
735 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700736 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800737 }
738 }
739 }.start();
740 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
741 /*
742 * This event gets trumped if we're already in BAD_REMOVAL state
743 */
744 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
745 return true;
746 }
747 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700748 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800749 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400750 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800751
San Mehata5078592010-03-25 09:36:54 -0700752 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800753 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400754 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800755 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700756 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800757 /* Send the media unmounted event first */
758 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400759 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800760
San Mehata5078592010-03-25 09:36:54 -0700761 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800762 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400763 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800764 } else {
San Mehata5078592010-03-25 09:36:54 -0700765 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800766 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400767
768 if (action != null) {
769 sendStorageIntent(action, path);
770 }
San Mehat4270e1e2010-01-29 05:32:19 -0800771 } else {
772 return false;
773 }
774
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400775 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800776 }
777
San Mehat207e5382010-02-04 20:46:54 -0800778 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800779 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700780 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800781
Mike Lockwooda5250c92011-05-23 13:44:04 -0400782 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800783
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500784 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700785 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400786 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500787 }
788
San Mehat4270e1e2010-01-29 05:32:19 -0800789 if (newState == VolumeState.Init) {
790 } else if (newState == VolumeState.NoMedia) {
791 // NoMedia is handled via Disk Remove events
792 } else if (newState == VolumeState.Idle) {
793 /*
794 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
795 * if we're in the process of enabling UMS
796 */
797 if (!vs.equals(
798 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
799 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800800 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700801 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800802 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400803 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800804 }
805 } else if (newState == VolumeState.Pending) {
806 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700807 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800808 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400809 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800810 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700811 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800812 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400813 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800814 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400815 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800816 } else if (newState == VolumeState.Formatting) {
817 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700818 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800819 /* Send the media unmounted event first */
820 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400821 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800822
San Mehata5078592010-03-25 09:36:54 -0700823 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800824 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400825 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700826 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800827 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700828 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800829 return;
830 } else {
San Mehata5078592010-03-25 09:36:54 -0700831 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800832 }
833
Mike Lockwooda5250c92011-05-23 13:44:04 -0400834 if (action != null) {
835 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800836 }
837 }
838
San Mehat207e5382010-02-04 20:46:54 -0800839 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800840 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800841
San Mehata5078592010-03-25 09:36:54 -0700842 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800843 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800844 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800845 } catch (NativeDaemonConnectorException e) {
846 /*
847 * Mount failed for some reason
848 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400849 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800850 int code = e.getCode();
851 if (code == VoldResponseCode.OpFailedNoMedia) {
852 /*
853 * Attempt to mount but no media inserted
854 */
San Mehatb1043402010-02-05 08:26:50 -0800855 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800856 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700857 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800858 /*
859 * Media is blank or does not contain a supported filesystem
860 */
861 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400862 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800863 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800864 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700865 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800866 /*
867 * Volume consistency check failed
868 */
869 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400870 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800871 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800872 } else {
San Mehatb1043402010-02-05 08:26:50 -0800873 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800874 }
875
876 /*
877 * Send broadcast intent (if required for the failure)
878 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400879 if (action != null) {
880 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800881 }
882 }
883
884 return rc;
885 }
886
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800887 /*
888 * If force is not set, we do not unmount if there are
889 * processes holding references to the volume about to be unmounted.
890 * If force is set, all the processes holding references need to be
891 * killed via the ActivityManager before actually unmounting the volume.
892 * This might even take a while and might be retried after timed delays
893 * to make sure we dont end up in an instable state and kill some core
894 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700895 * If removeEncryption is set, force is implied, and the system will remove any encryption
896 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800897 */
Ben Komalo13c71972011-09-07 16:35:56 -0700898 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800899 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800900 return VoldResponseCode.OpFailedVolNotMounted;
901 }
Kenny Rootaa485402010-09-14 14:49:41 -0700902
903 /*
904 * Force a GC to make sure AssetManagers in other threads of the
905 * system_server are cleaned up. We have to do this since AssetManager
906 * instances are kept as a WeakReference and it's possible we have files
907 * open on the external storage.
908 */
909 Runtime.getRuntime().gc();
910
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800911 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700912 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800913 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800914 final Command cmd = new Command("volume", "unmount", path);
915 if (removeEncryption) {
916 cmd.appendArg("force_and_revert");
917 } else if (force) {
918 cmd.appendArg("force");
919 }
920 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700921 // We unmounted the volume. None of the asec containers are available now.
922 synchronized (mAsecMountSet) {
923 mAsecMountSet.clear();
924 }
San Mehatb1043402010-02-05 08:26:50 -0800925 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800926 } catch (NativeDaemonConnectorException e) {
927 // Don't worry about mismatch in PackageManager since the
928 // call back will handle the status changes any way.
929 int code = e.getCode();
930 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800931 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800932 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
933 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800934 } else {
San Mehatb1043402010-02-05 08:26:50 -0800935 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800936 }
937 }
938 }
939
940 private int doFormatVolume(String path) {
941 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800942 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -0800943 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800944 } catch (NativeDaemonConnectorException e) {
945 int code = e.getCode();
946 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800947 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800948 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800949 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800950 } else {
San Mehatb1043402010-02-05 08:26:50 -0800951 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800952 }
953 }
954 }
955
San Mehatb1043402010-02-05 08:26:50 -0800956 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800957 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700958 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800959 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700960 } catch (NativeDaemonConnectorException ex) {
961 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
962 return false;
963 }
San Mehatb1043402010-02-05 08:26:50 -0800964
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800965 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
966 return event.getMessage().endsWith("enabled");
967 } else {
968 return false;
San Mehatb1043402010-02-05 08:26:50 -0800969 }
San Mehatb1043402010-02-05 08:26:50 -0800970 }
971
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700972 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800973 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700974 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800975 for (int i = mListeners.size() -1; i >= 0; i--) {
976 MountServiceBinderListener bl = mListeners.get(i);
977 try {
San Mehatb1043402010-02-05 08:26:50 -0800978 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800979 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700980 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800981 mListeners.remove(i);
982 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700983 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800984 }
985 }
986 }
987
San Mehat207e5382010-02-04 20:46:54 -0800988 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800989 sendUmsIntent(avail);
990 } else {
991 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800992 }
San Mehat2fe718a2010-03-11 12:01:49 -0800993
994 final String path = Environment.getExternalStorageDirectory().getPath();
995 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
996 /*
997 * USB mass storage disconnected while enabled
998 */
999 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001000 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001001 public void run() {
1002 try {
1003 int rc;
San Mehata5078592010-03-25 09:36:54 -07001004 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001005 doShareUnshareVolume(path, "ums", false);
1006 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001007 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001008 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1009 path, rc));
1010 }
1011 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001012 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001013 }
1014 }
1015 }.start();
1016 }
San Mehat4270e1e2010-01-29 05:32:19 -08001017 }
1018
Mike Lockwooda5250c92011-05-23 13:44:04 -04001019 private void sendStorageIntent(String action, String path) {
1020 Intent intent = new Intent(action, Uri.parse("file://" + path));
1021 // add StorageVolume extra
1022 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1023 Slog.d(TAG, "sendStorageIntent " + intent);
1024 mContext.sendBroadcast(intent);
1025 }
1026
San Mehat6a965af22010-02-24 17:47:30 -08001027 private void sendUmsIntent(boolean c) {
1028 mContext.sendBroadcast(
1029 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1030 }
1031
San Mehat207e5382010-02-04 20:46:54 -08001032 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001033 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1034 throw new SecurityException(String.format("Requires %s permission", perm));
1035 }
1036 }
1037
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001038 // Storage list XML tags
1039 private static final String TAG_STORAGE_LIST = "StorageList";
1040 private static final String TAG_STORAGE = "storage";
1041
1042 private void readStorageList(Resources resources) {
1043 int id = com.android.internal.R.xml.storage_list;
1044 XmlResourceParser parser = resources.getXml(id);
1045 AttributeSet attrs = Xml.asAttributeSet(parser);
1046
1047 try {
1048 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1049 while (true) {
1050 XmlUtils.nextElement(parser);
1051
1052 String element = parser.getName();
1053 if (element == null) break;
1054
1055 if (TAG_STORAGE.equals(element)) {
1056 TypedArray a = resources.obtainAttributes(attrs,
1057 com.android.internal.R.styleable.Storage);
1058
1059 CharSequence path = a.getText(
1060 com.android.internal.R.styleable.Storage_mountPoint);
1061 CharSequence description = a.getText(
1062 com.android.internal.R.styleable.Storage_storageDescription);
1063 boolean primary = a.getBoolean(
1064 com.android.internal.R.styleable.Storage_primary, false);
1065 boolean removable = a.getBoolean(
1066 com.android.internal.R.styleable.Storage_removable, false);
1067 boolean emulated = a.getBoolean(
1068 com.android.internal.R.styleable.Storage_emulated, false);
1069 int mtpReserve = a.getInt(
1070 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001071 boolean allowMassStorage = a.getBoolean(
1072 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001073 // resource parser does not support longs, so XML value is in megabytes
1074 long maxFileSize = a.getInt(
1075 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001076
1077 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1078 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001079 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001080 " allowMassStorage: " + allowMassStorage +
1081 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001082 if (path == null || description == null) {
1083 Slog.e(TAG, "path or description is null in readStorageList");
1084 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001085 String pathString = path.toString();
1086 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001087 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001088 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001089 if (primary) {
1090 if (mPrimaryVolume == null) {
1091 mPrimaryVolume = volume;
1092 } else {
1093 Slog.e(TAG, "multiple primary volumes in storage list");
1094 }
1095 }
1096 if (mPrimaryVolume == volume) {
1097 // primay volume must be first
1098 mVolumes.add(0, volume);
1099 } else {
1100 mVolumes.add(volume);
1101 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001102 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001103 }
1104 a.recycle();
1105 }
1106 }
1107 } catch (XmlPullParserException e) {
1108 throw new RuntimeException(e);
1109 } catch (IOException e) {
1110 throw new RuntimeException(e);
1111 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001112 // compute storage ID for each volume
1113 int length = mVolumes.size();
1114 for (int i = 0; i < length; i++) {
1115 mVolumes.get(i).setStorageId(i);
1116 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001117 parser.close();
1118 }
1119 }
1120
San Mehat4270e1e2010-01-29 05:32:19 -08001121 /**
San Mehat207e5382010-02-04 20:46:54 -08001122 * Constructs a new MountService instance
1123 *
1124 * @param context Binder context for this service
1125 */
1126 public MountService(Context context) {
1127 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001128 Resources resources = context.getResources();
1129 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001130
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001131 if (mPrimaryVolume != null) {
1132 mExternalStoragePath = mPrimaryVolume.getPath();
1133 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1134 if (mEmulateExternalStorage) {
1135 Slog.d(TAG, "using emulated external storage");
1136 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1137 }
Mike Lockwood03559752010-07-19 18:25:03 -04001138 }
1139
San Mehat207e5382010-02-04 20:46:54 -08001140 // XXX: This will go away soon in favor of IMountServiceObserver
1141 mPms = (PackageManagerService) ServiceManager.getService("package");
1142
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001143 IntentFilter filter = new IntentFilter();
1144 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1145 // don't bother monitoring USB if mass storage is not supported on our primary volume
1146 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1147 filter.addAction(UsbManager.ACTION_USB_STATE);
1148 }
1149 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001150
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001151 mHandlerThread = new HandlerThread("MountService");
1152 mHandlerThread.start();
1153 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1154
Kenny Roota02b8b02010-08-05 16:14:17 -07001155 // Add OBB Action Handler to MountService thread.
1156 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1157
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001158 /*
1159 * Vold does not run in the simulator, so pretend the connector thread
1160 * ran and did its thing.
1161 */
1162 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1163 mReady = true;
1164 mUmsEnabling = true;
1165 return;
1166 }
1167
Kenny Root305bcbf2010-09-03 07:56:38 -07001168 /*
1169 * Create the connection to vold with a maximum queue of twice the
1170 * amount of containers we'd ever expect to have. This keeps an
1171 * "asec list" from blocking a thread repeatedly.
1172 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001173 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
San Mehat207e5382010-02-04 20:46:54 -08001174 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001175 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001176 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001177
Kenny Root07714d42011-08-17 17:49:28 -07001178 // Add ourself to the Watchdog monitors if enabled.
1179 if (WATCHDOG_ENABLE) {
1180 Watchdog.getInstance().addMonitor(this);
1181 }
San Mehat207e5382010-02-04 20:46:54 -08001182 }
1183
1184 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001185 * Exposed API calls below here
1186 */
1187
1188 public void registerListener(IMountServiceListener listener) {
1189 synchronized (mListeners) {
1190 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1191 try {
1192 listener.asBinder().linkToDeath(bl, 0);
1193 mListeners.add(bl);
1194 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001195 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001196 }
1197 }
1198 }
1199
1200 public void unregisterListener(IMountServiceListener listener) {
1201 synchronized (mListeners) {
1202 for(MountServiceBinderListener bl : mListeners) {
1203 if (bl.mListener == listener) {
1204 mListeners.remove(mListeners.indexOf(bl));
1205 return;
1206 }
1207 }
1208 }
1209 }
1210
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001211 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001212 validatePermission(android.Manifest.permission.SHUTDOWN);
1213
San Mehata5078592010-03-25 09:36:54 -07001214 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001215 synchronized (mVolumeStates) {
1216 for (String path : mVolumeStates.keySet()) {
1217 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001218
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001219 if (state.equals(Environment.MEDIA_SHARED)) {
1220 /*
1221 * If the media is currently shared, unshare it.
1222 * XXX: This is still dangerous!. We should not
1223 * be rebooting at *all* if UMS is enabled, since
1224 * the UMS host could have dirty FAT cache entries
1225 * yet to flush.
1226 */
1227 setUsbMassStorageEnabled(false);
1228 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1229 /*
1230 * If the media is being checked, then we need to wait for
1231 * it to complete before being able to proceed.
1232 */
1233 // XXX: @hackbod - Should we disable the ANR timer here?
1234 int retries = 30;
1235 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1236 try {
1237 Thread.sleep(1000);
1238 } catch (InterruptedException iex) {
1239 Slog.e(TAG, "Interrupted while waiting for media", iex);
1240 break;
1241 }
1242 state = Environment.getExternalStorageState();
1243 }
1244 if (retries == 0) {
1245 Slog.e(TAG, "Timed out waiting for media to check");
1246 }
San Mehat91c77612010-01-07 10:39:41 -08001247 }
San Mehat91c77612010-01-07 10:39:41 -08001248
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001249 if (state.equals(Environment.MEDIA_MOUNTED)) {
1250 // Post a unmount message.
1251 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1252 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1253 } else if (observer != null) {
1254 /*
1255 * Observer is waiting for onShutDownComplete when we are done.
1256 * Since nothing will be done send notification directly so shutdown
1257 * sequence can continue.
1258 */
1259 try {
1260 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1261 } catch (RemoteException e) {
1262 Slog.w(TAG, "RemoteException when shutting down");
1263 }
1264 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001265 }
San Mehat4270e1e2010-01-29 05:32:19 -08001266 }
1267 }
1268
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001269 private boolean getUmsEnabling() {
1270 synchronized (mListeners) {
1271 return mUmsEnabling;
1272 }
1273 }
1274
1275 private void setUmsEnabling(boolean enable) {
1276 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001277 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001278 }
1279 }
1280
San Mehatb1043402010-02-05 08:26:50 -08001281 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001282 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001283
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001284 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001285 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001286 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001287 synchronized (mListeners) {
1288 return mUmsAvailable;
1289 }
San Mehatb1043402010-02-05 08:26:50 -08001290 }
1291
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001292 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001293 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001294 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001295
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001296 // TODO: Add support for multiple share methods
1297
1298 /*
1299 * If the volume is mounted and we're enabling then unmount it
1300 */
1301 String path = Environment.getExternalStorageDirectory().getPath();
1302 String vs = getVolumeState(path);
1303 String method = "ums";
1304 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1305 // Override for isUsbMassStorageEnabled()
1306 setUmsEnabling(enable);
1307 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1308 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1309 // Clear override
1310 setUmsEnabling(false);
1311 }
1312 /*
1313 * If we disabled UMS then mount the volume
1314 */
1315 if (!enable) {
1316 doShareUnshareVolume(path, method, enable);
1317 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001318 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001319 " after disabling share method " + method);
1320 /*
1321 * Even though the mount failed, the unshare didn't so don't indicate an error.
1322 * The mountVolume() call will have set the storage state and sent the necessary
1323 * broadcasts.
1324 */
1325 }
1326 }
San Mehatb1043402010-02-05 08:26:50 -08001327 }
1328
1329 public boolean isUsbMassStorageEnabled() {
1330 waitForReady();
1331 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001333
San Mehat7fd0fee2009-12-17 07:12:23 -08001334 /**
1335 * @return state of the volume at the specified mount point
1336 */
San Mehat4270e1e2010-01-29 05:32:19 -08001337 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001338 synchronized (mVolumeStates) {
1339 String state = mVolumeStates.get(mountPoint);
1340 if (state == null) {
1341 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001342 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1343 state = Environment.MEDIA_REMOVED;
1344 } else {
1345 throw new IllegalArgumentException();
1346 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001347 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001348
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001349 return state;
1350 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001351 }
1352
Kenny Roote1ff2142010-10-12 11:20:01 -07001353 public boolean isExternalStorageEmulated() {
1354 return mEmulateExternalStorage;
1355 }
1356
San Mehat4270e1e2010-01-29 05:32:19 -08001357 public int mountVolume(String path) {
1358 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001359
San Mehat207e5382010-02-04 20:46:54 -08001360 waitForReady();
1361 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363
Ben Komalo13c71972011-09-07 16:35:56 -07001364 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001365 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001366 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001368 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001369 if (DEBUG_UNMOUNT) {
1370 Slog.i(TAG, "Unmounting " + path
1371 + " force = " + force
1372 + " removeEncryption = " + removeEncryption);
1373 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001374 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1375 Environment.MEDIA_REMOVED.equals(volState) ||
1376 Environment.MEDIA_SHARED.equals(volState) ||
1377 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1378 // Media already unmounted or cannot be unmounted.
1379 // TODO return valid return code when adding observer call back.
1380 return;
1381 }
Ben Komalo13c71972011-09-07 16:35:56 -07001382 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001383 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
San Mehat4270e1e2010-01-29 05:32:19 -08001386 public int formatVolume(String path) {
1387 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001388 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001389
San Mehat207e5382010-02-04 20:46:54 -08001390 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
1392
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001393 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001394 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1395 waitForReady();
1396 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001397 final String[] r = NativeDaemonEvent.filterMessageList(
1398 mConnector.executeForList("storage", "users", path),
1399 VoldResponseCode.StorageUsersListResult);
1400
San Mehatc1b4ce92010-02-16 17:13:03 -08001401 // FMT: <pid> <process name>
1402 int[] data = new int[r.length];
1403 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001404 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001405 try {
1406 data[i] = Integer.parseInt(tok[0]);
1407 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001408 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001409 return new int[0];
1410 }
1411 }
1412 return data;
1413 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001414 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001415 return new int[0];
1416 }
1417 }
1418
San Mehatb1043402010-02-05 08:26:50 -08001419 private void warnOnNotMounted() {
1420 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001421 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001422 }
1423 }
1424
San Mehat4270e1e2010-01-29 05:32:19 -08001425 public String[] getSecureContainerList() {
1426 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001427 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001428 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001429
San Mehat4270e1e2010-01-29 05:32:19 -08001430 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001431 return NativeDaemonEvent.filterMessageList(
1432 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001433 } catch (NativeDaemonConnectorException e) {
1434 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 }
San Mehat36972292010-01-06 11:06:32 -08001437
San Mehat4270e1e2010-01-29 05:32:19 -08001438 public int createSecureContainer(String id, int sizeMb, String fstype,
1439 String key, int ownerUid) {
1440 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001441 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001442 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001443
San Mehatb1043402010-02-05 08:26:50 -08001444 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001445 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001446 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001447 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001448 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001449 }
San Mehata181b212010-02-11 06:50:20 -08001450
1451 if (rc == StorageResultCode.OperationSucceeded) {
1452 synchronized (mAsecMountSet) {
1453 mAsecMountSet.add(id);
1454 }
1455 }
San Mehat4270e1e2010-01-29 05:32:19 -08001456 return rc;
San Mehat36972292010-01-06 11:06:32 -08001457 }
1458
San Mehat4270e1e2010-01-29 05:32:19 -08001459 public int finalizeSecureContainer(String id) {
1460 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001461 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001462
San Mehatb1043402010-02-05 08:26:50 -08001463 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001464 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001465 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001466 /*
1467 * Finalization does a remount, so no need
1468 * to update mAsecMountSet
1469 */
San Mehat4270e1e2010-01-29 05:32:19 -08001470 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001471 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001472 }
San Mehat4270e1e2010-01-29 05:32:19 -08001473 return rc;
San Mehat36972292010-01-06 11:06:32 -08001474 }
1475
San Mehatd9709982010-02-18 11:43:03 -08001476 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001477 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001478 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001479 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001480
Kenny Rootaa485402010-09-14 14:49:41 -07001481 /*
1482 * Force a GC to make sure AssetManagers in other threads of the
1483 * system_server are cleaned up. We have to do this since AssetManager
1484 * instances are kept as a WeakReference and it's possible we have files
1485 * open on the external storage.
1486 */
1487 Runtime.getRuntime().gc();
1488
San Mehatb1043402010-02-05 08:26:50 -08001489 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001490 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001491 final Command cmd = new Command("asec", "destroy", id);
1492 if (force) {
1493 cmd.appendArg("force");
1494 }
1495 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001496 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001497 int code = e.getCode();
1498 if (code == VoldResponseCode.OpFailedStorageBusy) {
1499 rc = StorageResultCode.OperationFailedStorageBusy;
1500 } else {
1501 rc = StorageResultCode.OperationFailedInternalError;
1502 }
San Mehat02735bc2010-01-26 15:18:08 -08001503 }
San Mehata181b212010-02-11 06:50:20 -08001504
1505 if (rc == StorageResultCode.OperationSucceeded) {
1506 synchronized (mAsecMountSet) {
1507 if (mAsecMountSet.contains(id)) {
1508 mAsecMountSet.remove(id);
1509 }
1510 }
1511 }
1512
San Mehat4270e1e2010-01-29 05:32:19 -08001513 return rc;
San Mehat36972292010-01-06 11:06:32 -08001514 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001515
San Mehat4270e1e2010-01-29 05:32:19 -08001516 public int mountSecureContainer(String id, String key, int ownerUid) {
1517 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001518 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001519 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001520
San Mehata181b212010-02-11 06:50:20 -08001521 synchronized (mAsecMountSet) {
1522 if (mAsecMountSet.contains(id)) {
1523 return StorageResultCode.OperationFailedStorageMounted;
1524 }
1525 }
1526
San Mehatb1043402010-02-05 08:26:50 -08001527 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001528 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001529 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001530 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001531 int code = e.getCode();
1532 if (code != VoldResponseCode.OpFailedStorageBusy) {
1533 rc = StorageResultCode.OperationFailedInternalError;
1534 }
San Mehat02735bc2010-01-26 15:18:08 -08001535 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001536
1537 if (rc == StorageResultCode.OperationSucceeded) {
1538 synchronized (mAsecMountSet) {
1539 mAsecMountSet.add(id);
1540 }
1541 }
San Mehat4270e1e2010-01-29 05:32:19 -08001542 return rc;
San Mehat36972292010-01-06 11:06:32 -08001543 }
1544
San Mehatd9709982010-02-18 11:43:03 -08001545 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001546 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001547 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001548 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001549
San Mehat6cdd9c02010-02-09 14:45:20 -08001550 synchronized (mAsecMountSet) {
1551 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001552 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001553 }
1554 }
1555
Kenny Rootaa485402010-09-14 14:49:41 -07001556 /*
1557 * Force a GC to make sure AssetManagers in other threads of the
1558 * system_server are cleaned up. We have to do this since AssetManager
1559 * instances are kept as a WeakReference and it's possible we have files
1560 * open on the external storage.
1561 */
1562 Runtime.getRuntime().gc();
1563
San Mehatb1043402010-02-05 08:26:50 -08001564 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001565 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001566 final Command cmd = new Command("asec", "unmount", id);
1567 if (force) {
1568 cmd.appendArg("force");
1569 }
1570 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001571 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001572 int code = e.getCode();
1573 if (code == VoldResponseCode.OpFailedStorageBusy) {
1574 rc = StorageResultCode.OperationFailedStorageBusy;
1575 } else {
1576 rc = StorageResultCode.OperationFailedInternalError;
1577 }
San Mehat02735bc2010-01-26 15:18:08 -08001578 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001579
1580 if (rc == StorageResultCode.OperationSucceeded) {
1581 synchronized (mAsecMountSet) {
1582 mAsecMountSet.remove(id);
1583 }
1584 }
San Mehat4270e1e2010-01-29 05:32:19 -08001585 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001586 }
1587
San Mehat6cdd9c02010-02-09 14:45:20 -08001588 public boolean isSecureContainerMounted(String id) {
1589 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1590 waitForReady();
1591 warnOnNotMounted();
1592
1593 synchronized (mAsecMountSet) {
1594 return mAsecMountSet.contains(id);
1595 }
1596 }
1597
San Mehat4270e1e2010-01-29 05:32:19 -08001598 public int renameSecureContainer(String oldId, String newId) {
1599 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001600 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001601 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001602
San Mehata181b212010-02-11 06:50:20 -08001603 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001604 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001605 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001606 * changed while active, we must ensure both ids are not currently mounted.
1607 */
1608 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001609 return StorageResultCode.OperationFailedStorageMounted;
1610 }
1611 }
1612
San Mehatb1043402010-02-05 08:26:50 -08001613 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001614 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001615 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001616 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001617 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001618 }
San Mehata181b212010-02-11 06:50:20 -08001619
San Mehat4270e1e2010-01-29 05:32:19 -08001620 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001621 }
1622
San Mehat4270e1e2010-01-29 05:32:19 -08001623 public String getSecureContainerPath(String id) {
1624 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001625 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001626 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001627
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001628 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001629 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001630 event = mConnector.execute("asec", "path", id);
1631 event.checkCode(VoldResponseCode.AsecPathResult);
1632 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001633 } catch (NativeDaemonConnectorException e) {
1634 int code = e.getCode();
1635 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001636 Slog.i(TAG, String.format("Container '%s' not found", id));
1637 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001638 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001639 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001640 }
1641 }
San Mehat22dd86e2010-01-12 12:21:18 -08001642 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001643
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001644 public String getSecureContainerFilesystemPath(String id) {
1645 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1646 waitForReady();
1647 warnOnNotMounted();
1648
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001649 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001650 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001651 event = mConnector.execute("asec", "fspath", id);
1652 event.checkCode(VoldResponseCode.AsecPathResult);
1653 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001654 } catch (NativeDaemonConnectorException e) {
1655 int code = e.getCode();
1656 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1657 Slog.i(TAG, String.format("Container '%s' not found", id));
1658 return null;
1659 } else {
1660 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1661 }
1662 }
1663 }
1664
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001665 public void finishMediaUpdate() {
1666 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1667 }
Kenny Root02c87302010-07-01 08:10:18 -07001668
Kenny Roota02b8b02010-08-05 16:14:17 -07001669 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1670 if (callerUid == android.os.Process.SYSTEM_UID) {
1671 return true;
1672 }
1673
Kenny Root02c87302010-07-01 08:10:18 -07001674 if (packageName == null) {
1675 return false;
1676 }
1677
Amith Yamasani483f3b02012-03-13 16:08:00 -07001678 final int packageUid = mPms.getPackageUid(packageName, UserId.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001679
1680 if (DEBUG_OBB) {
1681 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1682 packageUid + ", callerUid = " + callerUid);
1683 }
1684
1685 return callerUid == packageUid;
1686 }
1687
1688 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001689 if (filename == null) {
1690 throw new IllegalArgumentException("filename cannot be null");
1691 }
1692
Kenny Root02c87302010-07-01 08:10:18 -07001693 waitForReady();
1694 warnOnNotMounted();
1695
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001696 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001697 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001698 event = mConnector.execute("obb", "path", filename);
1699 event.checkCode(VoldResponseCode.AsecPathResult);
1700 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001701 } catch (NativeDaemonConnectorException e) {
1702 int code = e.getCode();
1703 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001704 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001705 } else {
1706 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1707 }
1708 }
1709 }
1710
1711 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001712 if (filename == null) {
1713 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001714 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001715
1716 synchronized (mObbMounts) {
1717 return mObbPathToStateMap.containsKey(filename);
1718 }
Kenny Root02c87302010-07-01 08:10:18 -07001719 }
1720
Kenny Rootaf9d6672010-10-08 09:21:39 -07001721 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001722 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001723 if (filename == null) {
1724 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001725 }
1726
1727 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001728 throw new IllegalArgumentException("token cannot be null");
1729 }
1730
Kenny Rootaf9d6672010-10-08 09:21:39 -07001731 final int callerUid = Binder.getCallingUid();
1732 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1733 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001734 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1735
1736 if (DEBUG_OBB)
1737 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001738 }
1739
Kenny Rootaf9d6672010-10-08 09:21:39 -07001740 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1741 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001742 if (filename == null) {
1743 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001744 }
1745
Kenny Rootaf9d6672010-10-08 09:21:39 -07001746 final int callerUid = Binder.getCallingUid();
1747 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1748 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001749 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001750
Kenny Roota02b8b02010-08-05 16:14:17 -07001751 if (DEBUG_OBB)
1752 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1753 }
1754
Ben Komalo444eca22011-09-01 15:17:44 -07001755 @Override
1756 public int getEncryptionState() {
1757 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1758 "no permission to access the crypt keeper");
1759
1760 waitForReady();
1761
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001762 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001763 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001764 event = mConnector.execute("cryptfs", "cryptocomplete");
1765 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001766 } catch (NumberFormatException e) {
1767 // Bad result - unexpected.
1768 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1769 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1770 } catch (NativeDaemonConnectorException e) {
1771 // Something bad happened.
1772 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1773 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1774 }
1775 }
1776
1777 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001778 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001779 if (TextUtils.isEmpty(password)) {
1780 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001781 }
1782
Jason parks8888c592011-01-20 22:46:41 -06001783 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1784 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001785
1786 waitForReady();
1787
1788 if (DEBUG_EVENTS) {
1789 Slog.i(TAG, "decrypting storage...");
1790 }
1791
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001792 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001793 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001794 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001795
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001796 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001797 if (code == 0) {
1798 // Decrypt was successful. Post a delayed message before restarting in order
1799 // to let the UI to clear itself
1800 mHandler.postDelayed(new Runnable() {
1801 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001802 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001803 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001804 } catch (NativeDaemonConnectorException e) {
1805 Slog.e(TAG, "problem executing in background", e);
1806 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001807 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001808 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001809 }
1810
1811 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001812 } catch (NativeDaemonConnectorException e) {
1813 // Decryption failed
1814 return e.getCode();
1815 }
Jason parks5af0b912010-11-29 09:05:25 -06001816 }
1817
Jason parks56aa5322011-01-07 09:01:15 -06001818 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001819 if (TextUtils.isEmpty(password)) {
1820 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001821 }
1822
Jason parks8888c592011-01-20 22:46:41 -06001823 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1824 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001825
1826 waitForReady();
1827
1828 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001829 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001830 }
1831
1832 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001833 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06001834 } catch (NativeDaemonConnectorException e) {
1835 // Encryption failed
1836 return e.getCode();
1837 }
1838
1839 return 0;
1840 }
1841
Jason parksf7b3cd42011-01-27 09:28:25 -06001842 public int changeEncryptionPassword(String password) {
1843 if (TextUtils.isEmpty(password)) {
1844 throw new IllegalArgumentException("password cannot be empty");
1845 }
1846
1847 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1848 "no permission to access the crypt keeper");
1849
1850 waitForReady();
1851
1852 if (DEBUG_EVENTS) {
1853 Slog.i(TAG, "changing encryption password...");
1854 }
1855
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001856 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06001857 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001858 event = mConnector.execute("cryptfs", "changepw", password);
1859 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06001860 } catch (NativeDaemonConnectorException e) {
1861 // Encryption failed
1862 return e.getCode();
1863 }
1864 }
1865
Christopher Tate32418be2011-10-10 13:51:12 -07001866 /**
1867 * Validate a user-supplied password string with cryptfs
1868 */
1869 @Override
1870 public int verifyEncryptionPassword(String password) throws RemoteException {
1871 // Only the system process is permitted to validate passwords
1872 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1873 throw new SecurityException("no permission to access the crypt keeper");
1874 }
1875
1876 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1877 "no permission to access the crypt keeper");
1878
1879 if (TextUtils.isEmpty(password)) {
1880 throw new IllegalArgumentException("password cannot be empty");
1881 }
1882
1883 waitForReady();
1884
1885 if (DEBUG_EVENTS) {
1886 Slog.i(TAG, "validating encryption password...");
1887 }
1888
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001889 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07001890 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001891 event = mConnector.execute("cryptfs", "verifypw", password);
1892 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
1893 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07001894 } catch (NativeDaemonConnectorException e) {
1895 // Encryption failed
1896 return e.getCode();
1897 }
1898 }
1899
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001900 public Parcelable[] getVolumeList() {
1901 synchronized(mVolumes) {
1902 int size = mVolumes.size();
1903 Parcelable[] result = new Parcelable[size];
1904 for (int i = 0; i < size; i++) {
1905 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001906 }
1907 return result;
1908 }
1909 }
1910
Kenny Rootaf9d6672010-10-08 09:21:39 -07001911 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1912 final IBinder binder = obbState.getBinder();
1913 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001914
Kenny Rootaf9d6672010-10-08 09:21:39 -07001915 if (obbStates == null) {
1916 obbStates = new ArrayList<ObbState>();
1917 mObbMounts.put(binder, obbStates);
1918 } else {
1919 for (final ObbState o : obbStates) {
1920 if (o.filename.equals(obbState.filename)) {
1921 throw new IllegalStateException("Attempt to add ObbState twice. "
1922 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001923 }
1924 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001925 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001926
1927 obbStates.add(obbState);
1928 try {
1929 obbState.link();
1930 } catch (RemoteException e) {
1931 /*
1932 * The binder died before we could link it, so clean up our state
1933 * and return failure.
1934 */
1935 obbStates.remove(obbState);
1936 if (obbStates.isEmpty()) {
1937 mObbMounts.remove(binder);
1938 }
1939
1940 // Rethrow the error so mountObb can get it
1941 throw e;
1942 }
1943
1944 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001945 }
1946
Kenny Rootaf9d6672010-10-08 09:21:39 -07001947 private void removeObbStateLocked(ObbState obbState) {
1948 final IBinder binder = obbState.getBinder();
1949 final List<ObbState> obbStates = mObbMounts.get(binder);
1950 if (obbStates != null) {
1951 if (obbStates.remove(obbState)) {
1952 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001953 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001954 if (obbStates.isEmpty()) {
1955 mObbMounts.remove(binder);
1956 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001957 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001958
Kenny Rootaf9d6672010-10-08 09:21:39 -07001959 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001960 }
1961
Kenny Roota02b8b02010-08-05 16:14:17 -07001962 private class ObbActionHandler extends Handler {
1963 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001964 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001965
1966 ObbActionHandler(Looper l) {
1967 super(l);
1968 }
1969
1970 @Override
1971 public void handleMessage(Message msg) {
1972 switch (msg.what) {
1973 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001974 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001975
1976 if (DEBUG_OBB)
1977 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1978
1979 // If a bind was already initiated we don't really
1980 // need to do anything. The pending install
1981 // will be processed later on.
1982 if (!mBound) {
1983 // If this is the only one pending we might
1984 // have to bind to the service again.
1985 if (!connectToService()) {
1986 Slog.e(TAG, "Failed to bind to media container service");
1987 action.handleError();
1988 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001989 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001990 }
Kenny Root735de3b2010-09-30 14:11:39 -07001991
Kenny Root735de3b2010-09-30 14:11:39 -07001992 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001993 break;
1994 }
1995 case OBB_MCS_BOUND: {
1996 if (DEBUG_OBB)
1997 Slog.i(TAG, "OBB_MCS_BOUND");
1998 if (msg.obj != null) {
1999 mContainerService = (IMediaContainerService) msg.obj;
2000 }
2001 if (mContainerService == null) {
2002 // Something seriously wrong. Bail out
2003 Slog.e(TAG, "Cannot bind to media container service");
2004 for (ObbAction action : mActions) {
2005 // Indicate service bind error
2006 action.handleError();
2007 }
2008 mActions.clear();
2009 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002010 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002011 if (action != null) {
2012 action.execute(this);
2013 }
2014 } else {
2015 // Should never happen ideally.
2016 Slog.w(TAG, "Empty queue");
2017 }
2018 break;
2019 }
2020 case OBB_MCS_RECONNECT: {
2021 if (DEBUG_OBB)
2022 Slog.i(TAG, "OBB_MCS_RECONNECT");
2023 if (mActions.size() > 0) {
2024 if (mBound) {
2025 disconnectService();
2026 }
2027 if (!connectToService()) {
2028 Slog.e(TAG, "Failed to bind to media container service");
2029 for (ObbAction action : mActions) {
2030 // Indicate service bind error
2031 action.handleError();
2032 }
2033 mActions.clear();
2034 }
2035 }
2036 break;
2037 }
2038 case OBB_MCS_UNBIND: {
2039 if (DEBUG_OBB)
2040 Slog.i(TAG, "OBB_MCS_UNBIND");
2041
2042 // Delete pending install
2043 if (mActions.size() > 0) {
2044 mActions.remove(0);
2045 }
2046 if (mActions.size() == 0) {
2047 if (mBound) {
2048 disconnectService();
2049 }
2050 } else {
2051 // There are more pending requests in queue.
2052 // Just post MCS_BOUND message to trigger processing
2053 // of next pending install.
2054 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2055 }
2056 break;
2057 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002058 case OBB_FLUSH_MOUNT_STATE: {
2059 final String path = (String) msg.obj;
2060
2061 if (DEBUG_OBB)
2062 Slog.i(TAG, "Flushing all OBB state for path " + path);
2063
2064 synchronized (mObbMounts) {
2065 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2066
2067 final Iterator<Entry<String, ObbState>> i =
2068 mObbPathToStateMap.entrySet().iterator();
2069 while (i.hasNext()) {
2070 final Entry<String, ObbState> obbEntry = i.next();
2071
2072 /*
2073 * If this entry's source file is in the volume path
2074 * that got unmounted, remove it because it's no
2075 * longer valid.
2076 */
2077 if (obbEntry.getKey().startsWith(path)) {
2078 obbStatesToRemove.add(obbEntry.getValue());
2079 }
2080 }
2081
2082 for (final ObbState obbState : obbStatesToRemove) {
2083 if (DEBUG_OBB)
2084 Slog.i(TAG, "Removing state for " + obbState.filename);
2085
2086 removeObbStateLocked(obbState);
2087
2088 try {
2089 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2090 OnObbStateChangeListener.UNMOUNTED);
2091 } catch (RemoteException e) {
2092 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2093 + obbState.filename);
2094 }
2095 }
2096 }
2097 break;
2098 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002099 }
2100 }
2101
2102 private boolean connectToService() {
2103 if (DEBUG_OBB)
2104 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2105
2106 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2107 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2108 mBound = true;
2109 return true;
2110 }
2111 return false;
2112 }
2113
2114 private void disconnectService() {
2115 mContainerService = null;
2116 mBound = false;
2117 mContext.unbindService(mDefContainerConn);
2118 }
2119 }
2120
2121 abstract class ObbAction {
2122 private static final int MAX_RETRIES = 3;
2123 private int mRetries;
2124
2125 ObbState mObbState;
2126
2127 ObbAction(ObbState obbState) {
2128 mObbState = obbState;
2129 }
2130
2131 public void execute(ObbActionHandler handler) {
2132 try {
2133 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002134 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002135 mRetries++;
2136 if (mRetries > MAX_RETRIES) {
2137 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002138 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002139 handleError();
2140 return;
2141 } else {
2142 handleExecute();
2143 if (DEBUG_OBB)
2144 Slog.i(TAG, "Posting install MCS_UNBIND");
2145 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2146 }
2147 } catch (RemoteException e) {
2148 if (DEBUG_OBB)
2149 Slog.i(TAG, "Posting install MCS_RECONNECT");
2150 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2151 } catch (Exception e) {
2152 if (DEBUG_OBB)
2153 Slog.d(TAG, "Error handling OBB action", e);
2154 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002155 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002156 }
2157 }
2158
Kenny Root05105f72010-09-22 17:29:43 -07002159 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002160 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002161
2162 protected ObbInfo getObbInfo() throws IOException {
2163 ObbInfo obbInfo;
2164 try {
2165 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2166 } catch (RemoteException e) {
2167 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2168 + mObbState.filename);
2169 obbInfo = null;
2170 }
2171 if (obbInfo == null) {
2172 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2173 }
2174 return obbInfo;
2175 }
2176
Kenny Rootaf9d6672010-10-08 09:21:39 -07002177 protected void sendNewStatusOrIgnore(int status) {
2178 if (mObbState == null || mObbState.token == null) {
2179 return;
2180 }
2181
Kenny Root38cf8862010-09-26 14:18:51 -07002182 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002183 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002184 } catch (RemoteException e) {
2185 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2186 }
2187 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002188 }
2189
2190 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002191 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002192
2193 MountObbAction(ObbState obbState, String key) {
2194 super(obbState);
2195 mKey = key;
2196 }
2197
Jason parks5af0b912010-11-29 09:05:25 -06002198 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002199 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002200 waitForReady();
2201 warnOnNotMounted();
2202
Kenny Root38cf8862010-09-26 14:18:51 -07002203 final ObbInfo obbInfo = getObbInfo();
2204
Kenny Roota02b8b02010-08-05 16:14:17 -07002205 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002206 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2207 + " which is owned by " + obbInfo.packageName);
2208 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2209 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002210 }
2211
Kenny Rootaf9d6672010-10-08 09:21:39 -07002212 final boolean isMounted;
2213 synchronized (mObbMounts) {
2214 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2215 }
2216 if (isMounted) {
2217 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2218 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2219 return;
2220 }
2221
2222 /*
2223 * The filename passed in might not be the canonical name, so just
2224 * set the filename to the canonicalized version.
2225 */
2226 mObbState.filename = obbInfo.filename;
2227
2228 final String hashedKey;
2229 if (mKey == null) {
2230 hashedKey = "none";
2231 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002232 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002233 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2234
2235 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2236 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2237 SecretKey key = factory.generateSecret(ks);
2238 BigInteger bi = new BigInteger(key.getEncoded());
2239 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002240 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002241 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2242 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2243 return;
2244 } catch (InvalidKeySpecException e) {
2245 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2246 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002247 return;
2248 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002249 }
Kenny Root38cf8862010-09-26 14:18:51 -07002250
Kenny Rootaf9d6672010-10-08 09:21:39 -07002251 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002252 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002253 mConnector.execute(
2254 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002255 } catch (NativeDaemonConnectorException e) {
2256 int code = e.getCode();
2257 if (code != VoldResponseCode.OpFailedStorageBusy) {
2258 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002259 }
2260 }
2261
Kenny Rootaf9d6672010-10-08 09:21:39 -07002262 if (rc == StorageResultCode.OperationSucceeded) {
2263 if (DEBUG_OBB)
2264 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2265
2266 synchronized (mObbMounts) {
2267 addObbStateLocked(mObbState);
2268 }
2269
2270 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002271 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002272 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002273
Kenny Rootaf9d6672010-10-08 09:21:39 -07002274 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002275 }
2276 }
2277
Jason parks5af0b912010-11-29 09:05:25 -06002278 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002279 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002280 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002281 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002282
2283 @Override
2284 public String toString() {
2285 StringBuilder sb = new StringBuilder();
2286 sb.append("MountObbAction{");
2287 sb.append("filename=");
2288 sb.append(mObbState.filename);
2289 sb.append(",callerUid=");
2290 sb.append(mObbState.callerUid);
2291 sb.append(",token=");
2292 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002293 sb.append(",binder=");
2294 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002295 sb.append('}');
2296 return sb.toString();
2297 }
2298 }
2299
2300 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002301 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002302
2303 UnmountObbAction(ObbState obbState, boolean force) {
2304 super(obbState);
2305 mForceUnmount = force;
2306 }
2307
Jason parks5af0b912010-11-29 09:05:25 -06002308 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002309 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002310 waitForReady();
2311 warnOnNotMounted();
2312
Kenny Root38cf8862010-09-26 14:18:51 -07002313 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002314
Kenny Rootaf9d6672010-10-08 09:21:39 -07002315 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002316 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 obbState = mObbPathToStateMap.get(obbInfo.filename);
2318 }
Kenny Root38cf8862010-09-26 14:18:51 -07002319
Kenny Rootaf9d6672010-10-08 09:21:39 -07002320 if (obbState == null) {
2321 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2322 return;
2323 }
2324
2325 if (obbState.callerUid != mObbState.callerUid) {
2326 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2327 + " (owned by " + obbInfo.packageName + ")");
2328 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2329 return;
2330 }
2331
2332 mObbState.filename = obbInfo.filename;
2333
2334 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002335 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002336 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2337 if (mForceUnmount) {
2338 cmd.appendArg("force");
2339 }
2340 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002341 } catch (NativeDaemonConnectorException e) {
2342 int code = e.getCode();
2343 if (code == VoldResponseCode.OpFailedStorageBusy) {
2344 rc = StorageResultCode.OperationFailedStorageBusy;
2345 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2346 // If it's not mounted then we've already won.
2347 rc = StorageResultCode.OperationSucceeded;
2348 } else {
2349 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002350 }
2351 }
2352
Kenny Rootaf9d6672010-10-08 09:21:39 -07002353 if (rc == StorageResultCode.OperationSucceeded) {
2354 synchronized (mObbMounts) {
2355 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002356 }
2357
Kenny Rootaf9d6672010-10-08 09:21:39 -07002358 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002359 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002360 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2361 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002362 }
2363 }
2364
Jason parks5af0b912010-11-29 09:05:25 -06002365 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002366 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002367 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002368 }
2369
2370 @Override
2371 public String toString() {
2372 StringBuilder sb = new StringBuilder();
2373 sb.append("UnmountObbAction{");
2374 sb.append("filename=");
2375 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2376 sb.append(",force=");
2377 sb.append(mForceUnmount);
2378 sb.append(",callerUid=");
2379 sb.append(mObbState.callerUid);
2380 sb.append(",token=");
2381 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002382 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002383 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002384 sb.append('}');
2385 return sb.toString();
2386 }
Kenny Root02c87302010-07-01 08:10:18 -07002387 }
Kenny Root38cf8862010-09-26 14:18:51 -07002388
2389 @Override
2390 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2391 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2392 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2393 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2394 + " without permission " + android.Manifest.permission.DUMP);
2395 return;
2396 }
2397
Kenny Root38cf8862010-09-26 14:18:51 -07002398 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002399 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002400
Kenny Rootaf9d6672010-10-08 09:21:39 -07002401 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2402 while (binders.hasNext()) {
2403 Entry<IBinder, List<ObbState>> e = binders.next();
2404 pw.print(" Key="); pw.println(e.getKey().toString());
2405 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002406 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002407 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002408 }
2409 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002410
2411 pw.println("");
2412 pw.println(" mObbPathToStateMap:");
2413 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2414 while (maps.hasNext()) {
2415 final Entry<String, ObbState> e = maps.next();
2416 pw.print(" "); pw.print(e.getKey());
2417 pw.print(" -> "); pw.println(e.getValue().toString());
2418 }
Kenny Root38cf8862010-09-26 14:18:51 -07002419 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002420
2421 pw.println("");
2422
2423 synchronized (mVolumes) {
2424 pw.println(" mVolumes:");
2425
2426 final int N = mVolumes.size();
2427 for (int i = 0; i < N; i++) {
2428 final StorageVolume v = mVolumes.get(i);
2429 pw.print(" ");
2430 pw.println(v.toString());
2431 }
2432 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002433
2434 pw.println();
2435 pw.println(" mConnection:");
2436 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002439 /** {@inheritDoc} */
2440 public void monitor() {
2441 if (mConnector != null) {
2442 mConnector.monitor();
2443 }
2444 }
2445}