blob: c86f96237f4420f32a61211712b268a1cc58f621 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040040import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070041import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080043import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070044import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070049import android.os.storage.IMountService;
50import android.os.storage.IMountServiceListener;
51import android.os.storage.IMountShutdownObserver;
52import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070053import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070054import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070055import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060056import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070058import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.Xml;
60
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070063
Kenny Root38cf8862010-09-26 14:18:51 -070064import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070065import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070066import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070067import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070068import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070069import java.security.spec.InvalidKeySpecException;
70import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080071import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070072import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080073import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070074import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070075import java.util.LinkedList;
76import java.util.List;
77import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070078import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070079import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Kenny Root3b1abba2010-10-13 15:00:07 -070081import javax.crypto.SecretKey;
82import javax.crypto.SecretKeyFactory;
83import javax.crypto.spec.PBEKeySpec;
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085/**
San Mehatb1043402010-02-05 08:26:50 -080086 * MountService implements back-end services for platform storage
87 * management.
88 * @hide - Applications should use android.os.storage.StorageManager
89 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 */
Jason parks5af0b912010-11-29 09:05:25 -060091class MountService extends IMountService.Stub implements INativeDaemonConnectorCallbacks {
92
San Mehatb1043402010-02-05 08:26:50 -080093 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080094 private static final boolean DEBUG_UNMOUNT = false;
95 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080096 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private static final String TAG = "MountService";
99
Kenny Root305bcbf2010-09-03 07:56:38 -0700100 private static final String VOLD_TAG = "VoldConnector";
101
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700102 /** Maximum number of ASEC containers allowed to be mounted. */
103 private static final int MAX_CONTAINERS = 250;
104
San Mehat4270e1e2010-01-29 05:32:19 -0800105 /*
106 * Internal vold volume state constants
107 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800108 class VolumeState {
109 public static final int Init = -1;
110 public static final int NoMedia = 0;
111 public static final int Idle = 1;
112 public static final int Pending = 2;
113 public static final int Checking = 3;
114 public static final int Mounted = 4;
115 public static final int Unmounting = 5;
116 public static final int Formatting = 6;
117 public static final int Shared = 7;
118 public static final int SharedMnt = 8;
119 }
120
San Mehat4270e1e2010-01-29 05:32:19 -0800121 /*
122 * Internal vold response code constants
123 */
San Mehat22dd86e2010-01-12 12:21:18 -0800124 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800125 /*
126 * 100 series - Requestion action was initiated; expect another reply
127 * before proceeding with a new command.
128 */
San Mehat22dd86e2010-01-12 12:21:18 -0800129 public static final int VolumeListResult = 110;
130 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800131 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800132
San Mehat4270e1e2010-01-29 05:32:19 -0800133 /*
134 * 200 series - Requestion action has been successfully completed.
135 */
136 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800137 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800138 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 /*
141 * 400 series - Command was accepted, but the requested action
142 * did not take place.
143 */
144 public static final int OpFailedNoMedia = 401;
145 public static final int OpFailedMediaBlank = 402;
146 public static final int OpFailedMediaCorrupt = 403;
147 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800148 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700149 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800150
151 /*
152 * 600 series - Unsolicited broadcasts.
153 */
San Mehat22dd86e2010-01-12 12:21:18 -0800154 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800155 public static final int ShareAvailabilityChange = 620;
156 public static final int VolumeDiskInserted = 630;
157 public static final int VolumeDiskRemoved = 631;
158 public static final int VolumeBadRemoval = 632;
159 }
160
San Mehat4270e1e2010-01-29 05:32:19 -0800161 private Context mContext;
162 private NativeDaemonConnector mConnector;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700163 private final ArrayList<StorageVolume> mVolumes = new ArrayList<StorageVolume>();
164 private StorageVolume mPrimaryVolume;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400165 private final HashMap<String, String> mVolumeStates = new HashMap<String, String>();
Mike Lockwooda5250c92011-05-23 13:44:04 -0400166 private final HashMap<String, StorageVolume> mVolumeMap = new HashMap<String, StorageVolume>();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400167 private String mExternalStoragePath;
San Mehat4270e1e2010-01-29 05:32:19 -0800168 private PackageManagerService mPms;
169 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800170 // Used as a lock for methods that register/unregister listeners.
171 final private ArrayList<MountServiceBinderListener> mListeners =
172 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800173 private boolean mBooted = false;
174 private boolean mReady = false;
175 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400176 // true if we should fake MEDIA_MOUNTED state for external storage
177 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800178
San Mehat6cdd9c02010-02-09 14:45:20 -0800179 /**
180 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800181 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800182 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800183 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800184
Kenny Root02c87302010-07-01 08:10:18 -0700185 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700186 * The size of the crypto algorithm key in bits for OBB files. Currently
187 * Twofish is used which takes 128-bit keys.
188 */
189 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
190
191 /**
192 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
193 * 1024 is reasonably secure and not too slow.
194 */
195 private static final int PBKDF2_HASH_ROUNDS = 1024;
196
197 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700198 * Mounted OBB tracking information. Used to track the current state of all
199 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700200 */
Kenny Root735de3b2010-09-30 14:11:39 -0700201 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700202 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
203
204 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700205 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700206 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700207 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700208 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700209 this.token = token;
210 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700211 }
212
213 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700214 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700215
216 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700217 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700218
Kenny Rootaf9d6672010-10-08 09:21:39 -0700219 // Token of remote Binder caller
220 final IObbActionListener token;
221
222 // Identifier to pass back to the token
223 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700224
Kenny Root735de3b2010-09-30 14:11:39 -0700225 public IBinder getBinder() {
226 return token.asBinder();
227 }
228
Kenny Roota02b8b02010-08-05 16:14:17 -0700229 @Override
230 public void binderDied() {
231 ObbAction action = new UnmountObbAction(this, true);
232 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700233 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700234
Kenny Root5919ac62010-10-05 09:49:40 -0700235 public void link() throws RemoteException {
236 getBinder().linkToDeath(this, 0);
237 }
238
239 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700240 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700241 }
Kenny Root38cf8862010-09-26 14:18:51 -0700242
243 @Override
244 public String toString() {
245 StringBuilder sb = new StringBuilder("ObbState{");
246 sb.append("filename=");
247 sb.append(filename);
248 sb.append(",token=");
249 sb.append(token.toString());
250 sb.append(",callerUid=");
251 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700252 sb.append('}');
253 return sb.toString();
254 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700255 }
256
257 // OBB Action Handler
258 final private ObbActionHandler mObbActionHandler;
259
260 // OBB action handler messages
261 private static final int OBB_RUN_ACTION = 1;
262 private static final int OBB_MCS_BOUND = 2;
263 private static final int OBB_MCS_UNBIND = 3;
264 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700265 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700266
267 /*
268 * Default Container Service information
269 */
270 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
271 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
272
273 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
274
275 class DefaultContainerConnection implements ServiceConnection {
276 public void onServiceConnected(ComponentName name, IBinder service) {
277 if (DEBUG_OBB)
278 Slog.i(TAG, "onServiceConnected");
279 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
280 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
281 }
282
283 public void onServiceDisconnected(ComponentName name) {
284 if (DEBUG_OBB)
285 Slog.i(TAG, "onServiceDisconnected");
286 }
287 };
288
289 // Used in the ObbActionHandler
290 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700291
292 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800293 private static final int H_UNMOUNT_PM_UPDATE = 1;
294 private static final int H_UNMOUNT_PM_DONE = 2;
295 private static final int H_UNMOUNT_MS = 3;
296 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
297 private static final int MAX_UNMOUNT_RETRIES = 4;
298
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800299 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700300 final String path;
301 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800302 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800303
304 UnmountCallBack(String path, boolean force) {
305 retries = 0;
306 this.path = path;
307 this.force = force;
308 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800309
310 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700311 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800312 doUnmountVolume(path, true);
313 }
314 }
315
316 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700317 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800318
319 UmsEnableCallBack(String path, String method, boolean force) {
320 super(path, force);
321 this.method = method;
322 }
323
324 @Override
325 void handleFinished() {
326 super.handleFinished();
327 doShareUnshareVolume(path, method, true);
328 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800329 }
330
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800331 class ShutdownCallBack extends UnmountCallBack {
332 IMountShutdownObserver observer;
333 ShutdownCallBack(String path, IMountShutdownObserver observer) {
334 super(path, true);
335 this.observer = observer;
336 }
337
338 @Override
339 void handleFinished() {
340 int ret = doUnmountVolume(path, true);
341 if (observer != null) {
342 try {
343 observer.onShutDownComplete(ret);
344 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700345 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800346 }
347 }
348 }
349 }
350
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400351 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800352 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700353 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800354
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400355 MountServiceHandler(Looper l) {
356 super(l);
357 }
358
Jason parks5af0b912010-11-29 09:05:25 -0600359 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 public void handleMessage(Message msg) {
361 switch (msg.what) {
362 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700363 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800364 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
365 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700366 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800367 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700368 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700369 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700370 mUpdatingStatus = true;
371 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 }
373 break;
374 }
375 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700376 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700377 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700378 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800379 int size = mForceUnmounts.size();
380 int sizeArr[] = new int[size];
381 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700382 // Kill processes holding references first
383 ActivityManagerService ams = (ActivityManagerService)
384 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800385 for (int i = 0; i < size; i++) {
386 UnmountCallBack ucb = mForceUnmounts.get(i);
387 String path = ucb.path;
388 boolean done = false;
389 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800390 done = true;
391 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 int pids[] = getStorageUsers(path);
393 if (pids == null || pids.length == 0) {
394 done = true;
395 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800396 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800397 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700398 // Confirm if file references have been freed.
399 pids = getStorageUsers(path);
400 if (pids == null || pids.length == 0) {
401 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402 }
403 }
404 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700405 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
406 // Retry again
407 Slog.i(TAG, "Retrying to kill storage users again");
408 mHandler.sendMessageDelayed(
409 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
410 ucb.retries++),
411 RETRY_UNMOUNT_DELAY);
412 } else {
413 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
414 Slog.i(TAG, "Failed to unmount media inspite of " +
415 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
416 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800417 sizeArr[sizeArrN++] = i;
418 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
419 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800420 }
421 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800422 // Remove already processed elements from list.
423 for (int i = (sizeArrN-1); i >= 0; i--) {
424 mForceUnmounts.remove(sizeArr[i]);
425 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800426 break;
427 }
428 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700429 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800430 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800431 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800432 break;
433 }
434 }
435 }
436 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400437 final private HandlerThread mHandlerThread;
438 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439
San Mehat207e5382010-02-04 20:46:54 -0800440 private void waitForReady() {
441 while (mReady == false) {
442 for (int retries = 5; retries > 0; retries--) {
443 if (mReady) {
444 return;
445 }
446 SystemClock.sleep(1000);
447 }
San Mehata5078592010-03-25 09:36:54 -0700448 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800449 }
San Mehat1f6301e2010-01-07 22:40:27 -0800450 }
Kenny Root02c87302010-07-01 08:10:18 -0700451
San Mehat207e5382010-02-04 20:46:54 -0800452 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600453 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800455 String action = intent.getAction();
456
457 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800458 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800459
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800460 /*
461 * In the simulator, we need to broadcast a volume mounted event
462 * to make the media scanner run.
463 */
464 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400465 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
466 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800467 return;
468 }
San Mehatfafb0412010-02-18 19:40:04 -0800469 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600470 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800471 public void run() {
472 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400473 // it is not safe to call vold with mVolumeStates locked
474 // so we make a copy of the paths and states and process them
475 // outside the lock
476 String[] paths, states;
477 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400478 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400479 Set<String> keys = mVolumeStates.keySet();
480 count = keys.size();
481 paths = (String[])keys.toArray(new String[count]);
482 states = new String[count];
483 for (int i = 0; i < count; i++) {
484 states[i] = mVolumeStates.get(paths[i]);
485 }
486 }
San Mehat6a254402010-03-22 10:21:00 -0700487
Mike Lockwood84338c42011-04-05 10:05:47 -0400488 for (int i = 0; i < count; i++) {
489 String path = paths[i];
490 String state = states[i];
491
492 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
493 int rc = doMountVolume(path);
494 if (rc != StorageResultCode.OperationSucceeded) {
495 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
496 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400497 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400498 } else if (state.equals(Environment.MEDIA_SHARED)) {
499 /*
500 * Bootstrap UMS enabled state since vold indicates
501 * the volume is shared (runtime restart while ums enabled)
502 */
503 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
504 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800505 }
506 }
San Mehat6a254402010-03-22 10:21:00 -0700507
Mike Lockwood80e0a412011-04-05 10:21:51 -0400508 /* notify external storage has mounted to trigger media scanner */
509 if (mEmulateExternalStorage) {
510 notifyVolumeStateChange(null,
511 Environment.getExternalStorageDirectory().getPath(),
512 VolumeState.NoMedia, VolumeState.Mounted);
513 }
514
San Mehat6a965af22010-02-24 17:47:30 -0800515 /*
San Mehat6a254402010-03-22 10:21:00 -0700516 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800517 * now that we're up.
518 */
519 if (mSendUmsConnectedOnBoot) {
520 sendUmsIntent(true);
521 mSendUmsConnectedOnBoot = false;
522 }
San Mehatfafb0412010-02-18 19:40:04 -0800523 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700524 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800525 }
San Mehat207e5382010-02-04 20:46:54 -0800526 }
San Mehatfafb0412010-02-18 19:40:04 -0800527 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 }
529 }
530 };
San Mehat4270e1e2010-01-29 05:32:19 -0800531 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
532 final IMountServiceListener mListener;
533
534 MountServiceBinderListener(IMountServiceListener listener) {
535 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700536
San Mehat91c77612010-01-07 10:39:41 -0800537 }
538
San Mehat4270e1e2010-01-29 05:32:19 -0800539 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700540 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700541 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800542 mListeners.remove(this);
543 mListener.asBinder().unlinkToDeath(this, 0);
544 }
545 }
546 }
547
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800548 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800549 // TODO: Add support for multiple share methods
550 if (!method.equals("ums")) {
551 throw new IllegalArgumentException(String.format("Method %s not supported", method));
552 }
553
San Mehat4270e1e2010-01-29 05:32:19 -0800554 try {
555 mConnector.doCommand(String.format(
556 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
557 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700558 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800559 }
San Mehat4270e1e2010-01-29 05:32:19 -0800560 }
561
San Mehat207e5382010-02-04 20:46:54 -0800562 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400563 String oldState;
564 synchronized(mVolumeStates) {
565 oldState = mVolumeStates.put(path, state);
566 }
567 if (state.equals(oldState)) {
568 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
569 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800570 return;
571 }
San Mehatb1043402010-02-05 08:26:50 -0800572
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400573 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700574
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400575 if (path.equals(mExternalStoragePath)) {
576 // Update state on PackageManager, but only of real events
577 if (!mEmulateExternalStorage) {
578 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
579 mPms.updateExternalMediaStatus(false, false);
580
581 /*
582 * Some OBBs might have been unmounted when this volume was
583 * unmounted, so send a message to the handler to let it know to
584 * remove those from the list of mounted OBBS.
585 */
586 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
587 OBB_FLUSH_MOUNT_STATE, path));
588 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
589 mPms.updateExternalMediaStatus(true, false);
590 }
Mike Lockwood03559752010-07-19 18:25:03 -0400591 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800592 }
San Mehat4270e1e2010-01-29 05:32:19 -0800593 synchronized (mListeners) {
594 for (int i = mListeners.size() -1; i >= 0; i--) {
595 MountServiceBinderListener bl = mListeners.get(i);
596 try {
San Mehatb1043402010-02-05 08:26:50 -0800597 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800598 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700599 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800600 mListeners.remove(i);
601 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700602 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800603 }
604 }
605 }
606 }
607
608 /**
609 *
610 * Callback from NativeDaemonConnector
611 */
612 public void onDaemonConnected() {
613 /*
614 * Since we'll be calling back into the NativeDaemonConnector,
615 * we need to do our work in a new thread.
616 */
617 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600618 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800619 public void run() {
620 /**
621 * Determine media state and UMS detection status
622 */
San Mehat4270e1e2010-01-29 05:32:19 -0800623 try {
624 String[] vols = mConnector.doListCommand(
625 "volume list", VoldResponseCode.VolumeListResult);
626 for (String volstr : vols) {
627 String[] tok = volstr.split(" ");
628 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400629 String path = tok[1];
630 String state = Environment.MEDIA_REMOVED;
631
San Mehat4270e1e2010-01-29 05:32:19 -0800632 int st = Integer.parseInt(tok[2]);
633 if (st == VolumeState.NoMedia) {
634 state = Environment.MEDIA_REMOVED;
635 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800636 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800637 } else if (st == VolumeState.Mounted) {
638 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700639 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800640 } else if (st == VolumeState.Shared) {
641 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700642 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800643 } else {
644 throw new Exception(String.format("Unexpected state %d", st));
645 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400646
647 if (state != null) {
648 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
649 updatePublicVolumeState(path, state);
650 }
San Mehat4270e1e2010-01-29 05:32:19 -0800651 }
652 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700653 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400654 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800655 }
656
657 try {
San Mehat207e5382010-02-04 20:46:54 -0800658 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800659 notifyShareAvailabilityChange("ums", avail);
660 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700661 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800662 }
San Mehat207e5382010-02-04 20:46:54 -0800663 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600664 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800665 * the hounds!
666 */
667 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800668 }
669 }.start();
670 }
671
672 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800673 * Callback from NativeDaemonConnector
674 */
675 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800676 if (DEBUG_EVENTS) {
677 StringBuilder builder = new StringBuilder();
678 builder.append("onEvent::");
679 builder.append(" raw= " + raw);
680 if (cooked != null) {
681 builder.append(" cooked = " );
682 for (String str : cooked) {
683 builder.append(" " + str);
684 }
685 }
San Mehata5078592010-03-25 09:36:54 -0700686 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800687 }
San Mehat4270e1e2010-01-29 05:32:19 -0800688 if (code == VoldResponseCode.VolumeStateChange) {
689 /*
690 * One of the volumes we're managing has changed state.
691 * Format: "NNN Volume <label> <path> state changed
692 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
693 */
694 notifyVolumeStateChange(
695 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
696 Integer.parseInt(cooked[10]));
697 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
698 // FMT: NNN Share method <method> now <available|unavailable>
699 boolean avail = false;
700 if (cooked[5].equals("available")) {
701 avail = true;
702 }
703 notifyShareAvailabilityChange(cooked[3], avail);
704 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
705 (code == VoldResponseCode.VolumeDiskRemoved) ||
706 (code == VoldResponseCode.VolumeBadRemoval)) {
707 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
708 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
709 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400710 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800711 final String label = cooked[2];
712 final String path = cooked[3];
713 int major = -1;
714 int minor = -1;
715
716 try {
717 String devComp = cooked[6].substring(1, cooked[6].length() -1);
718 String[] devTok = devComp.split(":");
719 major = Integer.parseInt(devTok[0]);
720 minor = Integer.parseInt(devTok[1]);
721 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700722 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724
San Mehat4270e1e2010-01-29 05:32:19 -0800725 if (code == VoldResponseCode.VolumeDiskInserted) {
726 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600727 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800728 public void run() {
729 try {
730 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800731 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700732 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800733 }
734 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700735 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800736 }
737 }
738 }.start();
739 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
740 /*
741 * This event gets trumped if we're already in BAD_REMOVAL state
742 */
743 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
744 return true;
745 }
746 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700747 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800748 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400749 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800750
San Mehata5078592010-03-25 09:36:54 -0700751 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400753 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800754 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700755 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800756 /* Send the media unmounted event first */
757 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400758 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800759
San Mehata5078592010-03-25 09:36:54 -0700760 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800761 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400762 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800763 } else {
San Mehata5078592010-03-25 09:36:54 -0700764 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800765 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400766
767 if (action != null) {
768 sendStorageIntent(action, path);
769 }
San Mehat4270e1e2010-01-29 05:32:19 -0800770 } else {
771 return false;
772 }
773
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400774 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800775 }
776
San Mehat207e5382010-02-04 20:46:54 -0800777 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800778 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700779 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800780
Mike Lockwooda5250c92011-05-23 13:44:04 -0400781 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800782
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500783 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700784 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400785 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500786 }
787
San Mehat4270e1e2010-01-29 05:32:19 -0800788 if (newState == VolumeState.Init) {
789 } else if (newState == VolumeState.NoMedia) {
790 // NoMedia is handled via Disk Remove events
791 } else if (newState == VolumeState.Idle) {
792 /*
793 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
794 * if we're in the process of enabling UMS
795 */
796 if (!vs.equals(
797 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
798 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800799 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700800 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800801 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400802 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800803 }
804 } else if (newState == VolumeState.Pending) {
805 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700806 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800807 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800809 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700810 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800811 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400812 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800813 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400814 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800815 } else if (newState == VolumeState.Formatting) {
816 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700817 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800818 /* Send the media unmounted event first */
819 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400820 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800821
San Mehata5078592010-03-25 09:36:54 -0700822 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800823 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400824 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700825 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800826 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700827 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800828 return;
829 } else {
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800831 }
832
Mike Lockwooda5250c92011-05-23 13:44:04 -0400833 if (action != null) {
834 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800835 }
836 }
837
San Mehat207e5382010-02-04 20:46:54 -0800838 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700839 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700840 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700841 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700842 } catch (NativeDaemonConnectorException ex) {
843 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
844 return false;
845 }
San Mehat207e5382010-02-04 20:46:54 -0800846
847 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700848 String[] tok = line.split(" ");
849 if (tok.length < 3) {
850 Slog.e(TAG, "Malformed response to share status " + method);
851 return false;
852 }
853
San Mehat207e5382010-02-04 20:46:54 -0800854 int code;
855 try {
856 code = Integer.parseInt(tok[0]);
857 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700858 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800859 return false;
860 }
861 if (code == VoldResponseCode.ShareStatusResult) {
862 if (tok[2].equals("available"))
863 return true;
864 return false;
865 } else {
San Mehata5078592010-03-25 09:36:54 -0700866 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800867 return false;
868 }
869 }
San Mehata5078592010-03-25 09:36:54 -0700870 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800871 return false;
872 }
873
874 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800875 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800876
San Mehata5078592010-03-25 09:36:54 -0700877 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800878 try {
879 mConnector.doCommand(String.format("volume mount %s", path));
880 } catch (NativeDaemonConnectorException e) {
881 /*
882 * Mount failed for some reason
883 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400884 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800885 int code = e.getCode();
886 if (code == VoldResponseCode.OpFailedNoMedia) {
887 /*
888 * Attempt to mount but no media inserted
889 */
San Mehatb1043402010-02-05 08:26:50 -0800890 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800891 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700892 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800893 /*
894 * Media is blank or does not contain a supported filesystem
895 */
896 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400897 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800898 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800899 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700900 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800901 /*
902 * Volume consistency check failed
903 */
904 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400905 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800906 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800907 } else {
San Mehatb1043402010-02-05 08:26:50 -0800908 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800909 }
910
911 /*
912 * Send broadcast intent (if required for the failure)
913 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400914 if (action != null) {
915 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800916 }
917 }
918
919 return rc;
920 }
921
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800922 /*
923 * If force is not set, we do not unmount if there are
924 * processes holding references to the volume about to be unmounted.
925 * If force is set, all the processes holding references need to be
926 * killed via the ActivityManager before actually unmounting the volume.
927 * This might even take a while and might be retried after timed delays
928 * to make sure we dont end up in an instable state and kill some core
929 * processes.
930 */
San Mehatd9709982010-02-18 11:43:03 -0800931 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800932 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800933 return VoldResponseCode.OpFailedVolNotMounted;
934 }
Kenny Rootaa485402010-09-14 14:49:41 -0700935
936 /*
937 * Force a GC to make sure AssetManagers in other threads of the
938 * system_server are cleaned up. We have to do this since AssetManager
939 * instances are kept as a WeakReference and it's possible we have files
940 * open on the external storage.
941 */
942 Runtime.getRuntime().gc();
943
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800944 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700945 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800946 try {
San Mehatd9709982010-02-18 11:43:03 -0800947 mConnector.doCommand(String.format(
948 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700949 // We unmounted the volume. None of the asec containers are available now.
950 synchronized (mAsecMountSet) {
951 mAsecMountSet.clear();
952 }
San Mehatb1043402010-02-05 08:26:50 -0800953 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800954 } catch (NativeDaemonConnectorException e) {
955 // Don't worry about mismatch in PackageManager since the
956 // call back will handle the status changes any way.
957 int code = e.getCode();
958 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800959 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800960 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
961 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800962 } else {
San Mehatb1043402010-02-05 08:26:50 -0800963 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800964 }
965 }
966 }
967
968 private int doFormatVolume(String path) {
969 try {
970 String cmd = String.format("volume format %s", path);
971 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800972 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800973 } catch (NativeDaemonConnectorException e) {
974 int code = e.getCode();
975 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800976 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800977 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800978 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800979 } else {
San Mehatb1043402010-02-05 08:26:50 -0800980 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800981 }
982 }
983 }
984
San Mehatb1043402010-02-05 08:26:50 -0800985 private boolean doGetVolumeShared(String path, String method) {
986 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700987 ArrayList<String> rsp;
988
989 try {
990 rsp = mConnector.doCommand(cmd);
991 } catch (NativeDaemonConnectorException ex) {
992 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
993 return false;
994 }
San Mehatb1043402010-02-05 08:26:50 -0800995
996 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700997 String[] tok = line.split(" ");
998 if (tok.length < 3) {
999 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
1000 return false;
1001 }
1002
San Mehatb1043402010-02-05 08:26:50 -08001003 int code;
1004 try {
1005 code = Integer.parseInt(tok[0]);
1006 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001007 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -08001008 return false;
1009 }
1010 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -07001011 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -08001012 } else {
San Mehata5078592010-03-25 09:36:54 -07001013 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -08001014 return false;
1015 }
1016 }
San Mehata5078592010-03-25 09:36:54 -07001017 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -08001018 return false;
1019 }
1020
San Mehat207e5382010-02-04 20:46:54 -08001021 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001022 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -07001023 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001024 return;
1025 }
1026
1027 synchronized (mListeners) {
1028 for (int i = mListeners.size() -1; i >= 0; i--) {
1029 MountServiceBinderListener bl = mListeners.get(i);
1030 try {
San Mehatb1043402010-02-05 08:26:50 -08001031 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001032 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001033 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001034 mListeners.remove(i);
1035 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001036 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001037 }
1038 }
1039 }
1040
San Mehat207e5382010-02-04 20:46:54 -08001041 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001042 sendUmsIntent(avail);
1043 } else {
1044 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001045 }
San Mehat2fe718a2010-03-11 12:01:49 -08001046
1047 final String path = Environment.getExternalStorageDirectory().getPath();
1048 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1049 /*
1050 * USB mass storage disconnected while enabled
1051 */
1052 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001053 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001054 public void run() {
1055 try {
1056 int rc;
San Mehata5078592010-03-25 09:36:54 -07001057 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001058 doShareUnshareVolume(path, "ums", false);
1059 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001060 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001061 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1062 path, rc));
1063 }
1064 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001065 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001066 }
1067 }
1068 }.start();
1069 }
San Mehat4270e1e2010-01-29 05:32:19 -08001070 }
1071
Mike Lockwooda5250c92011-05-23 13:44:04 -04001072 private void sendStorageIntent(String action, String path) {
1073 Intent intent = new Intent(action, Uri.parse("file://" + path));
1074 // add StorageVolume extra
1075 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1076 Slog.d(TAG, "sendStorageIntent " + intent);
1077 mContext.sendBroadcast(intent);
1078 }
1079
San Mehat6a965af22010-02-24 17:47:30 -08001080 private void sendUmsIntent(boolean c) {
1081 mContext.sendBroadcast(
1082 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1083 }
1084
San Mehat207e5382010-02-04 20:46:54 -08001085 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001086 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1087 throw new SecurityException(String.format("Requires %s permission", perm));
1088 }
1089 }
1090
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001091 // Storage list XML tags
1092 private static final String TAG_STORAGE_LIST = "StorageList";
1093 private static final String TAG_STORAGE = "storage";
1094
1095 private void readStorageList(Resources resources) {
1096 int id = com.android.internal.R.xml.storage_list;
1097 XmlResourceParser parser = resources.getXml(id);
1098 AttributeSet attrs = Xml.asAttributeSet(parser);
1099
1100 try {
1101 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1102 while (true) {
1103 XmlUtils.nextElement(parser);
1104
1105 String element = parser.getName();
1106 if (element == null) break;
1107
1108 if (TAG_STORAGE.equals(element)) {
1109 TypedArray a = resources.obtainAttributes(attrs,
1110 com.android.internal.R.styleable.Storage);
1111
1112 CharSequence path = a.getText(
1113 com.android.internal.R.styleable.Storage_mountPoint);
1114 CharSequence description = a.getText(
1115 com.android.internal.R.styleable.Storage_storageDescription);
1116 boolean primary = a.getBoolean(
1117 com.android.internal.R.styleable.Storage_primary, false);
1118 boolean removable = a.getBoolean(
1119 com.android.internal.R.styleable.Storage_removable, false);
1120 boolean emulated = a.getBoolean(
1121 com.android.internal.R.styleable.Storage_emulated, false);
1122 int mtpReserve = a.getInt(
1123 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001124 boolean allowMassStorage = a.getBoolean(
1125 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001126
1127 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1128 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001129 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
1130 " allowMassStorage: " + allowMassStorage);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001131 if (path == null || description == null) {
1132 Slog.e(TAG, "path or description is null in readStorageList");
1133 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001134 String pathString = path.toString();
1135 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001136 description.toString(), removable, emulated,
1137 mtpReserve, allowMassStorage);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001138 if (primary) {
1139 if (mPrimaryVolume == null) {
1140 mPrimaryVolume = volume;
1141 } else {
1142 Slog.e(TAG, "multiple primary volumes in storage list");
1143 }
1144 }
1145 if (mPrimaryVolume == volume) {
1146 // primay volume must be first
1147 mVolumes.add(0, volume);
1148 } else {
1149 mVolumes.add(volume);
1150 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001151 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001152 }
1153 a.recycle();
1154 }
1155 }
1156 } catch (XmlPullParserException e) {
1157 throw new RuntimeException(e);
1158 } catch (IOException e) {
1159 throw new RuntimeException(e);
1160 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001161 // compute storage ID for each volume
1162 int length = mVolumes.size();
1163 for (int i = 0; i < length; i++) {
1164 mVolumes.get(i).setStorageId(i);
1165 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001166 parser.close();
1167 }
1168 }
1169
San Mehat4270e1e2010-01-29 05:32:19 -08001170 /**
San Mehat207e5382010-02-04 20:46:54 -08001171 * Constructs a new MountService instance
1172 *
1173 * @param context Binder context for this service
1174 */
1175 public MountService(Context context) {
1176 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001177 Resources resources = context.getResources();
1178 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001179
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001180 if (mPrimaryVolume != null) {
1181 mExternalStoragePath = mPrimaryVolume.getPath();
1182 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1183 if (mEmulateExternalStorage) {
1184 Slog.d(TAG, "using emulated external storage");
1185 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1186 }
Mike Lockwood03559752010-07-19 18:25:03 -04001187 }
1188
San Mehat207e5382010-02-04 20:46:54 -08001189 // XXX: This will go away soon in favor of IMountServiceObserver
1190 mPms = (PackageManagerService) ServiceManager.getService("package");
1191
1192 mContext.registerReceiver(mBroadcastReceiver,
1193 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1194
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001195 mHandlerThread = new HandlerThread("MountService");
1196 mHandlerThread.start();
1197 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1198
Kenny Roota02b8b02010-08-05 16:14:17 -07001199 // Add OBB Action Handler to MountService thread.
1200 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1201
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001202 /*
1203 * Vold does not run in the simulator, so pretend the connector thread
1204 * ran and did its thing.
1205 */
1206 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1207 mReady = true;
1208 mUmsEnabling = true;
1209 return;
1210 }
1211
Kenny Root305bcbf2010-09-03 07:56:38 -07001212 /*
1213 * Create the connection to vold with a maximum queue of twice the
1214 * amount of containers we'd ever expect to have. This keeps an
1215 * "asec list" from blocking a thread repeatedly.
1216 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001217 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001218 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001219 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001220 thread.start();
1221 }
1222
1223 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001224 * Exposed API calls below here
1225 */
1226
1227 public void registerListener(IMountServiceListener listener) {
1228 synchronized (mListeners) {
1229 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1230 try {
1231 listener.asBinder().linkToDeath(bl, 0);
1232 mListeners.add(bl);
1233 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001234 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001235 }
1236 }
1237 }
1238
1239 public void unregisterListener(IMountServiceListener listener) {
1240 synchronized (mListeners) {
1241 for(MountServiceBinderListener bl : mListeners) {
1242 if (bl.mListener == listener) {
1243 mListeners.remove(mListeners.indexOf(bl));
1244 return;
1245 }
1246 }
1247 }
1248 }
1249
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001250 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001251 validatePermission(android.Manifest.permission.SHUTDOWN);
1252
San Mehata5078592010-03-25 09:36:54 -07001253 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001254 synchronized (mVolumeStates) {
1255 for (String path : mVolumeStates.keySet()) {
1256 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001257
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001258 if (state.equals(Environment.MEDIA_SHARED)) {
1259 /*
1260 * If the media is currently shared, unshare it.
1261 * XXX: This is still dangerous!. We should not
1262 * be rebooting at *all* if UMS is enabled, since
1263 * the UMS host could have dirty FAT cache entries
1264 * yet to flush.
1265 */
1266 setUsbMassStorageEnabled(false);
1267 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1268 /*
1269 * If the media is being checked, then we need to wait for
1270 * it to complete before being able to proceed.
1271 */
1272 // XXX: @hackbod - Should we disable the ANR timer here?
1273 int retries = 30;
1274 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1275 try {
1276 Thread.sleep(1000);
1277 } catch (InterruptedException iex) {
1278 Slog.e(TAG, "Interrupted while waiting for media", iex);
1279 break;
1280 }
1281 state = Environment.getExternalStorageState();
1282 }
1283 if (retries == 0) {
1284 Slog.e(TAG, "Timed out waiting for media to check");
1285 }
San Mehat91c77612010-01-07 10:39:41 -08001286 }
San Mehat91c77612010-01-07 10:39:41 -08001287
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001288 if (state.equals(Environment.MEDIA_MOUNTED)) {
1289 // Post a unmount message.
1290 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1291 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1292 } else if (observer != null) {
1293 /*
1294 * Observer is waiting for onShutDownComplete when we are done.
1295 * Since nothing will be done send notification directly so shutdown
1296 * sequence can continue.
1297 */
1298 try {
1299 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1300 } catch (RemoteException e) {
1301 Slog.w(TAG, "RemoteException when shutting down");
1302 }
1303 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001304 }
San Mehat4270e1e2010-01-29 05:32:19 -08001305 }
1306 }
1307
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001308 private boolean getUmsEnabling() {
1309 synchronized (mListeners) {
1310 return mUmsEnabling;
1311 }
1312 }
1313
1314 private void setUmsEnabling(boolean enable) {
1315 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001316 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001317 }
1318 }
1319
San Mehatb1043402010-02-05 08:26:50 -08001320 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001321 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001322
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001323 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001324 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001325 }
San Mehatb1043402010-02-05 08:26:50 -08001326 return doGetShareMethodAvailable("ums");
1327 }
1328
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001329 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001330 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001331 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001332
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001333 // TODO: Add support for multiple share methods
1334
1335 /*
1336 * If the volume is mounted and we're enabling then unmount it
1337 */
1338 String path = Environment.getExternalStorageDirectory().getPath();
1339 String vs = getVolumeState(path);
1340 String method = "ums";
1341 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1342 // Override for isUsbMassStorageEnabled()
1343 setUmsEnabling(enable);
1344 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1345 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1346 // Clear override
1347 setUmsEnabling(false);
1348 }
1349 /*
1350 * If we disabled UMS then mount the volume
1351 */
1352 if (!enable) {
1353 doShareUnshareVolume(path, method, enable);
1354 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001355 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001356 " after disabling share method " + method);
1357 /*
1358 * Even though the mount failed, the unshare didn't so don't indicate an error.
1359 * The mountVolume() call will have set the storage state and sent the necessary
1360 * broadcasts.
1361 */
1362 }
1363 }
San Mehatb1043402010-02-05 08:26:50 -08001364 }
1365
1366 public boolean isUsbMassStorageEnabled() {
1367 waitForReady();
1368 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001370
San Mehat7fd0fee2009-12-17 07:12:23 -08001371 /**
1372 * @return state of the volume at the specified mount point
1373 */
San Mehat4270e1e2010-01-29 05:32:19 -08001374 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001375 synchronized (mVolumeStates) {
1376 String state = mVolumeStates.get(mountPoint);
1377 if (state == null) {
1378 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1379 throw new IllegalArgumentException();
1380 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001381
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001382 return state;
1383 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001384 }
1385
Kenny Roote1ff2142010-10-12 11:20:01 -07001386 public boolean isExternalStorageEmulated() {
1387 return mEmulateExternalStorage;
1388 }
1389
San Mehat4270e1e2010-01-29 05:32:19 -08001390 public int mountVolume(String path) {
1391 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001392
San Mehat207e5382010-02-04 20:46:54 -08001393 waitForReady();
1394 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001397 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001398 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001399 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001401 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001402 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001403 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1404 Environment.MEDIA_REMOVED.equals(volState) ||
1405 Environment.MEDIA_SHARED.equals(volState) ||
1406 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1407 // Media already unmounted or cannot be unmounted.
1408 // TODO return valid return code when adding observer call back.
1409 return;
1410 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001411 UnmountCallBack ucb = new UnmountCallBack(path, force);
1412 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414
San Mehat4270e1e2010-01-29 05:32:19 -08001415 public int formatVolume(String path) {
1416 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001417 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001418
San Mehat207e5382010-02-04 20:46:54 -08001419 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421
San Mehatc1b4ce92010-02-16 17:13:03 -08001422 public int []getStorageUsers(String path) {
1423 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1424 waitForReady();
1425 try {
1426 String[] r = mConnector.doListCommand(
1427 String.format("storage users %s", path),
1428 VoldResponseCode.StorageUsersListResult);
1429 // FMT: <pid> <process name>
1430 int[] data = new int[r.length];
1431 for (int i = 0; i < r.length; i++) {
1432 String []tok = r[i].split(" ");
1433 try {
1434 data[i] = Integer.parseInt(tok[0]);
1435 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001436 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001437 return new int[0];
1438 }
1439 }
1440 return data;
1441 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001442 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001443 return new int[0];
1444 }
1445 }
1446
San Mehatb1043402010-02-05 08:26:50 -08001447 private void warnOnNotMounted() {
1448 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001449 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001450 }
1451 }
1452
San Mehat4270e1e2010-01-29 05:32:19 -08001453 public String[] getSecureContainerList() {
1454 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001455 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001456 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001457
San Mehat4270e1e2010-01-29 05:32:19 -08001458 try {
1459 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1460 } catch (NativeDaemonConnectorException e) {
1461 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463 }
San Mehat36972292010-01-06 11:06:32 -08001464
San Mehat4270e1e2010-01-29 05:32:19 -08001465 public int createSecureContainer(String id, int sizeMb, String fstype,
1466 String key, int ownerUid) {
1467 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001468 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001469 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001470
San Mehatb1043402010-02-05 08:26:50 -08001471 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001472 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1473 try {
1474 mConnector.doCommand(cmd);
1475 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001476 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001477 }
San Mehata181b212010-02-11 06:50:20 -08001478
1479 if (rc == StorageResultCode.OperationSucceeded) {
1480 synchronized (mAsecMountSet) {
1481 mAsecMountSet.add(id);
1482 }
1483 }
San Mehat4270e1e2010-01-29 05:32:19 -08001484 return rc;
San Mehat36972292010-01-06 11:06:32 -08001485 }
1486
San Mehat4270e1e2010-01-29 05:32:19 -08001487 public int finalizeSecureContainer(String id) {
1488 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001489 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001490
San Mehatb1043402010-02-05 08:26:50 -08001491 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001492 try {
1493 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001494 /*
1495 * Finalization does a remount, so no need
1496 * to update mAsecMountSet
1497 */
San Mehat4270e1e2010-01-29 05:32:19 -08001498 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001499 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001500 }
San Mehat4270e1e2010-01-29 05:32:19 -08001501 return rc;
San Mehat36972292010-01-06 11:06:32 -08001502 }
1503
San Mehatd9709982010-02-18 11:43:03 -08001504 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001505 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001506 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001507 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001508
Kenny Rootaa485402010-09-14 14:49:41 -07001509 /*
1510 * Force a GC to make sure AssetManagers in other threads of the
1511 * system_server are cleaned up. We have to do this since AssetManager
1512 * instances are kept as a WeakReference and it's possible we have files
1513 * open on the external storage.
1514 */
1515 Runtime.getRuntime().gc();
1516
San Mehatb1043402010-02-05 08:26:50 -08001517 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001518 try {
San Mehatd9709982010-02-18 11:43:03 -08001519 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001520 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001521 int code = e.getCode();
1522 if (code == VoldResponseCode.OpFailedStorageBusy) {
1523 rc = StorageResultCode.OperationFailedStorageBusy;
1524 } else {
1525 rc = StorageResultCode.OperationFailedInternalError;
1526 }
San Mehat02735bc2010-01-26 15:18:08 -08001527 }
San Mehata181b212010-02-11 06:50:20 -08001528
1529 if (rc == StorageResultCode.OperationSucceeded) {
1530 synchronized (mAsecMountSet) {
1531 if (mAsecMountSet.contains(id)) {
1532 mAsecMountSet.remove(id);
1533 }
1534 }
1535 }
1536
San Mehat4270e1e2010-01-29 05:32:19 -08001537 return rc;
San Mehat36972292010-01-06 11:06:32 -08001538 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001539
San Mehat4270e1e2010-01-29 05:32:19 -08001540 public int mountSecureContainer(String id, String key, int ownerUid) {
1541 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001542 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001543 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001544
San Mehata181b212010-02-11 06:50:20 -08001545 synchronized (mAsecMountSet) {
1546 if (mAsecMountSet.contains(id)) {
1547 return StorageResultCode.OperationFailedStorageMounted;
1548 }
1549 }
1550
San Mehatb1043402010-02-05 08:26:50 -08001551 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001552 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1553 try {
1554 mConnector.doCommand(cmd);
1555 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001556 int code = e.getCode();
1557 if (code != VoldResponseCode.OpFailedStorageBusy) {
1558 rc = StorageResultCode.OperationFailedInternalError;
1559 }
San Mehat02735bc2010-01-26 15:18:08 -08001560 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001561
1562 if (rc == StorageResultCode.OperationSucceeded) {
1563 synchronized (mAsecMountSet) {
1564 mAsecMountSet.add(id);
1565 }
1566 }
San Mehat4270e1e2010-01-29 05:32:19 -08001567 return rc;
San Mehat36972292010-01-06 11:06:32 -08001568 }
1569
San Mehatd9709982010-02-18 11:43:03 -08001570 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001571 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001572 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001573 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001574
San Mehat6cdd9c02010-02-09 14:45:20 -08001575 synchronized (mAsecMountSet) {
1576 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001577 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001578 }
1579 }
1580
Kenny Rootaa485402010-09-14 14:49:41 -07001581 /*
1582 * Force a GC to make sure AssetManagers in other threads of the
1583 * system_server are cleaned up. We have to do this since AssetManager
1584 * instances are kept as a WeakReference and it's possible we have files
1585 * open on the external storage.
1586 */
1587 Runtime.getRuntime().gc();
1588
San Mehatb1043402010-02-05 08:26:50 -08001589 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001590 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001591 try {
1592 mConnector.doCommand(cmd);
1593 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001594 int code = e.getCode();
1595 if (code == VoldResponseCode.OpFailedStorageBusy) {
1596 rc = StorageResultCode.OperationFailedStorageBusy;
1597 } else {
1598 rc = StorageResultCode.OperationFailedInternalError;
1599 }
San Mehat02735bc2010-01-26 15:18:08 -08001600 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001601
1602 if (rc == StorageResultCode.OperationSucceeded) {
1603 synchronized (mAsecMountSet) {
1604 mAsecMountSet.remove(id);
1605 }
1606 }
San Mehat4270e1e2010-01-29 05:32:19 -08001607 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001608 }
1609
San Mehat6cdd9c02010-02-09 14:45:20 -08001610 public boolean isSecureContainerMounted(String id) {
1611 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1612 waitForReady();
1613 warnOnNotMounted();
1614
1615 synchronized (mAsecMountSet) {
1616 return mAsecMountSet.contains(id);
1617 }
1618 }
1619
San Mehat4270e1e2010-01-29 05:32:19 -08001620 public int renameSecureContainer(String oldId, String newId) {
1621 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001622 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001623 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001624
San Mehata181b212010-02-11 06:50:20 -08001625 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001626 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001627 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001628 * changed while active, we must ensure both ids are not currently mounted.
1629 */
1630 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001631 return StorageResultCode.OperationFailedStorageMounted;
1632 }
1633 }
1634
San Mehatb1043402010-02-05 08:26:50 -08001635 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001636 String cmd = String.format("asec rename %s %s", oldId, newId);
1637 try {
1638 mConnector.doCommand(cmd);
1639 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001640 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001641 }
San Mehata181b212010-02-11 06:50:20 -08001642
San Mehat4270e1e2010-01-29 05:32:19 -08001643 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001644 }
1645
San Mehat4270e1e2010-01-29 05:32:19 -08001646 public String getSecureContainerPath(String id) {
1647 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001648 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001649 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001650
San Mehat2d66cef2010-03-23 11:12:52 -07001651 try {
1652 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1653 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001654 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001655 if (code != VoldResponseCode.AsecPathResult) {
1656 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1657 }
1658 return tok[1];
1659 } catch (NativeDaemonConnectorException e) {
1660 int code = e.getCode();
1661 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001662 Slog.i(TAG, String.format("Container '%s' not found", id));
1663 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001664 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001665 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001666 }
1667 }
San Mehat22dd86e2010-01-12 12:21:18 -08001668 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001669
1670 public void finishMediaUpdate() {
1671 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1672 }
Kenny Root02c87302010-07-01 08:10:18 -07001673
Kenny Roota02b8b02010-08-05 16:14:17 -07001674 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1675 if (callerUid == android.os.Process.SYSTEM_UID) {
1676 return true;
1677 }
1678
Kenny Root02c87302010-07-01 08:10:18 -07001679 if (packageName == null) {
1680 return false;
1681 }
1682
1683 final int packageUid = mPms.getPackageUid(packageName);
1684
1685 if (DEBUG_OBB) {
1686 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1687 packageUid + ", callerUid = " + callerUid);
1688 }
1689
1690 return callerUid == packageUid;
1691 }
1692
1693 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001694 if (filename == null) {
1695 throw new IllegalArgumentException("filename cannot be null");
1696 }
1697
Kenny Root02c87302010-07-01 08:10:18 -07001698 waitForReady();
1699 warnOnNotMounted();
1700
Kenny Root02c87302010-07-01 08:10:18 -07001701 try {
1702 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1703 String []tok = rsp.get(0).split(" ");
1704 int code = Integer.parseInt(tok[0]);
1705 if (code != VoldResponseCode.AsecPathResult) {
1706 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1707 }
1708 return tok[1];
1709 } catch (NativeDaemonConnectorException e) {
1710 int code = e.getCode();
1711 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001712 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001713 } else {
1714 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1715 }
1716 }
1717 }
1718
1719 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001720 if (filename == null) {
1721 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001722 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001723
1724 synchronized (mObbMounts) {
1725 return mObbPathToStateMap.containsKey(filename);
1726 }
Kenny Root02c87302010-07-01 08:10:18 -07001727 }
1728
Kenny Rootaf9d6672010-10-08 09:21:39 -07001729 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001730 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001731 if (filename == null) {
1732 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001733 }
1734
1735 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001736 throw new IllegalArgumentException("token cannot be null");
1737 }
1738
Kenny Rootaf9d6672010-10-08 09:21:39 -07001739 final int callerUid = Binder.getCallingUid();
1740 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1741 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001742 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1743
1744 if (DEBUG_OBB)
1745 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001746 }
1747
Kenny Rootaf9d6672010-10-08 09:21:39 -07001748 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1749 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001750 if (filename == null) {
1751 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001752 }
1753
Kenny Rootaf9d6672010-10-08 09:21:39 -07001754 final int callerUid = Binder.getCallingUid();
1755 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1756 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001757 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001758
Kenny Roota02b8b02010-08-05 16:14:17 -07001759 if (DEBUG_OBB)
1760 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1761 }
1762
Jason parks5af0b912010-11-29 09:05:25 -06001763 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001764 if (TextUtils.isEmpty(password)) {
1765 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001766 }
1767
Jason parks8888c592011-01-20 22:46:41 -06001768 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1769 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001770
1771 waitForReady();
1772
1773 if (DEBUG_EVENTS) {
1774 Slog.i(TAG, "decrypting storage...");
1775 }
1776
1777 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001778 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001779 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001780
Jason parksf7b3cd42011-01-27 09:28:25 -06001781 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001782 return -1;
1783 }
1784
Jason parksf7b3cd42011-01-27 09:28:25 -06001785 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001786
1787 if (code == 0) {
1788 // Decrypt was successful. Post a delayed message before restarting in order
1789 // to let the UI to clear itself
1790 mHandler.postDelayed(new Runnable() {
1791 public void run() {
1792 mConnector.doCommand(String.format("cryptfs restart"));
1793 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001794 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001795 }
1796
1797 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001798 } catch (NativeDaemonConnectorException e) {
1799 // Decryption failed
1800 return e.getCode();
1801 }
Jason parks5af0b912010-11-29 09:05:25 -06001802 }
1803
Jason parks56aa5322011-01-07 09:01:15 -06001804 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001805 if (TextUtils.isEmpty(password)) {
1806 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001807 }
1808
Jason parks8888c592011-01-20 22:46:41 -06001809 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1810 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001811
1812 waitForReady();
1813
1814 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001815 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001816 }
1817
1818 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001819 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001820 } catch (NativeDaemonConnectorException e) {
1821 // Encryption failed
1822 return e.getCode();
1823 }
1824
1825 return 0;
1826 }
1827
Jason parksf7b3cd42011-01-27 09:28:25 -06001828 public int changeEncryptionPassword(String password) {
1829 if (TextUtils.isEmpty(password)) {
1830 throw new IllegalArgumentException("password cannot be empty");
1831 }
1832
1833 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1834 "no permission to access the crypt keeper");
1835
1836 waitForReady();
1837
1838 if (DEBUG_EVENTS) {
1839 Slog.i(TAG, "changing encryption password...");
1840 }
1841
1842 try {
1843 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1844
1845 String[] tokens = response.get(0).split(" ");
1846
1847 if (tokens == null || tokens.length != 2) {
1848 return -1;
1849 }
1850
1851 return Integer.parseInt(tokens[1]);
1852 } catch (NativeDaemonConnectorException e) {
1853 // Encryption failed
1854 return e.getCode();
1855 }
1856 }
1857
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001858 public Parcelable[] getVolumeList() {
1859 synchronized(mVolumes) {
1860 int size = mVolumes.size();
1861 Parcelable[] result = new Parcelable[size];
1862 for (int i = 0; i < size; i++) {
1863 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001864 }
1865 return result;
1866 }
1867 }
1868
Kenny Rootaf9d6672010-10-08 09:21:39 -07001869 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1870 final IBinder binder = obbState.getBinder();
1871 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001872
Kenny Rootaf9d6672010-10-08 09:21:39 -07001873 if (obbStates == null) {
1874 obbStates = new ArrayList<ObbState>();
1875 mObbMounts.put(binder, obbStates);
1876 } else {
1877 for (final ObbState o : obbStates) {
1878 if (o.filename.equals(obbState.filename)) {
1879 throw new IllegalStateException("Attempt to add ObbState twice. "
1880 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001881 }
1882 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001883 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001884
1885 obbStates.add(obbState);
1886 try {
1887 obbState.link();
1888 } catch (RemoteException e) {
1889 /*
1890 * The binder died before we could link it, so clean up our state
1891 * and return failure.
1892 */
1893 obbStates.remove(obbState);
1894 if (obbStates.isEmpty()) {
1895 mObbMounts.remove(binder);
1896 }
1897
1898 // Rethrow the error so mountObb can get it
1899 throw e;
1900 }
1901
1902 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001903 }
1904
Kenny Rootaf9d6672010-10-08 09:21:39 -07001905 private void removeObbStateLocked(ObbState obbState) {
1906 final IBinder binder = obbState.getBinder();
1907 final List<ObbState> obbStates = mObbMounts.get(binder);
1908 if (obbStates != null) {
1909 if (obbStates.remove(obbState)) {
1910 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001911 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001912 if (obbStates.isEmpty()) {
1913 mObbMounts.remove(binder);
1914 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001915 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001916
Kenny Rootaf9d6672010-10-08 09:21:39 -07001917 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001918 }
1919
Kenny Roota02b8b02010-08-05 16:14:17 -07001920 private class ObbActionHandler extends Handler {
1921 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001922 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001923
1924 ObbActionHandler(Looper l) {
1925 super(l);
1926 }
1927
1928 @Override
1929 public void handleMessage(Message msg) {
1930 switch (msg.what) {
1931 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001932 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001933
1934 if (DEBUG_OBB)
1935 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1936
1937 // If a bind was already initiated we don't really
1938 // need to do anything. The pending install
1939 // will be processed later on.
1940 if (!mBound) {
1941 // If this is the only one pending we might
1942 // have to bind to the service again.
1943 if (!connectToService()) {
1944 Slog.e(TAG, "Failed to bind to media container service");
1945 action.handleError();
1946 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001947 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001948 }
Kenny Root735de3b2010-09-30 14:11:39 -07001949
Kenny Root735de3b2010-09-30 14:11:39 -07001950 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001951 break;
1952 }
1953 case OBB_MCS_BOUND: {
1954 if (DEBUG_OBB)
1955 Slog.i(TAG, "OBB_MCS_BOUND");
1956 if (msg.obj != null) {
1957 mContainerService = (IMediaContainerService) msg.obj;
1958 }
1959 if (mContainerService == null) {
1960 // Something seriously wrong. Bail out
1961 Slog.e(TAG, "Cannot bind to media container service");
1962 for (ObbAction action : mActions) {
1963 // Indicate service bind error
1964 action.handleError();
1965 }
1966 mActions.clear();
1967 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001968 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001969 if (action != null) {
1970 action.execute(this);
1971 }
1972 } else {
1973 // Should never happen ideally.
1974 Slog.w(TAG, "Empty queue");
1975 }
1976 break;
1977 }
1978 case OBB_MCS_RECONNECT: {
1979 if (DEBUG_OBB)
1980 Slog.i(TAG, "OBB_MCS_RECONNECT");
1981 if (mActions.size() > 0) {
1982 if (mBound) {
1983 disconnectService();
1984 }
1985 if (!connectToService()) {
1986 Slog.e(TAG, "Failed to bind to media container service");
1987 for (ObbAction action : mActions) {
1988 // Indicate service bind error
1989 action.handleError();
1990 }
1991 mActions.clear();
1992 }
1993 }
1994 break;
1995 }
1996 case OBB_MCS_UNBIND: {
1997 if (DEBUG_OBB)
1998 Slog.i(TAG, "OBB_MCS_UNBIND");
1999
2000 // Delete pending install
2001 if (mActions.size() > 0) {
2002 mActions.remove(0);
2003 }
2004 if (mActions.size() == 0) {
2005 if (mBound) {
2006 disconnectService();
2007 }
2008 } else {
2009 // There are more pending requests in queue.
2010 // Just post MCS_BOUND message to trigger processing
2011 // of next pending install.
2012 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2013 }
2014 break;
2015 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002016 case OBB_FLUSH_MOUNT_STATE: {
2017 final String path = (String) msg.obj;
2018
2019 if (DEBUG_OBB)
2020 Slog.i(TAG, "Flushing all OBB state for path " + path);
2021
2022 synchronized (mObbMounts) {
2023 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2024
2025 final Iterator<Entry<String, ObbState>> i =
2026 mObbPathToStateMap.entrySet().iterator();
2027 while (i.hasNext()) {
2028 final Entry<String, ObbState> obbEntry = i.next();
2029
2030 /*
2031 * If this entry's source file is in the volume path
2032 * that got unmounted, remove it because it's no
2033 * longer valid.
2034 */
2035 if (obbEntry.getKey().startsWith(path)) {
2036 obbStatesToRemove.add(obbEntry.getValue());
2037 }
2038 }
2039
2040 for (final ObbState obbState : obbStatesToRemove) {
2041 if (DEBUG_OBB)
2042 Slog.i(TAG, "Removing state for " + obbState.filename);
2043
2044 removeObbStateLocked(obbState);
2045
2046 try {
2047 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2048 OnObbStateChangeListener.UNMOUNTED);
2049 } catch (RemoteException e) {
2050 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2051 + obbState.filename);
2052 }
2053 }
2054 }
2055 break;
2056 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002057 }
2058 }
2059
2060 private boolean connectToService() {
2061 if (DEBUG_OBB)
2062 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2063
2064 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2065 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2066 mBound = true;
2067 return true;
2068 }
2069 return false;
2070 }
2071
2072 private void disconnectService() {
2073 mContainerService = null;
2074 mBound = false;
2075 mContext.unbindService(mDefContainerConn);
2076 }
2077 }
2078
2079 abstract class ObbAction {
2080 private static final int MAX_RETRIES = 3;
2081 private int mRetries;
2082
2083 ObbState mObbState;
2084
2085 ObbAction(ObbState obbState) {
2086 mObbState = obbState;
2087 }
2088
2089 public void execute(ObbActionHandler handler) {
2090 try {
2091 if (DEBUG_OBB)
2092 Slog.i(TAG, "Starting to execute action: " + this.toString());
2093 mRetries++;
2094 if (mRetries > MAX_RETRIES) {
2095 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002096 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002097 handleError();
2098 return;
2099 } else {
2100 handleExecute();
2101 if (DEBUG_OBB)
2102 Slog.i(TAG, "Posting install MCS_UNBIND");
2103 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2104 }
2105 } catch (RemoteException e) {
2106 if (DEBUG_OBB)
2107 Slog.i(TAG, "Posting install MCS_RECONNECT");
2108 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2109 } catch (Exception e) {
2110 if (DEBUG_OBB)
2111 Slog.d(TAG, "Error handling OBB action", e);
2112 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002113 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002114 }
2115 }
2116
Kenny Root05105f72010-09-22 17:29:43 -07002117 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002118 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002119
2120 protected ObbInfo getObbInfo() throws IOException {
2121 ObbInfo obbInfo;
2122 try {
2123 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2124 } catch (RemoteException e) {
2125 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2126 + mObbState.filename);
2127 obbInfo = null;
2128 }
2129 if (obbInfo == null) {
2130 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2131 }
2132 return obbInfo;
2133 }
2134
Kenny Rootaf9d6672010-10-08 09:21:39 -07002135 protected void sendNewStatusOrIgnore(int status) {
2136 if (mObbState == null || mObbState.token == null) {
2137 return;
2138 }
2139
Kenny Root38cf8862010-09-26 14:18:51 -07002140 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002141 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002142 } catch (RemoteException e) {
2143 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2144 }
2145 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002146 }
2147
2148 class MountObbAction extends ObbAction {
2149 private String mKey;
2150
2151 MountObbAction(ObbState obbState, String key) {
2152 super(obbState);
2153 mKey = key;
2154 }
2155
Jason parks5af0b912010-11-29 09:05:25 -06002156 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002157 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002158 waitForReady();
2159 warnOnNotMounted();
2160
Kenny Root38cf8862010-09-26 14:18:51 -07002161 final ObbInfo obbInfo = getObbInfo();
2162
Kenny Roota02b8b02010-08-05 16:14:17 -07002163 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002164 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2165 + " which is owned by " + obbInfo.packageName);
2166 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2167 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002168 }
2169
Kenny Rootaf9d6672010-10-08 09:21:39 -07002170 final boolean isMounted;
2171 synchronized (mObbMounts) {
2172 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2173 }
2174 if (isMounted) {
2175 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2176 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2177 return;
2178 }
2179
2180 /*
2181 * The filename passed in might not be the canonical name, so just
2182 * set the filename to the canonicalized version.
2183 */
2184 mObbState.filename = obbInfo.filename;
2185
2186 final String hashedKey;
2187 if (mKey == null) {
2188 hashedKey = "none";
2189 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002190 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002191 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2192
2193 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2194 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2195 SecretKey key = factory.generateSecret(ks);
2196 BigInteger bi = new BigInteger(key.getEncoded());
2197 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002198 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002199 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2200 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2201 return;
2202 } catch (InvalidKeySpecException e) {
2203 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2204 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002205 return;
2206 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002207 }
Kenny Root38cf8862010-09-26 14:18:51 -07002208
Kenny Rootaf9d6672010-10-08 09:21:39 -07002209 int rc = StorageResultCode.OperationSucceeded;
2210 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2211 mObbState.callerUid);
2212 try {
2213 mConnector.doCommand(cmd);
2214 } catch (NativeDaemonConnectorException e) {
2215 int code = e.getCode();
2216 if (code != VoldResponseCode.OpFailedStorageBusy) {
2217 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002218 }
2219 }
2220
Kenny Rootaf9d6672010-10-08 09:21:39 -07002221 if (rc == StorageResultCode.OperationSucceeded) {
2222 if (DEBUG_OBB)
2223 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2224
2225 synchronized (mObbMounts) {
2226 addObbStateLocked(mObbState);
2227 }
2228
2229 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002230 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002231 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002232
Kenny Rootaf9d6672010-10-08 09:21:39 -07002233 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002234 }
2235 }
2236
Jason parks5af0b912010-11-29 09:05:25 -06002237 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002238 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002239 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002240 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002241
2242 @Override
2243 public String toString() {
2244 StringBuilder sb = new StringBuilder();
2245 sb.append("MountObbAction{");
2246 sb.append("filename=");
2247 sb.append(mObbState.filename);
2248 sb.append(",callerUid=");
2249 sb.append(mObbState.callerUid);
2250 sb.append(",token=");
2251 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002252 sb.append(",binder=");
2253 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002254 sb.append('}');
2255 return sb.toString();
2256 }
2257 }
2258
2259 class UnmountObbAction extends ObbAction {
2260 private boolean mForceUnmount;
2261
2262 UnmountObbAction(ObbState obbState, boolean force) {
2263 super(obbState);
2264 mForceUnmount = force;
2265 }
2266
Jason parks5af0b912010-11-29 09:05:25 -06002267 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002268 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002269 waitForReady();
2270 warnOnNotMounted();
2271
Kenny Root38cf8862010-09-26 14:18:51 -07002272 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002273
Kenny Rootaf9d6672010-10-08 09:21:39 -07002274 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002275 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002276 obbState = mObbPathToStateMap.get(obbInfo.filename);
2277 }
Kenny Root38cf8862010-09-26 14:18:51 -07002278
Kenny Rootaf9d6672010-10-08 09:21:39 -07002279 if (obbState == null) {
2280 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2281 return;
2282 }
2283
2284 if (obbState.callerUid != mObbState.callerUid) {
2285 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2286 + " (owned by " + obbInfo.packageName + ")");
2287 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2288 return;
2289 }
2290
2291 mObbState.filename = obbInfo.filename;
2292
2293 int rc = StorageResultCode.OperationSucceeded;
2294 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2295 (mForceUnmount ? " force" : ""));
2296 try {
2297 mConnector.doCommand(cmd);
2298 } catch (NativeDaemonConnectorException e) {
2299 int code = e.getCode();
2300 if (code == VoldResponseCode.OpFailedStorageBusy) {
2301 rc = StorageResultCode.OperationFailedStorageBusy;
2302 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2303 // If it's not mounted then we've already won.
2304 rc = StorageResultCode.OperationSucceeded;
2305 } else {
2306 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002307 }
2308 }
2309
Kenny Rootaf9d6672010-10-08 09:21:39 -07002310 if (rc == StorageResultCode.OperationSucceeded) {
2311 synchronized (mObbMounts) {
2312 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002313 }
2314
Kenny Rootaf9d6672010-10-08 09:21:39 -07002315 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002316 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2318 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002319 }
2320 }
2321
Jason parks5af0b912010-11-29 09:05:25 -06002322 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002323 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002324 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002325 }
2326
2327 @Override
2328 public String toString() {
2329 StringBuilder sb = new StringBuilder();
2330 sb.append("UnmountObbAction{");
2331 sb.append("filename=");
2332 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2333 sb.append(",force=");
2334 sb.append(mForceUnmount);
2335 sb.append(",callerUid=");
2336 sb.append(mObbState.callerUid);
2337 sb.append(",token=");
2338 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002339 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002340 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002341 sb.append('}');
2342 return sb.toString();
2343 }
Kenny Root02c87302010-07-01 08:10:18 -07002344 }
Kenny Root38cf8862010-09-26 14:18:51 -07002345
2346 @Override
2347 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2348 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2349 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2350 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2351 + " without permission " + android.Manifest.permission.DUMP);
2352 return;
2353 }
2354
Kenny Root38cf8862010-09-26 14:18:51 -07002355 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002356 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002357
Kenny Rootaf9d6672010-10-08 09:21:39 -07002358 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2359 while (binders.hasNext()) {
2360 Entry<IBinder, List<ObbState>> e = binders.next();
2361 pw.print(" Key="); pw.println(e.getKey().toString());
2362 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002363 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002364 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002365 }
2366 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002367
2368 pw.println("");
2369 pw.println(" mObbPathToStateMap:");
2370 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2371 while (maps.hasNext()) {
2372 final Entry<String, ObbState> e = maps.next();
2373 pw.print(" "); pw.print(e.getKey());
2374 pw.print(" -> "); pw.println(e.getValue().toString());
2375 }
Kenny Root38cf8862010-09-26 14:18:51 -07002376 }
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378}
2379