blob: 54e54327f8f713ca0f1f7156a27b7492e30eba77 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070020import com.android.internal.util.XmlUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
Kenny Rootcf0b38c2011-03-22 14:17:59 -070022import com.android.server.pm.PackageManagerService;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080023
Jason parks8888c592011-01-20 22:46:41 -060024import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070026import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070030import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070033import android.content.res.Resources;
34import android.content.res.TypedArray;
35import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070036import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070038import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070039import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070045import android.os.Parcelable;
San Mehat4270e1e2010-01-29 05:32:19 -080046import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080047import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080048import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
62import org.xmlpull.v1.XmlPullParser;
63import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070064
Kenny Root38cf8862010-09-26 14:18:51 -070065import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070066import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070067import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070068import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070069import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070070import java.security.spec.InvalidKeySpecException;
71import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080072import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070073import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080074import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070076import java.util.LinkedList;
77import java.util.List;
78import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.util.Map.Entry;
Mike Lockwood8fa5f802011-03-24 08:12:30 -070080import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Kenny Root3b1abba2010-10-13 15:00:07 -070082import javax.crypto.SecretKey;
83import javax.crypto.SecretKeyFactory;
84import javax.crypto.spec.PBEKeySpec;
85
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086/**
San Mehatb1043402010-02-05 08:26:50 -080087 * MountService implements back-end services for platform storage
88 * management.
89 * @hide - Applications should use android.os.storage.StorageManager
90 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 */
Jason parks5af0b912010-11-29 09:05:25 -060092class MountService extends IMountService.Stub implements INativeDaemonConnectorCallbacks {
93
San Mehatb1043402010-02-05 08:26:50 -080094 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080095 private static final boolean DEBUG_UNMOUNT = false;
96 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -080097 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -070098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private static final String TAG = "MountService";
100
Kenny Root305bcbf2010-09-03 07:56:38 -0700101 private static final String VOLD_TAG = "VoldConnector";
102
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700103 /** Maximum number of ASEC containers allowed to be mounted. */
104 private static final int MAX_CONTAINERS = 250;
105
San Mehat4270e1e2010-01-29 05:32:19 -0800106 /*
107 * Internal vold volume state constants
108 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800109 class VolumeState {
110 public static final int Init = -1;
111 public static final int NoMedia = 0;
112 public static final int Idle = 1;
113 public static final int Pending = 2;
114 public static final int Checking = 3;
115 public static final int Mounted = 4;
116 public static final int Unmounting = 5;
117 public static final int Formatting = 6;
118 public static final int Shared = 7;
119 public static final int SharedMnt = 8;
120 }
121
San Mehat4270e1e2010-01-29 05:32:19 -0800122 /*
123 * Internal vold response code constants
124 */
San Mehat22dd86e2010-01-12 12:21:18 -0800125 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800126 /*
127 * 100 series - Requestion action was initiated; expect another reply
128 * before proceeding with a new command.
129 */
San Mehat22dd86e2010-01-12 12:21:18 -0800130 public static final int VolumeListResult = 110;
131 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800132 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800133
San Mehat4270e1e2010-01-29 05:32:19 -0800134 /*
135 * 200 series - Requestion action has been successfully completed.
136 */
137 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800138 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800139 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800140
San Mehat4270e1e2010-01-29 05:32:19 -0800141 /*
142 * 400 series - Command was accepted, but the requested action
143 * did not take place.
144 */
145 public static final int OpFailedNoMedia = 401;
146 public static final int OpFailedMediaBlank = 402;
147 public static final int OpFailedMediaCorrupt = 403;
148 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800149 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700150 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800151
152 /*
153 * 600 series - Unsolicited broadcasts.
154 */
San Mehat22dd86e2010-01-12 12:21:18 -0800155 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800156 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;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700170 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800171 // Used as a lock for methods that register/unregister listeners.
172 final private ArrayList<MountServiceBinderListener> mListeners =
173 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800174 private boolean mBooted = false;
175 private boolean mReady = false;
176 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400177 // true if we should fake MEDIA_MOUNTED state for external storage
178 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800179
San Mehat6cdd9c02010-02-09 14:45:20 -0800180 /**
181 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800182 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800183 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800184 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800185
Kenny Root02c87302010-07-01 08:10:18 -0700186 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700187 * The size of the crypto algorithm key in bits for OBB files. Currently
188 * Twofish is used which takes 128-bit keys.
189 */
190 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
191
192 /**
193 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
194 * 1024 is reasonably secure and not too slow.
195 */
196 private static final int PBKDF2_HASH_ROUNDS = 1024;
197
198 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700199 * Mounted OBB tracking information. Used to track the current state of all
200 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700201 */
Kenny Root735de3b2010-09-30 14:11:39 -0700202 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
204
205 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700206 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700207 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700208 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700209 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700210 this.token = token;
211 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700212 }
213
214 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700215 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700216
217 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700218 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700219
Kenny Rootaf9d6672010-10-08 09:21:39 -0700220 // Token of remote Binder caller
221 final IObbActionListener token;
222
223 // Identifier to pass back to the token
224 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700225
Kenny Root735de3b2010-09-30 14:11:39 -0700226 public IBinder getBinder() {
227 return token.asBinder();
228 }
229
Kenny Roota02b8b02010-08-05 16:14:17 -0700230 @Override
231 public void binderDied() {
232 ObbAction action = new UnmountObbAction(this, true);
233 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700234 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700235
Kenny Root5919ac62010-10-05 09:49:40 -0700236 public void link() throws RemoteException {
237 getBinder().linkToDeath(this, 0);
238 }
239
240 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700241 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700242 }
Kenny Root38cf8862010-09-26 14:18:51 -0700243
244 @Override
245 public String toString() {
246 StringBuilder sb = new StringBuilder("ObbState{");
247 sb.append("filename=");
248 sb.append(filename);
249 sb.append(",token=");
250 sb.append(token.toString());
251 sb.append(",callerUid=");
252 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700253 sb.append('}');
254 return sb.toString();
255 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700256 }
257
258 // OBB Action Handler
259 final private ObbActionHandler mObbActionHandler;
260
261 // OBB action handler messages
262 private static final int OBB_RUN_ACTION = 1;
263 private static final int OBB_MCS_BOUND = 2;
264 private static final int OBB_MCS_UNBIND = 3;
265 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700266 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700267
268 /*
269 * Default Container Service information
270 */
271 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
272 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
273
274 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
275
276 class DefaultContainerConnection implements ServiceConnection {
277 public void onServiceConnected(ComponentName name, IBinder service) {
278 if (DEBUG_OBB)
279 Slog.i(TAG, "onServiceConnected");
280 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
281 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
282 }
283
284 public void onServiceDisconnected(ComponentName name) {
285 if (DEBUG_OBB)
286 Slog.i(TAG, "onServiceDisconnected");
287 }
288 };
289
290 // Used in the ObbActionHandler
291 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700292
293 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800294 private static final int H_UNMOUNT_PM_UPDATE = 1;
295 private static final int H_UNMOUNT_PM_DONE = 2;
296 private static final int H_UNMOUNT_MS = 3;
297 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
298 private static final int MAX_UNMOUNT_RETRIES = 4;
299
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800300 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700301 final String path;
302 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800303 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800304
305 UnmountCallBack(String path, boolean force) {
306 retries = 0;
307 this.path = path;
308 this.force = force;
309 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800310
311 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700312 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800313 doUnmountVolume(path, true);
314 }
315 }
316
317 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700318 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800319
320 UmsEnableCallBack(String path, String method, boolean force) {
321 super(path, force);
322 this.method = method;
323 }
324
325 @Override
326 void handleFinished() {
327 super.handleFinished();
328 doShareUnshareVolume(path, method, true);
329 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800330 }
331
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800332 class ShutdownCallBack extends UnmountCallBack {
333 IMountShutdownObserver observer;
334 ShutdownCallBack(String path, IMountShutdownObserver observer) {
335 super(path, true);
336 this.observer = observer;
337 }
338
339 @Override
340 void handleFinished() {
341 int ret = doUnmountVolume(path, true);
342 if (observer != null) {
343 try {
344 observer.onShutDownComplete(ret);
345 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700346 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800347 }
348 }
349 }
350 }
351
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400352 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700354 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800355
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400356 MountServiceHandler(Looper l) {
357 super(l);
358 }
359
Jason parks5af0b912010-11-29 09:05:25 -0600360 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800361 public void handleMessage(Message msg) {
362 switch (msg.what) {
363 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700364 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
366 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700367 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800368 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700369 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700370 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700371 mUpdatingStatus = true;
372 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800373 }
374 break;
375 }
376 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700377 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700378 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700379 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 int size = mForceUnmounts.size();
381 int sizeArr[] = new int[size];
382 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700383 // Kill processes holding references first
384 ActivityManagerService ams = (ActivityManagerService)
385 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800386 for (int i = 0; i < size; i++) {
387 UnmountCallBack ucb = mForceUnmounts.get(i);
388 String path = ucb.path;
389 boolean done = false;
390 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800391 done = true;
392 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800393 int pids[] = getStorageUsers(path);
394 if (pids == null || pids.length == 0) {
395 done = true;
396 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800397 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800398 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700399 // Confirm if file references have been freed.
400 pids = getStorageUsers(path);
401 if (pids == null || pids.length == 0) {
402 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800403 }
404 }
405 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700406 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
407 // Retry again
408 Slog.i(TAG, "Retrying to kill storage users again");
409 mHandler.sendMessageDelayed(
410 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
411 ucb.retries++),
412 RETRY_UNMOUNT_DELAY);
413 } else {
414 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
415 Slog.i(TAG, "Failed to unmount media inspite of " +
416 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
417 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800418 sizeArr[sizeArrN++] = i;
419 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
420 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 }
422 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800423 // Remove already processed elements from list.
424 for (int i = (sizeArrN-1); i >= 0; i--) {
425 mForceUnmounts.remove(sizeArr[i]);
426 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800427 break;
428 }
429 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700430 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800431 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800432 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800433 break;
434 }
435 }
436 }
437 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400438 final private HandlerThread mHandlerThread;
439 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800440
San Mehat207e5382010-02-04 20:46:54 -0800441 private void waitForReady() {
442 while (mReady == false) {
443 for (int retries = 5; retries > 0; retries--) {
444 if (mReady) {
445 return;
446 }
447 SystemClock.sleep(1000);
448 }
San Mehata5078592010-03-25 09:36:54 -0700449 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800450 }
San Mehat1f6301e2010-01-07 22:40:27 -0800451 }
Kenny Root02c87302010-07-01 08:10:18 -0700452
San Mehat207e5382010-02-04 20:46:54 -0800453 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600454 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800456 String action = intent.getAction();
457
458 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800459 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800460
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800461 /*
462 * In the simulator, we need to broadcast a volume mounted event
463 * to make the media scanner run.
464 */
465 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400466 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia,
467 VolumeState.Mounted);
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800468 return;
469 }
San Mehatfafb0412010-02-18 19:40:04 -0800470 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600471 @Override
San Mehatfafb0412010-02-18 19:40:04 -0800472 public void run() {
473 try {
Mike Lockwood84338c42011-04-05 10:05:47 -0400474 // it is not safe to call vold with mVolumeStates locked
475 // so we make a copy of the paths and states and process them
476 // outside the lock
477 String[] paths, states;
478 int count;
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400479 synchronized (mVolumeStates) {
Mike Lockwood84338c42011-04-05 10:05:47 -0400480 Set<String> keys = mVolumeStates.keySet();
481 count = keys.size();
482 paths = (String[])keys.toArray(new String[count]);
483 states = new String[count];
484 for (int i = 0; i < count; i++) {
485 states[i] = mVolumeStates.get(paths[i]);
486 }
487 }
San Mehat6a254402010-03-22 10:21:00 -0700488
Mike Lockwood84338c42011-04-05 10:05:47 -0400489 for (int i = 0; i < count; i++) {
490 String path = paths[i];
491 String state = states[i];
492
493 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
494 int rc = doMountVolume(path);
495 if (rc != StorageResultCode.OperationSucceeded) {
496 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
497 rc));
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400498 }
Mike Lockwood84338c42011-04-05 10:05:47 -0400499 } else if (state.equals(Environment.MEDIA_SHARED)) {
500 /*
501 * Bootstrap UMS enabled state since vold indicates
502 * the volume is shared (runtime restart while ums enabled)
503 */
504 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
505 VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800506 }
507 }
San Mehat6a254402010-03-22 10:21:00 -0700508
Mike Lockwood80e0a412011-04-05 10:21:51 -0400509 /* notify external storage has mounted to trigger media scanner */
510 if (mEmulateExternalStorage) {
511 notifyVolumeStateChange(null,
512 Environment.getExternalStorageDirectory().getPath(),
513 VolumeState.NoMedia, VolumeState.Mounted);
514 }
515
San Mehat6a965af22010-02-24 17:47:30 -0800516 /*
San Mehat6a254402010-03-22 10:21:00 -0700517 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800518 * now that we're up.
519 */
520 if (mSendUmsConnectedOnBoot) {
521 sendUmsIntent(true);
522 mSendUmsConnectedOnBoot = false;
523 }
San Mehatfafb0412010-02-18 19:40:04 -0800524 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700525 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800526 }
San Mehat207e5382010-02-04 20:46:54 -0800527 }
San Mehatfafb0412010-02-18 19:40:04 -0800528 }.start();
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700529 } else if (action.equals(UsbManager.ACTION_USB_STATE)) {
530 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
531 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
532 notifyShareAvailabilityChange(available);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
534 }
535 };
San Mehat4270e1e2010-01-29 05:32:19 -0800536 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
537 final IMountServiceListener mListener;
538
539 MountServiceBinderListener(IMountServiceListener listener) {
540 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700541
San Mehat91c77612010-01-07 10:39:41 -0800542 }
543
San Mehat4270e1e2010-01-29 05:32:19 -0800544 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700545 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700546 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800547 mListeners.remove(this);
548 mListener.asBinder().unlinkToDeath(this, 0);
549 }
550 }
551 }
552
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800553 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800554 // TODO: Add support for multiple share methods
555 if (!method.equals("ums")) {
556 throw new IllegalArgumentException(String.format("Method %s not supported", method));
557 }
558
San Mehat4270e1e2010-01-29 05:32:19 -0800559 try {
560 mConnector.doCommand(String.format(
561 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
562 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700563 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800564 }
San Mehat4270e1e2010-01-29 05:32:19 -0800565 }
566
San Mehat207e5382010-02-04 20:46:54 -0800567 private void updatePublicVolumeState(String path, String state) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400568 String oldState;
569 synchronized(mVolumeStates) {
570 oldState = mVolumeStates.put(path, state);
571 }
572 if (state.equals(oldState)) {
573 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
574 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800575 return;
576 }
San Mehatb1043402010-02-05 08:26:50 -0800577
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400578 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700579
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400580 if (path.equals(mExternalStoragePath)) {
581 // Update state on PackageManager, but only of real events
582 if (!mEmulateExternalStorage) {
583 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
584 mPms.updateExternalMediaStatus(false, false);
585
586 /*
587 * Some OBBs might have been unmounted when this volume was
588 * unmounted, so send a message to the handler to let it know to
589 * remove those from the list of mounted OBBS.
590 */
591 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
592 OBB_FLUSH_MOUNT_STATE, path));
593 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
594 mPms.updateExternalMediaStatus(true, false);
595 }
Mike Lockwood03559752010-07-19 18:25:03 -0400596 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800597 }
San Mehat4270e1e2010-01-29 05:32:19 -0800598 synchronized (mListeners) {
599 for (int i = mListeners.size() -1; i >= 0; i--) {
600 MountServiceBinderListener bl = mListeners.get(i);
601 try {
San Mehatb1043402010-02-05 08:26:50 -0800602 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800603 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700604 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800605 mListeners.remove(i);
606 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700607 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800608 }
609 }
610 }
611 }
612
613 /**
614 *
615 * Callback from NativeDaemonConnector
616 */
617 public void onDaemonConnected() {
618 /*
619 * Since we'll be calling back into the NativeDaemonConnector,
620 * we need to do our work in a new thread.
621 */
622 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600623 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800624 public void run() {
625 /**
626 * Determine media state and UMS detection status
627 */
San Mehat4270e1e2010-01-29 05:32:19 -0800628 try {
629 String[] vols = mConnector.doListCommand(
630 "volume list", VoldResponseCode.VolumeListResult);
631 for (String volstr : vols) {
632 String[] tok = volstr.split(" ");
633 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400634 String path = tok[1];
635 String state = Environment.MEDIA_REMOVED;
636
San Mehat4270e1e2010-01-29 05:32:19 -0800637 int st = Integer.parseInt(tok[2]);
638 if (st == VolumeState.NoMedia) {
639 state = Environment.MEDIA_REMOVED;
640 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800641 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800642 } else if (st == VolumeState.Mounted) {
643 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700644 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800645 } else if (st == VolumeState.Shared) {
646 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700647 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800648 } else {
649 throw new Exception(String.format("Unexpected state %d", st));
650 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400651
652 if (state != null) {
653 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
654 updatePublicVolumeState(path, state);
655 }
San Mehat4270e1e2010-01-29 05:32:19 -0800656 }
657 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700658 Slog.e(TAG, "Error processing initial volume state", e);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400659 updatePublicVolumeState(mExternalStoragePath, Environment.MEDIA_REMOVED);
San Mehat4270e1e2010-01-29 05:32:19 -0800660 }
661
San Mehat207e5382010-02-04 20:46:54 -0800662 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600663 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800664 * the hounds!
665 */
666 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800667 }
668 }.start();
669 }
670
671 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800672 * Callback from NativeDaemonConnector
673 */
674 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800675 if (DEBUG_EVENTS) {
676 StringBuilder builder = new StringBuilder();
677 builder.append("onEvent::");
678 builder.append(" raw= " + raw);
679 if (cooked != null) {
680 builder.append(" cooked = " );
681 for (String str : cooked) {
682 builder.append(" " + str);
683 }
684 }
San Mehata5078592010-03-25 09:36:54 -0700685 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800686 }
San Mehat4270e1e2010-01-29 05:32:19 -0800687 if (code == VoldResponseCode.VolumeStateChange) {
688 /*
689 * One of the volumes we're managing has changed state.
690 * Format: "NNN Volume <label> <path> state changed
691 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
692 */
693 notifyVolumeStateChange(
694 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
695 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800696 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
697 (code == VoldResponseCode.VolumeDiskRemoved) ||
698 (code == VoldResponseCode.VolumeBadRemoval)) {
699 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
700 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
701 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400702 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800703 final String label = cooked[2];
704 final String path = cooked[3];
705 int major = -1;
706 int minor = -1;
707
708 try {
709 String devComp = cooked[6].substring(1, cooked[6].length() -1);
710 String[] devTok = devComp.split(":");
711 major = Integer.parseInt(devTok[0]);
712 minor = Integer.parseInt(devTok[1]);
713 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700714 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800715 }
716
San Mehat4270e1e2010-01-29 05:32:19 -0800717 if (code == VoldResponseCode.VolumeDiskInserted) {
718 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600719 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800720 public void run() {
721 try {
722 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800723 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700724 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800725 }
726 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700727 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800728 }
729 }
730 }.start();
731 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
732 /*
733 * This event gets trumped if we're already in BAD_REMOVAL state
734 */
735 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
736 return true;
737 }
738 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700739 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800740 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400741 sendStorageIntent(Environment.MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800742
San Mehata5078592010-03-25 09:36:54 -0700743 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800744 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400745 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800746 } else if (code == VoldResponseCode.VolumeBadRemoval) {
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 /* Send the media unmounted event first */
749 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400750 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800751
San Mehata5078592010-03-25 09:36:54 -0700752 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800753 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400754 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800755 } else {
San Mehata5078592010-03-25 09:36:54 -0700756 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800757 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400758
759 if (action != null) {
760 sendStorageIntent(action, path);
761 }
San Mehat4270e1e2010-01-29 05:32:19 -0800762 } else {
763 return false;
764 }
765
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400766 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800767 }
768
San Mehat207e5382010-02-04 20:46:54 -0800769 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800770 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700771 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800772
Mike Lockwooda5250c92011-05-23 13:44:04 -0400773 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800774
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500775 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700776 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwooda5250c92011-05-23 13:44:04 -0400777 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, path);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500778 }
779
San Mehat4270e1e2010-01-29 05:32:19 -0800780 if (newState == VolumeState.Init) {
781 } else if (newState == VolumeState.NoMedia) {
782 // NoMedia is handled via Disk Remove events
783 } else if (newState == VolumeState.Idle) {
784 /*
785 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
786 * if we're in the process of enabling UMS
787 */
788 if (!vs.equals(
789 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
790 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800791 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700792 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800793 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400794 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800795 }
796 } else if (newState == VolumeState.Pending) {
797 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700798 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800799 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400800 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800801 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700802 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800803 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400804 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800805 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400806 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800807 } else if (newState == VolumeState.Formatting) {
808 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700809 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800810 /* Send the media unmounted event first */
811 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400812 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800813
San Mehata5078592010-03-25 09:36:54 -0700814 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800815 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400816 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700817 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800818 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700819 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800820 return;
821 } else {
San Mehata5078592010-03-25 09:36:54 -0700822 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800823 }
824
Mike Lockwooda5250c92011-05-23 13:44:04 -0400825 if (action != null) {
826 sendStorageIntent(action, path);
San Mehat4270e1e2010-01-29 05:32:19 -0800827 }
828 }
829
San Mehat207e5382010-02-04 20:46:54 -0800830 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800831 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800832
San Mehata5078592010-03-25 09:36:54 -0700833 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800834 try {
835 mConnector.doCommand(String.format("volume mount %s", path));
836 } catch (NativeDaemonConnectorException e) {
837 /*
838 * Mount failed for some reason
839 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400840 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800841 int code = e.getCode();
842 if (code == VoldResponseCode.OpFailedNoMedia) {
843 /*
844 * Attempt to mount but no media inserted
845 */
San Mehatb1043402010-02-05 08:26:50 -0800846 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800847 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700848 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800849 /*
850 * Media is blank or does not contain a supported filesystem
851 */
852 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400853 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800854 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800855 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700856 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800857 /*
858 * Volume consistency check failed
859 */
860 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400861 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800862 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800863 } else {
San Mehatb1043402010-02-05 08:26:50 -0800864 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800865 }
866
867 /*
868 * Send broadcast intent (if required for the failure)
869 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400870 if (action != null) {
871 sendStorageIntent(action, path);
San Mehat207e5382010-02-04 20:46:54 -0800872 }
873 }
874
875 return rc;
876 }
877
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800878 /*
879 * If force is not set, we do not unmount if there are
880 * processes holding references to the volume about to be unmounted.
881 * If force is set, all the processes holding references need to be
882 * killed via the ActivityManager before actually unmounting the volume.
883 * This might even take a while and might be retried after timed delays
884 * to make sure we dont end up in an instable state and kill some core
885 * processes.
886 */
San Mehatd9709982010-02-18 11:43:03 -0800887 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800888 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800889 return VoldResponseCode.OpFailedVolNotMounted;
890 }
Kenny Rootaa485402010-09-14 14:49:41 -0700891
892 /*
893 * Force a GC to make sure AssetManagers in other threads of the
894 * system_server are cleaned up. We have to do this since AssetManager
895 * instances are kept as a WeakReference and it's possible we have files
896 * open on the external storage.
897 */
898 Runtime.getRuntime().gc();
899
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800900 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700901 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800902 try {
San Mehatd9709982010-02-18 11:43:03 -0800903 mConnector.doCommand(String.format(
904 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700905 // We unmounted the volume. None of the asec containers are available now.
906 synchronized (mAsecMountSet) {
907 mAsecMountSet.clear();
908 }
San Mehatb1043402010-02-05 08:26:50 -0800909 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800910 } catch (NativeDaemonConnectorException e) {
911 // Don't worry about mismatch in PackageManager since the
912 // call back will handle the status changes any way.
913 int code = e.getCode();
914 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800915 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800916 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
917 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800918 } else {
San Mehatb1043402010-02-05 08:26:50 -0800919 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800920 }
921 }
922 }
923
924 private int doFormatVolume(String path) {
925 try {
926 String cmd = String.format("volume format %s", path);
927 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800928 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800929 } catch (NativeDaemonConnectorException e) {
930 int code = e.getCode();
931 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800932 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800933 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800935 } else {
San Mehatb1043402010-02-05 08:26:50 -0800936 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800937 }
938 }
939 }
940
San Mehatb1043402010-02-05 08:26:50 -0800941 private boolean doGetVolumeShared(String path, String method) {
942 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700943 ArrayList<String> rsp;
944
945 try {
946 rsp = mConnector.doCommand(cmd);
947 } catch (NativeDaemonConnectorException ex) {
948 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
949 return false;
950 }
San Mehatb1043402010-02-05 08:26:50 -0800951
952 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700953 String[] tok = line.split(" ");
954 if (tok.length < 3) {
955 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
956 return false;
957 }
958
San Mehatb1043402010-02-05 08:26:50 -0800959 int code;
960 try {
961 code = Integer.parseInt(tok[0]);
962 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700963 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800964 return false;
965 }
966 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700967 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800968 } else {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800970 return false;
971 }
972 }
San Mehata5078592010-03-25 09:36:54 -0700973 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800974 return false;
975 }
976
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700977 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800978 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700979 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800980 for (int i = mListeners.size() -1; i >= 0; i--) {
981 MountServiceBinderListener bl = mListeners.get(i);
982 try {
San Mehatb1043402010-02-05 08:26:50 -0800983 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800984 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700985 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800986 mListeners.remove(i);
987 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700988 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800989 }
990 }
991 }
992
San Mehat207e5382010-02-04 20:46:54 -0800993 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800994 sendUmsIntent(avail);
995 } else {
996 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800997 }
San Mehat2fe718a2010-03-11 12:01:49 -0800998
999 final String path = Environment.getExternalStorageDirectory().getPath();
1000 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1001 /*
1002 * USB mass storage disconnected while enabled
1003 */
1004 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001005 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001006 public void run() {
1007 try {
1008 int rc;
San Mehata5078592010-03-25 09:36:54 -07001009 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001010 doShareUnshareVolume(path, "ums", false);
1011 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001012 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001013 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1014 path, rc));
1015 }
1016 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001017 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001018 }
1019 }
1020 }.start();
1021 }
San Mehat4270e1e2010-01-29 05:32:19 -08001022 }
1023
Mike Lockwooda5250c92011-05-23 13:44:04 -04001024 private void sendStorageIntent(String action, String path) {
1025 Intent intent = new Intent(action, Uri.parse("file://" + path));
1026 // add StorageVolume extra
1027 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, mVolumeMap.get(path));
1028 Slog.d(TAG, "sendStorageIntent " + intent);
1029 mContext.sendBroadcast(intent);
1030 }
1031
San Mehat6a965af22010-02-24 17:47:30 -08001032 private void sendUmsIntent(boolean c) {
1033 mContext.sendBroadcast(
1034 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1035 }
1036
San Mehat207e5382010-02-04 20:46:54 -08001037 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001038 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1039 throw new SecurityException(String.format("Requires %s permission", perm));
1040 }
1041 }
1042
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001043 // Storage list XML tags
1044 private static final String TAG_STORAGE_LIST = "StorageList";
1045 private static final String TAG_STORAGE = "storage";
1046
1047 private void readStorageList(Resources resources) {
1048 int id = com.android.internal.R.xml.storage_list;
1049 XmlResourceParser parser = resources.getXml(id);
1050 AttributeSet attrs = Xml.asAttributeSet(parser);
1051
1052 try {
1053 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1054 while (true) {
1055 XmlUtils.nextElement(parser);
1056
1057 String element = parser.getName();
1058 if (element == null) break;
1059
1060 if (TAG_STORAGE.equals(element)) {
1061 TypedArray a = resources.obtainAttributes(attrs,
1062 com.android.internal.R.styleable.Storage);
1063
1064 CharSequence path = a.getText(
1065 com.android.internal.R.styleable.Storage_mountPoint);
1066 CharSequence description = a.getText(
1067 com.android.internal.R.styleable.Storage_storageDescription);
1068 boolean primary = a.getBoolean(
1069 com.android.internal.R.styleable.Storage_primary, false);
1070 boolean removable = a.getBoolean(
1071 com.android.internal.R.styleable.Storage_removable, false);
1072 boolean emulated = a.getBoolean(
1073 com.android.internal.R.styleable.Storage_emulated, false);
1074 int mtpReserve = a.getInt(
1075 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001076 boolean allowMassStorage = a.getBoolean(
1077 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001078
1079 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1080 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001081 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
1082 " allowMassStorage: " + allowMassStorage);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001083 if (path == null || description == null) {
1084 Slog.e(TAG, "path or description is null in readStorageList");
1085 } else {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001086 String pathString = path.toString();
1087 StorageVolume volume = new StorageVolume(pathString,
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001088 description.toString(), removable, emulated,
1089 mtpReserve, allowMassStorage);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001090 if (primary) {
1091 if (mPrimaryVolume == null) {
1092 mPrimaryVolume = volume;
1093 } else {
1094 Slog.e(TAG, "multiple primary volumes in storage list");
1095 }
1096 }
1097 if (mPrimaryVolume == volume) {
1098 // primay volume must be first
1099 mVolumes.add(0, volume);
1100 } else {
1101 mVolumes.add(volume);
1102 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001103 mVolumeMap.put(pathString, volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001104 }
1105 a.recycle();
1106 }
1107 }
1108 } catch (XmlPullParserException e) {
1109 throw new RuntimeException(e);
1110 } catch (IOException e) {
1111 throw new RuntimeException(e);
1112 } finally {
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001113 // compute storage ID for each volume
1114 int length = mVolumes.size();
1115 for (int i = 0; i < length; i++) {
1116 mVolumes.get(i).setStorageId(i);
1117 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001118 parser.close();
1119 }
1120 }
1121
San Mehat4270e1e2010-01-29 05:32:19 -08001122 /**
San Mehat207e5382010-02-04 20:46:54 -08001123 * Constructs a new MountService instance
1124 *
1125 * @param context Binder context for this service
1126 */
1127 public MountService(Context context) {
1128 mContext = context;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001129 Resources resources = context.getResources();
1130 readStorageList(resources);
San Mehat207e5382010-02-04 20:46:54 -08001131
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001132 if (mPrimaryVolume != null) {
1133 mExternalStoragePath = mPrimaryVolume.getPath();
1134 mEmulateExternalStorage = mPrimaryVolume.isEmulated();
1135 if (mEmulateExternalStorage) {
1136 Slog.d(TAG, "using emulated external storage");
1137 mVolumeStates.put(mExternalStoragePath, Environment.MEDIA_MOUNTED);
1138 }
Mike Lockwood03559752010-07-19 18:25:03 -04001139 }
1140
San Mehat207e5382010-02-04 20:46:54 -08001141 // XXX: This will go away soon in favor of IMountServiceObserver
1142 mPms = (PackageManagerService) ServiceManager.getService("package");
1143
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001144 IntentFilter filter = new IntentFilter();
1145 filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1146 // don't bother monitoring USB if mass storage is not supported on our primary volume
1147 if (mPrimaryVolume != null && mPrimaryVolume.allowMassStorage()) {
1148 filter.addAction(UsbManager.ACTION_USB_STATE);
1149 }
1150 mContext.registerReceiver(mBroadcastReceiver, filter, null, null);
San Mehat207e5382010-02-04 20:46:54 -08001151
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001152 mHandlerThread = new HandlerThread("MountService");
1153 mHandlerThread.start();
1154 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1155
Kenny Roota02b8b02010-08-05 16:14:17 -07001156 // Add OBB Action Handler to MountService thread.
1157 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1158
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001159 /*
1160 * Vold does not run in the simulator, so pretend the connector thread
1161 * ran and did its thing.
1162 */
1163 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1164 mReady = true;
1165 mUmsEnabling = true;
1166 return;
1167 }
1168
Kenny Root305bcbf2010-09-03 07:56:38 -07001169 /*
1170 * Create the connection to vold with a maximum queue of twice the
1171 * amount of containers we'd ever expect to have. This keeps an
1172 * "asec list" from blocking a thread repeatedly.
1173 */
Kenny Rootcf0b38c2011-03-22 14:17:59 -07001174 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001175 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001176 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001177 thread.start();
1178 }
1179
1180 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001181 * Exposed API calls below here
1182 */
1183
1184 public void registerListener(IMountServiceListener listener) {
1185 synchronized (mListeners) {
1186 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1187 try {
1188 listener.asBinder().linkToDeath(bl, 0);
1189 mListeners.add(bl);
1190 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001191 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001192 }
1193 }
1194 }
1195
1196 public void unregisterListener(IMountServiceListener listener) {
1197 synchronized (mListeners) {
1198 for(MountServiceBinderListener bl : mListeners) {
1199 if (bl.mListener == listener) {
1200 mListeners.remove(mListeners.indexOf(bl));
1201 return;
1202 }
1203 }
1204 }
1205 }
1206
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001207 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001208 validatePermission(android.Manifest.permission.SHUTDOWN);
1209
San Mehata5078592010-03-25 09:36:54 -07001210 Slog.i(TAG, "Shutting down");
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001211 synchronized (mVolumeStates) {
1212 for (String path : mVolumeStates.keySet()) {
1213 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001214
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001215 if (state.equals(Environment.MEDIA_SHARED)) {
1216 /*
1217 * If the media is currently shared, unshare it.
1218 * XXX: This is still dangerous!. We should not
1219 * be rebooting at *all* if UMS is enabled, since
1220 * the UMS host could have dirty FAT cache entries
1221 * yet to flush.
1222 */
1223 setUsbMassStorageEnabled(false);
1224 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1225 /*
1226 * If the media is being checked, then we need to wait for
1227 * it to complete before being able to proceed.
1228 */
1229 // XXX: @hackbod - Should we disable the ANR timer here?
1230 int retries = 30;
1231 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1232 try {
1233 Thread.sleep(1000);
1234 } catch (InterruptedException iex) {
1235 Slog.e(TAG, "Interrupted while waiting for media", iex);
1236 break;
1237 }
1238 state = Environment.getExternalStorageState();
1239 }
1240 if (retries == 0) {
1241 Slog.e(TAG, "Timed out waiting for media to check");
1242 }
San Mehat91c77612010-01-07 10:39:41 -08001243 }
San Mehat91c77612010-01-07 10:39:41 -08001244
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001245 if (state.equals(Environment.MEDIA_MOUNTED)) {
1246 // Post a unmount message.
1247 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1248 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1249 } else if (observer != null) {
1250 /*
1251 * Observer is waiting for onShutDownComplete when we are done.
1252 * Since nothing will be done send notification directly so shutdown
1253 * sequence can continue.
1254 */
1255 try {
1256 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1257 } catch (RemoteException e) {
1258 Slog.w(TAG, "RemoteException when shutting down");
1259 }
1260 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001261 }
San Mehat4270e1e2010-01-29 05:32:19 -08001262 }
1263 }
1264
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001265 private boolean getUmsEnabling() {
1266 synchronized (mListeners) {
1267 return mUmsEnabling;
1268 }
1269 }
1270
1271 private void setUmsEnabling(boolean enable) {
1272 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001273 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001274 }
1275 }
1276
San Mehatb1043402010-02-05 08:26:50 -08001277 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001278 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001279
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001280 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001281 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001282 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001283 synchronized (mListeners) {
1284 return mUmsAvailable;
1285 }
San Mehatb1043402010-02-05 08:26:50 -08001286 }
1287
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001288 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001289 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001290 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001291
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001292 // TODO: Add support for multiple share methods
1293
1294 /*
1295 * If the volume is mounted and we're enabling then unmount it
1296 */
1297 String path = Environment.getExternalStorageDirectory().getPath();
1298 String vs = getVolumeState(path);
1299 String method = "ums";
1300 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1301 // Override for isUsbMassStorageEnabled()
1302 setUmsEnabling(enable);
1303 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1304 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1305 // Clear override
1306 setUmsEnabling(false);
1307 }
1308 /*
1309 * If we disabled UMS then mount the volume
1310 */
1311 if (!enable) {
1312 doShareUnshareVolume(path, method, enable);
1313 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001314 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001315 " after disabling share method " + method);
1316 /*
1317 * Even though the mount failed, the unshare didn't so don't indicate an error.
1318 * The mountVolume() call will have set the storage state and sent the necessary
1319 * broadcasts.
1320 */
1321 }
1322 }
San Mehatb1043402010-02-05 08:26:50 -08001323 }
1324
1325 public boolean isUsbMassStorageEnabled() {
1326 waitForReady();
1327 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001329
San Mehat7fd0fee2009-12-17 07:12:23 -08001330 /**
1331 * @return state of the volume at the specified mount point
1332 */
San Mehat4270e1e2010-01-29 05:32:19 -08001333 public String getVolumeState(String mountPoint) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001334 synchronized (mVolumeStates) {
1335 String state = mVolumeStates.get(mountPoint);
1336 if (state == null) {
1337 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
1338 throw new IllegalArgumentException();
1339 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001340
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001341 return state;
1342 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001343 }
1344
Kenny Roote1ff2142010-10-12 11:20:01 -07001345 public boolean isExternalStorageEmulated() {
1346 return mEmulateExternalStorage;
1347 }
1348
San Mehat4270e1e2010-01-29 05:32:19 -08001349 public int mountVolume(String path) {
1350 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001351
San Mehat207e5382010-02-04 20:46:54 -08001352 waitForReady();
1353 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001356 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001357 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001358 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001360 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001361 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001362 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1363 Environment.MEDIA_REMOVED.equals(volState) ||
1364 Environment.MEDIA_SHARED.equals(volState) ||
1365 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1366 // Media already unmounted or cannot be unmounted.
1367 // TODO return valid return code when adding observer call back.
1368 return;
1369 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001370 UnmountCallBack ucb = new UnmountCallBack(path, force);
1371 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373
San Mehat4270e1e2010-01-29 05:32:19 -08001374 public int formatVolume(String path) {
1375 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001376 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001377
San Mehat207e5382010-02-04 20:46:54 -08001378 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
1380
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001381 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001382 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1383 waitForReady();
1384 try {
1385 String[] r = mConnector.doListCommand(
1386 String.format("storage users %s", path),
1387 VoldResponseCode.StorageUsersListResult);
1388 // FMT: <pid> <process name>
1389 int[] data = new int[r.length];
1390 for (int i = 0; i < r.length; i++) {
1391 String []tok = r[i].split(" ");
1392 try {
1393 data[i] = Integer.parseInt(tok[0]);
1394 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001395 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001396 return new int[0];
1397 }
1398 }
1399 return data;
1400 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001401 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001402 return new int[0];
1403 }
1404 }
1405
San Mehatb1043402010-02-05 08:26:50 -08001406 private void warnOnNotMounted() {
1407 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001408 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001409 }
1410 }
1411
San Mehat4270e1e2010-01-29 05:32:19 -08001412 public String[] getSecureContainerList() {
1413 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001414 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001415 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001416
San Mehat4270e1e2010-01-29 05:32:19 -08001417 try {
1418 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1419 } catch (NativeDaemonConnectorException e) {
1420 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422 }
San Mehat36972292010-01-06 11:06:32 -08001423
San Mehat4270e1e2010-01-29 05:32:19 -08001424 public int createSecureContainer(String id, int sizeMb, String fstype,
1425 String key, int ownerUid) {
1426 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001427 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001428 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001429
San Mehatb1043402010-02-05 08:26:50 -08001430 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001431 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1432 try {
1433 mConnector.doCommand(cmd);
1434 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001435 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001436 }
San Mehata181b212010-02-11 06:50:20 -08001437
1438 if (rc == StorageResultCode.OperationSucceeded) {
1439 synchronized (mAsecMountSet) {
1440 mAsecMountSet.add(id);
1441 }
1442 }
San Mehat4270e1e2010-01-29 05:32:19 -08001443 return rc;
San Mehat36972292010-01-06 11:06:32 -08001444 }
1445
San Mehat4270e1e2010-01-29 05:32:19 -08001446 public int finalizeSecureContainer(String id) {
1447 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001448 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001449
San Mehatb1043402010-02-05 08:26:50 -08001450 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001451 try {
1452 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001453 /*
1454 * Finalization does a remount, so no need
1455 * to update mAsecMountSet
1456 */
San Mehat4270e1e2010-01-29 05:32:19 -08001457 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001458 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001459 }
San Mehat4270e1e2010-01-29 05:32:19 -08001460 return rc;
San Mehat36972292010-01-06 11:06:32 -08001461 }
1462
San Mehatd9709982010-02-18 11:43:03 -08001463 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001464 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001465 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001466 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001467
Kenny Rootaa485402010-09-14 14:49:41 -07001468 /*
1469 * Force a GC to make sure AssetManagers in other threads of the
1470 * system_server are cleaned up. We have to do this since AssetManager
1471 * instances are kept as a WeakReference and it's possible we have files
1472 * open on the external storage.
1473 */
1474 Runtime.getRuntime().gc();
1475
San Mehatb1043402010-02-05 08:26:50 -08001476 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001477 try {
San Mehatd9709982010-02-18 11:43:03 -08001478 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001479 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001480 int code = e.getCode();
1481 if (code == VoldResponseCode.OpFailedStorageBusy) {
1482 rc = StorageResultCode.OperationFailedStorageBusy;
1483 } else {
1484 rc = StorageResultCode.OperationFailedInternalError;
1485 }
San Mehat02735bc2010-01-26 15:18:08 -08001486 }
San Mehata181b212010-02-11 06:50:20 -08001487
1488 if (rc == StorageResultCode.OperationSucceeded) {
1489 synchronized (mAsecMountSet) {
1490 if (mAsecMountSet.contains(id)) {
1491 mAsecMountSet.remove(id);
1492 }
1493 }
1494 }
1495
San Mehat4270e1e2010-01-29 05:32:19 -08001496 return rc;
San Mehat36972292010-01-06 11:06:32 -08001497 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001498
San Mehat4270e1e2010-01-29 05:32:19 -08001499 public int mountSecureContainer(String id, String key, int ownerUid) {
1500 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001501 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001502 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001503
San Mehata181b212010-02-11 06:50:20 -08001504 synchronized (mAsecMountSet) {
1505 if (mAsecMountSet.contains(id)) {
1506 return StorageResultCode.OperationFailedStorageMounted;
1507 }
1508 }
1509
San Mehatb1043402010-02-05 08:26:50 -08001510 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001511 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1512 try {
1513 mConnector.doCommand(cmd);
1514 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001515 int code = e.getCode();
1516 if (code != VoldResponseCode.OpFailedStorageBusy) {
1517 rc = StorageResultCode.OperationFailedInternalError;
1518 }
San Mehat02735bc2010-01-26 15:18:08 -08001519 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001520
1521 if (rc == StorageResultCode.OperationSucceeded) {
1522 synchronized (mAsecMountSet) {
1523 mAsecMountSet.add(id);
1524 }
1525 }
San Mehat4270e1e2010-01-29 05:32:19 -08001526 return rc;
San Mehat36972292010-01-06 11:06:32 -08001527 }
1528
San Mehatd9709982010-02-18 11:43:03 -08001529 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001530 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001531 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001532 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001533
San Mehat6cdd9c02010-02-09 14:45:20 -08001534 synchronized (mAsecMountSet) {
1535 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001536 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001537 }
1538 }
1539
Kenny Rootaa485402010-09-14 14:49:41 -07001540 /*
1541 * Force a GC to make sure AssetManagers in other threads of the
1542 * system_server are cleaned up. We have to do this since AssetManager
1543 * instances are kept as a WeakReference and it's possible we have files
1544 * open on the external storage.
1545 */
1546 Runtime.getRuntime().gc();
1547
San Mehatb1043402010-02-05 08:26:50 -08001548 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001549 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001550 try {
1551 mConnector.doCommand(cmd);
1552 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001553 int code = e.getCode();
1554 if (code == VoldResponseCode.OpFailedStorageBusy) {
1555 rc = StorageResultCode.OperationFailedStorageBusy;
1556 } else {
1557 rc = StorageResultCode.OperationFailedInternalError;
1558 }
San Mehat02735bc2010-01-26 15:18:08 -08001559 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001560
1561 if (rc == StorageResultCode.OperationSucceeded) {
1562 synchronized (mAsecMountSet) {
1563 mAsecMountSet.remove(id);
1564 }
1565 }
San Mehat4270e1e2010-01-29 05:32:19 -08001566 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001567 }
1568
San Mehat6cdd9c02010-02-09 14:45:20 -08001569 public boolean isSecureContainerMounted(String id) {
1570 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1571 waitForReady();
1572 warnOnNotMounted();
1573
1574 synchronized (mAsecMountSet) {
1575 return mAsecMountSet.contains(id);
1576 }
1577 }
1578
San Mehat4270e1e2010-01-29 05:32:19 -08001579 public int renameSecureContainer(String oldId, String newId) {
1580 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001581 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001582 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001583
San Mehata181b212010-02-11 06:50:20 -08001584 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001585 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001586 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001587 * changed while active, we must ensure both ids are not currently mounted.
1588 */
1589 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001590 return StorageResultCode.OperationFailedStorageMounted;
1591 }
1592 }
1593
San Mehatb1043402010-02-05 08:26:50 -08001594 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001595 String cmd = String.format("asec rename %s %s", oldId, newId);
1596 try {
1597 mConnector.doCommand(cmd);
1598 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001599 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001600 }
San Mehata181b212010-02-11 06:50:20 -08001601
San Mehat4270e1e2010-01-29 05:32:19 -08001602 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001603 }
1604
San Mehat4270e1e2010-01-29 05:32:19 -08001605 public String getSecureContainerPath(String id) {
1606 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001607 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001608 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001609
San Mehat2d66cef2010-03-23 11:12:52 -07001610 try {
1611 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1612 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001613 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001614 if (code != VoldResponseCode.AsecPathResult) {
1615 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1616 }
1617 return tok[1];
1618 } catch (NativeDaemonConnectorException e) {
1619 int code = e.getCode();
1620 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001621 Slog.i(TAG, String.format("Container '%s' not found", id));
1622 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001623 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001624 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001625 }
1626 }
San Mehat22dd86e2010-01-12 12:21:18 -08001627 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001628
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001629 public String getSecureContainerFilesystemPath(String id) {
1630 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1631 waitForReady();
1632 warnOnNotMounted();
1633
1634 try {
1635 ArrayList<String> rsp = mConnector.doCommand(String.format("asec fspath %s", id));
1636 String []tok = rsp.get(0).split(" ");
1637 int code = Integer.parseInt(tok[0]);
1638 if (code != VoldResponseCode.AsecPathResult) {
1639 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1640 }
1641 return tok[1];
1642 } catch (NativeDaemonConnectorException e) {
1643 int code = e.getCode();
1644 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1645 Slog.i(TAG, String.format("Container '%s' not found", id));
1646 return null;
1647 } else {
1648 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1649 }
1650 }
1651 }
1652
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001653 public void finishMediaUpdate() {
1654 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1655 }
Kenny Root02c87302010-07-01 08:10:18 -07001656
Kenny Roota02b8b02010-08-05 16:14:17 -07001657 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1658 if (callerUid == android.os.Process.SYSTEM_UID) {
1659 return true;
1660 }
1661
Kenny Root02c87302010-07-01 08:10:18 -07001662 if (packageName == null) {
1663 return false;
1664 }
1665
1666 final int packageUid = mPms.getPackageUid(packageName);
1667
1668 if (DEBUG_OBB) {
1669 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1670 packageUid + ", callerUid = " + callerUid);
1671 }
1672
1673 return callerUid == packageUid;
1674 }
1675
1676 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001677 if (filename == null) {
1678 throw new IllegalArgumentException("filename cannot be null");
1679 }
1680
Kenny Root02c87302010-07-01 08:10:18 -07001681 waitForReady();
1682 warnOnNotMounted();
1683
Kenny Root02c87302010-07-01 08:10:18 -07001684 try {
1685 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1686 String []tok = rsp.get(0).split(" ");
1687 int code = Integer.parseInt(tok[0]);
1688 if (code != VoldResponseCode.AsecPathResult) {
1689 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1690 }
1691 return tok[1];
1692 } catch (NativeDaemonConnectorException e) {
1693 int code = e.getCode();
1694 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001695 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001696 } else {
1697 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1698 }
1699 }
1700 }
1701
1702 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001703 if (filename == null) {
1704 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001705 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001706
1707 synchronized (mObbMounts) {
1708 return mObbPathToStateMap.containsKey(filename);
1709 }
Kenny Root02c87302010-07-01 08:10:18 -07001710 }
1711
Kenny Rootaf9d6672010-10-08 09:21:39 -07001712 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001713 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001714 if (filename == null) {
1715 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001716 }
1717
1718 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001719 throw new IllegalArgumentException("token cannot be null");
1720 }
1721
Kenny Rootaf9d6672010-10-08 09:21:39 -07001722 final int callerUid = Binder.getCallingUid();
1723 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1724 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001725 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1726
1727 if (DEBUG_OBB)
1728 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001729 }
1730
Kenny Rootaf9d6672010-10-08 09:21:39 -07001731 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1732 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001733 if (filename == null) {
1734 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001735 }
1736
Kenny Rootaf9d6672010-10-08 09:21:39 -07001737 final int callerUid = Binder.getCallingUid();
1738 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1739 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001740 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001741
Kenny Roota02b8b02010-08-05 16:14:17 -07001742 if (DEBUG_OBB)
1743 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1744 }
1745
Jason parks5af0b912010-11-29 09:05:25 -06001746 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001747 if (TextUtils.isEmpty(password)) {
1748 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001749 }
1750
Jason parks8888c592011-01-20 22:46:41 -06001751 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1752 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001753
1754 waitForReady();
1755
1756 if (DEBUG_EVENTS) {
1757 Slog.i(TAG, "decrypting storage...");
1758 }
1759
1760 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001761 ArrayList<String> rsp = mConnector.doCommand("cryptfs checkpw " + password);
Jason parksf7b3cd42011-01-27 09:28:25 -06001762 String[] tokens = rsp.get(0).split(" ");
Jason parks9ed98bc2011-01-17 09:58:35 -06001763
Jason parksf7b3cd42011-01-27 09:28:25 -06001764 if (tokens == null || tokens.length != 2) {
Jason parks9ed98bc2011-01-17 09:58:35 -06001765 return -1;
1766 }
1767
Jason parksf7b3cd42011-01-27 09:28:25 -06001768 int code = Integer.parseInt(tokens[1]);
Jason parks9ed98bc2011-01-17 09:58:35 -06001769
1770 if (code == 0) {
1771 // Decrypt was successful. Post a delayed message before restarting in order
1772 // to let the UI to clear itself
1773 mHandler.postDelayed(new Runnable() {
1774 public void run() {
1775 mConnector.doCommand(String.format("cryptfs restart"));
1776 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001777 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001778 }
1779
1780 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001781 } catch (NativeDaemonConnectorException e) {
1782 // Decryption failed
1783 return e.getCode();
1784 }
Jason parks5af0b912010-11-29 09:05:25 -06001785 }
1786
Jason parks56aa5322011-01-07 09:01:15 -06001787 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001788 if (TextUtils.isEmpty(password)) {
1789 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001790 }
1791
Jason parks8888c592011-01-20 22:46:41 -06001792 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1793 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001794
1795 waitForReady();
1796
1797 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001798 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001799 }
1800
1801 try {
Jason parks9ed98bc2011-01-17 09:58:35 -06001802 mConnector.doCommand(String.format("cryptfs enablecrypto inplace %s", password));
Jason parks56aa5322011-01-07 09:01:15 -06001803 } catch (NativeDaemonConnectorException e) {
1804 // Encryption failed
1805 return e.getCode();
1806 }
1807
1808 return 0;
1809 }
1810
Jason parksf7b3cd42011-01-27 09:28:25 -06001811 public int changeEncryptionPassword(String password) {
1812 if (TextUtils.isEmpty(password)) {
1813 throw new IllegalArgumentException("password cannot be empty");
1814 }
1815
1816 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1817 "no permission to access the crypt keeper");
1818
1819 waitForReady();
1820
1821 if (DEBUG_EVENTS) {
1822 Slog.i(TAG, "changing encryption password...");
1823 }
1824
1825 try {
1826 ArrayList<String> response = mConnector.doCommand("cryptfs changepw " + password);
1827
1828 String[] tokens = response.get(0).split(" ");
1829
1830 if (tokens == null || tokens.length != 2) {
1831 return -1;
1832 }
1833
1834 return Integer.parseInt(tokens[1]);
1835 } catch (NativeDaemonConnectorException e) {
1836 // Encryption failed
1837 return e.getCode();
1838 }
1839 }
1840
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001841 public Parcelable[] getVolumeList() {
1842 synchronized(mVolumes) {
1843 int size = mVolumes.size();
1844 Parcelable[] result = new Parcelable[size];
1845 for (int i = 0; i < size; i++) {
1846 result[i] = mVolumes.get(i);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07001847 }
1848 return result;
1849 }
1850 }
1851
Kenny Rootaf9d6672010-10-08 09:21:39 -07001852 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1853 final IBinder binder = obbState.getBinder();
1854 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001855
Kenny Rootaf9d6672010-10-08 09:21:39 -07001856 if (obbStates == null) {
1857 obbStates = new ArrayList<ObbState>();
1858 mObbMounts.put(binder, obbStates);
1859 } else {
1860 for (final ObbState o : obbStates) {
1861 if (o.filename.equals(obbState.filename)) {
1862 throw new IllegalStateException("Attempt to add ObbState twice. "
1863 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001864 }
1865 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001866 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001867
1868 obbStates.add(obbState);
1869 try {
1870 obbState.link();
1871 } catch (RemoteException e) {
1872 /*
1873 * The binder died before we could link it, so clean up our state
1874 * and return failure.
1875 */
1876 obbStates.remove(obbState);
1877 if (obbStates.isEmpty()) {
1878 mObbMounts.remove(binder);
1879 }
1880
1881 // Rethrow the error so mountObb can get it
1882 throw e;
1883 }
1884
1885 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001886 }
1887
Kenny Rootaf9d6672010-10-08 09:21:39 -07001888 private void removeObbStateLocked(ObbState obbState) {
1889 final IBinder binder = obbState.getBinder();
1890 final List<ObbState> obbStates = mObbMounts.get(binder);
1891 if (obbStates != null) {
1892 if (obbStates.remove(obbState)) {
1893 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001894 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001895 if (obbStates.isEmpty()) {
1896 mObbMounts.remove(binder);
1897 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001898 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001899
Kenny Rootaf9d6672010-10-08 09:21:39 -07001900 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001901 }
1902
Kenny Roota02b8b02010-08-05 16:14:17 -07001903 private class ObbActionHandler extends Handler {
1904 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001905 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001906
1907 ObbActionHandler(Looper l) {
1908 super(l);
1909 }
1910
1911 @Override
1912 public void handleMessage(Message msg) {
1913 switch (msg.what) {
1914 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001915 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001916
1917 if (DEBUG_OBB)
1918 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1919
1920 // If a bind was already initiated we don't really
1921 // need to do anything. The pending install
1922 // will be processed later on.
1923 if (!mBound) {
1924 // If this is the only one pending we might
1925 // have to bind to the service again.
1926 if (!connectToService()) {
1927 Slog.e(TAG, "Failed to bind to media container service");
1928 action.handleError();
1929 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001930 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001931 }
Kenny Root735de3b2010-09-30 14:11:39 -07001932
Kenny Root735de3b2010-09-30 14:11:39 -07001933 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001934 break;
1935 }
1936 case OBB_MCS_BOUND: {
1937 if (DEBUG_OBB)
1938 Slog.i(TAG, "OBB_MCS_BOUND");
1939 if (msg.obj != null) {
1940 mContainerService = (IMediaContainerService) msg.obj;
1941 }
1942 if (mContainerService == null) {
1943 // Something seriously wrong. Bail out
1944 Slog.e(TAG, "Cannot bind to media container service");
1945 for (ObbAction action : mActions) {
1946 // Indicate service bind error
1947 action.handleError();
1948 }
1949 mActions.clear();
1950 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001951 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001952 if (action != null) {
1953 action.execute(this);
1954 }
1955 } else {
1956 // Should never happen ideally.
1957 Slog.w(TAG, "Empty queue");
1958 }
1959 break;
1960 }
1961 case OBB_MCS_RECONNECT: {
1962 if (DEBUG_OBB)
1963 Slog.i(TAG, "OBB_MCS_RECONNECT");
1964 if (mActions.size() > 0) {
1965 if (mBound) {
1966 disconnectService();
1967 }
1968 if (!connectToService()) {
1969 Slog.e(TAG, "Failed to bind to media container service");
1970 for (ObbAction action : mActions) {
1971 // Indicate service bind error
1972 action.handleError();
1973 }
1974 mActions.clear();
1975 }
1976 }
1977 break;
1978 }
1979 case OBB_MCS_UNBIND: {
1980 if (DEBUG_OBB)
1981 Slog.i(TAG, "OBB_MCS_UNBIND");
1982
1983 // Delete pending install
1984 if (mActions.size() > 0) {
1985 mActions.remove(0);
1986 }
1987 if (mActions.size() == 0) {
1988 if (mBound) {
1989 disconnectService();
1990 }
1991 } else {
1992 // There are more pending requests in queue.
1993 // Just post MCS_BOUND message to trigger processing
1994 // of next pending install.
1995 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1996 }
1997 break;
1998 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001999 case OBB_FLUSH_MOUNT_STATE: {
2000 final String path = (String) msg.obj;
2001
2002 if (DEBUG_OBB)
2003 Slog.i(TAG, "Flushing all OBB state for path " + path);
2004
2005 synchronized (mObbMounts) {
2006 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2007
2008 final Iterator<Entry<String, ObbState>> i =
2009 mObbPathToStateMap.entrySet().iterator();
2010 while (i.hasNext()) {
2011 final Entry<String, ObbState> obbEntry = i.next();
2012
2013 /*
2014 * If this entry's source file is in the volume path
2015 * that got unmounted, remove it because it's no
2016 * longer valid.
2017 */
2018 if (obbEntry.getKey().startsWith(path)) {
2019 obbStatesToRemove.add(obbEntry.getValue());
2020 }
2021 }
2022
2023 for (final ObbState obbState : obbStatesToRemove) {
2024 if (DEBUG_OBB)
2025 Slog.i(TAG, "Removing state for " + obbState.filename);
2026
2027 removeObbStateLocked(obbState);
2028
2029 try {
2030 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2031 OnObbStateChangeListener.UNMOUNTED);
2032 } catch (RemoteException e) {
2033 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2034 + obbState.filename);
2035 }
2036 }
2037 }
2038 break;
2039 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002040 }
2041 }
2042
2043 private boolean connectToService() {
2044 if (DEBUG_OBB)
2045 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2046
2047 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2048 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2049 mBound = true;
2050 return true;
2051 }
2052 return false;
2053 }
2054
2055 private void disconnectService() {
2056 mContainerService = null;
2057 mBound = false;
2058 mContext.unbindService(mDefContainerConn);
2059 }
2060 }
2061
2062 abstract class ObbAction {
2063 private static final int MAX_RETRIES = 3;
2064 private int mRetries;
2065
2066 ObbState mObbState;
2067
2068 ObbAction(ObbState obbState) {
2069 mObbState = obbState;
2070 }
2071
2072 public void execute(ObbActionHandler handler) {
2073 try {
2074 if (DEBUG_OBB)
2075 Slog.i(TAG, "Starting to execute action: " + this.toString());
2076 mRetries++;
2077 if (mRetries > MAX_RETRIES) {
2078 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002079 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002080 handleError();
2081 return;
2082 } else {
2083 handleExecute();
2084 if (DEBUG_OBB)
2085 Slog.i(TAG, "Posting install MCS_UNBIND");
2086 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2087 }
2088 } catch (RemoteException e) {
2089 if (DEBUG_OBB)
2090 Slog.i(TAG, "Posting install MCS_RECONNECT");
2091 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2092 } catch (Exception e) {
2093 if (DEBUG_OBB)
2094 Slog.d(TAG, "Error handling OBB action", e);
2095 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002096 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002097 }
2098 }
2099
Kenny Root05105f72010-09-22 17:29:43 -07002100 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002101 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002102
2103 protected ObbInfo getObbInfo() throws IOException {
2104 ObbInfo obbInfo;
2105 try {
2106 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2107 } catch (RemoteException e) {
2108 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2109 + mObbState.filename);
2110 obbInfo = null;
2111 }
2112 if (obbInfo == null) {
2113 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2114 }
2115 return obbInfo;
2116 }
2117
Kenny Rootaf9d6672010-10-08 09:21:39 -07002118 protected void sendNewStatusOrIgnore(int status) {
2119 if (mObbState == null || mObbState.token == null) {
2120 return;
2121 }
2122
Kenny Root38cf8862010-09-26 14:18:51 -07002123 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002124 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002125 } catch (RemoteException e) {
2126 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2127 }
2128 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002129 }
2130
2131 class MountObbAction extends ObbAction {
2132 private String mKey;
2133
2134 MountObbAction(ObbState obbState, String key) {
2135 super(obbState);
2136 mKey = key;
2137 }
2138
Jason parks5af0b912010-11-29 09:05:25 -06002139 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002140 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002141 waitForReady();
2142 warnOnNotMounted();
2143
Kenny Root38cf8862010-09-26 14:18:51 -07002144 final ObbInfo obbInfo = getObbInfo();
2145
Kenny Roota02b8b02010-08-05 16:14:17 -07002146 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002147 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2148 + " which is owned by " + obbInfo.packageName);
2149 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2150 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002151 }
2152
Kenny Rootaf9d6672010-10-08 09:21:39 -07002153 final boolean isMounted;
2154 synchronized (mObbMounts) {
2155 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2156 }
2157 if (isMounted) {
2158 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2159 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2160 return;
2161 }
2162
2163 /*
2164 * The filename passed in might not be the canonical name, so just
2165 * set the filename to the canonicalized version.
2166 */
2167 mObbState.filename = obbInfo.filename;
2168
2169 final String hashedKey;
2170 if (mKey == null) {
2171 hashedKey = "none";
2172 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002173 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002174 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2175
2176 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2177 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2178 SecretKey key = factory.generateSecret(ks);
2179 BigInteger bi = new BigInteger(key.getEncoded());
2180 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002181 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002182 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2183 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2184 return;
2185 } catch (InvalidKeySpecException e) {
2186 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2187 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002188 return;
2189 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002190 }
Kenny Root38cf8862010-09-26 14:18:51 -07002191
Kenny Rootaf9d6672010-10-08 09:21:39 -07002192 int rc = StorageResultCode.OperationSucceeded;
2193 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
2194 mObbState.callerUid);
2195 try {
2196 mConnector.doCommand(cmd);
2197 } catch (NativeDaemonConnectorException e) {
2198 int code = e.getCode();
2199 if (code != VoldResponseCode.OpFailedStorageBusy) {
2200 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002201 }
2202 }
2203
Kenny Rootaf9d6672010-10-08 09:21:39 -07002204 if (rc == StorageResultCode.OperationSucceeded) {
2205 if (DEBUG_OBB)
2206 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2207
2208 synchronized (mObbMounts) {
2209 addObbStateLocked(mObbState);
2210 }
2211
2212 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002213 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002214 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002215
Kenny Rootaf9d6672010-10-08 09:21:39 -07002216 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002217 }
2218 }
2219
Jason parks5af0b912010-11-29 09:05:25 -06002220 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002221 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002222 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002223 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002224
2225 @Override
2226 public String toString() {
2227 StringBuilder sb = new StringBuilder();
2228 sb.append("MountObbAction{");
2229 sb.append("filename=");
2230 sb.append(mObbState.filename);
2231 sb.append(",callerUid=");
2232 sb.append(mObbState.callerUid);
2233 sb.append(",token=");
2234 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002235 sb.append(",binder=");
2236 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002237 sb.append('}');
2238 return sb.toString();
2239 }
2240 }
2241
2242 class UnmountObbAction extends ObbAction {
2243 private boolean mForceUnmount;
2244
2245 UnmountObbAction(ObbState obbState, boolean force) {
2246 super(obbState);
2247 mForceUnmount = force;
2248 }
2249
Jason parks5af0b912010-11-29 09:05:25 -06002250 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002251 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002252 waitForReady();
2253 warnOnNotMounted();
2254
Kenny Root38cf8862010-09-26 14:18:51 -07002255 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002256
Kenny Rootaf9d6672010-10-08 09:21:39 -07002257 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002258 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002259 obbState = mObbPathToStateMap.get(obbInfo.filename);
2260 }
Kenny Root38cf8862010-09-26 14:18:51 -07002261
Kenny Rootaf9d6672010-10-08 09:21:39 -07002262 if (obbState == null) {
2263 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2264 return;
2265 }
2266
2267 if (obbState.callerUid != mObbState.callerUid) {
2268 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2269 + " (owned by " + obbInfo.packageName + ")");
2270 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2271 return;
2272 }
2273
2274 mObbState.filename = obbInfo.filename;
2275
2276 int rc = StorageResultCode.OperationSucceeded;
2277 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2278 (mForceUnmount ? " force" : ""));
2279 try {
2280 mConnector.doCommand(cmd);
2281 } catch (NativeDaemonConnectorException e) {
2282 int code = e.getCode();
2283 if (code == VoldResponseCode.OpFailedStorageBusy) {
2284 rc = StorageResultCode.OperationFailedStorageBusy;
2285 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2286 // If it's not mounted then we've already won.
2287 rc = StorageResultCode.OperationSucceeded;
2288 } else {
2289 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002290 }
2291 }
2292
Kenny Rootaf9d6672010-10-08 09:21:39 -07002293 if (rc == StorageResultCode.OperationSucceeded) {
2294 synchronized (mObbMounts) {
2295 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002296 }
2297
Kenny Rootaf9d6672010-10-08 09:21:39 -07002298 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002299 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002300 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2301 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002302 }
2303 }
2304
Jason parks5af0b912010-11-29 09:05:25 -06002305 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002306 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002307 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002308 }
2309
2310 @Override
2311 public String toString() {
2312 StringBuilder sb = new StringBuilder();
2313 sb.append("UnmountObbAction{");
2314 sb.append("filename=");
2315 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2316 sb.append(",force=");
2317 sb.append(mForceUnmount);
2318 sb.append(",callerUid=");
2319 sb.append(mObbState.callerUid);
2320 sb.append(",token=");
2321 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002322 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002323 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002324 sb.append('}');
2325 return sb.toString();
2326 }
Kenny Root02c87302010-07-01 08:10:18 -07002327 }
Kenny Root38cf8862010-09-26 14:18:51 -07002328
2329 @Override
2330 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2331 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2332 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2333 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2334 + " without permission " + android.Manifest.permission.DUMP);
2335 return;
2336 }
2337
Kenny Root38cf8862010-09-26 14:18:51 -07002338 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002339 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002340
Kenny Rootaf9d6672010-10-08 09:21:39 -07002341 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2342 while (binders.hasNext()) {
2343 Entry<IBinder, List<ObbState>> e = binders.next();
2344 pw.print(" Key="); pw.println(e.getKey().toString());
2345 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002346 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002347 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002348 }
2349 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002350
2351 pw.println("");
2352 pw.println(" mObbPathToStateMap:");
2353 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2354 while (maps.hasNext()) {
2355 final Entry<String, ObbState> e = maps.next();
2356 pw.print(" "); pw.print(e.getKey());
2357 pw.print(" -> "); pw.println(e.getValue().toString());
2358 }
Kenny Root38cf8862010-09-26 14:18:51 -07002359 }
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361}
2362