blob: 582f0ede6c63bede36e7adaacf01be2758e9afe3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070020import com.android.internal.util.XmlUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070022import com.android.server.pm.PackageManagerService;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080023
Jason parks8888c592011-01-20 22:46:41 -060024import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070026import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070030import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070033import android.content.res.Resources;
34import android.content.res.TypedArray;
35import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070036import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070038import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070039import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070045import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080046import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080047import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080048import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
62import org.xmlpull.v1.XmlPullParser;
63import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070064
Kenny Root38cf8862010-09-26 14:18:51 -070065import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070066import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070067import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070068import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070069import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070070import java.security.spec.InvalidKeySpecException;
71import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080072import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070073import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080074import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070076import java.util.LinkedList;
77import java.util.List;
78import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070080import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Kenny Root3b1abba2010-10-13 15:00:07 -070082import javax.crypto.SecretKey;
83import javax.crypto.SecretKeyFactory;
84import javax.crypto.spec.PBEKeySpec;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086/**
San Mehatb1043402010-02-05 08:26:50 -080087 * MountService implements back-end services for platform storage
88 * management.
89 * @hide - Applications should use android.os.storage.StorageManager
90 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070092class MountService extends IMountService.Stub
93 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -060094
San Mehatb1043402010-02-05 08:26:50 -080095 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080096 private static final boolean DEBUG_UNMOUNT = false;
97 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080098 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070099
Kenny Root07714d42011-08-17 17:49:28 -0700100 // Disable this since it messes up long-running cryptfs operations.
101 private static final boolean WATCHDOG_ENABLE = false;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private static final String TAG = "MountService";
104
Kenny Root305bcbf2010-09-03 07:56:38 -0700105 private static final String VOLD_TAG = "VoldConnector";
106
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700107 /** Maximum number of ASEC containers allowed to be mounted. */
108 private static final int MAX_CONTAINERS = 250;
109
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * Internal vold volume state constants
112 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800113 class VolumeState {
114 public static final int Init = -1;
115 public static final int NoMedia = 0;
116 public static final int Idle = 1;
117 public static final int Pending = 2;
118 public static final int Checking = 3;
119 public static final int Mounted = 4;
120 public static final int Unmounting = 5;
121 public static final int Formatting = 6;
122 public static final int Shared = 7;
123 public static final int SharedMnt = 8;
124 }
125
San Mehat4270e1e2010-01-29 05:32:19 -0800126 /*
127 * Internal vold response code constants
128 */
San Mehat22dd86e2010-01-12 12:21:18 -0800129 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800130 /*
131 * 100 series - Requestion action was initiated; expect another reply
132 * before proceeding with a new command.
133 */
San Mehat22dd86e2010-01-12 12:21:18 -0800134 public static final int VolumeListResult = 110;
135 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800136 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800137
San Mehat4270e1e2010-01-29 05:32:19 -0800138 /*
139 * 200 series - Requestion action has been successfully completed.
140 */
141 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800142 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800143 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800144
San Mehat4270e1e2010-01-29 05:32:19 -0800145 /*
146 * 400 series - Command was accepted, but the requested action
147 * did not take place.
148 */
149 public static final int OpFailedNoMedia = 401;
150 public static final int OpFailedMediaBlank = 402;
151 public static final int OpFailedMediaCorrupt = 403;
152 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800153 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700154 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800155
156 /*
157 * 600 series - Unsolicited broadcasts.
158 */
San Mehat22dd86e2010-01-12 12:21:18 -0800159 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800160 public static final int VolumeDiskInserted = 630;
161 public static final int VolumeDiskRemoved = 631;
162 public static final int VolumeBadRemoval = 632;
163 }
164
San Mehat4270e1e2010-01-29 05:32:19 -0800165 private Context mContext;
166 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700167 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
168 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400169 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400170 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400171 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800172 private PackageManagerService mPms;
173 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700174 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800175 // Used as a lock for methods that register/unregister listeners.
176 final private ArrayList<MountServiceBinderListener> mListeners =
177 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800178 private boolean mBooted = false;
179 private boolean mReady = false;
180 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400181 // true if we should fake MEDIA_MOUNTED state for external storage
182 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800183
San Mehat6cdd9c02010-02-09 14:45:20 -0800184 /**
185 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800186 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800187 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800188 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800189
Kenny Root02c87302010-07-01 08:10:18 -0700190 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700191 * The size of the crypto algorithm key in bits for OBB files. Currently
192 * Twofish is used which takes 128-bit keys.
193 */
194 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
195
196 /**
197 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
198 * 1024 is reasonably secure and not too slow.
199 */
200 private static final int PBKDF2_HASH_ROUNDS = 1024;
201
202 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 * Mounted OBB tracking information. Used to track the current state of all
204 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700205 */
Kenny Root735de3b2010-09-30 14:11:39 -0700206 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700207 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
208
209 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700210 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700211 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700212 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700213 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700214 this.token = token;
215 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700216 }
217
218 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700219 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700220
221 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700222 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700223
Kenny Rootaf9d6672010-10-08 09:21:39 -0700224 // Token of remote Binder caller
225 final IObbActionListener token;
226
227 // Identifier to pass back to the token
228 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700229
Kenny Root735de3b2010-09-30 14:11:39 -0700230 public IBinder getBinder() {
231 return token.asBinder();
232 }
233
Kenny Roota02b8b02010-08-05 16:14:17 -0700234 @Override
235 public void binderDied() {
236 ObbAction action = new UnmountObbAction(this, true);
237 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700238 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700239
Kenny Root5919ac62010-10-05 09:49:40 -0700240 public void link() throws RemoteException {
241 getBinder().linkToDeath(this, 0);
242 }
243
244 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700245 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700246 }
Kenny Root38cf8862010-09-26 14:18:51 -0700247
248 @Override
249 public String toString() {
250 StringBuilder sb = new StringBuilder("ObbState{");
251 sb.append("filename=");
252 sb.append(filename);
253 sb.append(",token=");
254 sb.append(token.toString());
255 sb.append(",callerUid=");
256 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700257 sb.append('}');
258 return sb.toString();
259 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700260 }
261
262 // OBB Action Handler
263 final private ObbActionHandler mObbActionHandler;
264
265 // OBB action handler messages
266 private static final int OBB_RUN_ACTION = 1;
267 private static final int OBB_MCS_BOUND = 2;
268 private static final int OBB_MCS_UNBIND = 3;
269 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700270 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700271
272 /*
273 * Default Container Service information
274 */
275 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
276 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
277
278 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
279
280 class DefaultContainerConnection implements ServiceConnection {
281 public void onServiceConnected(ComponentName name, IBinder service) {
282 if (DEBUG_OBB)
283 Slog.i(TAG, "onServiceConnected");
284 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
285 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
286 }
287
288 public void onServiceDisconnected(ComponentName name) {
289 if (DEBUG_OBB)
290 Slog.i(TAG, "onServiceDisconnected");
291 }
292 };
293
294 // Used in the ObbActionHandler
295 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700296
297 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800298 private static final int H_UNMOUNT_PM_UPDATE = 1;
299 private static final int H_UNMOUNT_PM_DONE = 2;
300 private static final int H_UNMOUNT_MS = 3;
301 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
302 private static final int MAX_UNMOUNT_RETRIES = 4;
303
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800304 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700305 final String path;
306 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700307 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800308 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800309
Ben Komalo13c71972011-09-07 16:35:56 -0700310 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800311 retries = 0;
312 this.path = path;
313 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700314 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800315 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800316
317 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700318 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700319 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800320 }
321 }
322
323 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700324 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800325
326 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700327 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800328 this.method = method;
329 }
330
331 @Override
332 void handleFinished() {
333 super.handleFinished();
334 doShareUnshareVolume(path, method, true);
335 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800336 }
337
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800338 class ShutdownCallBack extends UnmountCallBack {
339 IMountShutdownObserver observer;
340 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700341 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800342 this.observer = observer;
343 }
344
345 @Override
346 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700347 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800348 if (observer != null) {
349 try {
350 observer.onShutDownComplete(ret);
351 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700352 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800353 }
354 }
355 }
356 }
357
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400358 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700360 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800361
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400362 MountServiceHandler(Looper l) {
363 super(l);
364 }
365
Jason parks5af0b912010-11-29 09:05:25 -0600366 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800367 public void handleMessage(Message msg) {
368 switch (msg.what) {
369 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700370 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800371 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
372 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700373 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800374 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700375 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700376 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700377 mUpdatingStatus = true;
378 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800379 }
380 break;
381 }
382 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700383 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700384 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700385 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800386 int size = mForceUnmounts.size();
387 int sizeArr[] = new int[size];
388 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700389 // Kill processes holding references first
390 ActivityManagerService ams = (ActivityManagerService)
391 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 for (int i = 0; i < size; i++) {
393 UnmountCallBack ucb = mForceUnmounts.get(i);
394 String path = ucb.path;
395 boolean done = false;
396 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800397 done = true;
398 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800399 int pids[] = getStorageUsers(path);
400 if (pids == null || pids.length == 0) {
401 done = true;
402 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800404 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700405 // Confirm if file references have been freed.
406 pids = getStorageUsers(path);
407 if (pids == null || pids.length == 0) {
408 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 }
410 }
411 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700412 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
413 // Retry again
414 Slog.i(TAG, "Retrying to kill storage users again");
415 mHandler.sendMessageDelayed(
416 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
417 ucb.retries++),
418 RETRY_UNMOUNT_DELAY);
419 } else {
420 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
421 Slog.i(TAG, "Failed to unmount media inspite of " +
422 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
423 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800424 sizeArr[sizeArrN++] = i;
425 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
426 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800427 }
428 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800429 // Remove already processed elements from list.
430 for (int i = (sizeArrN-1); i >= 0; i--) {
431 mForceUnmounts.remove(sizeArr[i]);
432 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800433 break;
434 }
435 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700436 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800437 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800438 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 break;
440 }
441 }
442 }
443 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400444 final private HandlerThread mHandlerThread;
445 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800446
San Mehat207e5382010-02-04 20:46:54 -0800447 private void waitForReady() {
448 while (mReady == false) {
449 for (int retries = 5; retries > 0; retries--) {
450 if (mReady) {
451 return;
452 }
453 SystemClock.sleep(1000);
454 }
San Mehata5078592010-03-25 09:36:54 -0700455 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800456 }
San Mehat1f6301e2010-01-07 22:40:27 -0800457 }
Kenny Root02c87302010-07-01 08:10:18 -0700458
Ben Komalo444eca22011-09-01 15:17:44 -0700459 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600460 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800462 String action = intent.getAction();
463
464 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800465 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800466
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800467 /*
468 * In the simulator, we need to broadcast a volume mounted event
469 * to make the media scanner run.
470 */
471 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400472 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
473 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800474 return;
475 }
San Mehatfafb0412010-02-18 19:40:04 -0800476 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600477 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800478 public void run() {
479 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400480 // it is not safe to call vold with mVolumeStates locked
481 // so we make a copy of the paths and states and process them
482 // outside the lock
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700483 String[] paths;
484 String[] states;
Mike Lockwood84338c42011-04-05 10:05:47 -0400485 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400486 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400487 Set<String> keys = mVolumeStates.keySet();
488 count = keys.size();
Ben Komalo444eca22011-09-01 15:17:44 -0700489 paths = keys.toArray(new String[count]);
Mike Lockwood84338c42011-04-05 10:05:47 -0400490 states = new String[count];
491 for (int i = 0; i < count; i++) {
492 states[i] = mVolumeStates.get(paths[i]);
493 }
494 }
San Mehat6a254402010-03-22 10:21:00 -0700495
Mike Lockwood84338c42011-04-05 10:05:47 -0400496 for (int i = 0; i < count; i++) {
497 String path = paths[i];
498 String state = states[i];
499
500 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
501 int rc = doMountVolume(path);
502 if (rc != StorageResultCode.OperationSucceeded) {
503 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
504 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400505 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400506 } else if (state.equals(Environment.MEDIA_SHARED)) {
507 /*
508 * Bootstrap UMS enabled state since vold indicates
509 * the volume is shared (runtime restart while ums enabled)
510 */
511 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
512 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800513 }
514 }
San Mehat6a254402010-03-22 10:21:00 -0700515
Mike Lockwood80e0a412011-04-05 10:21:51 -0400516 /* notify external storage has mounted to trigger media scanner */
517 if (mEmulateExternalStorage) {
518 notifyVolumeStateChange(null,
519 Environment.getExternalStorageDirectory().getPath(),
520 VolumeState.NoMedia, VolumeState.Mounted);
521 }
522
San Mehat6a965af22010-02-24 17:47:30 -0800523 /*
San Mehat6a254402010-03-22 10:21:00 -0700524 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800525 * now that we're up.
526 */
527 if (mSendUmsConnectedOnBoot) {
528 sendUmsIntent(true);
529 mSendUmsConnectedOnBoot = false;
530 }
San Mehatfafb0412010-02-18 19:40:04 -0800531 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700532 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800533 }
San Mehat207e5382010-02-04 20:46:54 -0800534 }
San Mehatfafb0412010-02-18 19:40:04 -0800535 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700536 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
537 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
538 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
539 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541 }
542 };
San Mehat4270e1e2010-01-29 05:32:19 -0800543 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
544 final IMountServiceListener mListener;
545
546 MountServiceBinderListener(IMountServiceListener listener) {
547 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700548
San Mehat91c77612010-01-07 10:39:41 -0800549 }
550
San Mehat4270e1e2010-01-29 05:32:19 -0800551 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700552 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700553 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800554 mListeners.remove(this);
555 mListener.asBinder().unlinkToDeath(this, 0);
556 }
557 }
558 }
559
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800560 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800561 // TODO: Add support for multiple share methods
562 if (!method.equals("ums")) {
563 throw new IllegalArgumentException(String.format("Method %s not supported", method));
564 }
565
San Mehat4270e1e2010-01-29 05:32:19 -0800566 try {
567 mConnector.doCommand(String.format(
568 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
569 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700570 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800571 }
San Mehat4270e1e2010-01-29 05:32:19 -0800572 }
573
San Mehat207e5382010-02-04 20:46:54 -0800574 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400575 String oldState;
576 synchronized(mVolumeStates) {
577 oldState = mVolumeStates.put(path, state);
578 }
579 if (state.equals(oldState)) {
580 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
581 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800582 return;
583 }
San Mehatb1043402010-02-05 08:26:50 -0800584
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400585 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700586
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400587 if (path.equals(mExternalStoragePath)) {
588 // Update state on PackageManager, but only of real events
589 if (!mEmulateExternalStorage) {
590 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
591 mPms.updateExternalMediaStatus(false, false);
592
593 /*
594 * Some OBBs might have been unmounted when this volume was
595 * unmounted, so send a message to the handler to let it know to
596 * remove those from the list of mounted OBBS.
597 */
598 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
599 OBB_FLUSH_MOUNT_STATE, path));
600 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
601 mPms.updateExternalMediaStatus(true, false);
602 }
Mike Lockwood03559752010-07-19 18:25:03 -0400603 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800604 }
San Mehat4270e1e2010-01-29 05:32:19 -0800605 synchronized (mListeners) {
606 for (int i = mListeners.size() -1; i >= 0; i--) {
607 MountServiceBinderListener bl = mListeners.get(i);
608 try {
San Mehatb1043402010-02-05 08:26:50 -0800609 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800610 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700611 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800612 mListeners.remove(i);
613 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700614 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800615 }
616 }
617 }
618 }
619
620 /**
621 *
622 * Callback from NativeDaemonConnector
623 */
624 public void onDaemonConnected() {
625 /*
626 * Since we'll be calling back into the NativeDaemonConnector,
627 * we need to do our work in a new thread.
628 */
629 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600630 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800631 public void run() {
632 /**
633 * Determine media state and UMS detection status
634 */
San Mehat4270e1e2010-01-29 05:32:19 -0800635 try {
636 String[] vols = mConnector.doListCommand(
637 "volume list", VoldResponseCode.VolumeListResult);
638 for (String volstr : vols) {
639 String[] tok = volstr.split(" ");
640 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400641 String path = tok[1];
642 String state = Environment.MEDIA_REMOVED;
643
San Mehat4270e1e2010-01-29 05:32:19 -0800644 int st = Integer.parseInt(tok[2]);
645 if (st == VolumeState.NoMedia) {
646 state = Environment.MEDIA_REMOVED;
647 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800648 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800649 } else if (st == VolumeState.Mounted) {
650 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700651 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800652 } else if (st == VolumeState.Shared) {
653 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700654 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800655 } else {
656 throw new Exception(String.format("Unexpected state %d", st));
657 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400658
659 if (state != null) {
660 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
661 updatePublicVolumeState(path, state);
662 }
San Mehat4270e1e2010-01-29 05:32:19 -0800663 }
664 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700665 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400666 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800667 }
668
San Mehat207e5382010-02-04 20:46:54 -0800669 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600670 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800671 * the hounds!
672 */
673 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800674 }
675 }.start();
676 }
677
678 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800679 * Callback from NativeDaemonConnector
680 */
681 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800682 if (DEBUG_EVENTS) {
683 StringBuilder builder = new StringBuilder();
684 builder.append("onEvent::");
685 builder.append(" raw= " + raw);
686 if (cooked != null) {
687 builder.append(" cooked = " );
688 for (String str : cooked) {
689 builder.append(" " + str);
690 }
691 }
San Mehata5078592010-03-25 09:36:54 -0700692 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800693 }
San Mehat4270e1e2010-01-29 05:32:19 -0800694 if (code == VoldResponseCode.VolumeStateChange) {
695 /*
696 * One of the volumes we're managing has changed state.
697 * Format: "NNN Volume <label> <path> state changed
698 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
699 */
700 notifyVolumeStateChange(
701 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
702 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800703 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
704 (code == VoldResponseCode.VolumeDiskRemoved) ||
705 (code == VoldResponseCode.VolumeBadRemoval)) {
706 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
707 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
708 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400709 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800710 final String label = cooked[2];
711 final String path = cooked[3];
712 int major = -1;
713 int minor = -1;
714
715 try {
716 String devComp = cooked[6].substring(1, cooked[6].length() -1);
717 String[] devTok = devComp.split(":");
718 major = Integer.parseInt(devTok[0]);
719 minor = Integer.parseInt(devTok[1]);
720 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700721 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800722 }
723
San Mehat4270e1e2010-01-29 05:32:19 -0800724 if (code == VoldResponseCode.VolumeDiskInserted) {
725 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600726 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800727 public void run() {
728 try {
729 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800730 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700731 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800732 }
733 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700734 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800735 }
736 }
737 }.start();
738 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
739 /*
740 * This event gets trumped if we're already in BAD_REMOVAL state
741 */
742 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
743 return true;
744 }
745 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700746 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800747 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400748 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800749
San Mehata5078592010-03-25 09:36:54 -0700750 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800751 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400752 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800753 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700754 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800755 /* Send the media unmounted event first */
756 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400757 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800758
San Mehata5078592010-03-25 09:36:54 -0700759 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800760 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400761 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800762 } else {
San Mehata5078592010-03-25 09:36:54 -0700763 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800764 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400765
766 if (action != null) {
767 sendStorageIntent(action, path);
768 }
San Mehat4270e1e2010-01-29 05:32:19 -0800769 } else {
770 return false;
771 }
772
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400773 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800774 }
775
San Mehat207e5382010-02-04 20:46:54 -0800776 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800777 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700778 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800779
Mike Lockwooda5250c92011-05-23 13:44:04 -0400780 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800781
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500782 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700783 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400784 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500785 }
786
San Mehat4270e1e2010-01-29 05:32:19 -0800787 if (newState == VolumeState.Init) {
788 } else if (newState == VolumeState.NoMedia) {
789 // NoMedia is handled via Disk Remove events
790 } else if (newState == VolumeState.Idle) {
791 /*
792 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
793 * if we're in the process of enabling UMS
794 */
795 if (!vs.equals(
796 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
797 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800798 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700799 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800800 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400801 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800802 }
803 } else if (newState == VolumeState.Pending) {
804 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700805 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800806 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400807 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800808 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700809 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800810 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400811 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800812 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400813 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800814 } else if (newState == VolumeState.Formatting) {
815 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700816 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800817 /* Send the media unmounted event first */
818 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400819 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800820
San Mehata5078592010-03-25 09:36:54 -0700821 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800822 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400823 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700824 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800825 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700826 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800827 return;
828 } else {
San Mehata5078592010-03-25 09:36:54 -0700829 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800830 }
831
Mike Lockwooda5250c92011-05-23 13:44:04 -0400832 if (action != null) {
833 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800834 }
835 }
836
San Mehat207e5382010-02-04 20:46:54 -0800837 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800838 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800839
San Mehata5078592010-03-25 09:36:54 -0700840 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800841 try {
842 mConnector.doCommand(String.format("volume mount %s", path));
843 } catch (NativeDaemonConnectorException e) {
844 /*
845 * Mount failed for some reason
846 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400847 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800848 int code = e.getCode();
849 if (code == VoldResponseCode.OpFailedNoMedia) {
850 /*
851 * Attempt to mount but no media inserted
852 */
San Mehatb1043402010-02-05 08:26:50 -0800853 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800854 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700855 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800856 /*
857 * Media is blank or does not contain a supported filesystem
858 */
859 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400860 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800861 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800862 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700863 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800864 /*
865 * Volume consistency check failed
866 */
867 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400868 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800869 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800870 } else {
San Mehatb1043402010-02-05 08:26:50 -0800871 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800872 }
873
874 /*
875 * Send broadcast intent (if required for the failure)
876 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400877 if (action != null) {
878 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800879 }
880 }
881
882 return rc;
883 }
884
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800885 /*
886 * If force is not set, we do not unmount if there are
887 * processes holding references to the volume about to be unmounted.
888 * If force is set, all the processes holding references need to be
889 * killed via the ActivityManager before actually unmounting the volume.
890 * This might even take a while and might be retried after timed delays
891 * to make sure we dont end up in an instable state and kill some core
892 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700893 * If removeEncryption is set, force is implied, and the system will remove any encryption
894 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800895 */
Ben Komalo13c71972011-09-07 16:35:56 -0700896 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800897 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800898 return VoldResponseCode.OpFailedVolNotMounted;
899 }
Kenny Rootaa485402010-09-14 14:49:41 -0700900
901 /*
902 * Force a GC to make sure AssetManagers in other threads of the
903 * system_server are cleaned up. We have to do this since AssetManager
904 * instances are kept as a WeakReference and it's possible we have files
905 * open on the external storage.
906 */
907 Runtime.getRuntime().gc();
908
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800909 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700910 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800911 try {
Ben Komalo13c71972011-09-07 16:35:56 -0700912 String arg = removeEncryption
913 ? " force_and_revert"
914 : (force ? " force" : "");
915 mConnector.doCommand(String.format("volume unmount %s%s", path, arg));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700916 // We unmounted the volume. None of the asec containers are available now.
917 synchronized (mAsecMountSet) {
918 mAsecMountSet.clear();
919 }
San Mehatb1043402010-02-05 08:26:50 -0800920 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800921 } catch (NativeDaemonConnectorException e) {
922 // Don't worry about mismatch in PackageManager since the
923 // call back will handle the status changes any way.
924 int code = e.getCode();
925 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800926 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800927 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
928 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800929 } else {
San Mehatb1043402010-02-05 08:26:50 -0800930 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800931 }
932 }
933 }
934
935 private int doFormatVolume(String path) {
936 try {
937 String cmd = String.format("volume format %s", path);
938 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800939 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800940 } catch (NativeDaemonConnectorException e) {
941 int code = e.getCode();
942 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800943 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800944 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800945 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800946 } else {
San Mehatb1043402010-02-05 08:26:50 -0800947 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800948 }
949 }
950 }
951
San Mehatb1043402010-02-05 08:26:50 -0800952 private boolean doGetVolumeShared(String path, String method) {
953 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700954 ArrayList<String> rsp;
955
956 try {
957 rsp = mConnector.doCommand(cmd);
958 } catch (NativeDaemonConnectorException ex) {
959 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
960 return false;
961 }
San Mehatb1043402010-02-05 08:26:50 -0800962
963 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700964 String[] tok = line.split(" ");
965 if (tok.length < 3) {
966 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
967 return false;
968 }
969
San Mehatb1043402010-02-05 08:26:50 -0800970 int code;
971 try {
972 code = Integer.parseInt(tok[0]);
973 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700974 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800975 return false;
976 }
977 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700978 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800979 } else {
San Mehata5078592010-03-25 09:36:54 -0700980 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800981 return false;
982 }
983 }
San Mehata5078592010-03-25 09:36:54 -0700984 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800985 return false;
986 }
987
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700988 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800989 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700990 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800991 for (int i = mListeners.size() -1; i >= 0; i--) {
992 MountServiceBinderListener bl = mListeners.get(i);
993 try {
San Mehatb1043402010-02-05 08:26:50 -0800994 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800995 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700996 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800997 mListeners.remove(i);
998 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700999 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001000 }
1001 }
1002 }
1003
San Mehat207e5382010-02-04 20:46:54 -08001004 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001005 sendUmsIntent(avail);
1006 } else {
1007 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001008 }
San Mehat2fe718a2010-03-11 12:01:49 -08001009
1010 final String path = Environment.getExternalStorageDirectory().getPath();
1011 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1012 /*
1013 * USB mass storage disconnected while enabled
1014 */
1015 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001016 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001017 public void run() {
1018 try {
1019 int rc;
San Mehata5078592010-03-25 09:36:54 -07001020 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001021 doShareUnshareVolume(path, "ums", false);
1022 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001023 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001024 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1025 path, rc));
1026 }
1027 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001028 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001029 }
1030 }
1031 }.start();
1032 }
San Mehat4270e1e2010-01-29 05:32:19 -08001033 }
1034
Mike Lockwooda5250c92011-05-23 13:44:04 -04001035 private void sendStorageIntent(String action, String path) {
1036 Intent intent = new Intent(action, Uri.parse("file://" + path));
1037 // add StorageVolume extra
1038 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1039 Slog.d(TAG, "sendStorageIntent " + intent);
1040 mContext.sendBroadcast(intent);
1041 }
1042
San Mehat6a965af22010-02-24 17:47:30 -08001043 private void sendUmsIntent(boolean c) {
1044 mContext.sendBroadcast(
1045 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1046 }
1047
San Mehat207e5382010-02-04 20:46:54 -08001048 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001049 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1050 throw new SecurityException(String.format("Requires %s permission", perm));
1051 }
1052 }
1053
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001054 // Storage list XML tags
1055 private static final String TAG_STORAGE_LIST = "StorageList";
1056 private static final String TAG_STORAGE = "storage";
1057
1058 private void readStorageList(Resources resources) {
1059 int id = com.android.internal.R.xml.storage_list;
1060 XmlResourceParser parser = resources.getXml(id);
1061 AttributeSet attrs = Xml.asAttributeSet(parser);
1062
1063 try {
1064 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1065 while (true) {
1066 XmlUtils.nextElement(parser);
1067
1068 String element = parser.getName();
1069 if (element == null) break;
1070
1071 if (TAG_STORAGE.equals(element)) {
1072 TypedArray a = resources.obtainAttributes(attrs,
1073 com.android.internal.R.styleable.Storage);
1074
1075 CharSequence path = a.getText(
1076 com.android.internal.R.styleable.Storage_mountPoint);
1077 CharSequence description = a.getText(
1078 com.android.internal.R.styleable.Storage_storageDescription);
1079 boolean primary = a.getBoolean(
1080 com.android.internal.R.styleable.Storage_primary, false);
1081 boolean removable = a.getBoolean(
1082 com.android.internal.R.styleable.Storage_removable, false);
1083 boolean emulated = a.getBoolean(
1084 com.android.internal.R.styleable.Storage_emulated, false);
1085 int mtpReserve = a.getInt(
1086 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001087 boolean allowMassStorage = a.getBoolean(
1088 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001089 // resource parser does not support longs, so XML value is in megabytes
1090 long maxFileSize = a.getInt(
1091 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001092
1093 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1094 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001095 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001096 " allowMassStorage: " + allowMassStorage +
1097 " maxFileSize: " + maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001098 if (path == null || description == null) {
1099 Slog.e(TAG, "path or description is null in readStorageList");
1100 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001101 String pathString = path.toString();
1102 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001103 description.toString(), removable, emulated,
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001104 mtpReserve, allowMassStorage, maxFileSize);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001105 if (primary) {
1106 if (mPrimaryVolume == null) {
1107 mPrimaryVolume = volume;
1108 } else {
1109 Slog.e(TAG, "multiple primary volumes in storage list");
1110 }
1111 }
1112 if (mPrimaryVolume == volume) {
1113 // primay volume must be first
1114 mVolumes.add(0, volume);
1115 } else {
1116 mVolumes.add(volume);
1117 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001118 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001119 }
1120 a.recycle();
1121 }
1122 }
1123 } catch (XmlPullParserException e) {
1124 throw new RuntimeException(e);
1125 } catch (IOException e) {
1126 throw new RuntimeException(e);
1127 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001128 // compute storage ID for each volume
1129 int length = mVolumes.size();
1130 for (int i = 0; i < length; i++) {
1131 mVolumes.get(i).setStorageId(i);
1132 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001133 parser.close();
1134 }
1135 }
1136
San Mehat4270e1e2010-01-29 05:32:19 -08001137 /**
San Mehat207e5382010-02-04 20:46:54 -08001138 * Constructs a new MountService instance
1139 *
1140 * @param context Binder context for this service
1141 */
1142 public MountService(Context context) {
1143 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001144 Resources resources = context.getResources();
1145 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001146
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001147 if (mPrimaryVolume != null) {
1148 mExternalStoragePath = mPrimaryVolume.getPath();
1149 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1150 if (mEmulateExternalStorage) {
1151 Slog.d(TAG, "using emulated external storage");
1152 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1153 }
Mike Lockwood03559752010-07-19 18:25:03 -04001154 }
1155
San Mehat207e5382010-02-04 20:46:54 -08001156 // XXX: This will go away soon in favor of IMountServiceObserver
1157 mPms = (PackageManagerService) ServiceManager.getService("package");
1158
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001159 IntentFilter filter = new IntentFilter();
1160 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1161 // don't bother monitoring USB if mass storage is not supported on our primary volume
1162 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1163 filter.addAction(UsbManager.ACTION_USB_STATE);
1164 }
1165 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001166
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001167 mHandlerThread = new HandlerThread("MountService");
1168 mHandlerThread.start();
1169 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1170
Kenny Roota02b8b02010-08-05 16:14:17 -07001171 // Add OBB Action Handler to MountService thread.
1172 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1173
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001174 /*
1175 * Vold does not run in the simulator, so pretend the connector thread
1176 * ran and did its thing.
1177 */
1178 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1179 mReady = true;
1180 mUmsEnabling = true;
1181 return;
1182 }
1183
Kenny Root305bcbf2010-09-03 07:56:38 -07001184 /*
1185 * 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 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001189 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001190 mReady = false;
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 {
1413 String[] r = mConnector.doListCommand(
1414 String.format("storage users %s", path),
1415 VoldResponseCode.StorageUsersListResult);
1416 // FMT: <pid> <process name>
1417 int[] data = new int[r.length];
1418 for (int i = 0; i < r.length; i++) {
1419 String []tok = r[i].split(" ");
1420 try {
1421 data[i] = Integer.parseInt(tok[0]);
1422 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001423 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001424 return new int[0];
1425 }
1426 }
1427 return data;
1428 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001429 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001430 return new int[0];
1431 }
1432 }
1433
San Mehatb1043402010-02-05 08:26:50 -08001434 private void warnOnNotMounted() {
1435 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001436 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001437 }
1438 }
1439
San Mehat4270e1e2010-01-29 05:32:19 -08001440 public String[] getSecureContainerList() {
1441 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001442 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001443 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001444
San Mehat4270e1e2010-01-29 05:32:19 -08001445 try {
1446 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1447 } catch (NativeDaemonConnectorException e) {
1448 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
1450 }
San Mehat36972292010-01-06 11:06:32 -08001451
San Mehat4270e1e2010-01-29 05:32:19 -08001452 public int createSecureContainer(String id, int sizeMb, String fstype,
1453 String key, int ownerUid) {
1454 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001455 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001456 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001457
San Mehatb1043402010-02-05 08:26:50 -08001458 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001459 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1460 try {
1461 mConnector.doCommand(cmd);
1462 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001463 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001464 }
San Mehata181b212010-02-11 06:50:20 -08001465
1466 if (rc == StorageResultCode.OperationSucceeded) {
1467 synchronized (mAsecMountSet) {
1468 mAsecMountSet.add(id);
1469 }
1470 }
San Mehat4270e1e2010-01-29 05:32:19 -08001471 return rc;
San Mehat36972292010-01-06 11:06:32 -08001472 }
1473
San Mehat4270e1e2010-01-29 05:32:19 -08001474 public int finalizeSecureContainer(String id) {
1475 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001476 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001477
San Mehatb1043402010-02-05 08:26:50 -08001478 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001479 try {
1480 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001481 /*
1482 * Finalization does a remount, so no need
1483 * to update mAsecMountSet
1484 */
San Mehat4270e1e2010-01-29 05:32:19 -08001485 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001486 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001487 }
San Mehat4270e1e2010-01-29 05:32:19 -08001488 return rc;
San Mehat36972292010-01-06 11:06:32 -08001489 }
1490
San Mehatd9709982010-02-18 11:43:03 -08001491 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001492 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001493 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001494 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001495
Kenny Rootaa485402010-09-14 14:49:41 -07001496 /*
1497 * Force a GC to make sure AssetManagers in other threads of the
1498 * system_server are cleaned up. We have to do this since AssetManager
1499 * instances are kept as a WeakReference and it's possible we have files
1500 * open on the external storage.
1501 */
1502 Runtime.getRuntime().gc();
1503
San Mehatb1043402010-02-05 08:26:50 -08001504 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001505 try {
San Mehatd9709982010-02-18 11:43:03 -08001506 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001507 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001508 int code = e.getCode();
1509 if (code == VoldResponseCode.OpFailedStorageBusy) {
1510 rc = StorageResultCode.OperationFailedStorageBusy;
1511 } else {
1512 rc = StorageResultCode.OperationFailedInternalError;
1513 }
San Mehat02735bc2010-01-26 15:18:08 -08001514 }
San Mehata181b212010-02-11 06:50:20 -08001515
1516 if (rc == StorageResultCode.OperationSucceeded) {
1517 synchronized (mAsecMountSet) {
1518 if (mAsecMountSet.contains(id)) {
1519 mAsecMountSet.remove(id);
1520 }
1521 }
1522 }
1523
San Mehat4270e1e2010-01-29 05:32:19 -08001524 return rc;
San Mehat36972292010-01-06 11:06:32 -08001525 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001526
San Mehat4270e1e2010-01-29 05:32:19 -08001527 public int mountSecureContainer(String id, String key, int ownerUid) {
1528 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001529 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001530 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001531
San Mehata181b212010-02-11 06:50:20 -08001532 synchronized (mAsecMountSet) {
1533 if (mAsecMountSet.contains(id)) {
1534 return StorageResultCode.OperationFailedStorageMounted;
1535 }
1536 }
1537
San Mehatb1043402010-02-05 08:26:50 -08001538 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001539 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1540 try {
1541 mConnector.doCommand(cmd);
1542 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001543 int code = e.getCode();
1544 if (code != VoldResponseCode.OpFailedStorageBusy) {
1545 rc = StorageResultCode.OperationFailedInternalError;
1546 }
San Mehat02735bc2010-01-26 15:18:08 -08001547 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001548
1549 if (rc == StorageResultCode.OperationSucceeded) {
1550 synchronized (mAsecMountSet) {
1551 mAsecMountSet.add(id);
1552 }
1553 }
San Mehat4270e1e2010-01-29 05:32:19 -08001554 return rc;
San Mehat36972292010-01-06 11:06:32 -08001555 }
1556
San Mehatd9709982010-02-18 11:43:03 -08001557 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001558 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001559 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001560 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001561
San Mehat6cdd9c02010-02-09 14:45:20 -08001562 synchronized (mAsecMountSet) {
1563 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001564 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001565 }
1566 }
1567
Kenny Rootaa485402010-09-14 14:49:41 -07001568 /*
1569 * Force a GC to make sure AssetManagers in other threads of the
1570 * system_server are cleaned up. We have to do this since AssetManager
1571 * instances are kept as a WeakReference and it's possible we have files
1572 * open on the external storage.
1573 */
1574 Runtime.getRuntime().gc();
1575
San Mehatb1043402010-02-05 08:26:50 -08001576 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001577 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001578 try {
1579 mConnector.doCommand(cmd);
1580 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001581 int code = e.getCode();
1582 if (code == VoldResponseCode.OpFailedStorageBusy) {
1583 rc = StorageResultCode.OperationFailedStorageBusy;
1584 } else {
1585 rc = StorageResultCode.OperationFailedInternalError;
1586 }
San Mehat02735bc2010-01-26 15:18:08 -08001587 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001588
1589 if (rc == StorageResultCode.OperationSucceeded) {
1590 synchronized (mAsecMountSet) {
1591 mAsecMountSet.remove(id);
1592 }
1593 }
San Mehat4270e1e2010-01-29 05:32:19 -08001594 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001595 }
1596
San Mehat6cdd9c02010-02-09 14:45:20 -08001597 public boolean isSecureContainerMounted(String id) {
1598 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1599 waitForReady();
1600 warnOnNotMounted();
1601
1602 synchronized (mAsecMountSet) {
1603 return mAsecMountSet.contains(id);
1604 }
1605 }
1606
San Mehat4270e1e2010-01-29 05:32:19 -08001607 public int renameSecureContainer(String oldId, String newId) {
1608 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001609 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001610 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001611
San Mehata181b212010-02-11 06:50:20 -08001612 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001613 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001614 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001615 * changed while active, we must ensure both ids are not currently mounted.
1616 */
1617 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001618 return StorageResultCode.OperationFailedStorageMounted;
1619 }
1620 }
1621
San Mehatb1043402010-02-05 08:26:50 -08001622 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001623 String cmd = String.format("asec rename %s %s", oldId, newId);
1624 try {
1625 mConnector.doCommand(cmd);
1626 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001627 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001628 }
San Mehata181b212010-02-11 06:50:20 -08001629
San Mehat4270e1e2010-01-29 05:32:19 -08001630 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001631 }
1632
San Mehat4270e1e2010-01-29 05:32:19 -08001633 public String getSecureContainerPath(String id) {
1634 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001635 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001636 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001637
San Mehat2d66cef2010-03-23 11:12:52 -07001638 try {
1639 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1640 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001641 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001642 if (code != VoldResponseCode.AsecPathResult) {
1643 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1644 }
1645 return tok[1];
1646 } catch (NativeDaemonConnectorException e) {
1647 int code = e.getCode();
1648 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001649 Slog.i(TAG, String.format("Container '%s' not found", id));
1650 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001651 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001652 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001653 }
1654 }
San Mehat22dd86e2010-01-12 12:21:18 -08001655 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001656
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001657 public String getSecureContainerFilesystemPath(String id) {
1658 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1659 waitForReady();
1660 warnOnNotMounted();
1661
1662 try {
1663 ArrayList<String> rsp = mConnector.doCommand(String.format("asec fspath %s", id));
1664 String []tok = rsp.get(0).split(" ");
1665 int code = Integer.parseInt(tok[0]);
1666 if (code != VoldResponseCode.AsecPathResult) {
1667 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1668 }
1669 return tok[1];
1670 } catch (NativeDaemonConnectorException e) {
1671 int code = e.getCode();
1672 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1673 Slog.i(TAG, String.format("Container '%s' not found", id));
1674 return null;
1675 } else {
1676 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1677 }
1678 }
1679 }
1680
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001681 public void finishMediaUpdate() {
1682 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1683 }
Kenny Root02c87302010-07-01 08:10:18 -07001684
Kenny Roota02b8b02010-08-05 16:14:17 -07001685 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1686 if (callerUid == android.os.Process.SYSTEM_UID) {
1687 return true;
1688 }
1689
Kenny Root02c87302010-07-01 08:10:18 -07001690 if (packageName == null) {
1691 return false;
1692 }
1693
1694 final int packageUid = mPms.getPackageUid(packageName);
1695
1696 if (DEBUG_OBB) {
1697 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1698 packageUid + ", callerUid = " + callerUid);
1699 }
1700
1701 return callerUid == packageUid;
1702 }
1703
1704 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001705 if (filename == null) {
1706 throw new IllegalArgumentException("filename cannot be null");
1707 }
1708
Kenny Root02c87302010-07-01 08:10:18 -07001709 waitForReady();
1710 warnOnNotMounted();
1711
Kenny Root02c87302010-07-01 08:10:18 -07001712 try {
1713 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1714 String []tok = rsp.get(0).split(" ");
1715 int code = Integer.parseInt(tok[0]);
1716 if (code != VoldResponseCode.AsecPathResult) {
1717 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1718 }
1719 return tok[1];
1720 } catch (NativeDaemonConnectorException e) {
1721 int code = e.getCode();
1722 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001723 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001724 } else {
1725 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1726 }
1727 }
1728 }
1729
1730 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001731 if (filename == null) {
1732 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001733 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001734
1735 synchronized (mObbMounts) {
1736 return mObbPathToStateMap.containsKey(filename);
1737 }
Kenny Root02c87302010-07-01 08:10:18 -07001738 }
1739
Kenny Rootaf9d6672010-10-08 09:21:39 -07001740 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001741 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001742 if (filename == null) {
1743 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001744 }
1745
1746 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001747 throw new IllegalArgumentException("token cannot be null");
1748 }
1749
Kenny Rootaf9d6672010-10-08 09:21:39 -07001750 final int callerUid = Binder.getCallingUid();
1751 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1752 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001753 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1754
1755 if (DEBUG_OBB)
1756 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001757 }
1758
Kenny Rootaf9d6672010-10-08 09:21:39 -07001759 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1760 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001761 if (filename == null) {
1762 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001763 }
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 UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001768 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001769
Kenny Roota02b8b02010-08-05 16:14:17 -07001770 if (DEBUG_OBB)
1771 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1772 }
1773
Ben Komalo444eca22011-09-01 15:17:44 -07001774 @Override
1775 public int getEncryptionState() {
1776 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1777 "no permission to access the crypt keeper");
1778
1779 waitForReady();
1780
1781 try {
1782 ArrayList<String> rsp = mConnector.doCommand("cryptfs cryptocomplete");
1783 String[] tokens = rsp.get(0).split(" ");
1784
1785 if (tokens == null || tokens.length != 2) {
1786 // Unexpected.
1787 Slog.w(TAG, "Unexpected result from cryptfs cryptocomplete");
1788 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1789 }
1790
1791 return Integer.parseInt(tokens[1]);
1792
1793 } catch (NumberFormatException e) {
1794 // Bad result - unexpected.
1795 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1796 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1797 } catch (NativeDaemonConnectorException e) {
1798 // Something bad happened.
1799 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1800 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1801 }
1802 }
1803
1804 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001805 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001806 if (TextUtils.isEmpty(password)) {
1807 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001808 }
1809
Jason parks8888c592011-01-20 22:46:41 -06001810 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1811 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001812
1813 waitForReady();
1814
1815 if (DEBUG_EVENTS) {
1816 Slog.i(TAG, "decrypting storage...");
1817 }
1818
1819 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001820 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001821 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001822
Jason parksf7b3cd42011-01-27 09:28:25 -06001823 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001824 return -1;
1825 }
1826
Jason parksf7b3cd42011-01-27 09:28:25 -06001827 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001828
1829 if (code == 0) {
1830 // Decrypt was successful. Post a delayed message before restarting in order
1831 // to let the UI to clear itself
1832 mHandler.postDelayed(new Runnable() {
1833 public void run() {
1834 mConnector.doCommand(String.format("cryptfs restart"));
1835 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001836 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001837 }
1838
1839 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001840 } catch (NativeDaemonConnectorException e) {
1841 // Decryption failed
1842 return e.getCode();
1843 }
Jason parks5af0b912010-11-29 09:05:25 -06001844 }
1845
Jason parks56aa5322011-01-07 09:01:15 -06001846 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001847 if (TextUtils.isEmpty(password)) {
1848 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001849 }
1850
Jason parks8888c592011-01-20 22:46:41 -06001851 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1852 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001853
1854 waitForReady();
1855
1856 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001857 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001858 }
1859
1860 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001861 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001862 } catch (NativeDaemonConnectorException e) {
1863 // Encryption failed
1864 return e.getCode();
1865 }
1866
1867 return 0;
1868 }
1869
Jason parksf7b3cd42011-01-27 09:28:25 -06001870 public int changeEncryptionPassword(String password) {
1871 if (TextUtils.isEmpty(password)) {
1872 throw new IllegalArgumentException("password cannot be empty");
1873 }
1874
1875 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1876 "no permission to access the crypt keeper");
1877
1878 waitForReady();
1879
1880 if (DEBUG_EVENTS) {
1881 Slog.i(TAG, "changing encryption password...");
1882 }
1883
1884 try {
1885 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1886
1887 String[] tokens = response.get(0).split(" ");
1888
1889 if (tokens == null || tokens.length != 2) {
1890 return -1;
1891 }
1892
1893 return Integer.parseInt(tokens[1]);
1894 } catch (NativeDaemonConnectorException e) {
1895 // Encryption failed
1896 return e.getCode();
1897 }
1898 }
1899
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001900 public Parcelable[] getVolumeList() {
1901 synchronized(mVolumes) {
1902 int size = mVolumes.size();
1903 Parcelable[] result = new Parcelable[size];
1904 for (int i = 0; i < size; i++) {
1905 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001906 }
1907 return result;
1908 }
1909 }
1910
Kenny Rootaf9d6672010-10-08 09:21:39 -07001911 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1912 final IBinder binder = obbState.getBinder();
1913 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001914
Kenny Rootaf9d6672010-10-08 09:21:39 -07001915 if (obbStates == null) {
1916 obbStates = new ArrayList<ObbState>();
1917 mObbMounts.put(binder, obbStates);
1918 } else {
1919 for (final ObbState o : obbStates) {
1920 if (o.filename.equals(obbState.filename)) {
1921 throw new IllegalStateException("Attempt to add ObbState twice. "
1922 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001923 }
1924 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001925 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001926
1927 obbStates.add(obbState);
1928 try {
1929 obbState.link();
1930 } catch (RemoteException e) {
1931 /*
1932 * The binder died before we could link it, so clean up our state
1933 * and return failure.
1934 */
1935 obbStates.remove(obbState);
1936 if (obbStates.isEmpty()) {
1937 mObbMounts.remove(binder);
1938 }
1939
1940 // Rethrow the error so mountObb can get it
1941 throw e;
1942 }
1943
1944 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001945 }
1946
Kenny Rootaf9d6672010-10-08 09:21:39 -07001947 private void removeObbStateLocked(ObbState obbState) {
1948 final IBinder binder = obbState.getBinder();
1949 final List<ObbState> obbStates = mObbMounts.get(binder);
1950 if (obbStates != null) {
1951 if (obbStates.remove(obbState)) {
1952 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001953 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001954 if (obbStates.isEmpty()) {
1955 mObbMounts.remove(binder);
1956 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001957 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001958
Kenny Rootaf9d6672010-10-08 09:21:39 -07001959 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001960 }
1961
Kenny Roota02b8b02010-08-05 16:14:17 -07001962 private class ObbActionHandler extends Handler {
1963 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001964 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001965
1966 ObbActionHandler(Looper l) {
1967 super(l);
1968 }
1969
1970 @Override
1971 public void handleMessage(Message msg) {
1972 switch (msg.what) {
1973 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001974 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001975
1976 if (DEBUG_OBB)
1977 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1978
1979 // If a bind was already initiated we don't really
1980 // need to do anything. The pending install
1981 // will be processed later on.
1982 if (!mBound) {
1983 // If this is the only one pending we might
1984 // have to bind to the service again.
1985 if (!connectToService()) {
1986 Slog.e(TAG, "Failed to bind to media container service");
1987 action.handleError();
1988 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001989 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001990 }
Kenny Root735de3b2010-09-30 14:11:39 -07001991
Kenny Root735de3b2010-09-30 14:11:39 -07001992 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001993 break;
1994 }
1995 case OBB_MCS_BOUND: {
1996 if (DEBUG_OBB)
1997 Slog.i(TAG, "OBB_MCS_BOUND");
1998 if (msg.obj != null) {
1999 mContainerService = (IMediaContainerService) msg.obj;
2000 }
2001 if (mContainerService == null) {
2002 // Something seriously wrong. Bail out
2003 Slog.e(TAG, "Cannot bind to media container service");
2004 for (ObbAction action : mActions) {
2005 // Indicate service bind error
2006 action.handleError();
2007 }
2008 mActions.clear();
2009 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002010 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002011 if (action != null) {
2012 action.execute(this);
2013 }
2014 } else {
2015 // Should never happen ideally.
2016 Slog.w(TAG, "Empty queue");
2017 }
2018 break;
2019 }
2020 case OBB_MCS_RECONNECT: {
2021 if (DEBUG_OBB)
2022 Slog.i(TAG, "OBB_MCS_RECONNECT");
2023 if (mActions.size() > 0) {
2024 if (mBound) {
2025 disconnectService();
2026 }
2027 if (!connectToService()) {
2028 Slog.e(TAG, "Failed to bind to media container service");
2029 for (ObbAction action : mActions) {
2030 // Indicate service bind error
2031 action.handleError();
2032 }
2033 mActions.clear();
2034 }
2035 }
2036 break;
2037 }
2038 case OBB_MCS_UNBIND: {
2039 if (DEBUG_OBB)
2040 Slog.i(TAG, "OBB_MCS_UNBIND");
2041
2042 // Delete pending install
2043 if (mActions.size() > 0) {
2044 mActions.remove(0);
2045 }
2046 if (mActions.size() == 0) {
2047 if (mBound) {
2048 disconnectService();
2049 }
2050 } else {
2051 // There are more pending requests in queue.
2052 // Just post MCS_BOUND message to trigger processing
2053 // of next pending install.
2054 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2055 }
2056 break;
2057 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002058 case OBB_FLUSH_MOUNT_STATE: {
2059 final String path = (String) msg.obj;
2060
2061 if (DEBUG_OBB)
2062 Slog.i(TAG, "Flushing all OBB state for path " + path);
2063
2064 synchronized (mObbMounts) {
2065 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2066
2067 final Iterator<Entry<String, ObbState>> i =
2068 mObbPathToStateMap.entrySet().iterator();
2069 while (i.hasNext()) {
2070 final Entry<String, ObbState> obbEntry = i.next();
2071
2072 /*
2073 * If this entry's source file is in the volume path
2074 * that got unmounted, remove it because it's no
2075 * longer valid.
2076 */
2077 if (obbEntry.getKey().startsWith(path)) {
2078 obbStatesToRemove.add(obbEntry.getValue());
2079 }
2080 }
2081
2082 for (final ObbState obbState : obbStatesToRemove) {
2083 if (DEBUG_OBB)
2084 Slog.i(TAG, "Removing state for " + obbState.filename);
2085
2086 removeObbStateLocked(obbState);
2087
2088 try {
2089 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2090 OnObbStateChangeListener.UNMOUNTED);
2091 } catch (RemoteException e) {
2092 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2093 + obbState.filename);
2094 }
2095 }
2096 }
2097 break;
2098 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002099 }
2100 }
2101
2102 private boolean connectToService() {
2103 if (DEBUG_OBB)
2104 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2105
2106 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2107 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2108 mBound = true;
2109 return true;
2110 }
2111 return false;
2112 }
2113
2114 private void disconnectService() {
2115 mContainerService = null;
2116 mBound = false;
2117 mContext.unbindService(mDefContainerConn);
2118 }
2119 }
2120
2121 abstract class ObbAction {
2122 private static final int MAX_RETRIES = 3;
2123 private int mRetries;
2124
2125 ObbState mObbState;
2126
2127 ObbAction(ObbState obbState) {
2128 mObbState = obbState;
2129 }
2130
2131 public void execute(ObbActionHandler handler) {
2132 try {
2133 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002134 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002135 mRetries++;
2136 if (mRetries > MAX_RETRIES) {
2137 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002138 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002139 handleError();
2140 return;
2141 } else {
2142 handleExecute();
2143 if (DEBUG_OBB)
2144 Slog.i(TAG, "Posting install MCS_UNBIND");
2145 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2146 }
2147 } catch (RemoteException e) {
2148 if (DEBUG_OBB)
2149 Slog.i(TAG, "Posting install MCS_RECONNECT");
2150 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2151 } catch (Exception e) {
2152 if (DEBUG_OBB)
2153 Slog.d(TAG, "Error handling OBB action", e);
2154 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002155 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002156 }
2157 }
2158
Kenny Root05105f72010-09-22 17:29:43 -07002159 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002160 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002161
2162 protected ObbInfo getObbInfo() throws IOException {
2163 ObbInfo obbInfo;
2164 try {
2165 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2166 } catch (RemoteException e) {
2167 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2168 + mObbState.filename);
2169 obbInfo = null;
2170 }
2171 if (obbInfo == null) {
2172 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2173 }
2174 return obbInfo;
2175 }
2176
Kenny Rootaf9d6672010-10-08 09:21:39 -07002177 protected void sendNewStatusOrIgnore(int status) {
2178 if (mObbState == null || mObbState.token == null) {
2179 return;
2180 }
2181
Kenny Root38cf8862010-09-26 14:18:51 -07002182 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002183 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002184 } catch (RemoteException e) {
2185 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2186 }
2187 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002188 }
2189
2190 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002191 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002192
2193 MountObbAction(ObbState obbState, String key) {
2194 super(obbState);
2195 mKey = key;
2196 }
2197
Jason parks5af0b912010-11-29 09:05:25 -06002198 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002199 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002200 waitForReady();
2201 warnOnNotMounted();
2202
Kenny Root38cf8862010-09-26 14:18:51 -07002203 final ObbInfo obbInfo = getObbInfo();
2204
Kenny Roota02b8b02010-08-05 16:14:17 -07002205 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002206 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2207 + " which is owned by " + obbInfo.packageName);
2208 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2209 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002210 }
2211
Kenny Rootaf9d6672010-10-08 09:21:39 -07002212 final boolean isMounted;
2213 synchronized (mObbMounts) {
2214 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2215 }
2216 if (isMounted) {
2217 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2218 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2219 return;
2220 }
2221
2222 /*
2223 * The filename passed in might not be the canonical name, so just
2224 * set the filename to the canonicalized version.
2225 */
2226 mObbState.filename = obbInfo.filename;
2227
2228 final String hashedKey;
2229 if (mKey == null) {
2230 hashedKey = "none";
2231 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002232 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002233 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2234
2235 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2236 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2237 SecretKey key = factory.generateSecret(ks);
2238 BigInteger bi = new BigInteger(key.getEncoded());
2239 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002240 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002241 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2242 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2243 return;
2244 } catch (InvalidKeySpecException e) {
2245 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2246 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002247 return;
2248 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002249 }
Kenny Root38cf8862010-09-26 14:18:51 -07002250
Kenny Rootaf9d6672010-10-08 09:21:39 -07002251 int rc = StorageResultCode.OperationSucceeded;
2252 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2253 mObbState.callerUid);
2254 try {
2255 mConnector.doCommand(cmd);
2256 } catch (NativeDaemonConnectorException e) {
2257 int code = e.getCode();
2258 if (code != VoldResponseCode.OpFailedStorageBusy) {
2259 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002260 }
2261 }
2262
Kenny Rootaf9d6672010-10-08 09:21:39 -07002263 if (rc == StorageResultCode.OperationSucceeded) {
2264 if (DEBUG_OBB)
2265 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2266
2267 synchronized (mObbMounts) {
2268 addObbStateLocked(mObbState);
2269 }
2270
2271 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002272 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002273 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002274
Kenny Rootaf9d6672010-10-08 09:21:39 -07002275 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002276 }
2277 }
2278
Jason parks5af0b912010-11-29 09:05:25 -06002279 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002280 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002281 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002282 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002283
2284 @Override
2285 public String toString() {
2286 StringBuilder sb = new StringBuilder();
2287 sb.append("MountObbAction{");
2288 sb.append("filename=");
2289 sb.append(mObbState.filename);
2290 sb.append(",callerUid=");
2291 sb.append(mObbState.callerUid);
2292 sb.append(",token=");
2293 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002294 sb.append(",binder=");
2295 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002296 sb.append('}');
2297 return sb.toString();
2298 }
2299 }
2300
2301 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002302 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002303
2304 UnmountObbAction(ObbState obbState, boolean force) {
2305 super(obbState);
2306 mForceUnmount = force;
2307 }
2308
Jason parks5af0b912010-11-29 09:05:25 -06002309 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002310 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002311 waitForReady();
2312 warnOnNotMounted();
2313
Kenny Root38cf8862010-09-26 14:18:51 -07002314 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002315
Kenny Rootaf9d6672010-10-08 09:21:39 -07002316 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002317 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002318 obbState = mObbPathToStateMap.get(obbInfo.filename);
2319 }
Kenny Root38cf8862010-09-26 14:18:51 -07002320
Kenny Rootaf9d6672010-10-08 09:21:39 -07002321 if (obbState == null) {
2322 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2323 return;
2324 }
2325
2326 if (obbState.callerUid != mObbState.callerUid) {
2327 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2328 + " (owned by " + obbInfo.packageName + ")");
2329 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2330 return;
2331 }
2332
2333 mObbState.filename = obbInfo.filename;
2334
2335 int rc = StorageResultCode.OperationSucceeded;
2336 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2337 (mForceUnmount ? " force" : ""));
2338 try {
2339 mConnector.doCommand(cmd);
2340 } catch (NativeDaemonConnectorException e) {
2341 int code = e.getCode();
2342 if (code == VoldResponseCode.OpFailedStorageBusy) {
2343 rc = StorageResultCode.OperationFailedStorageBusy;
2344 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2345 // If it's not mounted then we've already won.
2346 rc = StorageResultCode.OperationSucceeded;
2347 } else {
2348 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002349 }
2350 }
2351
Kenny Rootaf9d6672010-10-08 09:21:39 -07002352 if (rc == StorageResultCode.OperationSucceeded) {
2353 synchronized (mObbMounts) {
2354 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002355 }
2356
Kenny Rootaf9d6672010-10-08 09:21:39 -07002357 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002358 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002359 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2360 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002361 }
2362 }
2363
Jason parks5af0b912010-11-29 09:05:25 -06002364 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002365 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002366 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002367 }
2368
2369 @Override
2370 public String toString() {
2371 StringBuilder sb = new StringBuilder();
2372 sb.append("UnmountObbAction{");
2373 sb.append("filename=");
2374 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2375 sb.append(",force=");
2376 sb.append(mForceUnmount);
2377 sb.append(",callerUid=");
2378 sb.append(mObbState.callerUid);
2379 sb.append(",token=");
2380 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002381 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002382 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002383 sb.append('}');
2384 return sb.toString();
2385 }
Kenny Root02c87302010-07-01 08:10:18 -07002386 }
Kenny Root38cf8862010-09-26 14:18:51 -07002387
2388 @Override
2389 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2390 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2391 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2392 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2393 + " without permission " + android.Manifest.permission.DUMP);
2394 return;
2395 }
2396
Kenny Root38cf8862010-09-26 14:18:51 -07002397 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002398 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002399
Kenny Rootaf9d6672010-10-08 09:21:39 -07002400 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2401 while (binders.hasNext()) {
2402 Entry<IBinder, List<ObbState>> e = binders.next();
2403 pw.print(" Key="); pw.println(e.getKey().toString());
2404 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002405 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002406 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002407 }
2408 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409
2410 pw.println("");
2411 pw.println(" mObbPathToStateMap:");
2412 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2413 while (maps.hasNext()) {
2414 final Entry<String, ObbState> e = maps.next();
2415 pw.print(" "); pw.print(e.getKey());
2416 pw.print(" -> "); pw.println(e.getValue().toString());
2417 }
Kenny Root38cf8862010-09-26 14:18:51 -07002418 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002419
2420 pw.println("");
2421
2422 synchronized (mVolumes) {
2423 pw.println(" mVolumes:");
2424
2425 final int N = mVolumes.size();
2426 for (int i = 0; i < N; i++) {
2427 final StorageVolume v = mVolumes.get(i);
2428 pw.print(" ");
2429 pw.println(v.toString());
2430 }
2431 }
Kenny Root38cf8862010-09-26 14:18:51 -07002432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002434 /** {@inheritDoc} */
2435 public void monitor() {
2436 if (mConnector != null) {
2437 mConnector.monitor();
2438 }
2439 }
2440}