blob: f78dca96d24386234763ea8a6fbd7f74fa8c23b3 [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);
1124
1125 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1126 " primary: " + primary + " removable: " + removable +
1127 " emulated: " + emulated + " mtpReserve: " + mtpReserve);
1128 if (path == null || description == null) {
1129 Slog.e(TAG, "path or description is null in readStorageList");
1130 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001131 String pathString = path.toString();
1132 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001133 description.toString(), removable, emulated, mtpReserve);
1134 if (primary) {
1135 if (mPrimaryVolume == null) {
1136 mPrimaryVolume = volume;
1137 } else {
1138 Slog.e(TAG, "multiple primary volumes in storage list");
1139 }
1140 }
1141 if (mPrimaryVolume == volume) {
1142 // primay volume must be first
1143 mVolumes.add(0, volume);
1144 } else {
1145 mVolumes.add(volume);
1146 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001147 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001148 }
1149 a.recycle();
1150 }
1151 }
1152 } catch (XmlPullParserException e) {
1153 throw new RuntimeException(e);
1154 } catch (IOException e) {
1155 throw new RuntimeException(e);
1156 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001157 // compute storage ID for each volume
1158 int length = mVolumes.size();
1159 for (int i = 0; i < length; i++) {
1160 mVolumes.get(i).setStorageId(i);
1161 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001162 parser.close();
1163 }
1164 }
1165
San Mehat4270e1e2010-01-29 05:32:19 -08001166 /**
San Mehat207e5382010-02-04 20:46:54 -08001167 * Constructs a new MountService instance
1168 *
1169 * @param context Binder context for this service
1170 */
1171 public MountService(Context context) {
1172 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001173 Resources resources = context.getResources();
1174 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001175
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001176 if (mPrimaryVolume != null) {
1177 mExternalStoragePath = mPrimaryVolume.getPath();
1178 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1179 if (mEmulateExternalStorage) {
1180 Slog.d(TAG, "using emulated external storage");
1181 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1182 }
Mike Lockwood03559752010-07-19 18:25:03 -04001183 }
1184
San Mehat207e5382010-02-04 20:46:54 -08001185 // XXX: This will go away soon in favor of IMountServiceObserver
1186 mPms = (PackageManagerService) ServiceManager.getService("package");
1187
1188 mContext.registerReceiver(mBroadcastReceiver,
1189 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1190
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001191 mHandlerThread = new HandlerThread("MountService");
1192 mHandlerThread.start();
1193 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1194
Kenny Roota02b8b02010-08-05 16:14:17 -07001195 // Add OBB Action Handler to MountService thread.
1196 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1197
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001198 /*
1199 * Vold does not run in the simulator, so pretend the connector thread
1200 * ran and did its thing.
1201 */
1202 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1203 mReady = true;
1204 mUmsEnabling = true;
1205 return;
1206 }
1207
Kenny Root305bcbf2010-09-03 07:56:38 -07001208 /*
1209 * Create the connection to vold with a maximum queue of twice the
1210 * amount of containers we'd ever expect to have. This keeps an
1211 * "asec list" from blocking a thread repeatedly.
1212 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001213 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001214 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001215 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001216 thread.start();
1217 }
1218
1219 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001220 * Exposed API calls below here
1221 */
1222
1223 public void registerListener(IMountServiceListener listener) {
1224 synchronized (mListeners) {
1225 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1226 try {
1227 listener.asBinder().linkToDeath(bl, 0);
1228 mListeners.add(bl);
1229 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001230 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001231 }
1232 }
1233 }
1234
1235 public void unregisterListener(IMountServiceListener listener) {
1236 synchronized (mListeners) {
1237 for(MountServiceBinderListener bl : mListeners) {
1238 if (bl.mListener == listener) {
1239 mListeners.remove(mListeners.indexOf(bl));
1240 return;
1241 }
1242 }
1243 }
1244 }
1245
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001246 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001247 validatePermission(android.Manifest.permission.SHUTDOWN);
1248
San Mehata5078592010-03-25 09:36:54 -07001249 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001250 synchronized (mVolumeStates) {
1251 for (String path : mVolumeStates.keySet()) {
1252 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001253
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001254 if (state.equals(Environment.MEDIA_SHARED)) {
1255 /*
1256 * If the media is currently shared, unshare it.
1257 * XXX: This is still dangerous!. We should not
1258 * be rebooting at *all* if UMS is enabled, since
1259 * the UMS host could have dirty FAT cache entries
1260 * yet to flush.
1261 */
1262 setUsbMassStorageEnabled(false);
1263 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1264 /*
1265 * If the media is being checked, then we need to wait for
1266 * it to complete before being able to proceed.
1267 */
1268 // XXX: @hackbod - Should we disable the ANR timer here?
1269 int retries = 30;
1270 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1271 try {
1272 Thread.sleep(1000);
1273 } catch (InterruptedException iex) {
1274 Slog.e(TAG, "Interrupted while waiting for media", iex);
1275 break;
1276 }
1277 state = Environment.getExternalStorageState();
1278 }
1279 if (retries == 0) {
1280 Slog.e(TAG, "Timed out waiting for media to check");
1281 }
San Mehat91c77612010-01-07 10:39:41 -08001282 }
San Mehat91c77612010-01-07 10:39:41 -08001283
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001284 if (state.equals(Environment.MEDIA_MOUNTED)) {
1285 // Post a unmount message.
1286 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1287 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1288 } else if (observer != null) {
1289 /*
1290 * Observer is waiting for onShutDownComplete when we are done.
1291 * Since nothing will be done send notification directly so shutdown
1292 * sequence can continue.
1293 */
1294 try {
1295 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1296 } catch (RemoteException e) {
1297 Slog.w(TAG, "RemoteException when shutting down");
1298 }
1299 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001300 }
San Mehat4270e1e2010-01-29 05:32:19 -08001301 }
1302 }
1303
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001304 private boolean getUmsEnabling() {
1305 synchronized (mListeners) {
1306 return mUmsEnabling;
1307 }
1308 }
1309
1310 private void setUmsEnabling(boolean enable) {
1311 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001312 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001313 }
1314 }
1315
San Mehatb1043402010-02-05 08:26:50 -08001316 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001317 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001318
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001319 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001320 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001321 }
San Mehatb1043402010-02-05 08:26:50 -08001322 return doGetShareMethodAvailable("ums");
1323 }
1324
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001325 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001326 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001327 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001328
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001329 // TODO: Add support for multiple share methods
1330
1331 /*
1332 * If the volume is mounted and we're enabling then unmount it
1333 */
1334 String path = Environment.getExternalStorageDirectory().getPath();
1335 String vs = getVolumeState(path);
1336 String method = "ums";
1337 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1338 // Override for isUsbMassStorageEnabled()
1339 setUmsEnabling(enable);
1340 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1341 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1342 // Clear override
1343 setUmsEnabling(false);
1344 }
1345 /*
1346 * If we disabled UMS then mount the volume
1347 */
1348 if (!enable) {
1349 doShareUnshareVolume(path, method, enable);
1350 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001351 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001352 " after disabling share method " + method);
1353 /*
1354 * Even though the mount failed, the unshare didn't so don't indicate an error.
1355 * The mountVolume() call will have set the storage state and sent the necessary
1356 * broadcasts.
1357 */
1358 }
1359 }
San Mehatb1043402010-02-05 08:26:50 -08001360 }
1361
1362 public boolean isUsbMassStorageEnabled() {
1363 waitForReady();
1364 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001366
San Mehat7fd0fee2009-12-17 07:12:23 -08001367 /**
1368 * @return state of the volume at the specified mount point
1369 */
San Mehat4270e1e2010-01-29 05:32:19 -08001370 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001371 synchronized (mVolumeStates) {
1372 String state = mVolumeStates.get(mountPoint);
1373 if (state == null) {
1374 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1375 throw new IllegalArgumentException();
1376 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001377
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001378 return state;
1379 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001380 }
1381
Kenny Roote1ff2142010-10-12 11:20:01 -07001382 public boolean isExternalStorageEmulated() {
1383 return mEmulateExternalStorage;
1384 }
1385
San Mehat4270e1e2010-01-29 05:32:19 -08001386 public int mountVolume(String path) {
1387 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001388
San Mehat207e5382010-02-04 20:46:54 -08001389 waitForReady();
1390 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
1392
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001393 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001394 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001395 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001397 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001398 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001399 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1400 Environment.MEDIA_REMOVED.equals(volState) ||
1401 Environment.MEDIA_SHARED.equals(volState) ||
1402 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1403 // Media already unmounted or cannot be unmounted.
1404 // TODO return valid return code when adding observer call back.
1405 return;
1406 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001407 UnmountCallBack ucb = new UnmountCallBack(path, force);
1408 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 }
1410
San Mehat4270e1e2010-01-29 05:32:19 -08001411 public int formatVolume(String path) {
1412 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001413 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001414
San Mehat207e5382010-02-04 20:46:54 -08001415 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 }
1417
San Mehatc1b4ce92010-02-16 17:13:03 -08001418 public int []getStorageUsers(String path) {
1419 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1420 waitForReady();
1421 try {
1422 String[] r = mConnector.doListCommand(
1423 String.format("storage users %s", path),
1424 VoldResponseCode.StorageUsersListResult);
1425 // FMT: <pid> <process name>
1426 int[] data = new int[r.length];
1427 for (int i = 0; i < r.length; i++) {
1428 String []tok = r[i].split(" ");
1429 try {
1430 data[i] = Integer.parseInt(tok[0]);
1431 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001432 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001433 return new int[0];
1434 }
1435 }
1436 return data;
1437 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001438 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001439 return new int[0];
1440 }
1441 }
1442
San Mehatb1043402010-02-05 08:26:50 -08001443 private void warnOnNotMounted() {
1444 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001445 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001446 }
1447 }
1448
San Mehat4270e1e2010-01-29 05:32:19 -08001449 public String[] getSecureContainerList() {
1450 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001451 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001452 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001453
San Mehat4270e1e2010-01-29 05:32:19 -08001454 try {
1455 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1456 } catch (NativeDaemonConnectorException e) {
1457 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459 }
San Mehat36972292010-01-06 11:06:32 -08001460
San Mehat4270e1e2010-01-29 05:32:19 -08001461 public int createSecureContainer(String id, int sizeMb, String fstype,
1462 String key, int ownerUid) {
1463 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001464 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001465 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001466
San Mehatb1043402010-02-05 08:26:50 -08001467 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001468 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1469 try {
1470 mConnector.doCommand(cmd);
1471 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001472 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001473 }
San Mehata181b212010-02-11 06:50:20 -08001474
1475 if (rc == StorageResultCode.OperationSucceeded) {
1476 synchronized (mAsecMountSet) {
1477 mAsecMountSet.add(id);
1478 }
1479 }
San Mehat4270e1e2010-01-29 05:32:19 -08001480 return rc;
San Mehat36972292010-01-06 11:06:32 -08001481 }
1482
San Mehat4270e1e2010-01-29 05:32:19 -08001483 public int finalizeSecureContainer(String id) {
1484 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001485 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001486
San Mehatb1043402010-02-05 08:26:50 -08001487 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001488 try {
1489 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001490 /*
1491 * Finalization does a remount, so no need
1492 * to update mAsecMountSet
1493 */
San Mehat4270e1e2010-01-29 05:32:19 -08001494 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001495 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001496 }
San Mehat4270e1e2010-01-29 05:32:19 -08001497 return rc;
San Mehat36972292010-01-06 11:06:32 -08001498 }
1499
San Mehatd9709982010-02-18 11:43:03 -08001500 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001501 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001502 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001503 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001504
Kenny Rootaa485402010-09-14 14:49:41 -07001505 /*
1506 * Force a GC to make sure AssetManagers in other threads of the
1507 * system_server are cleaned up. We have to do this since AssetManager
1508 * instances are kept as a WeakReference and it's possible we have files
1509 * open on the external storage.
1510 */
1511 Runtime.getRuntime().gc();
1512
San Mehatb1043402010-02-05 08:26:50 -08001513 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001514 try {
San Mehatd9709982010-02-18 11:43:03 -08001515 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001516 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001517 int code = e.getCode();
1518 if (code == VoldResponseCode.OpFailedStorageBusy) {
1519 rc = StorageResultCode.OperationFailedStorageBusy;
1520 } else {
1521 rc = StorageResultCode.OperationFailedInternalError;
1522 }
San Mehat02735bc2010-01-26 15:18:08 -08001523 }
San Mehata181b212010-02-11 06:50:20 -08001524
1525 if (rc == StorageResultCode.OperationSucceeded) {
1526 synchronized (mAsecMountSet) {
1527 if (mAsecMountSet.contains(id)) {
1528 mAsecMountSet.remove(id);
1529 }
1530 }
1531 }
1532
San Mehat4270e1e2010-01-29 05:32:19 -08001533 return rc;
San Mehat36972292010-01-06 11:06:32 -08001534 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001535
San Mehat4270e1e2010-01-29 05:32:19 -08001536 public int mountSecureContainer(String id, String key, int ownerUid) {
1537 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001538 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001539 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001540
San Mehata181b212010-02-11 06:50:20 -08001541 synchronized (mAsecMountSet) {
1542 if (mAsecMountSet.contains(id)) {
1543 return StorageResultCode.OperationFailedStorageMounted;
1544 }
1545 }
1546
San Mehatb1043402010-02-05 08:26:50 -08001547 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001548 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1549 try {
1550 mConnector.doCommand(cmd);
1551 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001552 int code = e.getCode();
1553 if (code != VoldResponseCode.OpFailedStorageBusy) {
1554 rc = StorageResultCode.OperationFailedInternalError;
1555 }
San Mehat02735bc2010-01-26 15:18:08 -08001556 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001557
1558 if (rc == StorageResultCode.OperationSucceeded) {
1559 synchronized (mAsecMountSet) {
1560 mAsecMountSet.add(id);
1561 }
1562 }
San Mehat4270e1e2010-01-29 05:32:19 -08001563 return rc;
San Mehat36972292010-01-06 11:06:32 -08001564 }
1565
San Mehatd9709982010-02-18 11:43:03 -08001566 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001567 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001568 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001569 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001570
San Mehat6cdd9c02010-02-09 14:45:20 -08001571 synchronized (mAsecMountSet) {
1572 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001573 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001574 }
1575 }
1576
Kenny Rootaa485402010-09-14 14:49:41 -07001577 /*
1578 * Force a GC to make sure AssetManagers in other threads of the
1579 * system_server are cleaned up. We have to do this since AssetManager
1580 * instances are kept as a WeakReference and it's possible we have files
1581 * open on the external storage.
1582 */
1583 Runtime.getRuntime().gc();
1584
San Mehatb1043402010-02-05 08:26:50 -08001585 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001586 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001587 try {
1588 mConnector.doCommand(cmd);
1589 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001590 int code = e.getCode();
1591 if (code == VoldResponseCode.OpFailedStorageBusy) {
1592 rc = StorageResultCode.OperationFailedStorageBusy;
1593 } else {
1594 rc = StorageResultCode.OperationFailedInternalError;
1595 }
San Mehat02735bc2010-01-26 15:18:08 -08001596 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001597
1598 if (rc == StorageResultCode.OperationSucceeded) {
1599 synchronized (mAsecMountSet) {
1600 mAsecMountSet.remove(id);
1601 }
1602 }
San Mehat4270e1e2010-01-29 05:32:19 -08001603 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001604 }
1605
San Mehat6cdd9c02010-02-09 14:45:20 -08001606 public boolean isSecureContainerMounted(String id) {
1607 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1608 waitForReady();
1609 warnOnNotMounted();
1610
1611 synchronized (mAsecMountSet) {
1612 return mAsecMountSet.contains(id);
1613 }
1614 }
1615
San Mehat4270e1e2010-01-29 05:32:19 -08001616 public int renameSecureContainer(String oldId, String newId) {
1617 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001618 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001619 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001620
San Mehata181b212010-02-11 06:50:20 -08001621 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001622 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001623 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001624 * changed while active, we must ensure both ids are not currently mounted.
1625 */
1626 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001627 return StorageResultCode.OperationFailedStorageMounted;
1628 }
1629 }
1630
San Mehatb1043402010-02-05 08:26:50 -08001631 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001632 String cmd = String.format("asec rename %s %s", oldId, newId);
1633 try {
1634 mConnector.doCommand(cmd);
1635 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001636 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001637 }
San Mehata181b212010-02-11 06:50:20 -08001638
San Mehat4270e1e2010-01-29 05:32:19 -08001639 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001640 }
1641
San Mehat4270e1e2010-01-29 05:32:19 -08001642 public String getSecureContainerPath(String id) {
1643 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001644 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001645 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001646
San Mehat2d66cef2010-03-23 11:12:52 -07001647 try {
1648 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1649 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001650 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001651 if (code != VoldResponseCode.AsecPathResult) {
1652 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1653 }
1654 return tok[1];
1655 } catch (NativeDaemonConnectorException e) {
1656 int code = e.getCode();
1657 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001658 Slog.i(TAG, String.format("Container '%s' not found", id));
1659 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001660 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001661 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001662 }
1663 }
San Mehat22dd86e2010-01-12 12:21:18 -08001664 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001665
1666 public void finishMediaUpdate() {
1667 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1668 }
Kenny Root02c87302010-07-01 08:10:18 -07001669
Kenny Roota02b8b02010-08-05 16:14:17 -07001670 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1671 if (callerUid == android.os.Process.SYSTEM_UID) {
1672 return true;
1673 }
1674
Kenny Root02c87302010-07-01 08:10:18 -07001675 if (packageName == null) {
1676 return false;
1677 }
1678
1679 final int packageUid = mPms.getPackageUid(packageName);
1680
1681 if (DEBUG_OBB) {
1682 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1683 packageUid + ", callerUid = " + callerUid);
1684 }
1685
1686 return callerUid == packageUid;
1687 }
1688
1689 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001690 if (filename == null) {
1691 throw new IllegalArgumentException("filename cannot be null");
1692 }
1693
Kenny Root02c87302010-07-01 08:10:18 -07001694 waitForReady();
1695 warnOnNotMounted();
1696
Kenny Root02c87302010-07-01 08:10:18 -07001697 try {
1698 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1699 String []tok = rsp.get(0).split(" ");
1700 int code = Integer.parseInt(tok[0]);
1701 if (code != VoldResponseCode.AsecPathResult) {
1702 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1703 }
1704 return tok[1];
1705 } catch (NativeDaemonConnectorException e) {
1706 int code = e.getCode();
1707 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001708 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001709 } else {
1710 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1711 }
1712 }
1713 }
1714
1715 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001716 if (filename == null) {
1717 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001718 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001719
1720 synchronized (mObbMounts) {
1721 return mObbPathToStateMap.containsKey(filename);
1722 }
Kenny Root02c87302010-07-01 08:10:18 -07001723 }
1724
Kenny Rootaf9d6672010-10-08 09:21:39 -07001725 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001726 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001727 if (filename == null) {
1728 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001729 }
1730
1731 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001732 throw new IllegalArgumentException("token cannot be null");
1733 }
1734
Kenny Rootaf9d6672010-10-08 09:21:39 -07001735 final int callerUid = Binder.getCallingUid();
1736 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1737 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001738 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1739
1740 if (DEBUG_OBB)
1741 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001742 }
1743
Kenny Rootaf9d6672010-10-08 09:21:39 -07001744 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1745 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001746 if (filename == null) {
1747 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001748 }
1749
Kenny Rootaf9d6672010-10-08 09:21:39 -07001750 final int callerUid = Binder.getCallingUid();
1751 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1752 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001753 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001754
Kenny Roota02b8b02010-08-05 16:14:17 -07001755 if (DEBUG_OBB)
1756 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1757 }
1758
Jason parks5af0b912010-11-29 09:05:25 -06001759 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001760 if (TextUtils.isEmpty(password)) {
1761 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001762 }
1763
Jason parks8888c592011-01-20 22:46:41 -06001764 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1765 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001766
1767 waitForReady();
1768
1769 if (DEBUG_EVENTS) {
1770 Slog.i(TAG, "decrypting storage...");
1771 }
1772
1773 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001774 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001775 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001776
Jason parksf7b3cd42011-01-27 09:28:25 -06001777 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001778 return -1;
1779 }
1780
Jason parksf7b3cd42011-01-27 09:28:25 -06001781 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001782
1783 if (code == 0) {
1784 // Decrypt was successful. Post a delayed message before restarting in order
1785 // to let the UI to clear itself
1786 mHandler.postDelayed(new Runnable() {
1787 public void run() {
1788 mConnector.doCommand(String.format("cryptfs restart"));
1789 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001790 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001791 }
1792
1793 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001794 } catch (NativeDaemonConnectorException e) {
1795 // Decryption failed
1796 return e.getCode();
1797 }
Jason parks5af0b912010-11-29 09:05:25 -06001798 }
1799
Jason parks56aa5322011-01-07 09:01:15 -06001800 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001801 if (TextUtils.isEmpty(password)) {
1802 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001803 }
1804
Jason parks8888c592011-01-20 22:46:41 -06001805 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1806 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001807
1808 waitForReady();
1809
1810 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001811 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001812 }
1813
1814 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001815 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001816 } catch (NativeDaemonConnectorException e) {
1817 // Encryption failed
1818 return e.getCode();
1819 }
1820
1821 return 0;
1822 }
1823
Jason parksf7b3cd42011-01-27 09:28:25 -06001824 public int changeEncryptionPassword(String password) {
1825 if (TextUtils.isEmpty(password)) {
1826 throw new IllegalArgumentException("password cannot be empty");
1827 }
1828
1829 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1830 "no permission to access the crypt keeper");
1831
1832 waitForReady();
1833
1834 if (DEBUG_EVENTS) {
1835 Slog.i(TAG, "changing encryption password...");
1836 }
1837
1838 try {
1839 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1840
1841 String[] tokens = response.get(0).split(" ");
1842
1843 if (tokens == null || tokens.length != 2) {
1844 return -1;
1845 }
1846
1847 return Integer.parseInt(tokens[1]);
1848 } catch (NativeDaemonConnectorException e) {
1849 // Encryption failed
1850 return e.getCode();
1851 }
1852 }
1853
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001854 public Parcelable[] getVolumeList() {
1855 synchronized(mVolumes) {
1856 int size = mVolumes.size();
1857 Parcelable[] result = new Parcelable[size];
1858 for (int i = 0; i < size; i++) {
1859 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001860 }
1861 return result;
1862 }
1863 }
1864
Kenny Rootaf9d6672010-10-08 09:21:39 -07001865 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1866 final IBinder binder = obbState.getBinder();
1867 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001868
Kenny Rootaf9d6672010-10-08 09:21:39 -07001869 if (obbStates == null) {
1870 obbStates = new ArrayList<ObbState>();
1871 mObbMounts.put(binder, obbStates);
1872 } else {
1873 for (final ObbState o : obbStates) {
1874 if (o.filename.equals(obbState.filename)) {
1875 throw new IllegalStateException("Attempt to add ObbState twice. "
1876 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001877 }
1878 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001879 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001880
1881 obbStates.add(obbState);
1882 try {
1883 obbState.link();
1884 } catch (RemoteException e) {
1885 /*
1886 * The binder died before we could link it, so clean up our state
1887 * and return failure.
1888 */
1889 obbStates.remove(obbState);
1890 if (obbStates.isEmpty()) {
1891 mObbMounts.remove(binder);
1892 }
1893
1894 // Rethrow the error so mountObb can get it
1895 throw e;
1896 }
1897
1898 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001899 }
1900
Kenny Rootaf9d6672010-10-08 09:21:39 -07001901 private void removeObbStateLocked(ObbState obbState) {
1902 final IBinder binder = obbState.getBinder();
1903 final List<ObbState> obbStates = mObbMounts.get(binder);
1904 if (obbStates != null) {
1905 if (obbStates.remove(obbState)) {
1906 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001907 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001908 if (obbStates.isEmpty()) {
1909 mObbMounts.remove(binder);
1910 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001911 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001912
Kenny Rootaf9d6672010-10-08 09:21:39 -07001913 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001914 }
1915
Kenny Roota02b8b02010-08-05 16:14:17 -07001916 private class ObbActionHandler extends Handler {
1917 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001918 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001919
1920 ObbActionHandler(Looper l) {
1921 super(l);
1922 }
1923
1924 @Override
1925 public void handleMessage(Message msg) {
1926 switch (msg.what) {
1927 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001928 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001929
1930 if (DEBUG_OBB)
1931 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1932
1933 // If a bind was already initiated we don't really
1934 // need to do anything. The pending install
1935 // will be processed later on.
1936 if (!mBound) {
1937 // If this is the only one pending we might
1938 // have to bind to the service again.
1939 if (!connectToService()) {
1940 Slog.e(TAG, "Failed to bind to media container service");
1941 action.handleError();
1942 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001943 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 }
Kenny Root735de3b2010-09-30 14:11:39 -07001945
Kenny Root735de3b2010-09-30 14:11:39 -07001946 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001947 break;
1948 }
1949 case OBB_MCS_BOUND: {
1950 if (DEBUG_OBB)
1951 Slog.i(TAG, "OBB_MCS_BOUND");
1952 if (msg.obj != null) {
1953 mContainerService = (IMediaContainerService) msg.obj;
1954 }
1955 if (mContainerService == null) {
1956 // Something seriously wrong. Bail out
1957 Slog.e(TAG, "Cannot bind to media container service");
1958 for (ObbAction action : mActions) {
1959 // Indicate service bind error
1960 action.handleError();
1961 }
1962 mActions.clear();
1963 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001964 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001965 if (action != null) {
1966 action.execute(this);
1967 }
1968 } else {
1969 // Should never happen ideally.
1970 Slog.w(TAG, "Empty queue");
1971 }
1972 break;
1973 }
1974 case OBB_MCS_RECONNECT: {
1975 if (DEBUG_OBB)
1976 Slog.i(TAG, "OBB_MCS_RECONNECT");
1977 if (mActions.size() > 0) {
1978 if (mBound) {
1979 disconnectService();
1980 }
1981 if (!connectToService()) {
1982 Slog.e(TAG, "Failed to bind to media container service");
1983 for (ObbAction action : mActions) {
1984 // Indicate service bind error
1985 action.handleError();
1986 }
1987 mActions.clear();
1988 }
1989 }
1990 break;
1991 }
1992 case OBB_MCS_UNBIND: {
1993 if (DEBUG_OBB)
1994 Slog.i(TAG, "OBB_MCS_UNBIND");
1995
1996 // Delete pending install
1997 if (mActions.size() > 0) {
1998 mActions.remove(0);
1999 }
2000 if (mActions.size() == 0) {
2001 if (mBound) {
2002 disconnectService();
2003 }
2004 } else {
2005 // There are more pending requests in queue.
2006 // Just post MCS_BOUND message to trigger processing
2007 // of next pending install.
2008 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2009 }
2010 break;
2011 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002012 case OBB_FLUSH_MOUNT_STATE: {
2013 final String path = (String) msg.obj;
2014
2015 if (DEBUG_OBB)
2016 Slog.i(TAG, "Flushing all OBB state for path " + path);
2017
2018 synchronized (mObbMounts) {
2019 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2020
2021 final Iterator<Entry<String, ObbState>> i =
2022 mObbPathToStateMap.entrySet().iterator();
2023 while (i.hasNext()) {
2024 final Entry<String, ObbState> obbEntry = i.next();
2025
2026 /*
2027 * If this entry's source file is in the volume path
2028 * that got unmounted, remove it because it's no
2029 * longer valid.
2030 */
2031 if (obbEntry.getKey().startsWith(path)) {
2032 obbStatesToRemove.add(obbEntry.getValue());
2033 }
2034 }
2035
2036 for (final ObbState obbState : obbStatesToRemove) {
2037 if (DEBUG_OBB)
2038 Slog.i(TAG, "Removing state for " + obbState.filename);
2039
2040 removeObbStateLocked(obbState);
2041
2042 try {
2043 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2044 OnObbStateChangeListener.UNMOUNTED);
2045 } catch (RemoteException e) {
2046 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2047 + obbState.filename);
2048 }
2049 }
2050 }
2051 break;
2052 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002053 }
2054 }
2055
2056 private boolean connectToService() {
2057 if (DEBUG_OBB)
2058 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2059
2060 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2061 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2062 mBound = true;
2063 return true;
2064 }
2065 return false;
2066 }
2067
2068 private void disconnectService() {
2069 mContainerService = null;
2070 mBound = false;
2071 mContext.unbindService(mDefContainerConn);
2072 }
2073 }
2074
2075 abstract class ObbAction {
2076 private static final int MAX_RETRIES = 3;
2077 private int mRetries;
2078
2079 ObbState mObbState;
2080
2081 ObbAction(ObbState obbState) {
2082 mObbState = obbState;
2083 }
2084
2085 public void execute(ObbActionHandler handler) {
2086 try {
2087 if (DEBUG_OBB)
2088 Slog.i(TAG, "Starting to execute action: " + this.toString());
2089 mRetries++;
2090 if (mRetries > MAX_RETRIES) {
2091 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002092 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002093 handleError();
2094 return;
2095 } else {
2096 handleExecute();
2097 if (DEBUG_OBB)
2098 Slog.i(TAG, "Posting install MCS_UNBIND");
2099 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2100 }
2101 } catch (RemoteException e) {
2102 if (DEBUG_OBB)
2103 Slog.i(TAG, "Posting install MCS_RECONNECT");
2104 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2105 } catch (Exception e) {
2106 if (DEBUG_OBB)
2107 Slog.d(TAG, "Error handling OBB action", e);
2108 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002109 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002110 }
2111 }
2112
Kenny Root05105f72010-09-22 17:29:43 -07002113 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002114 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002115
2116 protected ObbInfo getObbInfo() throws IOException {
2117 ObbInfo obbInfo;
2118 try {
2119 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2120 } catch (RemoteException e) {
2121 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2122 + mObbState.filename);
2123 obbInfo = null;
2124 }
2125 if (obbInfo == null) {
2126 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2127 }
2128 return obbInfo;
2129 }
2130
Kenny Rootaf9d6672010-10-08 09:21:39 -07002131 protected void sendNewStatusOrIgnore(int status) {
2132 if (mObbState == null || mObbState.token == null) {
2133 return;
2134 }
2135
Kenny Root38cf8862010-09-26 14:18:51 -07002136 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002137 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002138 } catch (RemoteException e) {
2139 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2140 }
2141 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002142 }
2143
2144 class MountObbAction extends ObbAction {
2145 private String mKey;
2146
2147 MountObbAction(ObbState obbState, String key) {
2148 super(obbState);
2149 mKey = key;
2150 }
2151
Jason parks5af0b912010-11-29 09:05:25 -06002152 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002153 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154 waitForReady();
2155 warnOnNotMounted();
2156
Kenny Root38cf8862010-09-26 14:18:51 -07002157 final ObbInfo obbInfo = getObbInfo();
2158
Kenny Roota02b8b02010-08-05 16:14:17 -07002159 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002160 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2161 + " which is owned by " + obbInfo.packageName);
2162 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2163 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002164 }
2165
Kenny Rootaf9d6672010-10-08 09:21:39 -07002166 final boolean isMounted;
2167 synchronized (mObbMounts) {
2168 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2169 }
2170 if (isMounted) {
2171 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2172 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2173 return;
2174 }
2175
2176 /*
2177 * The filename passed in might not be the canonical name, so just
2178 * set the filename to the canonicalized version.
2179 */
2180 mObbState.filename = obbInfo.filename;
2181
2182 final String hashedKey;
2183 if (mKey == null) {
2184 hashedKey = "none";
2185 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002186 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002187 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2188
2189 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2190 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2191 SecretKey key = factory.generateSecret(ks);
2192 BigInteger bi = new BigInteger(key.getEncoded());
2193 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002194 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002195 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2196 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2197 return;
2198 } catch (InvalidKeySpecException e) {
2199 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2200 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002201 return;
2202 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002203 }
Kenny Root38cf8862010-09-26 14:18:51 -07002204
Kenny Rootaf9d6672010-10-08 09:21:39 -07002205 int rc = StorageResultCode.OperationSucceeded;
2206 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2207 mObbState.callerUid);
2208 try {
2209 mConnector.doCommand(cmd);
2210 } catch (NativeDaemonConnectorException e) {
2211 int code = e.getCode();
2212 if (code != VoldResponseCode.OpFailedStorageBusy) {
2213 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002214 }
2215 }
2216
Kenny Rootaf9d6672010-10-08 09:21:39 -07002217 if (rc == StorageResultCode.OperationSucceeded) {
2218 if (DEBUG_OBB)
2219 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2220
2221 synchronized (mObbMounts) {
2222 addObbStateLocked(mObbState);
2223 }
2224
2225 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002226 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002227 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002228
Kenny Rootaf9d6672010-10-08 09:21:39 -07002229 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002230 }
2231 }
2232
Jason parks5af0b912010-11-29 09:05:25 -06002233 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002234 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002235 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002236 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002237
2238 @Override
2239 public String toString() {
2240 StringBuilder sb = new StringBuilder();
2241 sb.append("MountObbAction{");
2242 sb.append("filename=");
2243 sb.append(mObbState.filename);
2244 sb.append(",callerUid=");
2245 sb.append(mObbState.callerUid);
2246 sb.append(",token=");
2247 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002248 sb.append(",binder=");
2249 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002250 sb.append('}');
2251 return sb.toString();
2252 }
2253 }
2254
2255 class UnmountObbAction extends ObbAction {
2256 private boolean mForceUnmount;
2257
2258 UnmountObbAction(ObbState obbState, boolean force) {
2259 super(obbState);
2260 mForceUnmount = force;
2261 }
2262
Jason parks5af0b912010-11-29 09:05:25 -06002263 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002264 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002265 waitForReady();
2266 warnOnNotMounted();
2267
Kenny Root38cf8862010-09-26 14:18:51 -07002268 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002269
Kenny Rootaf9d6672010-10-08 09:21:39 -07002270 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002271 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272 obbState = mObbPathToStateMap.get(obbInfo.filename);
2273 }
Kenny Root38cf8862010-09-26 14:18:51 -07002274
Kenny Rootaf9d6672010-10-08 09:21:39 -07002275 if (obbState == null) {
2276 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2277 return;
2278 }
2279
2280 if (obbState.callerUid != mObbState.callerUid) {
2281 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2282 + " (owned by " + obbInfo.packageName + ")");
2283 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2284 return;
2285 }
2286
2287 mObbState.filename = obbInfo.filename;
2288
2289 int rc = StorageResultCode.OperationSucceeded;
2290 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2291 (mForceUnmount ? " force" : ""));
2292 try {
2293 mConnector.doCommand(cmd);
2294 } catch (NativeDaemonConnectorException e) {
2295 int code = e.getCode();
2296 if (code == VoldResponseCode.OpFailedStorageBusy) {
2297 rc = StorageResultCode.OperationFailedStorageBusy;
2298 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2299 // If it's not mounted then we've already won.
2300 rc = StorageResultCode.OperationSucceeded;
2301 } else {
2302 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002303 }
2304 }
2305
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 if (rc == StorageResultCode.OperationSucceeded) {
2307 synchronized (mObbMounts) {
2308 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002309 }
2310
Kenny Rootaf9d6672010-10-08 09:21:39 -07002311 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002312 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002313 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2314 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002315 }
2316 }
2317
Jason parks5af0b912010-11-29 09:05:25 -06002318 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002319 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002320 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002321 }
2322
2323 @Override
2324 public String toString() {
2325 StringBuilder sb = new StringBuilder();
2326 sb.append("UnmountObbAction{");
2327 sb.append("filename=");
2328 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2329 sb.append(",force=");
2330 sb.append(mForceUnmount);
2331 sb.append(",callerUid=");
2332 sb.append(mObbState.callerUid);
2333 sb.append(",token=");
2334 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002335 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002336 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002337 sb.append('}');
2338 return sb.toString();
2339 }
Kenny Root02c87302010-07-01 08:10:18 -07002340 }
Kenny Root38cf8862010-09-26 14:18:51 -07002341
2342 @Override
2343 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2344 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2345 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2346 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2347 + " without permission " + android.Manifest.permission.DUMP);
2348 return;
2349 }
2350
Kenny Root38cf8862010-09-26 14:18:51 -07002351 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002352 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002353
Kenny Rootaf9d6672010-10-08 09:21:39 -07002354 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2355 while (binders.hasNext()) {
2356 Entry<IBinder, List<ObbState>> e = binders.next();
2357 pw.print(" Key="); pw.println(e.getKey().toString());
2358 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002359 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002360 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002361 }
2362 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002363
2364 pw.println("");
2365 pw.println(" mObbPathToStateMap:");
2366 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2367 while (maps.hasNext()) {
2368 final Entry<String, ObbState> e = maps.next();
2369 pw.print(" "); pw.print(e.getKey());
2370 pw.print(" -> "); pw.println(e.getValue().toString());
2371 }
Kenny Root38cf8862010-09-26 14:18:51 -07002372 }
2373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374}
2375