blob: 7870b06013fe77d41e9e6c31b77f4d4310025626 [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;
Kenny Root735de3b2010-09-30 14:11:39 -070020import com.android.internal.util.HexDump;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
47import android.os.storage.StorageResultCode;
Kenny Root735de3b2010-09-30 14:11:39 -070048import android.security.MessageDigest;
San Mehata5078592010-03-25 09:36:54 -070049import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070050
Kenny Root38cf8862010-09-26 14:18:51 -070051import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070052import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.io.PrintWriter;
Kenny Root735de3b2010-09-30 14:11:39 -070054import java.security.NoSuchAlgorithmException;
San Mehat22dd86e2010-01-12 12:21:18 -080055import java.util.ArrayList;
Kenny Root38cf8862010-09-26 14:18:51 -070056import java.util.Collection;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080058import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070059import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.LinkedList;
61import java.util.List;
62import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
San Mehatb1043402010-02-05 08:26:50 -080066 * MountService implements back-end services for platform storage
67 * management.
68 * @hide - Applications should use android.os.storage.StorageManager
69 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 */
San Mehat22dd86e2010-01-12 12:21:18 -080071class MountService extends IMountService.Stub
72 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080073 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080074 private static final boolean DEBUG_UNMOUNT = false;
75 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070076 private static final boolean DEBUG_OBB = true;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "MountService";
79
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String VOLD_TAG = "VoldConnector";
81
Kenny Root27358a62010-09-29 19:27:20 -070082 protected static final int MAX_OBBS = 8;
83
San Mehat4270e1e2010-01-29 05:32:19 -080084 /*
85 * Internal vold volume state constants
86 */
San Mehat7fd0fee2009-12-17 07:12:23 -080087 class VolumeState {
88 public static final int Init = -1;
89 public static final int NoMedia = 0;
90 public static final int Idle = 1;
91 public static final int Pending = 2;
92 public static final int Checking = 3;
93 public static final int Mounted = 4;
94 public static final int Unmounting = 5;
95 public static final int Formatting = 6;
96 public static final int Shared = 7;
97 public static final int SharedMnt = 8;
98 }
99
San Mehat4270e1e2010-01-29 05:32:19 -0800100 /*
101 * Internal vold response code constants
102 */
San Mehat22dd86e2010-01-12 12:21:18 -0800103 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800104 /*
105 * 100 series - Requestion action was initiated; expect another reply
106 * before proceeding with a new command.
107 */
San Mehat22dd86e2010-01-12 12:21:18 -0800108 public static final int VolumeListResult = 110;
109 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800110 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800111
San Mehat4270e1e2010-01-29 05:32:19 -0800112 /*
113 * 200 series - Requestion action has been successfully completed.
114 */
115 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800116 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800117 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800118
San Mehat4270e1e2010-01-29 05:32:19 -0800119 /*
120 * 400 series - Command was accepted, but the requested action
121 * did not take place.
122 */
123 public static final int OpFailedNoMedia = 401;
124 public static final int OpFailedMediaBlank = 402;
125 public static final int OpFailedMediaCorrupt = 403;
126 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800127 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700128 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800129
130 /*
131 * 600 series - Unsolicited broadcasts.
132 */
San Mehat22dd86e2010-01-12 12:21:18 -0800133 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800134 public static final int ShareAvailabilityChange = 620;
135 public static final int VolumeDiskInserted = 630;
136 public static final int VolumeDiskRemoved = 631;
137 public static final int VolumeBadRemoval = 632;
138 }
139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 private Context mContext;
141 private NativeDaemonConnector mConnector;
142 private String mLegacyState = Environment.MEDIA_REMOVED;
143 private PackageManagerService mPms;
144 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800145 // Used as a lock for methods that register/unregister listeners.
146 final private ArrayList<MountServiceBinderListener> mListeners =
147 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800148 private boolean mBooted = false;
149 private boolean mReady = false;
150 private boolean mSendUmsConnectedOnBoot = false;
Mike Lockwood03559752010-07-19 18:25:03 -0400151 // true if we should fake MEDIA_MOUNTED state for external storage
152 private boolean mEmulateExternalStorage = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800153
San Mehat6cdd9c02010-02-09 14:45:20 -0800154 /**
155 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800156 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800157 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800158 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800159
Kenny Root02c87302010-07-01 08:10:18 -0700160 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700161 * Mounted OBB tracking information. Used to track the current state of all
162 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700163 */
Kenny Root27358a62010-09-29 19:27:20 -0700164 final private Map<Integer, Integer> mObbUidUsage = new HashMap<Integer, Integer>();
Kenny Root735de3b2010-09-30 14:11:39 -0700165 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700166 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
167
168 class ObbState implements IBinder.DeathRecipient {
Kenny Root735de3b2010-09-30 14:11:39 -0700169 public ObbState(String filename, IObbActionListener token, int callerUid)
170 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700171 this.filename = filename;
172 this.token = token;
173 this.callerUid = callerUid;
174 mounted = false;
Kenny Root735de3b2010-09-30 14:11:39 -0700175
176 getBinder().linkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700177 }
178
179 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700180 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700181
182 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700183 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700184
185 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700186 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700187
188 // Whether this is mounted currently.
189 boolean mounted;
190
Kenny Root735de3b2010-09-30 14:11:39 -0700191 public IBinder getBinder() {
192 return token.asBinder();
193 }
194
Kenny Roota02b8b02010-08-05 16:14:17 -0700195 @Override
196 public void binderDied() {
197 ObbAction action = new UnmountObbAction(this, true);
198 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700199 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700200
Kenny Root735de3b2010-09-30 14:11:39 -0700201 public void cleanUp() {
202 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 }
Kenny Root38cf8862010-09-26 14:18:51 -0700204
205 @Override
206 public String toString() {
207 StringBuilder sb = new StringBuilder("ObbState{");
208 sb.append("filename=");
209 sb.append(filename);
210 sb.append(",token=");
211 sb.append(token.toString());
212 sb.append(",callerUid=");
213 sb.append(callerUid);
214 sb.append(",mounted=");
215 sb.append(mounted);
216 sb.append('}');
217 return sb.toString();
218 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700219 }
220
221 // OBB Action Handler
222 final private ObbActionHandler mObbActionHandler;
223
224 // OBB action handler messages
225 private static final int OBB_RUN_ACTION = 1;
226 private static final int OBB_MCS_BOUND = 2;
227 private static final int OBB_MCS_UNBIND = 3;
228 private static final int OBB_MCS_RECONNECT = 4;
229 private static final int OBB_MCS_GIVE_UP = 5;
230
231 /*
232 * Default Container Service information
233 */
234 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
235 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
236
237 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
238
239 class DefaultContainerConnection implements ServiceConnection {
240 public void onServiceConnected(ComponentName name, IBinder service) {
241 if (DEBUG_OBB)
242 Slog.i(TAG, "onServiceConnected");
243 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
244 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
245 }
246
247 public void onServiceDisconnected(ComponentName name) {
248 if (DEBUG_OBB)
249 Slog.i(TAG, "onServiceDisconnected");
250 }
251 };
252
253 // Used in the ObbActionHandler
254 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700255
256 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800257 private static final int H_UNMOUNT_PM_UPDATE = 1;
258 private static final int H_UNMOUNT_PM_DONE = 2;
259 private static final int H_UNMOUNT_MS = 3;
260 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
261 private static final int MAX_UNMOUNT_RETRIES = 4;
262
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800263 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700264 final String path;
265 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800266 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800267
268 UnmountCallBack(String path, boolean force) {
269 retries = 0;
270 this.path = path;
271 this.force = force;
272 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800273
274 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700275 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800276 doUnmountVolume(path, true);
277 }
278 }
279
280 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700281 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800282
283 UmsEnableCallBack(String path, String method, boolean force) {
284 super(path, force);
285 this.method = method;
286 }
287
288 @Override
289 void handleFinished() {
290 super.handleFinished();
291 doShareUnshareVolume(path, method, true);
292 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800293 }
294
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800295 class ShutdownCallBack extends UnmountCallBack {
296 IMountShutdownObserver observer;
297 ShutdownCallBack(String path, IMountShutdownObserver observer) {
298 super(path, true);
299 this.observer = observer;
300 }
301
302 @Override
303 void handleFinished() {
304 int ret = doUnmountVolume(path, true);
305 if (observer != null) {
306 try {
307 observer.onShutDownComplete(ret);
308 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700309 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800310 }
311 }
312 }
313 }
314
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400315 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800316 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700317 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800318
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400319 MountServiceHandler(Looper l) {
320 super(l);
321 }
322
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800323 public void handleMessage(Message msg) {
324 switch (msg.what) {
325 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700326 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800327 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
328 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700329 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800330 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700331 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700332 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700333 mUpdatingStatus = true;
334 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800335 }
336 break;
337 }
338 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700339 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700340 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700341 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800342 int size = mForceUnmounts.size();
343 int sizeArr[] = new int[size];
344 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700345 // Kill processes holding references first
346 ActivityManagerService ams = (ActivityManagerService)
347 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800348 for (int i = 0; i < size; i++) {
349 UnmountCallBack ucb = mForceUnmounts.get(i);
350 String path = ucb.path;
351 boolean done = false;
352 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 done = true;
354 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800355 int pids[] = getStorageUsers(path);
356 if (pids == null || pids.length == 0) {
357 done = true;
358 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800359 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700360 ams.killPids(pids, "unmount media");
361 // Confirm if file references have been freed.
362 pids = getStorageUsers(path);
363 if (pids == null || pids.length == 0) {
364 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 }
366 }
367 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700368 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
369 // Retry again
370 Slog.i(TAG, "Retrying to kill storage users again");
371 mHandler.sendMessageDelayed(
372 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
373 ucb.retries++),
374 RETRY_UNMOUNT_DELAY);
375 } else {
376 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
377 Slog.i(TAG, "Failed to unmount media inspite of " +
378 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
379 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 sizeArr[sizeArrN++] = i;
381 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
382 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800383 }
384 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800385 // Remove already processed elements from list.
386 for (int i = (sizeArrN-1); i >= 0; i--) {
387 mForceUnmounts.remove(sizeArr[i]);
388 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800389 break;
390 }
391 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700392 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800393 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800394 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800395 break;
396 }
397 }
398 }
399 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400400 final private HandlerThread mHandlerThread;
401 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402
San Mehat207e5382010-02-04 20:46:54 -0800403 private void waitForReady() {
404 while (mReady == false) {
405 for (int retries = 5; retries > 0; retries--) {
406 if (mReady) {
407 return;
408 }
409 SystemClock.sleep(1000);
410 }
San Mehata5078592010-03-25 09:36:54 -0700411 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800412 }
San Mehat1f6301e2010-01-07 22:40:27 -0800413 }
Kenny Root02c87302010-07-01 08:10:18 -0700414
San Mehat207e5382010-02-04 20:46:54 -0800415 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800417 String action = intent.getAction();
418
419 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800420 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800421
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800422 /*
423 * In the simulator, we need to broadcast a volume mounted event
424 * to make the media scanner run.
425 */
426 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
427 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
428 return;
429 }
San Mehatfafb0412010-02-18 19:40:04 -0800430 new Thread() {
431 public void run() {
432 try {
433 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700434 String state = getVolumeState(path);
435
Mike Lockwood03559752010-07-19 18:25:03 -0400436 if (mEmulateExternalStorage) {
437 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Mounted);
438 } else if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800439 int rc = doMountVolume(path);
440 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700441 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800442 }
San Mehat6a254402010-03-22 10:21:00 -0700443 } else if (state.equals(Environment.MEDIA_SHARED)) {
444 /*
445 * Bootstrap UMS enabled state since vold indicates
446 * the volume is shared (runtime restart while ums enabled)
447 */
448 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800449 }
San Mehat6a254402010-03-22 10:21:00 -0700450
San Mehat6a965af22010-02-24 17:47:30 -0800451 /*
San Mehat6a254402010-03-22 10:21:00 -0700452 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800453 * now that we're up.
454 */
455 if (mSendUmsConnectedOnBoot) {
456 sendUmsIntent(true);
457 mSendUmsConnectedOnBoot = false;
458 }
San Mehatfafb0412010-02-18 19:40:04 -0800459 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700460 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800461 }
San Mehat207e5382010-02-04 20:46:54 -0800462 }
San Mehatfafb0412010-02-18 19:40:04 -0800463 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
465 }
466 };
467
San Mehat4270e1e2010-01-29 05:32:19 -0800468 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
469 final IMountServiceListener mListener;
470
471 MountServiceBinderListener(IMountServiceListener listener) {
472 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700473
San Mehat91c77612010-01-07 10:39:41 -0800474 }
475
San Mehat4270e1e2010-01-29 05:32:19 -0800476 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700477 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700478 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800479 mListeners.remove(this);
480 mListener.asBinder().unlinkToDeath(this, 0);
481 }
482 }
483 }
484
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800485 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800486 // TODO: Add support for multiple share methods
487 if (!method.equals("ums")) {
488 throw new IllegalArgumentException(String.format("Method %s not supported", method));
489 }
490
San Mehat4270e1e2010-01-29 05:32:19 -0800491 try {
492 mConnector.doCommand(String.format(
493 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
494 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700495 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800496 }
San Mehat4270e1e2010-01-29 05:32:19 -0800497 }
498
San Mehat207e5382010-02-04 20:46:54 -0800499 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800500 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700501 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800502 return;
503 }
San Mehatb1043402010-02-05 08:26:50 -0800504
505 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700506 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800507 return;
508 }
Mike Lockwood03559752010-07-19 18:25:03 -0400509 // Update state on PackageManager, but only of real events
510 if (!mEmulateExternalStorage) {
511 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
512 mPms.updateExternalMediaStatus(false, false);
513 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
514 mPms.updateExternalMediaStatus(true, false);
515 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800516 }
Kenny Root38cf8862010-09-26 14:18:51 -0700517
518 // Remove all OBB mappings and listeners from this path
519 synchronized (mObbMounts) {
520 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
521
522 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
523 while (i.hasNext()) {
524 final Entry<String, ObbState> obbEntry = i.next();
525
526 // If this entry's source file is in the volume path that got
527 // unmounted, remove it because it's no longer valid.
528 if (obbEntry.getKey().startsWith(path)) {
529 obbStatesToRemove.add(obbEntry.getValue());
530 }
531 }
532
533 for (final ObbState obbState : obbStatesToRemove) {
534 removeObbState(obbState);
535
536 try {
537 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
538 } catch (RemoteException e) {
539 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
540 + obbState.filename);
541 }
542 }
543 }
544
San Mehat4270e1e2010-01-29 05:32:19 -0800545 String oldState = mLegacyState;
546 mLegacyState = state;
547
548 synchronized (mListeners) {
549 for (int i = mListeners.size() -1; i >= 0; i--) {
550 MountServiceBinderListener bl = mListeners.get(i);
551 try {
San Mehatb1043402010-02-05 08:26:50 -0800552 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800553 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700554 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800555 mListeners.remove(i);
556 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700557 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800558 }
559 }
560 }
561 }
562
563 /**
564 *
565 * Callback from NativeDaemonConnector
566 */
567 public void onDaemonConnected() {
568 /*
569 * Since we'll be calling back into the NativeDaemonConnector,
570 * we need to do our work in a new thread.
571 */
572 new Thread() {
573 public void run() {
574 /**
575 * Determine media state and UMS detection status
576 */
577 String path = Environment.getExternalStorageDirectory().getPath();
578 String state = Environment.MEDIA_REMOVED;
579
580 try {
581 String[] vols = mConnector.doListCommand(
582 "volume list", VoldResponseCode.VolumeListResult);
583 for (String volstr : vols) {
584 String[] tok = volstr.split(" ");
585 // FMT: <label> <mountpoint> <state>
586 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700587 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800588 "Skipping unknown volume '%s'",tok[1]));
589 continue;
590 }
591 int st = Integer.parseInt(tok[2]);
592 if (st == VolumeState.NoMedia) {
593 state = Environment.MEDIA_REMOVED;
594 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800595 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800596 } else if (st == VolumeState.Mounted) {
597 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700598 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800599 } else if (st == VolumeState.Shared) {
600 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700601 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800602 } else {
603 throw new Exception(String.format("Unexpected state %d", st));
604 }
605 }
606 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700607 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800608 updatePublicVolumeState(path, state);
609 }
610 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700611 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800612 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
613 }
614
615 try {
San Mehat207e5382010-02-04 20:46:54 -0800616 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800617 notifyShareAvailabilityChange("ums", avail);
618 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700619 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800620 }
San Mehat207e5382010-02-04 20:46:54 -0800621 /*
622 * Now that we've done our initialization, release
623 * the hounds!
624 */
625 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800626 }
627 }.start();
628 }
629
630 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800631 * Callback from NativeDaemonConnector
632 */
633 public boolean onEvent(int code, String raw, String[] cooked) {
634 Intent in = null;
635
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800636 if (DEBUG_EVENTS) {
637 StringBuilder builder = new StringBuilder();
638 builder.append("onEvent::");
639 builder.append(" raw= " + raw);
640 if (cooked != null) {
641 builder.append(" cooked = " );
642 for (String str : cooked) {
643 builder.append(" " + str);
644 }
645 }
San Mehata5078592010-03-25 09:36:54 -0700646 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800647 }
San Mehat4270e1e2010-01-29 05:32:19 -0800648 if (code == VoldResponseCode.VolumeStateChange) {
649 /*
650 * One of the volumes we're managing has changed state.
651 * Format: "NNN Volume <label> <path> state changed
652 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
653 */
654 notifyVolumeStateChange(
655 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
656 Integer.parseInt(cooked[10]));
657 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
658 // FMT: NNN Share method <method> now <available|unavailable>
659 boolean avail = false;
660 if (cooked[5].equals("available")) {
661 avail = true;
662 }
663 notifyShareAvailabilityChange(cooked[3], avail);
664 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
665 (code == VoldResponseCode.VolumeDiskRemoved) ||
666 (code == VoldResponseCode.VolumeBadRemoval)) {
667 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
668 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
669 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
670 final String label = cooked[2];
671 final String path = cooked[3];
672 int major = -1;
673 int minor = -1;
674
675 try {
676 String devComp = cooked[6].substring(1, cooked[6].length() -1);
677 String[] devTok = devComp.split(":");
678 major = Integer.parseInt(devTok[0]);
679 minor = Integer.parseInt(devTok[1]);
680 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700681 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800682 }
683
San Mehat4270e1e2010-01-29 05:32:19 -0800684 if (code == VoldResponseCode.VolumeDiskInserted) {
685 new Thread() {
686 public void run() {
687 try {
688 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800689 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700690 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800691 }
692 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700693 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800694 }
695 }
696 }.start();
697 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
698 /*
699 * This event gets trumped if we're already in BAD_REMOVAL state
700 */
701 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
702 return true;
703 }
704 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700705 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800706 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
707 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
708 mContext.sendBroadcast(in);
709
San Mehata5078592010-03-25 09:36:54 -0700710 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800711 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
712 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
713 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700714 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800715 /* Send the media unmounted event first */
716 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
717 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
718 mContext.sendBroadcast(in);
719
San Mehata5078592010-03-25 09:36:54 -0700720 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800721 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
722 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
723 } else {
San Mehata5078592010-03-25 09:36:54 -0700724 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800725 }
726 } else {
727 return false;
728 }
729
730 if (in != null) {
731 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400732 }
733 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800734 }
735
San Mehat207e5382010-02-04 20:46:54 -0800736 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800737 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700738 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800739
740 Intent in = null;
741
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500742 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700743 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500744 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
745 Uri.parse("file://" + path)));
746 }
747
San Mehat4270e1e2010-01-29 05:32:19 -0800748 if (newState == VolumeState.Init) {
749 } else if (newState == VolumeState.NoMedia) {
750 // NoMedia is handled via Disk Remove events
751 } else if (newState == VolumeState.Idle) {
752 /*
753 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
754 * if we're in the process of enabling UMS
755 */
756 if (!vs.equals(
757 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
758 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800759 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700760 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800761 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
762 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
763 }
764 } else if (newState == VolumeState.Pending) {
765 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700766 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800767 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
768 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
769 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700770 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800771 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800772 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
773 in.putExtra("read-only", false);
774 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800775 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
776 } else if (newState == VolumeState.Formatting) {
777 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700778 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800779 /* Send the media unmounted event first */
780 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
781 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
782 mContext.sendBroadcast(in);
783
San Mehata5078592010-03-25 09:36:54 -0700784 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800785 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
786 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700787 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800788 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700789 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800790 return;
791 } else {
San Mehata5078592010-03-25 09:36:54 -0700792 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800793 }
794
795 if (in != null) {
796 mContext.sendBroadcast(in);
797 }
798 }
799
San Mehat207e5382010-02-04 20:46:54 -0800800 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700801 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700802 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700803 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700804 } catch (NativeDaemonConnectorException ex) {
805 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
806 return false;
807 }
San Mehat207e5382010-02-04 20:46:54 -0800808
809 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700810 String[] tok = line.split(" ");
811 if (tok.length < 3) {
812 Slog.e(TAG, "Malformed response to share status " + method);
813 return false;
814 }
815
San Mehat207e5382010-02-04 20:46:54 -0800816 int code;
817 try {
818 code = Integer.parseInt(tok[0]);
819 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700820 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800821 return false;
822 }
823 if (code == VoldResponseCode.ShareStatusResult) {
824 if (tok[2].equals("available"))
825 return true;
826 return false;
827 } else {
San Mehata5078592010-03-25 09:36:54 -0700828 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800829 return false;
830 }
831 }
San Mehata5078592010-03-25 09:36:54 -0700832 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800833 return false;
834 }
835
836 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800837 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800838
San Mehata5078592010-03-25 09:36:54 -0700839 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800840 try {
841 mConnector.doCommand(String.format("volume mount %s", path));
842 } catch (NativeDaemonConnectorException e) {
843 /*
844 * Mount failed for some reason
845 */
846 Intent in = null;
847 int code = e.getCode();
848 if (code == VoldResponseCode.OpFailedNoMedia) {
849 /*
850 * Attempt to mount but no media inserted
851 */
San Mehatb1043402010-02-05 08:26:50 -0800852 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800853 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700854 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800855 /*
856 * Media is blank or does not contain a supported filesystem
857 */
858 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
859 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800860 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800861 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700862 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800863 /*
864 * Volume consistency check failed
865 */
866 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
867 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800868 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800869 } else {
San Mehatb1043402010-02-05 08:26:50 -0800870 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800871 }
872
873 /*
874 * Send broadcast intent (if required for the failure)
875 */
876 if (in != null) {
877 mContext.sendBroadcast(in);
878 }
879 }
880
881 return rc;
882 }
883
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800884 /*
885 * If force is not set, we do not unmount if there are
886 * processes holding references to the volume about to be unmounted.
887 * If force is set, all the processes holding references need to be
888 * killed via the ActivityManager before actually unmounting the volume.
889 * This might even take a while and might be retried after timed delays
890 * to make sure we dont end up in an instable state and kill some core
891 * processes.
892 */
San Mehatd9709982010-02-18 11:43:03 -0800893 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800894 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800895 return VoldResponseCode.OpFailedVolNotMounted;
896 }
Kenny Rootaa485402010-09-14 14:49:41 -0700897
898 /*
899 * Force a GC to make sure AssetManagers in other threads of the
900 * system_server are cleaned up. We have to do this since AssetManager
901 * instances are kept as a WeakReference and it's possible we have files
902 * open on the external storage.
903 */
904 Runtime.getRuntime().gc();
905
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800906 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700907 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800908 try {
San Mehatd9709982010-02-18 11:43:03 -0800909 mConnector.doCommand(String.format(
910 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700911 // We unmounted the volume. None of the asec containers are available now.
912 synchronized (mAsecMountSet) {
913 mAsecMountSet.clear();
914 }
San Mehatb1043402010-02-05 08:26:50 -0800915 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800916 } catch (NativeDaemonConnectorException e) {
917 // Don't worry about mismatch in PackageManager since the
918 // call back will handle the status changes any way.
919 int code = e.getCode();
920 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800921 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800922 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
923 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800924 } else {
San Mehatb1043402010-02-05 08:26:50 -0800925 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800926 }
927 }
928 }
929
930 private int doFormatVolume(String path) {
931 try {
932 String cmd = String.format("volume format %s", path);
933 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800935 } catch (NativeDaemonConnectorException e) {
936 int code = e.getCode();
937 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800938 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800939 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800940 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800941 } else {
San Mehatb1043402010-02-05 08:26:50 -0800942 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800943 }
944 }
945 }
946
San Mehatb1043402010-02-05 08:26:50 -0800947 private boolean doGetVolumeShared(String path, String method) {
948 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700949 ArrayList<String> rsp;
950
951 try {
952 rsp = mConnector.doCommand(cmd);
953 } catch (NativeDaemonConnectorException ex) {
954 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
955 return false;
956 }
San Mehatb1043402010-02-05 08:26:50 -0800957
958 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700959 String[] tok = line.split(" ");
960 if (tok.length < 3) {
961 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
962 return false;
963 }
964
San Mehatb1043402010-02-05 08:26:50 -0800965 int code;
966 try {
967 code = Integer.parseInt(tok[0]);
968 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800970 return false;
971 }
972 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700973 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800974 } else {
San Mehata5078592010-03-25 09:36:54 -0700975 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800976 return false;
977 }
978 }
San Mehata5078592010-03-25 09:36:54 -0700979 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800980 return false;
981 }
982
San Mehat207e5382010-02-04 20:46:54 -0800983 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800984 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700985 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800986 return;
987 }
988
989 synchronized (mListeners) {
990 for (int i = mListeners.size() -1; i >= 0; i--) {
991 MountServiceBinderListener bl = mListeners.get(i);
992 try {
San Mehatb1043402010-02-05 08:26:50 -0800993 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800994 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700995 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800996 mListeners.remove(i);
997 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700998 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800999 }
1000 }
1001 }
1002
San Mehat207e5382010-02-04 20:46:54 -08001003 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001004 sendUmsIntent(avail);
1005 } else {
1006 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001007 }
San Mehat2fe718a2010-03-11 12:01:49 -08001008
1009 final String path = Environment.getExternalStorageDirectory().getPath();
1010 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1011 /*
1012 * USB mass storage disconnected while enabled
1013 */
1014 new Thread() {
1015 public void run() {
1016 try {
1017 int rc;
San Mehata5078592010-03-25 09:36:54 -07001018 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001019 doShareUnshareVolume(path, "ums", false);
1020 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001021 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001022 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1023 path, rc));
1024 }
1025 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001026 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001027 }
1028 }
1029 }.start();
1030 }
San Mehat4270e1e2010-01-29 05:32:19 -08001031 }
1032
San Mehat6a965af22010-02-24 17:47:30 -08001033 private void sendUmsIntent(boolean c) {
1034 mContext.sendBroadcast(
1035 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1036 }
1037
San Mehat207e5382010-02-04 20:46:54 -08001038 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001039 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1040 throw new SecurityException(String.format("Requires %s permission", perm));
1041 }
1042 }
1043
1044 /**
San Mehat207e5382010-02-04 20:46:54 -08001045 * Constructs a new MountService instance
1046 *
1047 * @param context Binder context for this service
1048 */
1049 public MountService(Context context) {
1050 mContext = context;
1051
Mike Lockwood03559752010-07-19 18:25:03 -04001052 mEmulateExternalStorage = context.getResources().getBoolean(
1053 com.android.internal.R.bool.config_emulateExternalStorage);
1054 if (mEmulateExternalStorage) {
1055 Slog.d(TAG, "using emulated external storage");
1056 mLegacyState = Environment.MEDIA_MOUNTED;
1057 }
1058
San Mehat207e5382010-02-04 20:46:54 -08001059 // XXX: This will go away soon in favor of IMountServiceObserver
1060 mPms = (PackageManagerService) ServiceManager.getService("package");
1061
1062 mContext.registerReceiver(mBroadcastReceiver,
1063 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1064
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001065 mHandlerThread = new HandlerThread("MountService");
1066 mHandlerThread.start();
1067 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1068
Kenny Roota02b8b02010-08-05 16:14:17 -07001069 // Add OBB Action Handler to MountService thread.
1070 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1071
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001072 /*
1073 * Vold does not run in the simulator, so pretend the connector thread
1074 * ran and did its thing.
1075 */
1076 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1077 mReady = true;
1078 mUmsEnabling = true;
1079 return;
1080 }
1081
Kenny Root305bcbf2010-09-03 07:56:38 -07001082 /*
1083 * Create the connection to vold with a maximum queue of twice the
1084 * amount of containers we'd ever expect to have. This keeps an
1085 * "asec list" from blocking a thread repeatedly.
1086 */
1087 mConnector = new NativeDaemonConnector(this, "vold",
1088 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001089 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001090 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001091 thread.start();
1092 }
1093
1094 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001095 * Exposed API calls below here
1096 */
1097
1098 public void registerListener(IMountServiceListener listener) {
1099 synchronized (mListeners) {
1100 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1101 try {
1102 listener.asBinder().linkToDeath(bl, 0);
1103 mListeners.add(bl);
1104 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001105 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001106 }
1107 }
1108 }
1109
1110 public void unregisterListener(IMountServiceListener listener) {
1111 synchronized (mListeners) {
1112 for(MountServiceBinderListener bl : mListeners) {
1113 if (bl.mListener == listener) {
1114 mListeners.remove(mListeners.indexOf(bl));
1115 return;
1116 }
1117 }
1118 }
1119 }
1120
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001121 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001122 validatePermission(android.Manifest.permission.SHUTDOWN);
1123
San Mehata5078592010-03-25 09:36:54 -07001124 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001125
1126 String path = Environment.getExternalStorageDirectory().getPath();
1127 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001128
1129 if (state.equals(Environment.MEDIA_SHARED)) {
1130 /*
1131 * If the media is currently shared, unshare it.
1132 * XXX: This is still dangerous!. We should not
1133 * be rebooting at *all* if UMS is enabled, since
1134 * the UMS host could have dirty FAT cache entries
1135 * yet to flush.
1136 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001137 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001138 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1139 /*
1140 * If the media is being checked, then we need to wait for
1141 * it to complete before being able to proceed.
1142 */
1143 // XXX: @hackbod - Should we disable the ANR timer here?
1144 int retries = 30;
1145 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1146 try {
1147 Thread.sleep(1000);
1148 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001149 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001150 break;
1151 }
1152 state = Environment.getExternalStorageState();
1153 }
1154 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001155 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001156 }
1157 }
1158
1159 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001160 // Post a unmount message.
1161 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1162 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001163 }
1164 }
1165
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001166 private boolean getUmsEnabling() {
1167 synchronized (mListeners) {
1168 return mUmsEnabling;
1169 }
1170 }
1171
1172 private void setUmsEnabling(boolean enable) {
1173 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001174 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001175 }
1176 }
1177
San Mehatb1043402010-02-05 08:26:50 -08001178 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001179 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001180
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001181 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001182 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001183 }
San Mehatb1043402010-02-05 08:26:50 -08001184 return doGetShareMethodAvailable("ums");
1185 }
1186
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001187 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001188 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001189 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001190
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001191 // TODO: Add support for multiple share methods
1192
1193 /*
1194 * If the volume is mounted and we're enabling then unmount it
1195 */
1196 String path = Environment.getExternalStorageDirectory().getPath();
1197 String vs = getVolumeState(path);
1198 String method = "ums";
1199 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1200 // Override for isUsbMassStorageEnabled()
1201 setUmsEnabling(enable);
1202 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1203 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1204 // Clear override
1205 setUmsEnabling(false);
1206 }
1207 /*
1208 * If we disabled UMS then mount the volume
1209 */
1210 if (!enable) {
1211 doShareUnshareVolume(path, method, enable);
1212 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001213 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001214 " after disabling share method " + method);
1215 /*
1216 * Even though the mount failed, the unshare didn't so don't indicate an error.
1217 * The mountVolume() call will have set the storage state and sent the necessary
1218 * broadcasts.
1219 */
1220 }
1221 }
San Mehatb1043402010-02-05 08:26:50 -08001222 }
1223
1224 public boolean isUsbMassStorageEnabled() {
1225 waitForReady();
1226 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
San Mehat4270e1e2010-01-29 05:32:19 -08001228
San Mehat7fd0fee2009-12-17 07:12:23 -08001229 /**
1230 * @return state of the volume at the specified mount point
1231 */
San Mehat4270e1e2010-01-29 05:32:19 -08001232 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001233 /*
1234 * XXX: Until we have multiple volume discovery, just hardwire
1235 * this to /sdcard
1236 */
1237 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001238 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001239 throw new IllegalArgumentException();
1240 }
1241
1242 return mLegacyState;
1243 }
1244
San Mehat4270e1e2010-01-29 05:32:19 -08001245 public int mountVolume(String path) {
1246 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001247
San Mehat207e5382010-02-04 20:46:54 -08001248 waitForReady();
1249 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 }
1251
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001252 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001253 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001254 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001256 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001257 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001258 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1259 Environment.MEDIA_REMOVED.equals(volState) ||
1260 Environment.MEDIA_SHARED.equals(volState) ||
1261 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1262 // Media already unmounted or cannot be unmounted.
1263 // TODO return valid return code when adding observer call back.
1264 return;
1265 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001266 UnmountCallBack ucb = new UnmountCallBack(path, force);
1267 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
1269
San Mehat4270e1e2010-01-29 05:32:19 -08001270 public int formatVolume(String path) {
1271 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001272 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001273
San Mehat207e5382010-02-04 20:46:54 -08001274 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
1276
San Mehatc1b4ce92010-02-16 17:13:03 -08001277 public int []getStorageUsers(String path) {
1278 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1279 waitForReady();
1280 try {
1281 String[] r = mConnector.doListCommand(
1282 String.format("storage users %s", path),
1283 VoldResponseCode.StorageUsersListResult);
1284 // FMT: <pid> <process name>
1285 int[] data = new int[r.length];
1286 for (int i = 0; i < r.length; i++) {
1287 String []tok = r[i].split(" ");
1288 try {
1289 data[i] = Integer.parseInt(tok[0]);
1290 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001291 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001292 return new int[0];
1293 }
1294 }
1295 return data;
1296 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001297 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001298 return new int[0];
1299 }
1300 }
1301
San Mehatb1043402010-02-05 08:26:50 -08001302 private void warnOnNotMounted() {
1303 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001304 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001305 }
1306 }
1307
San Mehat4270e1e2010-01-29 05:32:19 -08001308 public String[] getSecureContainerList() {
1309 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001310 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001311 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001312
San Mehat4270e1e2010-01-29 05:32:19 -08001313 try {
1314 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1315 } catch (NativeDaemonConnectorException e) {
1316 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
1318 }
San Mehat36972292010-01-06 11:06:32 -08001319
San Mehat4270e1e2010-01-29 05:32:19 -08001320 public int createSecureContainer(String id, int sizeMb, String fstype,
1321 String key, int ownerUid) {
1322 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001323 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001324 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001325
San Mehatb1043402010-02-05 08:26:50 -08001326 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001327 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1328 try {
1329 mConnector.doCommand(cmd);
1330 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001331 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001332 }
San Mehata181b212010-02-11 06:50:20 -08001333
1334 if (rc == StorageResultCode.OperationSucceeded) {
1335 synchronized (mAsecMountSet) {
1336 mAsecMountSet.add(id);
1337 }
1338 }
San Mehat4270e1e2010-01-29 05:32:19 -08001339 return rc;
San Mehat36972292010-01-06 11:06:32 -08001340 }
1341
San Mehat4270e1e2010-01-29 05:32:19 -08001342 public int finalizeSecureContainer(String id) {
1343 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001344 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001345
San Mehatb1043402010-02-05 08:26:50 -08001346 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001347 try {
1348 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001349 /*
1350 * Finalization does a remount, so no need
1351 * to update mAsecMountSet
1352 */
San Mehat4270e1e2010-01-29 05:32:19 -08001353 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001354 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001355 }
San Mehat4270e1e2010-01-29 05:32:19 -08001356 return rc;
San Mehat36972292010-01-06 11:06:32 -08001357 }
1358
San Mehatd9709982010-02-18 11:43:03 -08001359 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001360 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001361 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001362 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001363
Kenny Rootaa485402010-09-14 14:49:41 -07001364 /*
1365 * Force a GC to make sure AssetManagers in other threads of the
1366 * system_server are cleaned up. We have to do this since AssetManager
1367 * instances are kept as a WeakReference and it's possible we have files
1368 * open on the external storage.
1369 */
1370 Runtime.getRuntime().gc();
1371
San Mehatb1043402010-02-05 08:26:50 -08001372 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001373 try {
San Mehatd9709982010-02-18 11:43:03 -08001374 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001375 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001376 int code = e.getCode();
1377 if (code == VoldResponseCode.OpFailedStorageBusy) {
1378 rc = StorageResultCode.OperationFailedStorageBusy;
1379 } else {
1380 rc = StorageResultCode.OperationFailedInternalError;
1381 }
San Mehat02735bc2010-01-26 15:18:08 -08001382 }
San Mehata181b212010-02-11 06:50:20 -08001383
1384 if (rc == StorageResultCode.OperationSucceeded) {
1385 synchronized (mAsecMountSet) {
1386 if (mAsecMountSet.contains(id)) {
1387 mAsecMountSet.remove(id);
1388 }
1389 }
1390 }
1391
San Mehat4270e1e2010-01-29 05:32:19 -08001392 return rc;
San Mehat36972292010-01-06 11:06:32 -08001393 }
1394
San Mehat4270e1e2010-01-29 05:32:19 -08001395 public int mountSecureContainer(String id, String key, int ownerUid) {
1396 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001397 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001398 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001399
San Mehata181b212010-02-11 06:50:20 -08001400 synchronized (mAsecMountSet) {
1401 if (mAsecMountSet.contains(id)) {
1402 return StorageResultCode.OperationFailedStorageMounted;
1403 }
1404 }
1405
San Mehatb1043402010-02-05 08:26:50 -08001406 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001407 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1408 try {
1409 mConnector.doCommand(cmd);
1410 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001411 int code = e.getCode();
1412 if (code != VoldResponseCode.OpFailedStorageBusy) {
1413 rc = StorageResultCode.OperationFailedInternalError;
1414 }
San Mehat02735bc2010-01-26 15:18:08 -08001415 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001416
1417 if (rc == StorageResultCode.OperationSucceeded) {
1418 synchronized (mAsecMountSet) {
1419 mAsecMountSet.add(id);
1420 }
1421 }
San Mehat4270e1e2010-01-29 05:32:19 -08001422 return rc;
San Mehat36972292010-01-06 11:06:32 -08001423 }
1424
San Mehatd9709982010-02-18 11:43:03 -08001425 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001426 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
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 Mehat6cdd9c02010-02-09 14:45:20 -08001430 synchronized (mAsecMountSet) {
1431 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001432 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001433 }
1434 }
1435
Kenny Rootaa485402010-09-14 14:49:41 -07001436 /*
1437 * Force a GC to make sure AssetManagers in other threads of the
1438 * system_server are cleaned up. We have to do this since AssetManager
1439 * instances are kept as a WeakReference and it's possible we have files
1440 * open on the external storage.
1441 */
1442 Runtime.getRuntime().gc();
1443
San Mehatb1043402010-02-05 08:26:50 -08001444 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001445 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001446 try {
1447 mConnector.doCommand(cmd);
1448 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001449 int code = e.getCode();
1450 if (code == VoldResponseCode.OpFailedStorageBusy) {
1451 rc = StorageResultCode.OperationFailedStorageBusy;
1452 } else {
1453 rc = StorageResultCode.OperationFailedInternalError;
1454 }
San Mehat02735bc2010-01-26 15:18:08 -08001455 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001456
1457 if (rc == StorageResultCode.OperationSucceeded) {
1458 synchronized (mAsecMountSet) {
1459 mAsecMountSet.remove(id);
1460 }
1461 }
San Mehat4270e1e2010-01-29 05:32:19 -08001462 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001463 }
1464
San Mehat6cdd9c02010-02-09 14:45:20 -08001465 public boolean isSecureContainerMounted(String id) {
1466 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1467 waitForReady();
1468 warnOnNotMounted();
1469
1470 synchronized (mAsecMountSet) {
1471 return mAsecMountSet.contains(id);
1472 }
1473 }
1474
San Mehat4270e1e2010-01-29 05:32:19 -08001475 public int renameSecureContainer(String oldId, String newId) {
1476 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001477 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001478 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001479
San Mehata181b212010-02-11 06:50:20 -08001480 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001481 /*
1482 * Because a mounted container has active internal state which cannot be
1483 * changed while active, we must ensure both ids are not currently mounted.
1484 */
1485 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001486 return StorageResultCode.OperationFailedStorageMounted;
1487 }
1488 }
1489
San Mehatb1043402010-02-05 08:26:50 -08001490 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001491 String cmd = String.format("asec rename %s %s", oldId, newId);
1492 try {
1493 mConnector.doCommand(cmd);
1494 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001495 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001496 }
San Mehata181b212010-02-11 06:50:20 -08001497
San Mehat4270e1e2010-01-29 05:32:19 -08001498 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001499 }
1500
San Mehat4270e1e2010-01-29 05:32:19 -08001501 public String getSecureContainerPath(String id) {
1502 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001503 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001504 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001505
San Mehat2d66cef2010-03-23 11:12:52 -07001506 try {
1507 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1508 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001509 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001510 if (code != VoldResponseCode.AsecPathResult) {
1511 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1512 }
1513 return tok[1];
1514 } catch (NativeDaemonConnectorException e) {
1515 int code = e.getCode();
1516 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1517 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001518 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001519 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001520 }
1521 }
San Mehat22dd86e2010-01-12 12:21:18 -08001522 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001523
1524 public void finishMediaUpdate() {
1525 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1526 }
Kenny Root02c87302010-07-01 08:10:18 -07001527
Kenny Roota02b8b02010-08-05 16:14:17 -07001528 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1529 if (callerUid == android.os.Process.SYSTEM_UID) {
1530 return true;
1531 }
1532
Kenny Root02c87302010-07-01 08:10:18 -07001533 if (packageName == null) {
1534 return false;
1535 }
1536
1537 final int packageUid = mPms.getPackageUid(packageName);
1538
1539 if (DEBUG_OBB) {
1540 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1541 packageUid + ", callerUid = " + callerUid);
1542 }
1543
1544 return callerUid == packageUid;
1545 }
1546
1547 public String getMountedObbPath(String filename) {
1548 waitForReady();
1549 warnOnNotMounted();
1550
Kenny Root02c87302010-07-01 08:10:18 -07001551 try {
1552 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1553 String []tok = rsp.get(0).split(" ");
1554 int code = Integer.parseInt(tok[0]);
1555 if (code != VoldResponseCode.AsecPathResult) {
1556 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1557 }
1558 return tok[1];
1559 } catch (NativeDaemonConnectorException e) {
1560 int code = e.getCode();
1561 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001562 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001563 } else {
1564 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1565 }
1566 }
1567 }
1568
1569 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001570 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001571 final ObbState obbState = mObbPathToStateMap.get(filename);
1572 if (obbState != null) {
1573 synchronized (obbState) {
1574 return obbState.mounted;
1575 }
1576 }
Kenny Root02c87302010-07-01 08:10:18 -07001577 }
Kenny Root38cf8862010-09-26 14:18:51 -07001578 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001579 }
1580
Kenny Root735de3b2010-09-30 14:11:39 -07001581 public void mountObb(String filename, String key, IObbActionListener token)
1582 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001583 waitForReady();
1584 warnOnNotMounted();
1585
Kenny Rootf1121dc2010-09-29 07:30:53 -07001586 if (filename == null) {
1587 throw new IllegalArgumentException("filename cannot be null");
1588 } else if (token == null) {
1589 throw new IllegalArgumentException("token cannot be null");
1590 }
1591
Kenny Roota02b8b02010-08-05 16:14:17 -07001592 final ObbState obbState;
1593
1594 synchronized (mObbMounts) {
1595 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001596 try {
1597 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1598 } catch (RemoteException e) {
1599 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1600 }
1601 return;
Kenny Root02c87302010-07-01 08:10:18 -07001602 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001603
Kenny Roota02b8b02010-08-05 16:14:17 -07001604 final int callerUid = Binder.getCallingUid();
Kenny Root27358a62010-09-29 19:27:20 -07001605
1606 final Integer uidUsage = mObbUidUsage.get(callerUid);
1607 if (uidUsage != null && uidUsage > MAX_OBBS) {
1608 throw new IllegalStateException("Maximum number of OBBs mounted!");
1609 }
1610
Kenny Roota02b8b02010-08-05 16:14:17 -07001611 obbState = new ObbState(filename, token, callerUid);
1612 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001613 }
1614
Kenny Root29423912010-10-01 08:37:20 -07001615 String hashedKey = null;
1616 if (key != null) {
1617 final MessageDigest md;
Kenny Root735de3b2010-09-30 14:11:39 -07001618 try {
Kenny Root29423912010-10-01 08:37:20 -07001619 md = MessageDigest.getInstance("MD5");
1620 } catch (NoSuchAlgorithmException e) {
1621 Slog.e(TAG, "Could not load MD5 algorithm", e);
1622 try {
1623 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1624 } catch (RemoteException e1) {
1625 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1626 }
1627 return;
Kenny Root735de3b2010-09-30 14:11:39 -07001628 }
Kenny Root02c87302010-07-01 08:10:18 -07001629
Kenny Root29423912010-10-01 08:37:20 -07001630 hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1631 }
Kenny Root735de3b2010-09-30 14:11:39 -07001632
1633 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001634 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1635
1636 if (DEBUG_OBB)
1637 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001638 }
1639
Kenny Roota02b8b02010-08-05 16:14:17 -07001640 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001641 if (filename == null) {
1642 throw new IllegalArgumentException("filename cannot be null");
1643 } else if (token == null) {
1644 throw new IllegalArgumentException("token cannot be null");
1645 }
1646
Kenny Roota02b8b02010-08-05 16:14:17 -07001647 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001648
Kenny Roota02b8b02010-08-05 16:14:17 -07001649 synchronized (mObbMounts) {
1650 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001651 try {
1652 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1653 } catch (RemoteException e) {
1654 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1655 }
1656 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001657 }
Kenny Root38cf8862010-09-26 14:18:51 -07001658
Kenny Roota02b8b02010-08-05 16:14:17 -07001659 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001660
1661 if (Binder.getCallingUid() != obbState.callerUid) {
1662 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001663 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001664 throw new SecurityException("caller does not match original mount caller");
1665 }
Kenny Root02c87302010-07-01 08:10:18 -07001666 }
1667
Kenny Root38cf8862010-09-26 14:18:51 -07001668 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001669 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001670
Kenny Roota02b8b02010-08-05 16:14:17 -07001671 if (DEBUG_OBB)
1672 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1673 }
1674
1675 private void addObbState(ObbState obbState) {
1676 synchronized (mObbMounts) {
Kenny Root735de3b2010-09-30 14:11:39 -07001677 List<ObbState> obbStates = mObbMounts.get(obbState.getBinder());
Kenny Root05105f72010-09-22 17:29:43 -07001678 if (obbStates == null) {
1679 obbStates = new ArrayList<ObbState>();
Kenny Root735de3b2010-09-30 14:11:39 -07001680 mObbMounts.put(obbState.getBinder(), obbStates);
Kenny Root05105f72010-09-22 17:29:43 -07001681 }
1682 obbStates.add(obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001683 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Root27358a62010-09-29 19:27:20 -07001684
1685 // Track the number of OBBs used by this UID.
1686 final int uid = obbState.callerUid;
1687 final Integer uidUsage = mObbUidUsage.get(uid);
1688 if (uidUsage == null) {
1689 mObbUidUsage.put(uid, 1);
1690 } else {
1691 mObbUidUsage.put(uid, uidUsage + 1);
1692 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001693 }
1694 }
1695
1696 private void removeObbState(ObbState obbState) {
1697 synchronized (mObbMounts) {
Kenny Root735de3b2010-09-30 14:11:39 -07001698 final List<ObbState> obbStates = mObbMounts.get(obbState.getBinder());
Kenny Root05105f72010-09-22 17:29:43 -07001699 if (obbStates != null) {
1700 obbStates.remove(obbState);
1701 }
1702 if (obbStates == null || obbStates.isEmpty()) {
Kenny Root735de3b2010-09-30 14:11:39 -07001703 mObbMounts.remove(obbState.getBinder());
1704 obbState.cleanUp();
Kenny Root05105f72010-09-22 17:29:43 -07001705 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001706 mObbPathToStateMap.remove(obbState.filename);
Kenny Root27358a62010-09-29 19:27:20 -07001707
1708 // Track the number of OBBs used by this UID.
1709 final int uid = obbState.callerUid;
1710 final Integer uidUsage = mObbUidUsage.get(uid);
1711 if (uidUsage == null) {
1712 Slog.e(TAG, "Called removeObbState for UID that isn't in map: " + uid);
1713 } else {
1714 final int newUsage = uidUsage - 1;
1715 if (newUsage == 0) {
1716 mObbUidUsage.remove(uid);
1717 } else {
1718 mObbUidUsage.put(uid, newUsage);
1719 }
1720 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001721 }
1722 }
1723
Kenny Root38cf8862010-09-26 14:18:51 -07001724 private void replaceObbState(ObbState oldObbState, ObbState newObbState) {
1725 synchronized (mObbMounts) {
1726 removeObbState(oldObbState);
1727 addObbState(newObbState);
1728 }
1729 }
1730
Kenny Roota02b8b02010-08-05 16:14:17 -07001731 private class ObbActionHandler extends Handler {
1732 private boolean mBound = false;
1733 private List<ObbAction> mActions = new LinkedList<ObbAction>();
1734
1735 ObbActionHandler(Looper l) {
1736 super(l);
1737 }
1738
1739 @Override
1740 public void handleMessage(Message msg) {
1741 switch (msg.what) {
1742 case OBB_RUN_ACTION: {
1743 ObbAction action = (ObbAction) msg.obj;
1744
1745 if (DEBUG_OBB)
1746 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1747
1748 // If a bind was already initiated we don't really
1749 // need to do anything. The pending install
1750 // will be processed later on.
1751 if (!mBound) {
1752 // If this is the only one pending we might
1753 // have to bind to the service again.
1754 if (!connectToService()) {
1755 Slog.e(TAG, "Failed to bind to media container service");
1756 action.handleError();
1757 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001758 }
1759
1760 mActions.add(action);
Kenny Root735de3b2010-09-30 14:11:39 -07001761 break;
Kenny Roota02b8b02010-08-05 16:14:17 -07001762 }
Kenny Root735de3b2010-09-30 14:11:39 -07001763
1764 // Once we bind to the service, the first
1765 // pending request will be processed.
1766 mActions.add(action);
1767 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001768 break;
1769 }
1770 case OBB_MCS_BOUND: {
1771 if (DEBUG_OBB)
1772 Slog.i(TAG, "OBB_MCS_BOUND");
1773 if (msg.obj != null) {
1774 mContainerService = (IMediaContainerService) msg.obj;
1775 }
1776 if (mContainerService == null) {
1777 // Something seriously wrong. Bail out
1778 Slog.e(TAG, "Cannot bind to media container service");
1779 for (ObbAction action : mActions) {
1780 // Indicate service bind error
1781 action.handleError();
1782 }
1783 mActions.clear();
1784 } else if (mActions.size() > 0) {
1785 ObbAction action = mActions.get(0);
1786 if (action != null) {
1787 action.execute(this);
1788 }
1789 } else {
1790 // Should never happen ideally.
1791 Slog.w(TAG, "Empty queue");
1792 }
1793 break;
1794 }
1795 case OBB_MCS_RECONNECT: {
1796 if (DEBUG_OBB)
1797 Slog.i(TAG, "OBB_MCS_RECONNECT");
1798 if (mActions.size() > 0) {
1799 if (mBound) {
1800 disconnectService();
1801 }
1802 if (!connectToService()) {
1803 Slog.e(TAG, "Failed to bind to media container service");
1804 for (ObbAction action : mActions) {
1805 // Indicate service bind error
1806 action.handleError();
1807 }
1808 mActions.clear();
1809 }
1810 }
1811 break;
1812 }
1813 case OBB_MCS_UNBIND: {
1814 if (DEBUG_OBB)
1815 Slog.i(TAG, "OBB_MCS_UNBIND");
1816
1817 // Delete pending install
1818 if (mActions.size() > 0) {
1819 mActions.remove(0);
1820 }
1821 if (mActions.size() == 0) {
1822 if (mBound) {
1823 disconnectService();
1824 }
1825 } else {
1826 // There are more pending requests in queue.
1827 // Just post MCS_BOUND message to trigger processing
1828 // of next pending install.
1829 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1830 }
1831 break;
1832 }
1833 case OBB_MCS_GIVE_UP: {
1834 if (DEBUG_OBB)
1835 Slog.i(TAG, "OBB_MCS_GIVE_UP");
1836 mActions.remove(0);
1837 break;
1838 }
1839 }
1840 }
1841
1842 private boolean connectToService() {
1843 if (DEBUG_OBB)
1844 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1845
1846 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1847 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1848 mBound = true;
1849 return true;
1850 }
1851 return false;
1852 }
1853
1854 private void disconnectService() {
1855 mContainerService = null;
1856 mBound = false;
1857 mContext.unbindService(mDefContainerConn);
1858 }
1859 }
1860
1861 abstract class ObbAction {
1862 private static final int MAX_RETRIES = 3;
1863 private int mRetries;
1864
1865 ObbState mObbState;
1866
1867 ObbAction(ObbState obbState) {
1868 mObbState = obbState;
1869 }
1870
1871 public void execute(ObbActionHandler handler) {
1872 try {
1873 if (DEBUG_OBB)
1874 Slog.i(TAG, "Starting to execute action: " + this.toString());
1875 mRetries++;
1876 if (mRetries > MAX_RETRIES) {
1877 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
1878 mObbActionHandler.sendEmptyMessage(OBB_MCS_GIVE_UP);
1879 handleError();
1880 return;
1881 } else {
1882 handleExecute();
1883 if (DEBUG_OBB)
1884 Slog.i(TAG, "Posting install MCS_UNBIND");
1885 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1886 }
1887 } catch (RemoteException e) {
1888 if (DEBUG_OBB)
1889 Slog.i(TAG, "Posting install MCS_RECONNECT");
1890 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1891 } catch (Exception e) {
1892 if (DEBUG_OBB)
1893 Slog.d(TAG, "Error handling OBB action", e);
1894 handleError();
1895 }
1896 }
1897
Kenny Root05105f72010-09-22 17:29:43 -07001898 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001899 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001900
1901 protected ObbInfo getObbInfo() throws IOException {
1902 ObbInfo obbInfo;
1903 try {
1904 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1905 } catch (RemoteException e) {
1906 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1907 + mObbState.filename);
1908 obbInfo = null;
1909 }
1910 if (obbInfo == null) {
1911 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1912 }
1913 return obbInfo;
1914 }
1915
1916 protected void sendNewStatusOrIgnore(String filename, String status) {
1917 try {
1918 mObbState.token.onObbResult(filename, status);
1919 } catch (RemoteException e) {
1920 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1921 }
1922 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001923 }
1924
1925 class MountObbAction extends ObbAction {
1926 private String mKey;
1927
1928 MountObbAction(ObbState obbState, String key) {
1929 super(obbState);
1930 mKey = key;
1931 }
1932
Kenny Root735de3b2010-09-30 14:11:39 -07001933 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001934 final ObbInfo obbInfo = getObbInfo();
1935
1936 /*
1937 * If someone tried to trick us with some weird characters, rectify
1938 * it here.
1939 */
1940 if (!mObbState.filename.equals(obbInfo.filename)) {
1941 if (DEBUG_OBB)
1942 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1943 + obbInfo.filename);
1944
1945 synchronized (mObbMounts) {
1946 /*
1947 * If the real filename is already mounted, discard this
1948 * state and notify the caller that the OBB is already
1949 * mounted.
1950 */
1951 if (isObbMounted(obbInfo.filename)) {
1952 if (DEBUG_OBB)
1953 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1954
1955 removeObbState(mObbState);
1956 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1957 return;
1958 }
1959
1960 /*
1961 * It's not already mounted, so we have to replace the state
1962 * with the state containing the actual filename.
1963 */
1964 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1965 mObbState.callerUid);
1966 replaceObbState(mObbState, newObbState);
1967 mObbState = newObbState;
1968 }
Kenny Root05105f72010-09-22 17:29:43 -07001969 }
1970
Kenny Roota02b8b02010-08-05 16:14:17 -07001971 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1972 throw new IllegalArgumentException("Caller package does not match OBB file");
1973 }
1974
Kenny Root38cf8862010-09-26 14:18:51 -07001975 boolean mounted = false;
1976 int rc;
1977 synchronized (mObbState) {
1978 if (mObbState.mounted) {
1979 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1980 return;
1981 }
1982
1983 rc = StorageResultCode.OperationSucceeded;
Kenny Root12ffd9b2010-10-01 12:56:59 -07001984 String cmd = String.format("obb mount %s %s %d", mObbState.filename,
1985 mKey != null ? mKey : "none",
Kenny Root38cf8862010-09-26 14:18:51 -07001986 mObbState.callerUid);
1987 try {
1988 mConnector.doCommand(cmd);
1989 } catch (NativeDaemonConnectorException e) {
1990 int code = e.getCode();
1991 if (code != VoldResponseCode.OpFailedStorageBusy) {
1992 rc = StorageResultCode.OperationFailedInternalError;
1993 }
1994 }
1995
1996 if (rc == StorageResultCode.OperationSucceeded) {
1997 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001998 }
1999 }
2000
Kenny Root38cf8862010-09-26 14:18:51 -07002001 if (mounted) {
2002 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002003 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002004 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002005
2006 // We didn't succeed, so remove this from the mount-set.
2007 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07002008
Kenny Root38cf8862010-09-26 14:18:51 -07002009 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002010 }
2011 }
2012
Kenny Roota02b8b02010-08-05 16:14:17 -07002013 public void handleError() {
2014 removeObbState(mObbState);
2015
Kenny Root38cf8862010-09-26 14:18:51 -07002016 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07002017 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002018
2019 @Override
2020 public String toString() {
2021 StringBuilder sb = new StringBuilder();
2022 sb.append("MountObbAction{");
2023 sb.append("filename=");
2024 sb.append(mObbState.filename);
2025 sb.append(",callerUid=");
2026 sb.append(mObbState.callerUid);
2027 sb.append(",token=");
2028 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2029 sb.append('}');
2030 return sb.toString();
2031 }
2032 }
2033
2034 class UnmountObbAction extends ObbAction {
2035 private boolean mForceUnmount;
2036
2037 UnmountObbAction(ObbState obbState, boolean force) {
2038 super(obbState);
2039 mForceUnmount = force;
2040 }
2041
Kenny Root38cf8862010-09-26 14:18:51 -07002042 public void handleExecute() throws IOException {
2043 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002044
Kenny Root38cf8862010-09-26 14:18:51 -07002045 /*
2046 * If someone tried to trick us with some weird characters, rectify
2047 * it here.
2048 */
2049 synchronized (mObbMounts) {
2050 if (!isObbMounted(obbInfo.filename)) {
2051 removeObbState(mObbState);
2052 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2053 return;
2054 }
2055
2056 if (!mObbState.filename.equals(obbInfo.filename)) {
2057 removeObbState(mObbState);
2058 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002059 }
2060 }
2061
Kenny Root38cf8862010-09-26 14:18:51 -07002062 boolean unmounted = false;
2063 synchronized (mObbState) {
2064 if (!mObbState.mounted) {
2065 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2066 return;
2067 }
2068
2069 int rc = StorageResultCode.OperationSucceeded;
2070 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2071 (mForceUnmount ? " force" : ""));
2072 try {
2073 mConnector.doCommand(cmd);
2074 } catch (NativeDaemonConnectorException e) {
2075 int code = e.getCode();
2076 if (code == VoldResponseCode.OpFailedStorageBusy) {
2077 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002078 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2079 // If it's not mounted then we've already won.
2080 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002081 } else {
2082 rc = StorageResultCode.OperationFailedInternalError;
2083 }
2084 }
2085
2086 if (rc == StorageResultCode.OperationSucceeded) {
2087 mObbState.mounted = false;
2088 unmounted = true;
2089 }
2090 }
2091
2092 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002093 removeObbState(mObbState);
2094
Kenny Root38cf8862010-09-26 14:18:51 -07002095 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002096 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002097 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002098 }
2099 }
2100
2101 public void handleError() {
2102 removeObbState(mObbState);
2103
Kenny Root38cf8862010-09-26 14:18:51 -07002104 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002105 }
2106
2107 @Override
2108 public String toString() {
2109 StringBuilder sb = new StringBuilder();
2110 sb.append("UnmountObbAction{");
2111 sb.append("filename=");
2112 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2113 sb.append(",force=");
2114 sb.append(mForceUnmount);
2115 sb.append(",callerUid=");
2116 sb.append(mObbState.callerUid);
2117 sb.append(",token=");
2118 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002119 sb.append(",binder=");
2120 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002121 sb.append('}');
2122 return sb.toString();
2123 }
Kenny Root02c87302010-07-01 08:10:18 -07002124 }
Kenny Root38cf8862010-09-26 14:18:51 -07002125
2126 @Override
2127 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2128 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2129 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2130 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2131 + " without permission " + android.Manifest.permission.DUMP);
2132 return;
2133 }
2134
2135 pw.println(" mObbMounts:");
2136
2137 synchronized (mObbMounts) {
2138 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2139
2140 for (final List<ObbState> obbStates : obbStateLists) {
2141 for (final ObbState obbState : obbStates) {
2142 pw.print(" "); pw.println(obbState.toString());
2143 }
2144 }
2145 }
2146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147}
2148