blob: d6606f63a68681f8b2878309a40d74982e1c773e [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
Kenny Root6dceb882012-04-12 14:23:49 -0700671 // Let package manager load internal ASECs.
672 mPms.updateExternalMediaStatus(true, false);
673
San Mehat207e5382010-02-04 20:46:54 -0800674 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600675 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800676 * the hounds!
677 */
678 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800679 }
680 }.start();
681 }
682
683 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800684 * Callback from NativeDaemonConnector
685 */
686 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800687 if (DEBUG_EVENTS) {
688 StringBuilder builder = new StringBuilder();
689 builder.append("onEvent::");
690 builder.append(" raw= " + raw);
691 if (cooked != null) {
692 builder.append(" cooked = " );
693 for (String str : cooked) {
694 builder.append(" " + str);
695 }
696 }
San Mehata5078592010-03-25 09:36:54 -0700697 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800698 }
San Mehat4270e1e2010-01-29 05:32:19 -0800699 if (code == VoldResponseCode.VolumeStateChange) {
700 /*
701 * One of the volumes we're managing has changed state.
702 * Format: "NNN Volume <label> <path> state changed
703 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
704 */
705 notifyVolumeStateChange(
706 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
707 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800708 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
709 (code == VoldResponseCode.VolumeDiskRemoved) ||
710 (code == VoldResponseCode.VolumeBadRemoval)) {
711 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
712 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
713 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400714 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800715 final String label = cooked[2];
716 final String path = cooked[3];
717 int major = -1;
718 int minor = -1;
719
720 try {
721 String devComp = cooked[6].substring(1, cooked[6].length() -1);
722 String[] devTok = devComp.split(":");
723 major = Integer.parseInt(devTok[0]);
724 minor = Integer.parseInt(devTok[1]);
725 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700726 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800727 }
728
San Mehat4270e1e2010-01-29 05:32:19 -0800729 if (code == VoldResponseCode.VolumeDiskInserted) {
730 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600731 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800732 public void run() {
733 try {
734 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800735 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700736 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800737 }
738 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700739 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800740 }
741 }
742 }.start();
743 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
744 /*
745 * This event gets trumped if we're already in BAD_REMOVAL state
746 */
747 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
748 return true;
749 }
750 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700751 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400753 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800754
San Mehata5078592010-03-25 09:36:54 -0700755 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800756 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400757 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800758 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700759 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800760 /* Send the media unmounted event first */
761 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400762 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800763
San Mehata5078592010-03-25 09:36:54 -0700764 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800765 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400766 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800767 } else {
San Mehata5078592010-03-25 09:36:54 -0700768 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800769 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400770
771 if (action != null) {
772 sendStorageIntent(action, path);
773 }
San Mehat4270e1e2010-01-29 05:32:19 -0800774 } else {
775 return false;
776 }
777
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400778 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800779 }
780
San Mehat207e5382010-02-04 20:46:54 -0800781 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800782 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700783 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800784
Mike Lockwooda5250c92011-05-23 13:44:04 -0400785 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800786
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500787 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700788 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400789 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500790 }
791
San Mehat4270e1e2010-01-29 05:32:19 -0800792 if (newState == VolumeState.Init) {
793 } else if (newState == VolumeState.NoMedia) {
794 // NoMedia is handled via Disk Remove events
795 } else if (newState == VolumeState.Idle) {
796 /*
797 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
798 * if we're in the process of enabling UMS
799 */
800 if (!vs.equals(
801 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
802 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800803 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700804 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800805 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400806 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800807 }
808 } else if (newState == VolumeState.Pending) {
809 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700810 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800811 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400812 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800813 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700814 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800815 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400816 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800817 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400818 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800819 } else if (newState == VolumeState.Formatting) {
820 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700821 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800822 /* Send the media unmounted event first */
823 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400824 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800825
San Mehata5078592010-03-25 09:36:54 -0700826 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800827 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400828 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700829 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800830 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700831 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800832 return;
833 } else {
San Mehata5078592010-03-25 09:36:54 -0700834 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800835 }
836
Mike Lockwooda5250c92011-05-23 13:44:04 -0400837 if (action != null) {
838 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800839 }
840 }
841
San Mehat207e5382010-02-04 20:46:54 -0800842 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800843 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800844
San Mehata5078592010-03-25 09:36:54 -0700845 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800846 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800847 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800848 } catch (NativeDaemonConnectorException e) {
849 /*
850 * Mount failed for some reason
851 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400852 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800853 int code = e.getCode();
854 if (code == VoldResponseCode.OpFailedNoMedia) {
855 /*
856 * Attempt to mount but no media inserted
857 */
San Mehatb1043402010-02-05 08:26:50 -0800858 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800859 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700860 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800861 /*
862 * Media is blank or does not contain a supported filesystem
863 */
864 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400865 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800866 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800867 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700868 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800869 /*
870 * Volume consistency check failed
871 */
872 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400873 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800874 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800875 } else {
San Mehatb1043402010-02-05 08:26:50 -0800876 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800877 }
878
879 /*
880 * Send broadcast intent (if required for the failure)
881 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400882 if (action != null) {
883 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800884 }
885 }
886
887 return rc;
888 }
889
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800890 /*
891 * If force is not set, we do not unmount if there are
892 * processes holding references to the volume about to be unmounted.
893 * If force is set, all the processes holding references need to be
894 * killed via the ActivityManager before actually unmounting the volume.
895 * This might even take a while and might be retried after timed delays
896 * to make sure we dont end up in an instable state and kill some core
897 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700898 * If removeEncryption is set, force is implied, and the system will remove any encryption
899 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800900 */
Ben Komalo13c71972011-09-07 16:35:56 -0700901 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800902 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800903 return VoldResponseCode.OpFailedVolNotMounted;
904 }
Kenny Rootaa485402010-09-14 14:49:41 -0700905
906 /*
907 * Force a GC to make sure AssetManagers in other threads of the
908 * system_server are cleaned up. We have to do this since AssetManager
909 * instances are kept as a WeakReference and it's possible we have files
910 * open on the external storage.
911 */
912 Runtime.getRuntime().gc();
913
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800914 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700915 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800916 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800917 final Command cmd = new Command("volume", "unmount", path);
918 if (removeEncryption) {
919 cmd.appendArg("force_and_revert");
920 } else if (force) {
921 cmd.appendArg("force");
922 }
923 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700924 // We unmounted the volume. None of the asec containers are available now.
925 synchronized (mAsecMountSet) {
926 mAsecMountSet.clear();
927 }
San Mehatb1043402010-02-05 08:26:50 -0800928 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800929 } catch (NativeDaemonConnectorException e) {
930 // Don't worry about mismatch in PackageManager since the
931 // call back will handle the status changes any way.
932 int code = e.getCode();
933 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800934 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800935 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
936 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800937 } else {
San Mehatb1043402010-02-05 08:26:50 -0800938 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800939 }
940 }
941 }
942
943 private int doFormatVolume(String path) {
944 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800945 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -0800946 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800947 } catch (NativeDaemonConnectorException e) {
948 int code = e.getCode();
949 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800950 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800951 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800952 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800953 } else {
San Mehatb1043402010-02-05 08:26:50 -0800954 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800955 }
956 }
957 }
958
San Mehatb1043402010-02-05 08:26:50 -0800959 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800960 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700961 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800962 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700963 } catch (NativeDaemonConnectorException ex) {
964 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
965 return false;
966 }
San Mehatb1043402010-02-05 08:26:50 -0800967
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800968 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
969 return event.getMessage().endsWith("enabled");
970 } else {
971 return false;
San Mehatb1043402010-02-05 08:26:50 -0800972 }
San Mehatb1043402010-02-05 08:26:50 -0800973 }
974
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700975 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800976 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700977 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800978 for (int i = mListeners.size() -1; i >= 0; i--) {
979 MountServiceBinderListener bl = mListeners.get(i);
980 try {
San Mehatb1043402010-02-05 08:26:50 -0800981 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800982 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700983 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800984 mListeners.remove(i);
985 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700986 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800987 }
988 }
989 }
990
San Mehat207e5382010-02-04 20:46:54 -0800991 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800992 sendUmsIntent(avail);
993 } else {
994 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800995 }
San Mehat2fe718a2010-03-11 12:01:49 -0800996
997 final String path = Environment.getExternalStorageDirectory().getPath();
998 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
999 /*
1000 * USB mass storage disconnected while enabled
1001 */
1002 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001003 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001004 public void run() {
1005 try {
1006 int rc;
San Mehata5078592010-03-25 09:36:54 -07001007 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001008 doShareUnshareVolume(path, "ums", false);
1009 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001010 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001011 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1012 path, rc));
1013 }
1014 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001015 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001016 }
1017 }
1018 }.start();
1019 }
San Mehat4270e1e2010-01-29 05:32:19 -08001020 }
1021
Mike Lockwooda5250c92011-05-23 13:44:04 -04001022 private void sendStorageIntent(String action, String path) {
1023 Intent intent = new Intent(action, Uri.parse("file://" + path));
1024 // add StorageVolume extra
1025 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1026 Slog.d(TAG, "sendStorageIntent " + intent);
1027 mContext.sendBroadcast(intent);
1028 }
1029
San Mehat6a965af22010-02-24 17:47:30 -08001030 private void sendUmsIntent(boolean c) {
1031 mContext.sendBroadcast(
1032 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1033 }
1034
San Mehat207e5382010-02-04 20:46:54 -08001035 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001036 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1037 throw new SecurityException(String.format("Requires %s permission", perm));
1038 }
1039 }
1040
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001041 // Storage list XML tags
1042 private static final String TAG_STORAGE_LIST = "StorageList";
1043 private static final String TAG_STORAGE = "storage";
1044
1045 private void readStorageList(Resources resources) {
1046 int id = com.android.internal.R.xml.storage_list;
1047 XmlResourceParser parser = resources.getXml(id);
1048 AttributeSet attrs = Xml.asAttributeSet(parser);
1049
1050 try {
1051 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1052 while (true) {
1053 XmlUtils.nextElement(parser);
1054
1055 String element = parser.getName();
1056 if (element == null) break;
1057
1058 if (TAG_STORAGE.equals(element)) {
1059 TypedArray a = resources.obtainAttributes(attrs,
1060 com.android.internal.R.styleable.Storage);
1061
1062 CharSequence path = a.getText(
1063 com.android.internal.R.styleable.Storage_mountPoint);
1064 CharSequence description = a.getText(
1065 com.android.internal.R.styleable.Storage_storageDescription);
1066 boolean primary = a.getBoolean(
1067 com.android.internal.R.styleable.Storage_primary, false);
1068 boolean removable = a.getBoolean(
1069 com.android.internal.R.styleable.Storage_removable, false);
1070 boolean emulated = a.getBoolean(
1071 com.android.internal.R.styleable.Storage_emulated, false);
1072 int mtpReserve = a.getInt(
1073 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001074 boolean allowMassStorage = a.getBoolean(
1075 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001076 // resource parser does not support longs, so XML value is in megabytes
1077 long maxFileSize = a.getInt(
1078 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001079
1080 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1081 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001082 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001083 " allowMassStorage: " + allowMassStorage +
1084 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001085 if (path == null || description == null) {
1086 Slog.e(TAG, "path or description is null in readStorageList");
1087 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001088 String pathString = path.toString();
1089 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001090 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001091 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001092 if (primary) {
1093 if (mPrimaryVolume == null) {
1094 mPrimaryVolume = volume;
1095 } else {
1096 Slog.e(TAG, "multiple primary volumes in storage list");
1097 }
1098 }
1099 if (mPrimaryVolume == volume) {
1100 // primay volume must be first
1101 mVolumes.add(0, volume);
1102 } else {
1103 mVolumes.add(volume);
1104 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001105 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001106 }
1107 a.recycle();
1108 }
1109 }
1110 } catch (XmlPullParserException e) {
1111 throw new RuntimeException(e);
1112 } catch (IOException e) {
1113 throw new RuntimeException(e);
1114 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001115 // compute storage ID for each volume
1116 int length = mVolumes.size();
1117 for (int i = 0; i < length; i++) {
1118 mVolumes.get(i).setStorageId(i);
1119 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001120 parser.close();
1121 }
1122 }
1123
San Mehat4270e1e2010-01-29 05:32:19 -08001124 /**
San Mehat207e5382010-02-04 20:46:54 -08001125 * Constructs a new MountService instance
1126 *
1127 * @param context Binder context for this service
1128 */
1129 public MountService(Context context) {
1130 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001131 Resources resources = context.getResources();
1132 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001133
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001134 if (mPrimaryVolume != null) {
1135 mExternalStoragePath = mPrimaryVolume.getPath();
1136 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1137 if (mEmulateExternalStorage) {
1138 Slog.d(TAG, "using emulated external storage");
1139 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1140 }
Mike Lockwood03559752010-07-19 18:25:03 -04001141 }
1142
San Mehat207e5382010-02-04 20:46:54 -08001143 // XXX: This will go away soon in favor of IMountServiceObserver
1144 mPms = (PackageManagerService) ServiceManager.getService("package");
1145
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001146 IntentFilter filter = new IntentFilter();
1147 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1148 // don't bother monitoring USB if mass storage is not supported on our primary volume
1149 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1150 filter.addAction(UsbManager.ACTION_USB_STATE);
1151 }
1152 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001153
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001154 mHandlerThread = new HandlerThread("MountService");
1155 mHandlerThread.start();
1156 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1157
Kenny Roota02b8b02010-08-05 16:14:17 -07001158 // Add OBB Action Handler to MountService thread.
1159 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1160
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001161 /*
1162 * Vold does not run in the simulator, so pretend the connector thread
1163 * ran and did its thing.
1164 */
1165 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1166 mReady = true;
1167 mUmsEnabling = true;
1168 return;
1169 }
1170
Kenny Root305bcbf2010-09-03 07:56:38 -07001171 /*
1172 * Create the connection to vold with a maximum queue of twice the
1173 * amount of containers we'd ever expect to have. This keeps an
1174 * "asec list" from blocking a thread repeatedly.
1175 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001176 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
San Mehat207e5382010-02-04 20:46:54 -08001177 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001178 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001179 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001180
Kenny Root07714d42011-08-17 17:49:28 -07001181 // Add ourself to the Watchdog monitors if enabled.
1182 if (WATCHDOG_ENABLE) {
1183 Watchdog.getInstance().addMonitor(this);
1184 }
San Mehat207e5382010-02-04 20:46:54 -08001185 }
1186
1187 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001188 * Exposed API calls below here
1189 */
1190
1191 public void registerListener(IMountServiceListener listener) {
1192 synchronized (mListeners) {
1193 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1194 try {
1195 listener.asBinder().linkToDeath(bl, 0);
1196 mListeners.add(bl);
1197 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001198 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001199 }
1200 }
1201 }
1202
1203 public void unregisterListener(IMountServiceListener listener) {
1204 synchronized (mListeners) {
1205 for(MountServiceBinderListener bl : mListeners) {
1206 if (bl.mListener == listener) {
1207 mListeners.remove(mListeners.indexOf(bl));
1208 return;
1209 }
1210 }
1211 }
1212 }
1213
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001214 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001215 validatePermission(android.Manifest.permission.SHUTDOWN);
1216
San Mehata5078592010-03-25 09:36:54 -07001217 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001218 synchronized (mVolumeStates) {
1219 for (String path : mVolumeStates.keySet()) {
1220 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001221
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001222 if (state.equals(Environment.MEDIA_SHARED)) {
1223 /*
1224 * If the media is currently shared, unshare it.
1225 * XXX: This is still dangerous!. We should not
1226 * be rebooting at *all* if UMS is enabled, since
1227 * the UMS host could have dirty FAT cache entries
1228 * yet to flush.
1229 */
1230 setUsbMassStorageEnabled(false);
1231 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1232 /*
1233 * If the media is being checked, then we need to wait for
1234 * it to complete before being able to proceed.
1235 */
1236 // XXX: @hackbod - Should we disable the ANR timer here?
1237 int retries = 30;
1238 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1239 try {
1240 Thread.sleep(1000);
1241 } catch (InterruptedException iex) {
1242 Slog.e(TAG, "Interrupted while waiting for media", iex);
1243 break;
1244 }
1245 state = Environment.getExternalStorageState();
1246 }
1247 if (retries == 0) {
1248 Slog.e(TAG, "Timed out waiting for media to check");
1249 }
San Mehat91c77612010-01-07 10:39:41 -08001250 }
San Mehat91c77612010-01-07 10:39:41 -08001251
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001252 if (state.equals(Environment.MEDIA_MOUNTED)) {
1253 // Post a unmount message.
1254 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1255 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1256 } else if (observer != null) {
1257 /*
1258 * Observer is waiting for onShutDownComplete when we are done.
1259 * Since nothing will be done send notification directly so shutdown
1260 * sequence can continue.
1261 */
1262 try {
1263 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1264 } catch (RemoteException e) {
1265 Slog.w(TAG, "RemoteException when shutting down");
1266 }
1267 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001268 }
San Mehat4270e1e2010-01-29 05:32:19 -08001269 }
1270 }
1271
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001272 private boolean getUmsEnabling() {
1273 synchronized (mListeners) {
1274 return mUmsEnabling;
1275 }
1276 }
1277
1278 private void setUmsEnabling(boolean enable) {
1279 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001280 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001281 }
1282 }
1283
San Mehatb1043402010-02-05 08:26:50 -08001284 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001285 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001286
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001287 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001288 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001289 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001290 synchronized (mListeners) {
1291 return mUmsAvailable;
1292 }
San Mehatb1043402010-02-05 08:26:50 -08001293 }
1294
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001295 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001296 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001297 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001298
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001299 // TODO: Add support for multiple share methods
1300
1301 /*
1302 * If the volume is mounted and we're enabling then unmount it
1303 */
1304 String path = Environment.getExternalStorageDirectory().getPath();
1305 String vs = getVolumeState(path);
1306 String method = "ums";
1307 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1308 // Override for isUsbMassStorageEnabled()
1309 setUmsEnabling(enable);
1310 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1311 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1312 // Clear override
1313 setUmsEnabling(false);
1314 }
1315 /*
1316 * If we disabled UMS then mount the volume
1317 */
1318 if (!enable) {
1319 doShareUnshareVolume(path, method, enable);
1320 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001321 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001322 " after disabling share method " + method);
1323 /*
1324 * Even though the mount failed, the unshare didn't so don't indicate an error.
1325 * The mountVolume() call will have set the storage state and sent the necessary
1326 * broadcasts.
1327 */
1328 }
1329 }
San Mehatb1043402010-02-05 08:26:50 -08001330 }
1331
1332 public boolean isUsbMassStorageEnabled() {
1333 waitForReady();
1334 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001336
San Mehat7fd0fee2009-12-17 07:12:23 -08001337 /**
1338 * @return state of the volume at the specified mount point
1339 */
San Mehat4270e1e2010-01-29 05:32:19 -08001340 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001341 synchronized (mVolumeStates) {
1342 String state = mVolumeStates.get(mountPoint);
1343 if (state == null) {
1344 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001345 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1346 state = Environment.MEDIA_REMOVED;
1347 } else {
1348 throw new IllegalArgumentException();
1349 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001350 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001351
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001352 return state;
1353 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001354 }
1355
Kenny Roote1ff2142010-10-12 11:20:01 -07001356 public boolean isExternalStorageEmulated() {
1357 return mEmulateExternalStorage;
1358 }
1359
San Mehat4270e1e2010-01-29 05:32:19 -08001360 public int mountVolume(String path) {
1361 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001362
San Mehat207e5382010-02-04 20:46:54 -08001363 waitForReady();
1364 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366
Ben Komalo13c71972011-09-07 16:35:56 -07001367 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001368 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001369 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001371 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001372 if (DEBUG_UNMOUNT) {
1373 Slog.i(TAG, "Unmounting " + path
1374 + " force = " + force
1375 + " removeEncryption = " + removeEncryption);
1376 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001377 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1378 Environment.MEDIA_REMOVED.equals(volState) ||
1379 Environment.MEDIA_SHARED.equals(volState) ||
1380 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1381 // Media already unmounted or cannot be unmounted.
1382 // TODO return valid return code when adding observer call back.
1383 return;
1384 }
Ben Komalo13c71972011-09-07 16:35:56 -07001385 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001386 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388
San Mehat4270e1e2010-01-29 05:32:19 -08001389 public int formatVolume(String path) {
1390 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001391 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001392
San Mehat207e5382010-02-04 20:46:54 -08001393 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001396 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001397 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1398 waitForReady();
1399 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001400 final String[] r = NativeDaemonEvent.filterMessageList(
1401 mConnector.executeForList("storage", "users", path),
1402 VoldResponseCode.StorageUsersListResult);
1403
San Mehatc1b4ce92010-02-16 17:13:03 -08001404 // FMT: <pid> <process name>
1405 int[] data = new int[r.length];
1406 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001407 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001408 try {
1409 data[i] = Integer.parseInt(tok[0]);
1410 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001411 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001412 return new int[0];
1413 }
1414 }
1415 return data;
1416 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001417 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001418 return new int[0];
1419 }
1420 }
1421
San Mehatb1043402010-02-05 08:26:50 -08001422 private void warnOnNotMounted() {
1423 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001424 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001425 }
1426 }
1427
San Mehat4270e1e2010-01-29 05:32:19 -08001428 public String[] getSecureContainerList() {
1429 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001430 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001431 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001432
San Mehat4270e1e2010-01-29 05:32:19 -08001433 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001434 return NativeDaemonEvent.filterMessageList(
1435 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001436 } catch (NativeDaemonConnectorException e) {
1437 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 }
San Mehat36972292010-01-06 11:06:32 -08001440
Kenny Root6dceb882012-04-12 14:23:49 -07001441 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1442 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001443 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001444 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001445 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001446
San Mehatb1043402010-02-05 08:26:50 -08001447 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001448 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001449 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1450 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001451 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001452 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001453 }
San Mehata181b212010-02-11 06:50:20 -08001454
1455 if (rc == StorageResultCode.OperationSucceeded) {
1456 synchronized (mAsecMountSet) {
1457 mAsecMountSet.add(id);
1458 }
1459 }
San Mehat4270e1e2010-01-29 05:32:19 -08001460 return rc;
San Mehat36972292010-01-06 11:06:32 -08001461 }
1462
San Mehat4270e1e2010-01-29 05:32:19 -08001463 public int finalizeSecureContainer(String id) {
1464 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001465 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001466
San Mehatb1043402010-02-05 08:26:50 -08001467 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001468 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001469 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001470 /*
1471 * Finalization does a remount, so no need
1472 * to update mAsecMountSet
1473 */
San Mehat4270e1e2010-01-29 05:32:19 -08001474 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001475 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001476 }
San Mehat4270e1e2010-01-29 05:32:19 -08001477 return rc;
San Mehat36972292010-01-06 11:06:32 -08001478 }
1479
Kenny Root6dceb882012-04-12 14:23:49 -07001480 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1481 validatePermission(android.Manifest.permission.ASEC_CREATE);
1482 warnOnNotMounted();
1483
1484 int rc = StorageResultCode.OperationSucceeded;
1485 try {
1486 mConnector.execute("asec", "fixperms", id, gid, filename);
1487 /*
1488 * Fix permissions does a remount, so no need to update
1489 * mAsecMountSet
1490 */
1491 } catch (NativeDaemonConnectorException e) {
1492 rc = StorageResultCode.OperationFailedInternalError;
1493 }
1494 return rc;
1495 }
1496
San Mehatd9709982010-02-18 11:43:03 -08001497 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001498 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001499 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001500 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001501
Kenny Rootaa485402010-09-14 14:49:41 -07001502 /*
1503 * Force a GC to make sure AssetManagers in other threads of the
1504 * system_server are cleaned up. We have to do this since AssetManager
1505 * instances are kept as a WeakReference and it's possible we have files
1506 * open on the external storage.
1507 */
1508 Runtime.getRuntime().gc();
1509
San Mehatb1043402010-02-05 08:26:50 -08001510 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001511 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001512 final Command cmd = new Command("asec", "destroy", id);
1513 if (force) {
1514 cmd.appendArg("force");
1515 }
1516 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001517 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001518 int code = e.getCode();
1519 if (code == VoldResponseCode.OpFailedStorageBusy) {
1520 rc = StorageResultCode.OperationFailedStorageBusy;
1521 } else {
1522 rc = StorageResultCode.OperationFailedInternalError;
1523 }
San Mehat02735bc2010-01-26 15:18:08 -08001524 }
San Mehata181b212010-02-11 06:50:20 -08001525
1526 if (rc == StorageResultCode.OperationSucceeded) {
1527 synchronized (mAsecMountSet) {
1528 if (mAsecMountSet.contains(id)) {
1529 mAsecMountSet.remove(id);
1530 }
1531 }
1532 }
1533
San Mehat4270e1e2010-01-29 05:32:19 -08001534 return rc;
San Mehat36972292010-01-06 11:06:32 -08001535 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001536
San Mehat4270e1e2010-01-29 05:32:19 -08001537 public int mountSecureContainer(String id, String key, int ownerUid) {
1538 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001539 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001540 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001541
San Mehata181b212010-02-11 06:50:20 -08001542 synchronized (mAsecMountSet) {
1543 if (mAsecMountSet.contains(id)) {
1544 return StorageResultCode.OperationFailedStorageMounted;
1545 }
1546 }
1547
San Mehatb1043402010-02-05 08:26:50 -08001548 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001549 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001550 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001551 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001552 int code = e.getCode();
1553 if (code != VoldResponseCode.OpFailedStorageBusy) {
1554 rc = StorageResultCode.OperationFailedInternalError;
1555 }
San Mehat02735bc2010-01-26 15:18:08 -08001556 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001557
1558 if (rc == StorageResultCode.OperationSucceeded) {
1559 synchronized (mAsecMountSet) {
1560 mAsecMountSet.add(id);
1561 }
1562 }
San Mehat4270e1e2010-01-29 05:32:19 -08001563 return rc;
San Mehat36972292010-01-06 11:06:32 -08001564 }
1565
San Mehatd9709982010-02-18 11:43:03 -08001566 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001567 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001568 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001569 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001570
San Mehat6cdd9c02010-02-09 14:45:20 -08001571 synchronized (mAsecMountSet) {
1572 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001573 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001574 }
1575 }
1576
Kenny Rootaa485402010-09-14 14:49:41 -07001577 /*
1578 * Force a GC to make sure AssetManagers in other threads of the
1579 * system_server are cleaned up. We have to do this since AssetManager
1580 * instances are kept as a WeakReference and it's possible we have files
1581 * open on the external storage.
1582 */
1583 Runtime.getRuntime().gc();
1584
San Mehatb1043402010-02-05 08:26:50 -08001585 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001586 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001587 final Command cmd = new Command("asec", "unmount", id);
1588 if (force) {
1589 cmd.appendArg("force");
1590 }
1591 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001592 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001593 int code = e.getCode();
1594 if (code == VoldResponseCode.OpFailedStorageBusy) {
1595 rc = StorageResultCode.OperationFailedStorageBusy;
1596 } else {
1597 rc = StorageResultCode.OperationFailedInternalError;
1598 }
San Mehat02735bc2010-01-26 15:18:08 -08001599 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001600
1601 if (rc == StorageResultCode.OperationSucceeded) {
1602 synchronized (mAsecMountSet) {
1603 mAsecMountSet.remove(id);
1604 }
1605 }
San Mehat4270e1e2010-01-29 05:32:19 -08001606 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001607 }
1608
San Mehat6cdd9c02010-02-09 14:45:20 -08001609 public boolean isSecureContainerMounted(String id) {
1610 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1611 waitForReady();
1612 warnOnNotMounted();
1613
1614 synchronized (mAsecMountSet) {
1615 return mAsecMountSet.contains(id);
1616 }
1617 }
1618
San Mehat4270e1e2010-01-29 05:32:19 -08001619 public int renameSecureContainer(String oldId, String newId) {
1620 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001621 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001622 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001623
San Mehata181b212010-02-11 06:50:20 -08001624 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001625 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001626 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001627 * changed while active, we must ensure both ids are not currently mounted.
1628 */
1629 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001630 return StorageResultCode.OperationFailedStorageMounted;
1631 }
1632 }
1633
San Mehatb1043402010-02-05 08:26:50 -08001634 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001635 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001636 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001637 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001638 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001639 }
San Mehata181b212010-02-11 06:50:20 -08001640
San Mehat4270e1e2010-01-29 05:32:19 -08001641 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001642 }
1643
San Mehat4270e1e2010-01-29 05:32:19 -08001644 public String getSecureContainerPath(String id) {
1645 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001646 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001647 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001648
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001649 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001650 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001651 event = mConnector.execute("asec", "path", id);
1652 event.checkCode(VoldResponseCode.AsecPathResult);
1653 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001654 } catch (NativeDaemonConnectorException e) {
1655 int code = e.getCode();
1656 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001657 Slog.i(TAG, String.format("Container '%s' not found", id));
1658 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001659 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001660 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001661 }
1662 }
San Mehat22dd86e2010-01-12 12:21:18 -08001663 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001664
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001665 public String getSecureContainerFilesystemPath(String id) {
1666 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1667 waitForReady();
1668 warnOnNotMounted();
1669
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001670 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001671 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001672 event = mConnector.execute("asec", "fspath", id);
1673 event.checkCode(VoldResponseCode.AsecPathResult);
1674 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001675 } catch (NativeDaemonConnectorException e) {
1676 int code = e.getCode();
1677 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1678 Slog.i(TAG, String.format("Container '%s' not found", id));
1679 return null;
1680 } else {
1681 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1682 }
1683 }
1684 }
1685
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001686 public void finishMediaUpdate() {
1687 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1688 }
Kenny Root02c87302010-07-01 08:10:18 -07001689
Kenny Roota02b8b02010-08-05 16:14:17 -07001690 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1691 if (callerUid == android.os.Process.SYSTEM_UID) {
1692 return true;
1693 }
1694
Kenny Root02c87302010-07-01 08:10:18 -07001695 if (packageName == null) {
1696 return false;
1697 }
1698
Amith Yamasani483f3b02012-03-13 16:08:00 -07001699 final int packageUid = mPms.getPackageUid(packageName, UserId.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001700
1701 if (DEBUG_OBB) {
1702 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1703 packageUid + ", callerUid = " + callerUid);
1704 }
1705
1706 return callerUid == packageUid;
1707 }
1708
1709 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001710 if (filename == null) {
1711 throw new IllegalArgumentException("filename cannot be null");
1712 }
1713
Kenny Root02c87302010-07-01 08:10:18 -07001714 waitForReady();
1715 warnOnNotMounted();
1716
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001717 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001718 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001719 event = mConnector.execute("obb", "path", filename);
1720 event.checkCode(VoldResponseCode.AsecPathResult);
1721 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001722 } catch (NativeDaemonConnectorException e) {
1723 int code = e.getCode();
1724 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001725 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001726 } else {
1727 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1728 }
1729 }
1730 }
1731
1732 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001733 if (filename == null) {
1734 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001735 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001736
1737 synchronized (mObbMounts) {
1738 return mObbPathToStateMap.containsKey(filename);
1739 }
Kenny Root02c87302010-07-01 08:10:18 -07001740 }
1741
Kenny Rootaf9d6672010-10-08 09:21:39 -07001742 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001743 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001744 if (filename == null) {
1745 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001746 }
1747
1748 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001749 throw new IllegalArgumentException("token cannot be null");
1750 }
1751
Kenny Rootaf9d6672010-10-08 09:21:39 -07001752 final int callerUid = Binder.getCallingUid();
1753 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1754 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001755 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1756
1757 if (DEBUG_OBB)
1758 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001759 }
1760
Kenny Rootaf9d6672010-10-08 09:21:39 -07001761 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1762 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001763 if (filename == null) {
1764 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001765 }
1766
Kenny Rootaf9d6672010-10-08 09:21:39 -07001767 final int callerUid = Binder.getCallingUid();
1768 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1769 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001770 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001771
Kenny Roota02b8b02010-08-05 16:14:17 -07001772 if (DEBUG_OBB)
1773 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1774 }
1775
Ben Komalo444eca22011-09-01 15:17:44 -07001776 @Override
1777 public int getEncryptionState() {
1778 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1779 "no permission to access the crypt keeper");
1780
1781 waitForReady();
1782
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001783 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001784 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001785 event = mConnector.execute("cryptfs", "cryptocomplete");
1786 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001787 } catch (NumberFormatException e) {
1788 // Bad result - unexpected.
1789 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1790 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1791 } catch (NativeDaemonConnectorException e) {
1792 // Something bad happened.
1793 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1794 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1795 }
1796 }
1797
1798 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001799 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001800 if (TextUtils.isEmpty(password)) {
1801 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001802 }
1803
Jason parks8888c592011-01-20 22:46:41 -06001804 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1805 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001806
1807 waitForReady();
1808
1809 if (DEBUG_EVENTS) {
1810 Slog.i(TAG, "decrypting storage...");
1811 }
1812
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001813 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001814 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001815 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001816
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001817 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001818 if (code == 0) {
1819 // Decrypt was successful. Post a delayed message before restarting in order
1820 // to let the UI to clear itself
1821 mHandler.postDelayed(new Runnable() {
1822 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001823 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001824 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001825 } catch (NativeDaemonConnectorException e) {
1826 Slog.e(TAG, "problem executing in background", e);
1827 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001828 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001829 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001830 }
1831
1832 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001833 } catch (NativeDaemonConnectorException e) {
1834 // Decryption failed
1835 return e.getCode();
1836 }
Jason parks5af0b912010-11-29 09:05:25 -06001837 }
1838
Jason parks56aa5322011-01-07 09:01:15 -06001839 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001840 if (TextUtils.isEmpty(password)) {
1841 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001842 }
1843
Jason parks8888c592011-01-20 22:46:41 -06001844 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1845 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001846
1847 waitForReady();
1848
1849 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001850 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001851 }
1852
1853 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001854 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06001855 } catch (NativeDaemonConnectorException e) {
1856 // Encryption failed
1857 return e.getCode();
1858 }
1859
1860 return 0;
1861 }
1862
Jason parksf7b3cd42011-01-27 09:28:25 -06001863 public int changeEncryptionPassword(String password) {
1864 if (TextUtils.isEmpty(password)) {
1865 throw new IllegalArgumentException("password cannot be empty");
1866 }
1867
1868 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1869 "no permission to access the crypt keeper");
1870
1871 waitForReady();
1872
1873 if (DEBUG_EVENTS) {
1874 Slog.i(TAG, "changing encryption password...");
1875 }
1876
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001877 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06001878 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001879 event = mConnector.execute("cryptfs", "changepw", password);
1880 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06001881 } catch (NativeDaemonConnectorException e) {
1882 // Encryption failed
1883 return e.getCode();
1884 }
1885 }
1886
Christopher Tate32418be2011-10-10 13:51:12 -07001887 /**
1888 * Validate a user-supplied password string with cryptfs
1889 */
1890 @Override
1891 public int verifyEncryptionPassword(String password) throws RemoteException {
1892 // Only the system process is permitted to validate passwords
1893 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1894 throw new SecurityException("no permission to access the crypt keeper");
1895 }
1896
1897 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1898 "no permission to access the crypt keeper");
1899
1900 if (TextUtils.isEmpty(password)) {
1901 throw new IllegalArgumentException("password cannot be empty");
1902 }
1903
1904 waitForReady();
1905
1906 if (DEBUG_EVENTS) {
1907 Slog.i(TAG, "validating encryption password...");
1908 }
1909
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001910 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07001911 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001912 event = mConnector.execute("cryptfs", "verifypw", password);
1913 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
1914 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07001915 } catch (NativeDaemonConnectorException e) {
1916 // Encryption failed
1917 return e.getCode();
1918 }
1919 }
1920
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001921 public Parcelable[] getVolumeList() {
1922 synchronized(mVolumes) {
1923 int size = mVolumes.size();
1924 Parcelable[] result = new Parcelable[size];
1925 for (int i = 0; i < size; i++) {
1926 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001927 }
1928 return result;
1929 }
1930 }
1931
Kenny Rootaf9d6672010-10-08 09:21:39 -07001932 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1933 final IBinder binder = obbState.getBinder();
1934 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001935
Kenny Rootaf9d6672010-10-08 09:21:39 -07001936 if (obbStates == null) {
1937 obbStates = new ArrayList<ObbState>();
1938 mObbMounts.put(binder, obbStates);
1939 } else {
1940 for (final ObbState o : obbStates) {
1941 if (o.filename.equals(obbState.filename)) {
1942 throw new IllegalStateException("Attempt to add ObbState twice. "
1943 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001944 }
1945 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001946 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001947
1948 obbStates.add(obbState);
1949 try {
1950 obbState.link();
1951 } catch (RemoteException e) {
1952 /*
1953 * The binder died before we could link it, so clean up our state
1954 * and return failure.
1955 */
1956 obbStates.remove(obbState);
1957 if (obbStates.isEmpty()) {
1958 mObbMounts.remove(binder);
1959 }
1960
1961 // Rethrow the error so mountObb can get it
1962 throw e;
1963 }
1964
1965 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001966 }
1967
Kenny Rootaf9d6672010-10-08 09:21:39 -07001968 private void removeObbStateLocked(ObbState obbState) {
1969 final IBinder binder = obbState.getBinder();
1970 final List<ObbState> obbStates = mObbMounts.get(binder);
1971 if (obbStates != null) {
1972 if (obbStates.remove(obbState)) {
1973 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001974 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001975 if (obbStates.isEmpty()) {
1976 mObbMounts.remove(binder);
1977 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001978 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001979
Kenny Rootaf9d6672010-10-08 09:21:39 -07001980 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001981 }
1982
Kenny Roota02b8b02010-08-05 16:14:17 -07001983 private class ObbActionHandler extends Handler {
1984 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001985 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001986
1987 ObbActionHandler(Looper l) {
1988 super(l);
1989 }
1990
1991 @Override
1992 public void handleMessage(Message msg) {
1993 switch (msg.what) {
1994 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001995 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001996
1997 if (DEBUG_OBB)
1998 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1999
2000 // If a bind was already initiated we don't really
2001 // need to do anything. The pending install
2002 // will be processed later on.
2003 if (!mBound) {
2004 // If this is the only one pending we might
2005 // have to bind to the service again.
2006 if (!connectToService()) {
2007 Slog.e(TAG, "Failed to bind to media container service");
2008 action.handleError();
2009 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002010 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002011 }
Kenny Root735de3b2010-09-30 14:11:39 -07002012
Kenny Root735de3b2010-09-30 14:11:39 -07002013 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002014 break;
2015 }
2016 case OBB_MCS_BOUND: {
2017 if (DEBUG_OBB)
2018 Slog.i(TAG, "OBB_MCS_BOUND");
2019 if (msg.obj != null) {
2020 mContainerService = (IMediaContainerService) msg.obj;
2021 }
2022 if (mContainerService == null) {
2023 // Something seriously wrong. Bail out
2024 Slog.e(TAG, "Cannot bind to media container service");
2025 for (ObbAction action : mActions) {
2026 // Indicate service bind error
2027 action.handleError();
2028 }
2029 mActions.clear();
2030 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002031 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002032 if (action != null) {
2033 action.execute(this);
2034 }
2035 } else {
2036 // Should never happen ideally.
2037 Slog.w(TAG, "Empty queue");
2038 }
2039 break;
2040 }
2041 case OBB_MCS_RECONNECT: {
2042 if (DEBUG_OBB)
2043 Slog.i(TAG, "OBB_MCS_RECONNECT");
2044 if (mActions.size() > 0) {
2045 if (mBound) {
2046 disconnectService();
2047 }
2048 if (!connectToService()) {
2049 Slog.e(TAG, "Failed to bind to media container service");
2050 for (ObbAction action : mActions) {
2051 // Indicate service bind error
2052 action.handleError();
2053 }
2054 mActions.clear();
2055 }
2056 }
2057 break;
2058 }
2059 case OBB_MCS_UNBIND: {
2060 if (DEBUG_OBB)
2061 Slog.i(TAG, "OBB_MCS_UNBIND");
2062
2063 // Delete pending install
2064 if (mActions.size() > 0) {
2065 mActions.remove(0);
2066 }
2067 if (mActions.size() == 0) {
2068 if (mBound) {
2069 disconnectService();
2070 }
2071 } else {
2072 // There are more pending requests in queue.
2073 // Just post MCS_BOUND message to trigger processing
2074 // of next pending install.
2075 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2076 }
2077 break;
2078 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002079 case OBB_FLUSH_MOUNT_STATE: {
2080 final String path = (String) msg.obj;
2081
2082 if (DEBUG_OBB)
2083 Slog.i(TAG, "Flushing all OBB state for path " + path);
2084
2085 synchronized (mObbMounts) {
2086 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2087
2088 final Iterator<Entry<String, ObbState>> i =
2089 mObbPathToStateMap.entrySet().iterator();
2090 while (i.hasNext()) {
2091 final Entry<String, ObbState> obbEntry = i.next();
2092
2093 /*
2094 * If this entry's source file is in the volume path
2095 * that got unmounted, remove it because it's no
2096 * longer valid.
2097 */
2098 if (obbEntry.getKey().startsWith(path)) {
2099 obbStatesToRemove.add(obbEntry.getValue());
2100 }
2101 }
2102
2103 for (final ObbState obbState : obbStatesToRemove) {
2104 if (DEBUG_OBB)
2105 Slog.i(TAG, "Removing state for " + obbState.filename);
2106
2107 removeObbStateLocked(obbState);
2108
2109 try {
2110 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2111 OnObbStateChangeListener.UNMOUNTED);
2112 } catch (RemoteException e) {
2113 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2114 + obbState.filename);
2115 }
2116 }
2117 }
2118 break;
2119 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002120 }
2121 }
2122
2123 private boolean connectToService() {
2124 if (DEBUG_OBB)
2125 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2126
2127 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2128 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2129 mBound = true;
2130 return true;
2131 }
2132 return false;
2133 }
2134
2135 private void disconnectService() {
2136 mContainerService = null;
2137 mBound = false;
2138 mContext.unbindService(mDefContainerConn);
2139 }
2140 }
2141
2142 abstract class ObbAction {
2143 private static final int MAX_RETRIES = 3;
2144 private int mRetries;
2145
2146 ObbState mObbState;
2147
2148 ObbAction(ObbState obbState) {
2149 mObbState = obbState;
2150 }
2151
2152 public void execute(ObbActionHandler handler) {
2153 try {
2154 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002155 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002156 mRetries++;
2157 if (mRetries > MAX_RETRIES) {
2158 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002159 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002160 handleError();
2161 return;
2162 } else {
2163 handleExecute();
2164 if (DEBUG_OBB)
2165 Slog.i(TAG, "Posting install MCS_UNBIND");
2166 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2167 }
2168 } catch (RemoteException e) {
2169 if (DEBUG_OBB)
2170 Slog.i(TAG, "Posting install MCS_RECONNECT");
2171 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2172 } catch (Exception e) {
2173 if (DEBUG_OBB)
2174 Slog.d(TAG, "Error handling OBB action", e);
2175 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002176 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002177 }
2178 }
2179
Kenny Root05105f72010-09-22 17:29:43 -07002180 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002181 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002182
2183 protected ObbInfo getObbInfo() throws IOException {
2184 ObbInfo obbInfo;
2185 try {
2186 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2187 } catch (RemoteException e) {
2188 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2189 + mObbState.filename);
2190 obbInfo = null;
2191 }
2192 if (obbInfo == null) {
2193 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2194 }
2195 return obbInfo;
2196 }
2197
Kenny Rootaf9d6672010-10-08 09:21:39 -07002198 protected void sendNewStatusOrIgnore(int status) {
2199 if (mObbState == null || mObbState.token == null) {
2200 return;
2201 }
2202
Kenny Root38cf8862010-09-26 14:18:51 -07002203 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002204 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002205 } catch (RemoteException e) {
2206 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2207 }
2208 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002209 }
2210
2211 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002212 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002213
2214 MountObbAction(ObbState obbState, String key) {
2215 super(obbState);
2216 mKey = key;
2217 }
2218
Jason parks5af0b912010-11-29 09:05:25 -06002219 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002220 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002221 waitForReady();
2222 warnOnNotMounted();
2223
Kenny Root38cf8862010-09-26 14:18:51 -07002224 final ObbInfo obbInfo = getObbInfo();
2225
Kenny Roota02b8b02010-08-05 16:14:17 -07002226 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002227 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2228 + " which is owned by " + obbInfo.packageName);
2229 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2230 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002231 }
2232
Kenny Rootaf9d6672010-10-08 09:21:39 -07002233 final boolean isMounted;
2234 synchronized (mObbMounts) {
2235 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2236 }
2237 if (isMounted) {
2238 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2239 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2240 return;
2241 }
2242
2243 /*
2244 * The filename passed in might not be the canonical name, so just
2245 * set the filename to the canonicalized version.
2246 */
2247 mObbState.filename = obbInfo.filename;
2248
2249 final String hashedKey;
2250 if (mKey == null) {
2251 hashedKey = "none";
2252 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002253 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002254 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2255
2256 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2257 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2258 SecretKey key = factory.generateSecret(ks);
2259 BigInteger bi = new BigInteger(key.getEncoded());
2260 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002261 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002262 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2263 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2264 return;
2265 } catch (InvalidKeySpecException e) {
2266 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2267 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002268 return;
2269 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002270 }
Kenny Root38cf8862010-09-26 14:18:51 -07002271
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002273 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002274 mConnector.execute(
2275 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002276 } catch (NativeDaemonConnectorException e) {
2277 int code = e.getCode();
2278 if (code != VoldResponseCode.OpFailedStorageBusy) {
2279 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002280 }
2281 }
2282
Kenny Rootaf9d6672010-10-08 09:21:39 -07002283 if (rc == StorageResultCode.OperationSucceeded) {
2284 if (DEBUG_OBB)
2285 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2286
2287 synchronized (mObbMounts) {
2288 addObbStateLocked(mObbState);
2289 }
2290
2291 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002292 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002293 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002294
Kenny Rootaf9d6672010-10-08 09:21:39 -07002295 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002296 }
2297 }
2298
Jason parks5af0b912010-11-29 09:05:25 -06002299 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002300 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002301 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002302 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002303
2304 @Override
2305 public String toString() {
2306 StringBuilder sb = new StringBuilder();
2307 sb.append("MountObbAction{");
2308 sb.append("filename=");
2309 sb.append(mObbState.filename);
2310 sb.append(",callerUid=");
2311 sb.append(mObbState.callerUid);
2312 sb.append(",token=");
2313 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002314 sb.append(",binder=");
2315 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002316 sb.append('}');
2317 return sb.toString();
2318 }
2319 }
2320
2321 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002322 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002323
2324 UnmountObbAction(ObbState obbState, boolean force) {
2325 super(obbState);
2326 mForceUnmount = force;
2327 }
2328
Jason parks5af0b912010-11-29 09:05:25 -06002329 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002330 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002331 waitForReady();
2332 warnOnNotMounted();
2333
Kenny Root38cf8862010-09-26 14:18:51 -07002334 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002335
Kenny Rootaf9d6672010-10-08 09:21:39 -07002336 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002337 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002338 obbState = mObbPathToStateMap.get(obbInfo.filename);
2339 }
Kenny Root38cf8862010-09-26 14:18:51 -07002340
Kenny Rootaf9d6672010-10-08 09:21:39 -07002341 if (obbState == null) {
2342 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2343 return;
2344 }
2345
2346 if (obbState.callerUid != mObbState.callerUid) {
2347 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2348 + " (owned by " + obbInfo.packageName + ")");
2349 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2350 return;
2351 }
2352
2353 mObbState.filename = obbInfo.filename;
2354
2355 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002356 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002357 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2358 if (mForceUnmount) {
2359 cmd.appendArg("force");
2360 }
2361 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002362 } catch (NativeDaemonConnectorException e) {
2363 int code = e.getCode();
2364 if (code == VoldResponseCode.OpFailedStorageBusy) {
2365 rc = StorageResultCode.OperationFailedStorageBusy;
2366 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2367 // If it's not mounted then we've already won.
2368 rc = StorageResultCode.OperationSucceeded;
2369 } else {
2370 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002371 }
2372 }
2373
Kenny Rootaf9d6672010-10-08 09:21:39 -07002374 if (rc == StorageResultCode.OperationSucceeded) {
2375 synchronized (mObbMounts) {
2376 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002377 }
2378
Kenny Rootaf9d6672010-10-08 09:21:39 -07002379 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002380 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002381 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2382 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002383 }
2384 }
2385
Jason parks5af0b912010-11-29 09:05:25 -06002386 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002387 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002388 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002389 }
2390
2391 @Override
2392 public String toString() {
2393 StringBuilder sb = new StringBuilder();
2394 sb.append("UnmountObbAction{");
2395 sb.append("filename=");
2396 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2397 sb.append(",force=");
2398 sb.append(mForceUnmount);
2399 sb.append(",callerUid=");
2400 sb.append(mObbState.callerUid);
2401 sb.append(",token=");
2402 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002403 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002404 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002405 sb.append('}');
2406 return sb.toString();
2407 }
Kenny Root02c87302010-07-01 08:10:18 -07002408 }
Kenny Root38cf8862010-09-26 14:18:51 -07002409
2410 @Override
2411 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2412 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2413 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2414 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2415 + " without permission " + android.Manifest.permission.DUMP);
2416 return;
2417 }
2418
Kenny Root38cf8862010-09-26 14:18:51 -07002419 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002420 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002421
Kenny Rootaf9d6672010-10-08 09:21:39 -07002422 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2423 while (binders.hasNext()) {
2424 Entry<IBinder, List<ObbState>> e = binders.next();
2425 pw.print(" Key="); pw.println(e.getKey().toString());
2426 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002427 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002428 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002429 }
2430 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002431
2432 pw.println("");
2433 pw.println(" mObbPathToStateMap:");
2434 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2435 while (maps.hasNext()) {
2436 final Entry<String, ObbState> e = maps.next();
2437 pw.print(" "); pw.print(e.getKey());
2438 pw.print(" -> "); pw.println(e.getValue().toString());
2439 }
Kenny Root38cf8862010-09-26 14:18:51 -07002440 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002441
2442 pw.println("");
2443
2444 synchronized (mVolumes) {
2445 pw.println(" mVolumes:");
2446
2447 final int N = mVolumes.size();
2448 for (int i = 0; i < N; i++) {
2449 final StorageVolume v = mVolumes.get(i);
2450 pw.print(" ");
2451 pw.println(v.toString());
2452 }
2453 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002454
2455 pw.println();
2456 pw.println(" mConnection:");
2457 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002460 /** {@inheritDoc} */
2461 public void monitor() {
2462 if (mConnector != null) {
2463 mConnector.monitor();
2464 }
2465 }
2466}