blob: 13ab586a5080cb91836b720033c0418c03ef2387 [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;
Kenny Root51a573c2012-05-17 13:30:28 -070082import java.util.concurrent.CountDownLatch;
83import java.util.concurrent.TimeUnit;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070084import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Kenny Root3b1abba2010-10-13 15:00:07 -070086import javax.crypto.SecretKey;
87import javax.crypto.SecretKeyFactory;
88import javax.crypto.spec.PBEKeySpec;
89
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090/**
San Mehatb1043402010-02-05 08:26:50 -080091 * MountService implements back-end services for platform storage
92 * management.
93 * @hide - Applications should use android.os.storage.StorageManager
94 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070096class MountService extends IMountService.Stub
97 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -060098
San Mehatb1043402010-02-05 08:26:50 -080099 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800100 private static final boolean DEBUG_UNMOUNT = false;
101 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800102 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700103
Kenny Root07714d42011-08-17 17:49:28 -0700104 // Disable this since it messes up long-running cryptfs operations.
105 private static final boolean WATCHDOG_ENABLE = false;
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 private static final String TAG = "MountService";
108
Kenny Root305bcbf2010-09-03 07:56:38 -0700109 private static final String VOLD_TAG = "VoldConnector";
110
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700111 /** Maximum number of ASEC containers allowed to be mounted. */
112 private static final int MAX_CONTAINERS = 250;
113
San Mehat4270e1e2010-01-29 05:32:19 -0800114 /*
115 * Internal vold volume state constants
116 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800117 class VolumeState {
118 public static final int Init = -1;
119 public static final int NoMedia = 0;
120 public static final int Idle = 1;
121 public static final int Pending = 2;
122 public static final int Checking = 3;
123 public static final int Mounted = 4;
124 public static final int Unmounting = 5;
125 public static final int Formatting = 6;
126 public static final int Shared = 7;
127 public static final int SharedMnt = 8;
128 }
129
San Mehat4270e1e2010-01-29 05:32:19 -0800130 /*
131 * Internal vold response code constants
132 */
San Mehat22dd86e2010-01-12 12:21:18 -0800133 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800134 /*
135 * 100 series - Requestion action was initiated; expect another reply
136 * before proceeding with a new command.
137 */
San Mehat22dd86e2010-01-12 12:21:18 -0800138 public static final int VolumeListResult = 110;
139 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800140 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800141
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * 200 series - Requestion action has been successfully completed.
144 */
145 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800146 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800147 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800148
San Mehat4270e1e2010-01-29 05:32:19 -0800149 /*
150 * 400 series - Command was accepted, but the requested action
151 * did not take place.
152 */
153 public static final int OpFailedNoMedia = 401;
154 public static final int OpFailedMediaBlank = 402;
155 public static final int OpFailedMediaCorrupt = 403;
156 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800157 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700158 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800159
160 /*
161 * 600 series - Unsolicited broadcasts.
162 */
San Mehat22dd86e2010-01-12 12:21:18 -0800163 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800164 public static final int VolumeDiskInserted = 630;
165 public static final int VolumeDiskRemoved = 631;
166 public static final int VolumeBadRemoval = 632;
167 }
168
San Mehat4270e1e2010-01-29 05:32:19 -0800169 private Context mContext;
170 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700171 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
172 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400173 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400174 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400175 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800176 private PackageManagerService mPms;
177 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700178 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800179 // Used as a lock for methods that register/unregister listeners.
180 final private ArrayList<MountServiceBinderListener> mListeners =
181 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800182 private boolean mBooted = false;
Kenny Root51a573c2012-05-17 13:30:28 -0700183 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
184 private CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800185 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400186 // true if we should fake MEDIA_MOUNTED state for external storage
187 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800188
San Mehat6cdd9c02010-02-09 14:45:20 -0800189 /**
190 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800191 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800192 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800193 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800194
Kenny Root02c87302010-07-01 08:10:18 -0700195 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700196 * The size of the crypto algorithm key in bits for OBB files. Currently
197 * Twofish is used which takes 128-bit keys.
198 */
199 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
200
201 /**
202 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
203 * 1024 is reasonably secure and not too slow.
204 */
205 private static final int PBKDF2_HASH_ROUNDS = 1024;
206
207 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700208 * Mounted OBB tracking information. Used to track the current state of all
209 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700210 */
Kenny Root735de3b2010-09-30 14:11:39 -0700211 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700212 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
213
214 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700215 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700216 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700217 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700218 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700219 this.token = token;
220 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700221 }
222
223 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700224 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700225
226 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700227 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700228
Kenny Rootaf9d6672010-10-08 09:21:39 -0700229 // Token of remote Binder caller
230 final IObbActionListener token;
231
232 // Identifier to pass back to the token
233 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700234
Kenny Root735de3b2010-09-30 14:11:39 -0700235 public IBinder getBinder() {
236 return token.asBinder();
237 }
238
Kenny Roota02b8b02010-08-05 16:14:17 -0700239 @Override
240 public void binderDied() {
241 ObbAction action = new UnmountObbAction(this, true);
242 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700243 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700244
Kenny Root5919ac62010-10-05 09:49:40 -0700245 public void link() throws RemoteException {
246 getBinder().linkToDeath(this, 0);
247 }
248
249 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700250 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700251 }
Kenny Root38cf8862010-09-26 14:18:51 -0700252
253 @Override
254 public String toString() {
255 StringBuilder sb = new StringBuilder("ObbState{");
256 sb.append("filename=");
257 sb.append(filename);
258 sb.append(",token=");
259 sb.append(token.toString());
260 sb.append(",callerUid=");
261 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700262 sb.append('}');
263 return sb.toString();
264 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700265 }
266
267 // OBB Action Handler
268 final private ObbActionHandler mObbActionHandler;
269
270 // OBB action handler messages
271 private static final int OBB_RUN_ACTION = 1;
272 private static final int OBB_MCS_BOUND = 2;
273 private static final int OBB_MCS_UNBIND = 3;
274 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700275 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700276
277 /*
278 * Default Container Service information
279 */
280 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
281 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
282
283 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
284
285 class DefaultContainerConnection implements ServiceConnection {
286 public void onServiceConnected(ComponentName name, IBinder service) {
287 if (DEBUG_OBB)
288 Slog.i(TAG, "onServiceConnected");
289 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
290 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
291 }
292
293 public void onServiceDisconnected(ComponentName name) {
294 if (DEBUG_OBB)
295 Slog.i(TAG, "onServiceDisconnected");
296 }
297 };
298
299 // Used in the ObbActionHandler
300 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700301
302 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800303 private static final int H_UNMOUNT_PM_UPDATE = 1;
304 private static final int H_UNMOUNT_PM_DONE = 2;
305 private static final int H_UNMOUNT_MS = 3;
306 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
307 private static final int MAX_UNMOUNT_RETRIES = 4;
308
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800309 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700310 final String path;
311 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700312 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800313 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800314
Ben Komalo13c71972011-09-07 16:35:56 -0700315 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800316 retries = 0;
317 this.path = path;
318 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700319 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800320 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800321
322 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700323 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700324 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800325 }
326 }
327
328 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700329 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800330
331 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700332 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800333 this.method = method;
334 }
335
336 @Override
337 void handleFinished() {
338 super.handleFinished();
339 doShareUnshareVolume(path, method, true);
340 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800341 }
342
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800343 class ShutdownCallBack extends UnmountCallBack {
344 IMountShutdownObserver observer;
345 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700346 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800347 this.observer = observer;
348 }
349
350 @Override
351 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700352 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800353 if (observer != null) {
354 try {
355 observer.onShutDownComplete(ret);
356 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700357 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800358 }
359 }
360 }
361 }
362
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400363 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800364 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800366
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400367 MountServiceHandler(Looper l) {
368 super(l);
369 }
370
Jason parks5af0b912010-11-29 09:05:25 -0600371 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 public void handleMessage(Message msg) {
373 switch (msg.what) {
374 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700375 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800376 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
377 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700378 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800379 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700380 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700381 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700382 mUpdatingStatus = true;
383 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 }
385 break;
386 }
387 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700388 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700389 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700390 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800391 int size = mForceUnmounts.size();
392 int sizeArr[] = new int[size];
393 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700394 // Kill processes holding references first
395 ActivityManagerService ams = (ActivityManagerService)
396 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800397 for (int i = 0; i < size; i++) {
398 UnmountCallBack ucb = mForceUnmounts.get(i);
399 String path = ucb.path;
400 boolean done = false;
401 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402 done = true;
403 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800404 int pids[] = getStorageUsers(path);
405 if (pids == null || pids.length == 0) {
406 done = true;
407 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800408 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800409 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700410 // Confirm if file references have been freed.
411 pids = getStorageUsers(path);
412 if (pids == null || pids.length == 0) {
413 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800414 }
415 }
416 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700417 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
418 // Retry again
419 Slog.i(TAG, "Retrying to kill storage users again");
420 mHandler.sendMessageDelayed(
421 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
422 ucb.retries++),
423 RETRY_UNMOUNT_DELAY);
424 } else {
425 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
426 Slog.i(TAG, "Failed to unmount media inspite of " +
427 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
428 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800429 sizeArr[sizeArrN++] = i;
430 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
431 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800432 }
433 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 // Remove already processed elements from list.
435 for (int i = (sizeArrN-1); i >= 0; i--) {
436 mForceUnmounts.remove(sizeArr[i]);
437 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800438 break;
439 }
440 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700441 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800442 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800443 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800444 break;
445 }
446 }
447 }
448 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400449 final private HandlerThread mHandlerThread;
450 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800451
Kenny Root51a573c2012-05-17 13:30:28 -0700452 void waitForAsecScan() {
453 waitForLatch(mAsecsScanned);
454 }
455
San Mehat207e5382010-02-04 20:46:54 -0800456 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700457 waitForLatch(mConnectedSignal);
458 }
459
460 private void waitForLatch(CountDownLatch latch) {
461 if (latch == null) {
462 return;
463 }
464
465 for (;;) {
466 try {
467 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800468 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700469 } else {
470 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
471 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800472 }
Kenny Root51a573c2012-05-17 13:30:28 -0700473 } catch (InterruptedException e) {
474 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800475 }
San Mehat207e5382010-02-04 20:46:54 -0800476 }
San Mehat1f6301e2010-01-07 22:40:27 -0800477 }
Kenny Root02c87302010-07-01 08:10:18 -0700478
Ben Komalo444eca22011-09-01 15:17:44 -0700479 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600480 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800482 String action = intent.getAction();
483
484 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800485 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800486
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800487 /*
488 * In the simulator, we need to broadcast a volume mounted event
489 * to make the media scanner run.
490 */
491 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400492 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
493 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800494 return;
495 }
San Mehatfafb0412010-02-18 19:40:04 -0800496 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600497 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800498 public void run() {
499 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400500 // it is not safe to call vold with mVolumeStates locked
501 // so we make a copy of the paths and states and process them
502 // outside the lock
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700503 String[] paths;
504 String[] states;
Mike Lockwood84338c42011-04-05 10:05:47 -0400505 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400506 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400507 Set<String> keys = mVolumeStates.keySet();
508 count = keys.size();
Ben Komalo444eca22011-09-01 15:17:44 -0700509 paths = keys.toArray(new String[count]);
Mike Lockwood84338c42011-04-05 10:05:47 -0400510 states = new String[count];
511 for (int i = 0; i < count; i++) {
512 states[i] = mVolumeStates.get(paths[i]);
513 }
514 }
San Mehat6a254402010-03-22 10:21:00 -0700515
Mike Lockwood84338c42011-04-05 10:05:47 -0400516 for (int i = 0; i < count; i++) {
517 String path = paths[i];
518 String state = states[i];
519
520 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
521 int rc = doMountVolume(path);
522 if (rc != StorageResultCode.OperationSucceeded) {
523 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
524 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400525 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400526 } else if (state.equals(Environment.MEDIA_SHARED)) {
527 /*
528 * Bootstrap UMS enabled state since vold indicates
529 * the volume is shared (runtime restart while ums enabled)
530 */
531 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
532 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800533 }
534 }
San Mehat6a254402010-03-22 10:21:00 -0700535
Mike Lockwood80e0a412011-04-05 10:21:51 -0400536 /* notify external storage has mounted to trigger media scanner */
537 if (mEmulateExternalStorage) {
538 notifyVolumeStateChange(null,
539 Environment.getExternalStorageDirectory().getPath(),
540 VolumeState.NoMedia, VolumeState.Mounted);
541 }
542
San Mehat6a965af22010-02-24 17:47:30 -0800543 /*
San Mehat6a254402010-03-22 10:21:00 -0700544 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800545 * now that we're up.
546 */
547 if (mSendUmsConnectedOnBoot) {
548 sendUmsIntent(true);
549 mSendUmsConnectedOnBoot = false;
550 }
San Mehatfafb0412010-02-18 19:40:04 -0800551 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700552 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800553 }
San Mehat207e5382010-02-04 20:46:54 -0800554 }
San Mehatfafb0412010-02-18 19:40:04 -0800555 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700556 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
557 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
558 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
559 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561 }
562 };
San Mehat4270e1e2010-01-29 05:32:19 -0800563 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
564 final IMountServiceListener mListener;
565
566 MountServiceBinderListener(IMountServiceListener listener) {
567 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700568
San Mehat91c77612010-01-07 10:39:41 -0800569 }
570
San Mehat4270e1e2010-01-29 05:32:19 -0800571 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700572 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700573 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800574 mListeners.remove(this);
575 mListener.asBinder().unlinkToDeath(this, 0);
576 }
577 }
578 }
579
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800580 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800581 // TODO: Add support for multiple share methods
582 if (!method.equals("ums")) {
583 throw new IllegalArgumentException(String.format("Method %s not supported", method));
584 }
585
San Mehat4270e1e2010-01-29 05:32:19 -0800586 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800587 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800588 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700589 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800590 }
San Mehat4270e1e2010-01-29 05:32:19 -0800591 }
592
San Mehat207e5382010-02-04 20:46:54 -0800593 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400594 String oldState;
595 synchronized(mVolumeStates) {
596 oldState = mVolumeStates.put(path, state);
597 }
598 if (state.equals(oldState)) {
599 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
600 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800601 return;
602 }
San Mehatb1043402010-02-05 08:26:50 -0800603
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400604 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700605
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400606 if (path.equals(mExternalStoragePath)) {
607 // Update state on PackageManager, but only of real events
608 if (!mEmulateExternalStorage) {
609 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
610 mPms.updateExternalMediaStatus(false, false);
611
612 /*
613 * Some OBBs might have been unmounted when this volume was
614 * unmounted, so send a message to the handler to let it know to
615 * remove those from the list of mounted OBBS.
616 */
617 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
618 OBB_FLUSH_MOUNT_STATE, path));
619 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
620 mPms.updateExternalMediaStatus(true, false);
621 }
Mike Lockwood03559752010-07-19 18:25:03 -0400622 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800623 }
San Mehat4270e1e2010-01-29 05:32:19 -0800624 synchronized (mListeners) {
625 for (int i = mListeners.size() -1; i >= 0; i--) {
626 MountServiceBinderListener bl = mListeners.get(i);
627 try {
San Mehatb1043402010-02-05 08:26:50 -0800628 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800629 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700630 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800631 mListeners.remove(i);
632 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700633 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800634 }
635 }
636 }
637 }
638
639 /**
640 *
641 * Callback from NativeDaemonConnector
642 */
643 public void onDaemonConnected() {
644 /*
645 * Since we'll be calling back into the NativeDaemonConnector,
646 * we need to do our work in a new thread.
647 */
Kenny Root51a573c2012-05-17 13:30:28 -0700648 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600649 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800650 public void run() {
651 /**
652 * Determine media state and UMS detection status
653 */
San Mehat4270e1e2010-01-29 05:32:19 -0800654 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800655 final String[] vols = NativeDaemonEvent.filterMessageList(
656 mConnector.executeForList("volume", "list"),
657 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800658 for (String volstr : vols) {
659 String[] tok = volstr.split(" ");
660 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400661 String path = tok[1];
662 String state = Environment.MEDIA_REMOVED;
663
San Mehat4270e1e2010-01-29 05:32:19 -0800664 int st = Integer.parseInt(tok[2]);
665 if (st == VolumeState.NoMedia) {
666 state = Environment.MEDIA_REMOVED;
667 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800668 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800669 } else if (st == VolumeState.Mounted) {
670 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700671 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800672 } else if (st == VolumeState.Shared) {
673 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700674 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800675 } else {
676 throw new Exception(String.format("Unexpected state %d", st));
677 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400678
679 if (state != null) {
680 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
681 updatePublicVolumeState(path, state);
682 }
San Mehat4270e1e2010-01-29 05:32:19 -0800683 }
684 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700685 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400686 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800687 }
688
San Mehat207e5382010-02-04 20:46:54 -0800689 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600690 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800691 * the hounds!
692 */
Kenny Root51a573c2012-05-17 13:30:28 -0700693 mConnectedSignal.countDown();
694 mConnectedSignal = null;
695
696 // Let package manager load internal ASECs.
697 mPms.scanAvailableAsecs();
698
699 // Notify people waiting for ASECs to be scanned that it's done.
700 mAsecsScanned.countDown();
701 mAsecsScanned = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800702 }
703 }.start();
704 }
705
706 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800707 * Callback from NativeDaemonConnector
708 */
709 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800710 if (DEBUG_EVENTS) {
711 StringBuilder builder = new StringBuilder();
712 builder.append("onEvent::");
713 builder.append(" raw= " + raw);
714 if (cooked != null) {
715 builder.append(" cooked = " );
716 for (String str : cooked) {
717 builder.append(" " + str);
718 }
719 }
San Mehata5078592010-03-25 09:36:54 -0700720 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800721 }
San Mehat4270e1e2010-01-29 05:32:19 -0800722 if (code == VoldResponseCode.VolumeStateChange) {
723 /*
724 * One of the volumes we're managing has changed state.
725 * Format: "NNN Volume <label> <path> state changed
726 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
727 */
728 notifyVolumeStateChange(
729 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
730 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800731 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
732 (code == VoldResponseCode.VolumeDiskRemoved) ||
733 (code == VoldResponseCode.VolumeBadRemoval)) {
734 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
735 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
736 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400737 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800738 final String label = cooked[2];
739 final String path = cooked[3];
740 int major = -1;
741 int minor = -1;
742
743 try {
744 String devComp = cooked[6].substring(1, cooked[6].length() -1);
745 String[] devTok = devComp.split(":");
746 major = Integer.parseInt(devTok[0]);
747 minor = Integer.parseInt(devTok[1]);
748 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700749 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800750 }
751
San Mehat4270e1e2010-01-29 05:32:19 -0800752 if (code == VoldResponseCode.VolumeDiskInserted) {
753 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600754 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800755 public void run() {
756 try {
757 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800758 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700759 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800760 }
761 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700762 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800763 }
764 }
765 }.start();
766 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
767 /*
768 * This event gets trumped if we're already in BAD_REMOVAL state
769 */
770 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
771 return true;
772 }
773 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700774 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800775 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400776 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800777
San Mehata5078592010-03-25 09:36:54 -0700778 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800779 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400780 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800781 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700782 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800783 /* Send the media unmounted event first */
784 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400785 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800786
San Mehata5078592010-03-25 09:36:54 -0700787 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800788 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400789 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800790 } else {
San Mehata5078592010-03-25 09:36:54 -0700791 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800792 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400793
794 if (action != null) {
795 sendStorageIntent(action, path);
796 }
San Mehat4270e1e2010-01-29 05:32:19 -0800797 } else {
798 return false;
799 }
800
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400801 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800802 }
803
San Mehat207e5382010-02-04 20:46:54 -0800804 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800805 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700806 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800807
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800809
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500810 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700811 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400812 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500813 }
814
San Mehat4270e1e2010-01-29 05:32:19 -0800815 if (newState == VolumeState.Init) {
816 } else if (newState == VolumeState.NoMedia) {
817 // NoMedia is handled via Disk Remove events
818 } else if (newState == VolumeState.Idle) {
819 /*
820 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
821 * if we're in the process of enabling UMS
822 */
823 if (!vs.equals(
824 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
825 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800826 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700827 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800828 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400829 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800830 }
831 } else if (newState == VolumeState.Pending) {
832 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700833 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800834 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400835 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800836 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700837 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800838 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400839 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800840 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400841 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800842 } else if (newState == VolumeState.Formatting) {
843 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700844 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800845 /* Send the media unmounted event first */
846 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400847 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800848
San Mehata5078592010-03-25 09:36:54 -0700849 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800850 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400851 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700852 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800853 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700854 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800855 return;
856 } else {
San Mehata5078592010-03-25 09:36:54 -0700857 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800858 }
859
Mike Lockwooda5250c92011-05-23 13:44:04 -0400860 if (action != null) {
861 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800862 }
863 }
864
San Mehat207e5382010-02-04 20:46:54 -0800865 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800866 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800867
San Mehata5078592010-03-25 09:36:54 -0700868 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800869 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800870 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800871 } catch (NativeDaemonConnectorException e) {
872 /*
873 * Mount failed for some reason
874 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400875 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800876 int code = e.getCode();
877 if (code == VoldResponseCode.OpFailedNoMedia) {
878 /*
879 * Attempt to mount but no media inserted
880 */
San Mehatb1043402010-02-05 08:26:50 -0800881 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800882 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700883 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800884 /*
885 * Media is blank or does not contain a supported filesystem
886 */
887 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400888 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800889 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800890 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700891 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800892 /*
893 * Volume consistency check failed
894 */
895 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400896 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800897 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800898 } else {
San Mehatb1043402010-02-05 08:26:50 -0800899 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800900 }
901
902 /*
903 * Send broadcast intent (if required for the failure)
904 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400905 if (action != null) {
906 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800907 }
908 }
909
910 return rc;
911 }
912
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800913 /*
914 * If force is not set, we do not unmount if there are
915 * processes holding references to the volume about to be unmounted.
916 * If force is set, all the processes holding references need to be
917 * killed via the ActivityManager before actually unmounting the volume.
918 * This might even take a while and might be retried after timed delays
919 * to make sure we dont end up in an instable state and kill some core
920 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700921 * If removeEncryption is set, force is implied, and the system will remove any encryption
922 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800923 */
Ben Komalo13c71972011-09-07 16:35:56 -0700924 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800925 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800926 return VoldResponseCode.OpFailedVolNotMounted;
927 }
Kenny Rootaa485402010-09-14 14:49:41 -0700928
929 /*
930 * Force a GC to make sure AssetManagers in other threads of the
931 * system_server are cleaned up. We have to do this since AssetManager
932 * instances are kept as a WeakReference and it's possible we have files
933 * open on the external storage.
934 */
935 Runtime.getRuntime().gc();
936
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800937 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700938 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800939 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800940 final Command cmd = new Command("volume", "unmount", path);
941 if (removeEncryption) {
942 cmd.appendArg("force_and_revert");
943 } else if (force) {
944 cmd.appendArg("force");
945 }
946 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700947 // We unmounted the volume. None of the asec containers are available now.
948 synchronized (mAsecMountSet) {
949 mAsecMountSet.clear();
950 }
San Mehatb1043402010-02-05 08:26:50 -0800951 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800952 } catch (NativeDaemonConnectorException e) {
953 // Don't worry about mismatch in PackageManager since the
954 // call back will handle the status changes any way.
955 int code = e.getCode();
956 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800957 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800958 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
959 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800960 } else {
San Mehatb1043402010-02-05 08:26:50 -0800961 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800962 }
963 }
964 }
965
966 private int doFormatVolume(String path) {
967 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800968 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -0800969 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800970 } catch (NativeDaemonConnectorException e) {
971 int code = e.getCode();
972 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800973 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800974 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800975 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800976 } else {
San Mehatb1043402010-02-05 08:26:50 -0800977 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800978 }
979 }
980 }
981
San Mehatb1043402010-02-05 08:26:50 -0800982 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800983 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700984 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800985 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700986 } catch (NativeDaemonConnectorException ex) {
987 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
988 return false;
989 }
San Mehatb1043402010-02-05 08:26:50 -0800990
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800991 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
992 return event.getMessage().endsWith("enabled");
993 } else {
994 return false;
San Mehatb1043402010-02-05 08:26:50 -0800995 }
San Mehatb1043402010-02-05 08:26:50 -0800996 }
997
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700998 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800999 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001000 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001001 for (int i = mListeners.size() -1; i >= 0; i--) {
1002 MountServiceBinderListener bl = mListeners.get(i);
1003 try {
San Mehatb1043402010-02-05 08:26:50 -08001004 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001005 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001006 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001007 mListeners.remove(i);
1008 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001009 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001010 }
1011 }
1012 }
1013
San Mehat207e5382010-02-04 20:46:54 -08001014 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001015 sendUmsIntent(avail);
1016 } else {
1017 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001018 }
San Mehat2fe718a2010-03-11 12:01:49 -08001019
1020 final String path = Environment.getExternalStorageDirectory().getPath();
1021 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1022 /*
1023 * USB mass storage disconnected while enabled
1024 */
1025 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001026 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001027 public void run() {
1028 try {
1029 int rc;
San Mehata5078592010-03-25 09:36:54 -07001030 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001031 doShareUnshareVolume(path, "ums", false);
1032 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001033 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001034 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1035 path, rc));
1036 }
1037 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001038 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001039 }
1040 }
1041 }.start();
1042 }
San Mehat4270e1e2010-01-29 05:32:19 -08001043 }
1044
Mike Lockwooda5250c92011-05-23 13:44:04 -04001045 private void sendStorageIntent(String action, String path) {
1046 Intent intent = new Intent(action, Uri.parse("file://" + path));
1047 // add StorageVolume extra
1048 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1049 Slog.d(TAG, "sendStorageIntent " + intent);
1050 mContext.sendBroadcast(intent);
1051 }
1052
San Mehat6a965af22010-02-24 17:47:30 -08001053 private void sendUmsIntent(boolean c) {
1054 mContext.sendBroadcast(
1055 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1056 }
1057
San Mehat207e5382010-02-04 20:46:54 -08001058 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001059 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1060 throw new SecurityException(String.format("Requires %s permission", perm));
1061 }
1062 }
1063
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001064 // Storage list XML tags
1065 private static final String TAG_STORAGE_LIST = "StorageList";
1066 private static final String TAG_STORAGE = "storage";
1067
1068 private void readStorageList(Resources resources) {
1069 int id = com.android.internal.R.xml.storage_list;
1070 XmlResourceParser parser = resources.getXml(id);
1071 AttributeSet attrs = Xml.asAttributeSet(parser);
1072
1073 try {
1074 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1075 while (true) {
1076 XmlUtils.nextElement(parser);
1077
1078 String element = parser.getName();
1079 if (element == null) break;
1080
1081 if (TAG_STORAGE.equals(element)) {
1082 TypedArray a = resources.obtainAttributes(attrs,
1083 com.android.internal.R.styleable.Storage);
1084
1085 CharSequence path = a.getText(
1086 com.android.internal.R.styleable.Storage_mountPoint);
1087 CharSequence description = a.getText(
1088 com.android.internal.R.styleable.Storage_storageDescription);
1089 boolean primary = a.getBoolean(
1090 com.android.internal.R.styleable.Storage_primary, false);
1091 boolean removable = a.getBoolean(
1092 com.android.internal.R.styleable.Storage_removable, false);
1093 boolean emulated = a.getBoolean(
1094 com.android.internal.R.styleable.Storage_emulated, false);
1095 int mtpReserve = a.getInt(
1096 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001097 boolean allowMassStorage = a.getBoolean(
1098 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001099 // resource parser does not support longs, so XML value is in megabytes
1100 long maxFileSize = a.getInt(
1101 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001102
1103 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1104 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001105 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001106 " allowMassStorage: " + allowMassStorage +
1107 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001108 if (path == null || description == null) {
1109 Slog.e(TAG, "path or description is null in readStorageList");
1110 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001111 String pathString = path.toString();
1112 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001113 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001114 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001115 if (primary) {
1116 if (mPrimaryVolume == null) {
1117 mPrimaryVolume = volume;
1118 } else {
1119 Slog.e(TAG, "multiple primary volumes in storage list");
1120 }
1121 }
1122 if (mPrimaryVolume == volume) {
1123 // primay volume must be first
1124 mVolumes.add(0, volume);
1125 } else {
1126 mVolumes.add(volume);
1127 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001128 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001129 }
1130 a.recycle();
1131 }
1132 }
1133 } catch (XmlPullParserException e) {
1134 throw new RuntimeException(e);
1135 } catch (IOException e) {
1136 throw new RuntimeException(e);
1137 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001138 // compute storage ID for each volume
1139 int length = mVolumes.size();
1140 for (int i = 0; i < length; i++) {
1141 mVolumes.get(i).setStorageId(i);
1142 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001143 parser.close();
1144 }
1145 }
1146
San Mehat4270e1e2010-01-29 05:32:19 -08001147 /**
San Mehat207e5382010-02-04 20:46:54 -08001148 * Constructs a new MountService instance
1149 *
1150 * @param context Binder context for this service
1151 */
1152 public MountService(Context context) {
1153 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001154 Resources resources = context.getResources();
1155 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001156
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001157 if (mPrimaryVolume != null) {
1158 mExternalStoragePath = mPrimaryVolume.getPath();
1159 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1160 if (mEmulateExternalStorage) {
1161 Slog.d(TAG, "using emulated external storage");
1162 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1163 }
Mike Lockwood03559752010-07-19 18:25:03 -04001164 }
1165
San Mehat207e5382010-02-04 20:46:54 -08001166 // XXX: This will go away soon in favor of IMountServiceObserver
1167 mPms = (PackageManagerService) ServiceManager.getService("package");
1168
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001169 IntentFilter filter = new IntentFilter();
1170 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1171 // don't bother monitoring USB if mass storage is not supported on our primary volume
1172 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1173 filter.addAction(UsbManager.ACTION_USB_STATE);
1174 }
1175 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001176
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001177 mHandlerThread = new HandlerThread("MountService");
1178 mHandlerThread.start();
1179 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1180
Kenny Roota02b8b02010-08-05 16:14:17 -07001181 // Add OBB Action Handler to MountService thread.
1182 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1183
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001184 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001185 * Create the connection to vold with a maximum queue of twice the
1186 * amount of containers we'd ever expect to have. This keeps an
1187 * "asec list" from blocking a thread repeatedly.
1188 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001189 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001190
Kenny Root305bcbf2010-09-03 07:56:38 -07001191 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001192 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001193
Kenny Root07714d42011-08-17 17:49:28 -07001194 // Add ourself to the Watchdog monitors if enabled.
1195 if (WATCHDOG_ENABLE) {
1196 Watchdog.getInstance().addMonitor(this);
1197 }
San Mehat207e5382010-02-04 20:46:54 -08001198 }
1199
1200 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001201 * Exposed API calls below here
1202 */
1203
1204 public void registerListener(IMountServiceListener listener) {
1205 synchronized (mListeners) {
1206 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1207 try {
1208 listener.asBinder().linkToDeath(bl, 0);
1209 mListeners.add(bl);
1210 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001211 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001212 }
1213 }
1214 }
1215
1216 public void unregisterListener(IMountServiceListener listener) {
1217 synchronized (mListeners) {
1218 for(MountServiceBinderListener bl : mListeners) {
1219 if (bl.mListener == listener) {
1220 mListeners.remove(mListeners.indexOf(bl));
1221 return;
1222 }
1223 }
1224 }
1225 }
1226
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001227 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001228 validatePermission(android.Manifest.permission.SHUTDOWN);
1229
San Mehata5078592010-03-25 09:36:54 -07001230 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001231 synchronized (mVolumeStates) {
1232 for (String path : mVolumeStates.keySet()) {
1233 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001234
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001235 if (state.equals(Environment.MEDIA_SHARED)) {
1236 /*
1237 * If the media is currently shared, unshare it.
1238 * XXX: This is still dangerous!. We should not
1239 * be rebooting at *all* if UMS is enabled, since
1240 * the UMS host could have dirty FAT cache entries
1241 * yet to flush.
1242 */
1243 setUsbMassStorageEnabled(false);
1244 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1245 /*
1246 * If the media is being checked, then we need to wait for
1247 * it to complete before being able to proceed.
1248 */
1249 // XXX: @hackbod - Should we disable the ANR timer here?
1250 int retries = 30;
1251 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1252 try {
1253 Thread.sleep(1000);
1254 } catch (InterruptedException iex) {
1255 Slog.e(TAG, "Interrupted while waiting for media", iex);
1256 break;
1257 }
1258 state = Environment.getExternalStorageState();
1259 }
1260 if (retries == 0) {
1261 Slog.e(TAG, "Timed out waiting for media to check");
1262 }
San Mehat91c77612010-01-07 10:39:41 -08001263 }
San Mehat91c77612010-01-07 10:39:41 -08001264
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001265 if (state.equals(Environment.MEDIA_MOUNTED)) {
1266 // Post a unmount message.
1267 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1268 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1269 } else if (observer != null) {
1270 /*
1271 * Observer is waiting for onShutDownComplete when we are done.
1272 * Since nothing will be done send notification directly so shutdown
1273 * sequence can continue.
1274 */
1275 try {
1276 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1277 } catch (RemoteException e) {
1278 Slog.w(TAG, "RemoteException when shutting down");
1279 }
1280 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001281 }
San Mehat4270e1e2010-01-29 05:32:19 -08001282 }
1283 }
1284
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001285 private boolean getUmsEnabling() {
1286 synchronized (mListeners) {
1287 return mUmsEnabling;
1288 }
1289 }
1290
1291 private void setUmsEnabling(boolean enable) {
1292 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001293 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001294 }
1295 }
1296
San Mehatb1043402010-02-05 08:26:50 -08001297 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001298 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001299
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001300 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001301 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001302 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001303 synchronized (mListeners) {
1304 return mUmsAvailable;
1305 }
San Mehatb1043402010-02-05 08:26:50 -08001306 }
1307
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001308 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001309 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001310 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001311
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001312 // TODO: Add support for multiple share methods
1313
1314 /*
1315 * If the volume is mounted and we're enabling then unmount it
1316 */
1317 String path = Environment.getExternalStorageDirectory().getPath();
1318 String vs = getVolumeState(path);
1319 String method = "ums";
1320 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1321 // Override for isUsbMassStorageEnabled()
1322 setUmsEnabling(enable);
1323 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1324 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1325 // Clear override
1326 setUmsEnabling(false);
1327 }
1328 /*
1329 * If we disabled UMS then mount the volume
1330 */
1331 if (!enable) {
1332 doShareUnshareVolume(path, method, enable);
1333 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001334 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001335 " after disabling share method " + method);
1336 /*
1337 * Even though the mount failed, the unshare didn't so don't indicate an error.
1338 * The mountVolume() call will have set the storage state and sent the necessary
1339 * broadcasts.
1340 */
1341 }
1342 }
San Mehatb1043402010-02-05 08:26:50 -08001343 }
1344
1345 public boolean isUsbMassStorageEnabled() {
1346 waitForReady();
1347 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001349
San Mehat7fd0fee2009-12-17 07:12:23 -08001350 /**
1351 * @return state of the volume at the specified mount point
1352 */
San Mehat4270e1e2010-01-29 05:32:19 -08001353 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001354 synchronized (mVolumeStates) {
1355 String state = mVolumeStates.get(mountPoint);
1356 if (state == null) {
1357 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001358 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1359 state = Environment.MEDIA_REMOVED;
1360 } else {
1361 throw new IllegalArgumentException();
1362 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001363 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001364
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001365 return state;
1366 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001367 }
1368
Kenny Roote1ff2142010-10-12 11:20:01 -07001369 public boolean isExternalStorageEmulated() {
1370 return mEmulateExternalStorage;
1371 }
1372
San Mehat4270e1e2010-01-29 05:32:19 -08001373 public int mountVolume(String path) {
1374 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001375
San Mehat207e5382010-02-04 20:46:54 -08001376 waitForReady();
1377 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Ben Komalo13c71972011-09-07 16:35:56 -07001380 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001381 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001382 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001384 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001385 if (DEBUG_UNMOUNT) {
1386 Slog.i(TAG, "Unmounting " + path
1387 + " force = " + force
1388 + " removeEncryption = " + removeEncryption);
1389 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001390 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1391 Environment.MEDIA_REMOVED.equals(volState) ||
1392 Environment.MEDIA_SHARED.equals(volState) ||
1393 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1394 // Media already unmounted or cannot be unmounted.
1395 // TODO return valid return code when adding observer call back.
1396 return;
1397 }
Ben Komalo13c71972011-09-07 16:35:56 -07001398 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001399 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401
San Mehat4270e1e2010-01-29 05:32:19 -08001402 public int formatVolume(String path) {
1403 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001404 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001405
San Mehat207e5382010-02-04 20:46:54 -08001406 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001409 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001410 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1411 waitForReady();
1412 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001413 final String[] r = NativeDaemonEvent.filterMessageList(
1414 mConnector.executeForList("storage", "users", path),
1415 VoldResponseCode.StorageUsersListResult);
1416
San Mehatc1b4ce92010-02-16 17:13:03 -08001417 // FMT: <pid> <process name>
1418 int[] data = new int[r.length];
1419 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001420 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001421 try {
1422 data[i] = Integer.parseInt(tok[0]);
1423 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001424 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001425 return new int[0];
1426 }
1427 }
1428 return data;
1429 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001430 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001431 return new int[0];
1432 }
1433 }
1434
San Mehatb1043402010-02-05 08:26:50 -08001435 private void warnOnNotMounted() {
1436 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001437 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001438 }
1439 }
1440
San Mehat4270e1e2010-01-29 05:32:19 -08001441 public String[] getSecureContainerList() {
1442 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001443 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001444 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001445
San Mehat4270e1e2010-01-29 05:32:19 -08001446 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001447 return NativeDaemonEvent.filterMessageList(
1448 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001449 } catch (NativeDaemonConnectorException e) {
1450 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452 }
San Mehat36972292010-01-06 11:06:32 -08001453
Kenny Root6dceb882012-04-12 14:23:49 -07001454 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1455 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001456 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001457 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001458 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001459
San Mehatb1043402010-02-05 08:26:50 -08001460 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001461 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001462 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1463 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001464 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001465 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001466 }
San Mehata181b212010-02-11 06:50:20 -08001467
1468 if (rc == StorageResultCode.OperationSucceeded) {
1469 synchronized (mAsecMountSet) {
1470 mAsecMountSet.add(id);
1471 }
1472 }
San Mehat4270e1e2010-01-29 05:32:19 -08001473 return rc;
San Mehat36972292010-01-06 11:06:32 -08001474 }
1475
San Mehat4270e1e2010-01-29 05:32:19 -08001476 public int finalizeSecureContainer(String id) {
1477 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001478 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001479
San Mehatb1043402010-02-05 08:26:50 -08001480 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001481 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001482 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001483 /*
1484 * Finalization does a remount, so no need
1485 * to update mAsecMountSet
1486 */
San Mehat4270e1e2010-01-29 05:32:19 -08001487 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001488 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001489 }
San Mehat4270e1e2010-01-29 05:32:19 -08001490 return rc;
San Mehat36972292010-01-06 11:06:32 -08001491 }
1492
Kenny Root6dceb882012-04-12 14:23:49 -07001493 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1494 validatePermission(android.Manifest.permission.ASEC_CREATE);
1495 warnOnNotMounted();
1496
1497 int rc = StorageResultCode.OperationSucceeded;
1498 try {
1499 mConnector.execute("asec", "fixperms", id, gid, filename);
1500 /*
1501 * Fix permissions does a remount, so no need to update
1502 * mAsecMountSet
1503 */
1504 } catch (NativeDaemonConnectorException e) {
1505 rc = StorageResultCode.OperationFailedInternalError;
1506 }
1507 return rc;
1508 }
1509
San Mehatd9709982010-02-18 11:43:03 -08001510 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001511 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001512 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001513 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001514
Kenny Rootaa485402010-09-14 14:49:41 -07001515 /*
1516 * Force a GC to make sure AssetManagers in other threads of the
1517 * system_server are cleaned up. We have to do this since AssetManager
1518 * instances are kept as a WeakReference and it's possible we have files
1519 * open on the external storage.
1520 */
1521 Runtime.getRuntime().gc();
1522
San Mehatb1043402010-02-05 08:26:50 -08001523 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001524 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001525 final Command cmd = new Command("asec", "destroy", id);
1526 if (force) {
1527 cmd.appendArg("force");
1528 }
1529 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001530 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001531 int code = e.getCode();
1532 if (code == VoldResponseCode.OpFailedStorageBusy) {
1533 rc = StorageResultCode.OperationFailedStorageBusy;
1534 } else {
1535 rc = StorageResultCode.OperationFailedInternalError;
1536 }
San Mehat02735bc2010-01-26 15:18:08 -08001537 }
San Mehata181b212010-02-11 06:50:20 -08001538
1539 if (rc == StorageResultCode.OperationSucceeded) {
1540 synchronized (mAsecMountSet) {
1541 if (mAsecMountSet.contains(id)) {
1542 mAsecMountSet.remove(id);
1543 }
1544 }
1545 }
1546
San Mehat4270e1e2010-01-29 05:32:19 -08001547 return rc;
San Mehat36972292010-01-06 11:06:32 -08001548 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001549
San Mehat4270e1e2010-01-29 05:32:19 -08001550 public int mountSecureContainer(String id, String key, int ownerUid) {
1551 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001552 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001553 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001554
San Mehata181b212010-02-11 06:50:20 -08001555 synchronized (mAsecMountSet) {
1556 if (mAsecMountSet.contains(id)) {
1557 return StorageResultCode.OperationFailedStorageMounted;
1558 }
1559 }
1560
San Mehatb1043402010-02-05 08:26:50 -08001561 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001562 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001563 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001564 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001565 int code = e.getCode();
1566 if (code != VoldResponseCode.OpFailedStorageBusy) {
1567 rc = StorageResultCode.OperationFailedInternalError;
1568 }
San Mehat02735bc2010-01-26 15:18:08 -08001569 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001570
1571 if (rc == StorageResultCode.OperationSucceeded) {
1572 synchronized (mAsecMountSet) {
1573 mAsecMountSet.add(id);
1574 }
1575 }
San Mehat4270e1e2010-01-29 05:32:19 -08001576 return rc;
San Mehat36972292010-01-06 11:06:32 -08001577 }
1578
San Mehatd9709982010-02-18 11:43:03 -08001579 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001580 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001581 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001582 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001583
San Mehat6cdd9c02010-02-09 14:45:20 -08001584 synchronized (mAsecMountSet) {
1585 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001586 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001587 }
1588 }
1589
Kenny Rootaa485402010-09-14 14:49:41 -07001590 /*
1591 * Force a GC to make sure AssetManagers in other threads of the
1592 * system_server are cleaned up. We have to do this since AssetManager
1593 * instances are kept as a WeakReference and it's possible we have files
1594 * open on the external storage.
1595 */
1596 Runtime.getRuntime().gc();
1597
San Mehatb1043402010-02-05 08:26:50 -08001598 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001599 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001600 final Command cmd = new Command("asec", "unmount", id);
1601 if (force) {
1602 cmd.appendArg("force");
1603 }
1604 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001605 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001606 int code = e.getCode();
1607 if (code == VoldResponseCode.OpFailedStorageBusy) {
1608 rc = StorageResultCode.OperationFailedStorageBusy;
1609 } else {
1610 rc = StorageResultCode.OperationFailedInternalError;
1611 }
San Mehat02735bc2010-01-26 15:18:08 -08001612 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001613
1614 if (rc == StorageResultCode.OperationSucceeded) {
1615 synchronized (mAsecMountSet) {
1616 mAsecMountSet.remove(id);
1617 }
1618 }
San Mehat4270e1e2010-01-29 05:32:19 -08001619 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001620 }
1621
San Mehat6cdd9c02010-02-09 14:45:20 -08001622 public boolean isSecureContainerMounted(String id) {
1623 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1624 waitForReady();
1625 warnOnNotMounted();
1626
1627 synchronized (mAsecMountSet) {
1628 return mAsecMountSet.contains(id);
1629 }
1630 }
1631
San Mehat4270e1e2010-01-29 05:32:19 -08001632 public int renameSecureContainer(String oldId, String newId) {
1633 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001634 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001635 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001636
San Mehata181b212010-02-11 06:50:20 -08001637 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001638 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001639 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001640 * changed while active, we must ensure both ids are not currently mounted.
1641 */
1642 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001643 return StorageResultCode.OperationFailedStorageMounted;
1644 }
1645 }
1646
San Mehatb1043402010-02-05 08:26:50 -08001647 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001648 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001649 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001650 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001651 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001652 }
San Mehata181b212010-02-11 06:50:20 -08001653
San Mehat4270e1e2010-01-29 05:32:19 -08001654 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001655 }
1656
San Mehat4270e1e2010-01-29 05:32:19 -08001657 public String getSecureContainerPath(String id) {
1658 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001659 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001660 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001661
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001662 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001663 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001664 event = mConnector.execute("asec", "path", id);
1665 event.checkCode(VoldResponseCode.AsecPathResult);
1666 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001667 } catch (NativeDaemonConnectorException e) {
1668 int code = e.getCode();
1669 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001670 Slog.i(TAG, String.format("Container '%s' not found", id));
1671 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001672 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001673 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001674 }
1675 }
San Mehat22dd86e2010-01-12 12:21:18 -08001676 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001677
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001678 public String getSecureContainerFilesystemPath(String id) {
1679 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1680 waitForReady();
1681 warnOnNotMounted();
1682
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001683 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001684 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001685 event = mConnector.execute("asec", "fspath", id);
1686 event.checkCode(VoldResponseCode.AsecPathResult);
1687 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001688 } catch (NativeDaemonConnectorException e) {
1689 int code = e.getCode();
1690 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1691 Slog.i(TAG, String.format("Container '%s' not found", id));
1692 return null;
1693 } else {
1694 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1695 }
1696 }
1697 }
1698
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001699 public void finishMediaUpdate() {
1700 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1701 }
Kenny Root02c87302010-07-01 08:10:18 -07001702
Kenny Roota02b8b02010-08-05 16:14:17 -07001703 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1704 if (callerUid == android.os.Process.SYSTEM_UID) {
1705 return true;
1706 }
1707
Kenny Root02c87302010-07-01 08:10:18 -07001708 if (packageName == null) {
1709 return false;
1710 }
1711
Amith Yamasani483f3b02012-03-13 16:08:00 -07001712 final int packageUid = mPms.getPackageUid(packageName, UserId.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001713
1714 if (DEBUG_OBB) {
1715 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1716 packageUid + ", callerUid = " + callerUid);
1717 }
1718
1719 return callerUid == packageUid;
1720 }
1721
1722 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001723 if (filename == null) {
1724 throw new IllegalArgumentException("filename cannot be null");
1725 }
1726
Kenny Root02c87302010-07-01 08:10:18 -07001727 waitForReady();
1728 warnOnNotMounted();
1729
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001730 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001731 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001732 event = mConnector.execute("obb", "path", filename);
1733 event.checkCode(VoldResponseCode.AsecPathResult);
1734 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001735 } catch (NativeDaemonConnectorException e) {
1736 int code = e.getCode();
1737 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001738 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001739 } else {
1740 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1741 }
1742 }
1743 }
1744
1745 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001746 if (filename == null) {
1747 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001748 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001749
1750 synchronized (mObbMounts) {
1751 return mObbPathToStateMap.containsKey(filename);
1752 }
Kenny Root02c87302010-07-01 08:10:18 -07001753 }
1754
Kenny Rootaf9d6672010-10-08 09:21:39 -07001755 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001756 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001757 if (filename == null) {
1758 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001759 }
1760
1761 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001762 throw new IllegalArgumentException("token cannot be null");
1763 }
1764
Kenny Rootaf9d6672010-10-08 09:21:39 -07001765 final int callerUid = Binder.getCallingUid();
1766 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1767 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001768 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1769
1770 if (DEBUG_OBB)
1771 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001772 }
1773
Kenny Rootaf9d6672010-10-08 09:21:39 -07001774 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1775 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001776 if (filename == null) {
1777 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001778 }
1779
Kenny Rootaf9d6672010-10-08 09:21:39 -07001780 final int callerUid = Binder.getCallingUid();
1781 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1782 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001783 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001784
Kenny Roota02b8b02010-08-05 16:14:17 -07001785 if (DEBUG_OBB)
1786 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1787 }
1788
Ben Komalo444eca22011-09-01 15:17:44 -07001789 @Override
1790 public int getEncryptionState() {
1791 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1792 "no permission to access the crypt keeper");
1793
1794 waitForReady();
1795
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001796 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001797 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001798 event = mConnector.execute("cryptfs", "cryptocomplete");
1799 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001800 } catch (NumberFormatException e) {
1801 // Bad result - unexpected.
1802 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1803 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1804 } catch (NativeDaemonConnectorException e) {
1805 // Something bad happened.
1806 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1807 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1808 }
1809 }
1810
1811 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001812 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001813 if (TextUtils.isEmpty(password)) {
1814 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001815 }
1816
Jason parks8888c592011-01-20 22:46:41 -06001817 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1818 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001819
1820 waitForReady();
1821
1822 if (DEBUG_EVENTS) {
1823 Slog.i(TAG, "decrypting storage...");
1824 }
1825
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001826 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001827 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001828 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001829
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001830 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001831 if (code == 0) {
1832 // Decrypt was successful. Post a delayed message before restarting in order
1833 // to let the UI to clear itself
1834 mHandler.postDelayed(new Runnable() {
1835 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001836 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001837 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001838 } catch (NativeDaemonConnectorException e) {
1839 Slog.e(TAG, "problem executing in background", e);
1840 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001841 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001842 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001843 }
1844
1845 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001846 } catch (NativeDaemonConnectorException e) {
1847 // Decryption failed
1848 return e.getCode();
1849 }
Jason parks5af0b912010-11-29 09:05:25 -06001850 }
1851
Jason parks56aa5322011-01-07 09:01:15 -06001852 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001853 if (TextUtils.isEmpty(password)) {
1854 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001855 }
1856
Jason parks8888c592011-01-20 22:46:41 -06001857 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1858 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001859
1860 waitForReady();
1861
1862 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001863 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001864 }
1865
1866 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001867 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06001868 } catch (NativeDaemonConnectorException e) {
1869 // Encryption failed
1870 return e.getCode();
1871 }
1872
1873 return 0;
1874 }
1875
Jason parksf7b3cd42011-01-27 09:28:25 -06001876 public int changeEncryptionPassword(String password) {
1877 if (TextUtils.isEmpty(password)) {
1878 throw new IllegalArgumentException("password cannot be empty");
1879 }
1880
1881 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1882 "no permission to access the crypt keeper");
1883
1884 waitForReady();
1885
1886 if (DEBUG_EVENTS) {
1887 Slog.i(TAG, "changing encryption password...");
1888 }
1889
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001890 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06001891 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001892 event = mConnector.execute("cryptfs", "changepw", password);
1893 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06001894 } catch (NativeDaemonConnectorException e) {
1895 // Encryption failed
1896 return e.getCode();
1897 }
1898 }
1899
Christopher Tate32418be2011-10-10 13:51:12 -07001900 /**
1901 * Validate a user-supplied password string with cryptfs
1902 */
1903 @Override
1904 public int verifyEncryptionPassword(String password) throws RemoteException {
1905 // Only the system process is permitted to validate passwords
1906 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
1907 throw new SecurityException("no permission to access the crypt keeper");
1908 }
1909
1910 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1911 "no permission to access the crypt keeper");
1912
1913 if (TextUtils.isEmpty(password)) {
1914 throw new IllegalArgumentException("password cannot be empty");
1915 }
1916
1917 waitForReady();
1918
1919 if (DEBUG_EVENTS) {
1920 Slog.i(TAG, "validating encryption password...");
1921 }
1922
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001923 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07001924 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001925 event = mConnector.execute("cryptfs", "verifypw", password);
1926 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
1927 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07001928 } catch (NativeDaemonConnectorException e) {
1929 // Encryption failed
1930 return e.getCode();
1931 }
1932 }
1933
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001934 public Parcelable[] getVolumeList() {
1935 synchronized(mVolumes) {
1936 int size = mVolumes.size();
1937 Parcelable[] result = new Parcelable[size];
1938 for (int i = 0; i < size; i++) {
1939 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001940 }
1941 return result;
1942 }
1943 }
1944
Kenny Rootaf9d6672010-10-08 09:21:39 -07001945 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1946 final IBinder binder = obbState.getBinder();
1947 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001948
Kenny Rootaf9d6672010-10-08 09:21:39 -07001949 if (obbStates == null) {
1950 obbStates = new ArrayList<ObbState>();
1951 mObbMounts.put(binder, obbStates);
1952 } else {
1953 for (final ObbState o : obbStates) {
1954 if (o.filename.equals(obbState.filename)) {
1955 throw new IllegalStateException("Attempt to add ObbState twice. "
1956 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001957 }
1958 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001959 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001960
1961 obbStates.add(obbState);
1962 try {
1963 obbState.link();
1964 } catch (RemoteException e) {
1965 /*
1966 * The binder died before we could link it, so clean up our state
1967 * and return failure.
1968 */
1969 obbStates.remove(obbState);
1970 if (obbStates.isEmpty()) {
1971 mObbMounts.remove(binder);
1972 }
1973
1974 // Rethrow the error so mountObb can get it
1975 throw e;
1976 }
1977
1978 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001979 }
1980
Kenny Rootaf9d6672010-10-08 09:21:39 -07001981 private void removeObbStateLocked(ObbState obbState) {
1982 final IBinder binder = obbState.getBinder();
1983 final List<ObbState> obbStates = mObbMounts.get(binder);
1984 if (obbStates != null) {
1985 if (obbStates.remove(obbState)) {
1986 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001987 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001988 if (obbStates.isEmpty()) {
1989 mObbMounts.remove(binder);
1990 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001991 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001992
Kenny Rootaf9d6672010-10-08 09:21:39 -07001993 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001994 }
1995
Kenny Roota02b8b02010-08-05 16:14:17 -07001996 private class ObbActionHandler extends Handler {
1997 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001998 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001999
2000 ObbActionHandler(Looper l) {
2001 super(l);
2002 }
2003
2004 @Override
2005 public void handleMessage(Message msg) {
2006 switch (msg.what) {
2007 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002008 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002009
2010 if (DEBUG_OBB)
2011 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2012
2013 // If a bind was already initiated we don't really
2014 // need to do anything. The pending install
2015 // will be processed later on.
2016 if (!mBound) {
2017 // If this is the only one pending we might
2018 // have to bind to the service again.
2019 if (!connectToService()) {
2020 Slog.e(TAG, "Failed to bind to media container service");
2021 action.handleError();
2022 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002023 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002024 }
Kenny Root735de3b2010-09-30 14:11:39 -07002025
Kenny Root735de3b2010-09-30 14:11:39 -07002026 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002027 break;
2028 }
2029 case OBB_MCS_BOUND: {
2030 if (DEBUG_OBB)
2031 Slog.i(TAG, "OBB_MCS_BOUND");
2032 if (msg.obj != null) {
2033 mContainerService = (IMediaContainerService) msg.obj;
2034 }
2035 if (mContainerService == null) {
2036 // Something seriously wrong. Bail out
2037 Slog.e(TAG, "Cannot bind to media container service");
2038 for (ObbAction action : mActions) {
2039 // Indicate service bind error
2040 action.handleError();
2041 }
2042 mActions.clear();
2043 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002044 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002045 if (action != null) {
2046 action.execute(this);
2047 }
2048 } else {
2049 // Should never happen ideally.
2050 Slog.w(TAG, "Empty queue");
2051 }
2052 break;
2053 }
2054 case OBB_MCS_RECONNECT: {
2055 if (DEBUG_OBB)
2056 Slog.i(TAG, "OBB_MCS_RECONNECT");
2057 if (mActions.size() > 0) {
2058 if (mBound) {
2059 disconnectService();
2060 }
2061 if (!connectToService()) {
2062 Slog.e(TAG, "Failed to bind to media container service");
2063 for (ObbAction action : mActions) {
2064 // Indicate service bind error
2065 action.handleError();
2066 }
2067 mActions.clear();
2068 }
2069 }
2070 break;
2071 }
2072 case OBB_MCS_UNBIND: {
2073 if (DEBUG_OBB)
2074 Slog.i(TAG, "OBB_MCS_UNBIND");
2075
2076 // Delete pending install
2077 if (mActions.size() > 0) {
2078 mActions.remove(0);
2079 }
2080 if (mActions.size() == 0) {
2081 if (mBound) {
2082 disconnectService();
2083 }
2084 } else {
2085 // There are more pending requests in queue.
2086 // Just post MCS_BOUND message to trigger processing
2087 // of next pending install.
2088 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2089 }
2090 break;
2091 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002092 case OBB_FLUSH_MOUNT_STATE: {
2093 final String path = (String) msg.obj;
2094
2095 if (DEBUG_OBB)
2096 Slog.i(TAG, "Flushing all OBB state for path " + path);
2097
2098 synchronized (mObbMounts) {
2099 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2100
2101 final Iterator<Entry<String, ObbState>> i =
2102 mObbPathToStateMap.entrySet().iterator();
2103 while (i.hasNext()) {
2104 final Entry<String, ObbState> obbEntry = i.next();
2105
2106 /*
2107 * If this entry's source file is in the volume path
2108 * that got unmounted, remove it because it's no
2109 * longer valid.
2110 */
2111 if (obbEntry.getKey().startsWith(path)) {
2112 obbStatesToRemove.add(obbEntry.getValue());
2113 }
2114 }
2115
2116 for (final ObbState obbState : obbStatesToRemove) {
2117 if (DEBUG_OBB)
2118 Slog.i(TAG, "Removing state for " + obbState.filename);
2119
2120 removeObbStateLocked(obbState);
2121
2122 try {
2123 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2124 OnObbStateChangeListener.UNMOUNTED);
2125 } catch (RemoteException e) {
2126 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2127 + obbState.filename);
2128 }
2129 }
2130 }
2131 break;
2132 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002133 }
2134 }
2135
2136 private boolean connectToService() {
2137 if (DEBUG_OBB)
2138 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2139
2140 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2141 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2142 mBound = true;
2143 return true;
2144 }
2145 return false;
2146 }
2147
2148 private void disconnectService() {
2149 mContainerService = null;
2150 mBound = false;
2151 mContext.unbindService(mDefContainerConn);
2152 }
2153 }
2154
2155 abstract class ObbAction {
2156 private static final int MAX_RETRIES = 3;
2157 private int mRetries;
2158
2159 ObbState mObbState;
2160
2161 ObbAction(ObbState obbState) {
2162 mObbState = obbState;
2163 }
2164
2165 public void execute(ObbActionHandler handler) {
2166 try {
2167 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002168 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002169 mRetries++;
2170 if (mRetries > MAX_RETRIES) {
2171 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002172 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002173 handleError();
2174 return;
2175 } else {
2176 handleExecute();
2177 if (DEBUG_OBB)
2178 Slog.i(TAG, "Posting install MCS_UNBIND");
2179 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2180 }
2181 } catch (RemoteException e) {
2182 if (DEBUG_OBB)
2183 Slog.i(TAG, "Posting install MCS_RECONNECT");
2184 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2185 } catch (Exception e) {
2186 if (DEBUG_OBB)
2187 Slog.d(TAG, "Error handling OBB action", e);
2188 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002189 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002190 }
2191 }
2192
Kenny Root05105f72010-09-22 17:29:43 -07002193 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002194 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002195
2196 protected ObbInfo getObbInfo() throws IOException {
2197 ObbInfo obbInfo;
2198 try {
2199 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2200 } catch (RemoteException e) {
2201 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2202 + mObbState.filename);
2203 obbInfo = null;
2204 }
2205 if (obbInfo == null) {
2206 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2207 }
2208 return obbInfo;
2209 }
2210
Kenny Rootaf9d6672010-10-08 09:21:39 -07002211 protected void sendNewStatusOrIgnore(int status) {
2212 if (mObbState == null || mObbState.token == null) {
2213 return;
2214 }
2215
Kenny Root38cf8862010-09-26 14:18:51 -07002216 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002217 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002218 } catch (RemoteException e) {
2219 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2220 }
2221 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002222 }
2223
2224 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002225 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002226
2227 MountObbAction(ObbState obbState, String key) {
2228 super(obbState);
2229 mKey = key;
2230 }
2231
Jason parks5af0b912010-11-29 09:05:25 -06002232 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002233 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002234 waitForReady();
2235 warnOnNotMounted();
2236
Kenny Root38cf8862010-09-26 14:18:51 -07002237 final ObbInfo obbInfo = getObbInfo();
2238
Kenny Roota02b8b02010-08-05 16:14:17 -07002239 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002240 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2241 + " which is owned by " + obbInfo.packageName);
2242 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2243 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002244 }
2245
Kenny Rootaf9d6672010-10-08 09:21:39 -07002246 final boolean isMounted;
2247 synchronized (mObbMounts) {
2248 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2249 }
2250 if (isMounted) {
2251 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2252 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2253 return;
2254 }
2255
2256 /*
2257 * The filename passed in might not be the canonical name, so just
2258 * set the filename to the canonicalized version.
2259 */
2260 mObbState.filename = obbInfo.filename;
2261
2262 final String hashedKey;
2263 if (mKey == null) {
2264 hashedKey = "none";
2265 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002266 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002267 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2268
2269 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2270 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2271 SecretKey key = factory.generateSecret(ks);
2272 BigInteger bi = new BigInteger(key.getEncoded());
2273 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002274 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002275 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2276 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2277 return;
2278 } catch (InvalidKeySpecException e) {
2279 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2280 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002281 return;
2282 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002283 }
Kenny Root38cf8862010-09-26 14:18:51 -07002284
Kenny Rootaf9d6672010-10-08 09:21:39 -07002285 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002286 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002287 mConnector.execute(
2288 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002289 } catch (NativeDaemonConnectorException e) {
2290 int code = e.getCode();
2291 if (code != VoldResponseCode.OpFailedStorageBusy) {
2292 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002293 }
2294 }
2295
Kenny Rootaf9d6672010-10-08 09:21:39 -07002296 if (rc == StorageResultCode.OperationSucceeded) {
2297 if (DEBUG_OBB)
2298 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2299
2300 synchronized (mObbMounts) {
2301 addObbStateLocked(mObbState);
2302 }
2303
2304 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002305 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002306 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002307
Kenny Rootaf9d6672010-10-08 09:21:39 -07002308 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002309 }
2310 }
2311
Jason parks5af0b912010-11-29 09:05:25 -06002312 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002313 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002314 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002315 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002316
2317 @Override
2318 public String toString() {
2319 StringBuilder sb = new StringBuilder();
2320 sb.append("MountObbAction{");
2321 sb.append("filename=");
2322 sb.append(mObbState.filename);
2323 sb.append(",callerUid=");
2324 sb.append(mObbState.callerUid);
2325 sb.append(",token=");
2326 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002327 sb.append(",binder=");
2328 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002329 sb.append('}');
2330 return sb.toString();
2331 }
2332 }
2333
2334 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002335 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002336
2337 UnmountObbAction(ObbState obbState, boolean force) {
2338 super(obbState);
2339 mForceUnmount = force;
2340 }
2341
Jason parks5af0b912010-11-29 09:05:25 -06002342 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002343 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002344 waitForReady();
2345 warnOnNotMounted();
2346
Kenny Root38cf8862010-09-26 14:18:51 -07002347 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002348
Kenny Rootaf9d6672010-10-08 09:21:39 -07002349 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002350 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002351 obbState = mObbPathToStateMap.get(obbInfo.filename);
2352 }
Kenny Root38cf8862010-09-26 14:18:51 -07002353
Kenny Rootaf9d6672010-10-08 09:21:39 -07002354 if (obbState == null) {
2355 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2356 return;
2357 }
2358
2359 if (obbState.callerUid != mObbState.callerUid) {
2360 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2361 + " (owned by " + obbInfo.packageName + ")");
2362 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2363 return;
2364 }
2365
2366 mObbState.filename = obbInfo.filename;
2367
2368 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002369 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002370 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2371 if (mForceUnmount) {
2372 cmd.appendArg("force");
2373 }
2374 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002375 } catch (NativeDaemonConnectorException e) {
2376 int code = e.getCode();
2377 if (code == VoldResponseCode.OpFailedStorageBusy) {
2378 rc = StorageResultCode.OperationFailedStorageBusy;
2379 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2380 // If it's not mounted then we've already won.
2381 rc = StorageResultCode.OperationSucceeded;
2382 } else {
2383 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002384 }
2385 }
2386
Kenny Rootaf9d6672010-10-08 09:21:39 -07002387 if (rc == StorageResultCode.OperationSucceeded) {
2388 synchronized (mObbMounts) {
2389 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002390 }
2391
Kenny Rootaf9d6672010-10-08 09:21:39 -07002392 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002393 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002394 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2395 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002396 }
2397 }
2398
Jason parks5af0b912010-11-29 09:05:25 -06002399 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002400 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002401 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002402 }
2403
2404 @Override
2405 public String toString() {
2406 StringBuilder sb = new StringBuilder();
2407 sb.append("UnmountObbAction{");
2408 sb.append("filename=");
2409 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2410 sb.append(",force=");
2411 sb.append(mForceUnmount);
2412 sb.append(",callerUid=");
2413 sb.append(mObbState.callerUid);
2414 sb.append(",token=");
2415 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002416 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002417 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002418 sb.append('}');
2419 return sb.toString();
2420 }
Kenny Root02c87302010-07-01 08:10:18 -07002421 }
Kenny Root38cf8862010-09-26 14:18:51 -07002422
2423 @Override
2424 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2425 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2426 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2427 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2428 + " without permission " + android.Manifest.permission.DUMP);
2429 return;
2430 }
2431
Kenny Root38cf8862010-09-26 14:18:51 -07002432 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002433 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002434
Kenny Rootaf9d6672010-10-08 09:21:39 -07002435 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2436 while (binders.hasNext()) {
2437 Entry<IBinder, List<ObbState>> e = binders.next();
2438 pw.print(" Key="); pw.println(e.getKey().toString());
2439 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002440 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002442 }
2443 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444
2445 pw.println("");
2446 pw.println(" mObbPathToStateMap:");
2447 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2448 while (maps.hasNext()) {
2449 final Entry<String, ObbState> e = maps.next();
2450 pw.print(" "); pw.print(e.getKey());
2451 pw.print(" -> "); pw.println(e.getValue().toString());
2452 }
Kenny Root38cf8862010-09-26 14:18:51 -07002453 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002454
2455 pw.println("");
2456
2457 synchronized (mVolumes) {
2458 pw.println(" mVolumes:");
2459
2460 final int N = mVolumes.size();
2461 for (int i = 0; i < N; i++) {
2462 final StorageVolume v = mVolumes.get(i);
2463 pw.print(" ");
2464 pw.println(v.toString());
2465 }
2466 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002467
2468 pw.println();
2469 pw.println(" mConnection:");
2470 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002473 /** {@inheritDoc} */
2474 public void monitor() {
2475 if (mConnector != null) {
2476 mConnector.monitor();
2477 }
2478 }
2479}