blob: 62a989447f2734e271adcc786889fbcbbfcdc5c6 [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;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020import com.android.server.am.ActivityManagerService;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070029import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070032import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080033import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040034import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070035import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040036import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080037import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080038import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080039import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080040import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.storage.IMountService;
43import android.os.storage.IMountServiceListener;
44import android.os.storage.IMountShutdownObserver;
45import android.os.storage.IObbActionListener;
46import android.os.storage.StorageResultCode;
San Mehata5078592010-03-25 09:36:54 -070047import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070048
Kenny Root38cf8862010-09-26 14:18:51 -070049import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070050import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070051import java.io.PrintWriter;
San Mehat22dd86e2010-01-12 12:21:18 -080052import java.util.ArrayList;
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.util.Collection;
Kenny Roota02b8b02010-08-05 16:14:17 -070054import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080055import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070056import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.LinkedList;
58import java.util.List;
59import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070060import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062/**
San Mehatb1043402010-02-05 08:26:50 -080063 * MountService implements back-end services for platform storage
64 * management.
65 * @hide - Applications should use android.os.storage.StorageManager
66 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 */
San Mehat22dd86e2010-01-12 12:21:18 -080068class MountService extends IMountService.Stub
69 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080070 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080071 private static final boolean DEBUG_UNMOUNT = false;
72 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070073 private static final boolean DEBUG_OBB = true;
74
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 private static final String TAG = "MountService";
76
Kenny Root305bcbf2010-09-03 07:56:38 -070077 private static final String VOLD_TAG = "VoldConnector";
78
Kenny Root27358a62010-09-29 19:27:20 -070079 protected static final int MAX_OBBS = 8;
80
San Mehat4270e1e2010-01-29 05:32:19 -080081 /*
82 * Internal vold volume state constants
83 */
San Mehat7fd0fee2009-12-17 07:12:23 -080084 class VolumeState {
85 public static final int Init = -1;
86 public static final int NoMedia = 0;
87 public static final int Idle = 1;
88 public static final int Pending = 2;
89 public static final int Checking = 3;
90 public static final int Mounted = 4;
91 public static final int Unmounting = 5;
92 public static final int Formatting = 6;
93 public static final int Shared = 7;
94 public static final int SharedMnt = 8;
95 }
96
San Mehat4270e1e2010-01-29 05:32:19 -080097 /*
98 * Internal vold response code constants
99 */
San Mehat22dd86e2010-01-12 12:21:18 -0800100 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800101 /*
102 * 100 series - Requestion action was initiated; expect another reply
103 * before proceeding with a new command.
104 */
San Mehat22dd86e2010-01-12 12:21:18 -0800105 public static final int VolumeListResult = 110;
106 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800107 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800108
San Mehat4270e1e2010-01-29 05:32:19 -0800109 /*
110 * 200 series - Requestion action has been successfully completed.
111 */
112 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800113 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800114 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800115
San Mehat4270e1e2010-01-29 05:32:19 -0800116 /*
117 * 400 series - Command was accepted, but the requested action
118 * did not take place.
119 */
120 public static final int OpFailedNoMedia = 401;
121 public static final int OpFailedMediaBlank = 402;
122 public static final int OpFailedMediaCorrupt = 403;
123 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800124 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700125 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800126
127 /*
128 * 600 series - Unsolicited broadcasts.
129 */
San Mehat22dd86e2010-01-12 12:21:18 -0800130 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800131 public static final int ShareAvailabilityChange = 620;
132 public static final int VolumeDiskInserted = 630;
133 public static final int VolumeDiskRemoved = 631;
134 public static final int VolumeBadRemoval = 632;
135 }
136
San Mehat4270e1e2010-01-29 05:32:19 -0800137 private Context mContext;
138 private NativeDaemonConnector mConnector;
139 private String mLegacyState = Environment.MEDIA_REMOVED;
140 private PackageManagerService mPms;
141 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800142 // Used as a lock for methods that register/unregister listeners.
143 final private ArrayList<MountServiceBinderListener> mListeners =
144 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800145 private boolean mBooted = false;
146 private boolean mReady = false;
147 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800148
San Mehat6cdd9c02010-02-09 14:45:20 -0800149 /**
150 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800151 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800152 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800153 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800154
Kenny Root02c87302010-07-01 08:10:18 -0700155 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700156 * Mounted OBB tracking information. Used to track the current state of all
157 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700158 */
Kenny Root27358a62010-09-29 19:27:20 -0700159 final private Map<Integer, Integer> mObbUidUsage = new HashMap<Integer, Integer>();
Kenny Root05105f72010-09-22 17:29:43 -0700160 final private Map<IObbActionListener, List<ObbState>> mObbMounts = new HashMap<IObbActionListener, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700161 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
162
163 class ObbState implements IBinder.DeathRecipient {
164 public ObbState(String filename, IObbActionListener token, int callerUid) {
165 this.filename = filename;
166 this.token = token;
167 this.callerUid = callerUid;
168 mounted = false;
169 }
170
171 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700172 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700173
174 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700175 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700176
177 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700178 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700179
180 // Whether this is mounted currently.
181 boolean mounted;
182
183 @Override
184 public void binderDied() {
185 ObbAction action = new UnmountObbAction(this, true);
186 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
187
188 removeObbState(this);
189
190 token.asBinder().unlinkToDeath(this, 0);
191 }
Kenny Root38cf8862010-09-26 14:18:51 -0700192
193 @Override
194 public String toString() {
195 StringBuilder sb = new StringBuilder("ObbState{");
196 sb.append("filename=");
197 sb.append(filename);
198 sb.append(",token=");
199 sb.append(token.toString());
200 sb.append(",callerUid=");
201 sb.append(callerUid);
202 sb.append(",mounted=");
203 sb.append(mounted);
204 sb.append('}');
205 return sb.toString();
206 }
207
Kenny Roota02b8b02010-08-05 16:14:17 -0700208 }
209
210 // OBB Action Handler
211 final private ObbActionHandler mObbActionHandler;
212
213 // OBB action handler messages
214 private static final int OBB_RUN_ACTION = 1;
215 private static final int OBB_MCS_BOUND = 2;
216 private static final int OBB_MCS_UNBIND = 3;
217 private static final int OBB_MCS_RECONNECT = 4;
218 private static final int OBB_MCS_GIVE_UP = 5;
219
220 /*
221 * Default Container Service information
222 */
223 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
224 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
225
226 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
227
228 class DefaultContainerConnection implements ServiceConnection {
229 public void onServiceConnected(ComponentName name, IBinder service) {
230 if (DEBUG_OBB)
231 Slog.i(TAG, "onServiceConnected");
232 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
233 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
234 }
235
236 public void onServiceDisconnected(ComponentName name) {
237 if (DEBUG_OBB)
238 Slog.i(TAG, "onServiceDisconnected");
239 }
240 };
241
242 // Used in the ObbActionHandler
243 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700244
245 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800246 private static final int H_UNMOUNT_PM_UPDATE = 1;
247 private static final int H_UNMOUNT_PM_DONE = 2;
248 private static final int H_UNMOUNT_MS = 3;
249 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
250 private static final int MAX_UNMOUNT_RETRIES = 4;
251
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800252 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700253 final String path;
254 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800255 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800256
257 UnmountCallBack(String path, boolean force) {
258 retries = 0;
259 this.path = path;
260 this.force = force;
261 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800262
263 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700264 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800265 doUnmountVolume(path, true);
266 }
267 }
268
269 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700270 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800271
272 UmsEnableCallBack(String path, String method, boolean force) {
273 super(path, force);
274 this.method = method;
275 }
276
277 @Override
278 void handleFinished() {
279 super.handleFinished();
280 doShareUnshareVolume(path, method, true);
281 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800282 }
283
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800284 class ShutdownCallBack extends UnmountCallBack {
285 IMountShutdownObserver observer;
286 ShutdownCallBack(String path, IMountShutdownObserver observer) {
287 super(path, true);
288 this.observer = observer;
289 }
290
291 @Override
292 void handleFinished() {
293 int ret = doUnmountVolume(path, true);
294 if (observer != null) {
295 try {
296 observer.onShutDownComplete(ret);
297 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700298 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800299 }
300 }
301 }
302 }
303
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400304 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800305 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700306 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800307
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400308 MountServiceHandler(Looper l) {
309 super(l);
310 }
311
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800312 public void handleMessage(Message msg) {
313 switch (msg.what) {
314 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700315 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800316 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
317 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700318 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800319 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700320 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700321 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700322 mUpdatingStatus = true;
323 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800324 }
325 break;
326 }
327 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700328 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700329 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700330 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800331 int size = mForceUnmounts.size();
332 int sizeArr[] = new int[size];
333 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700334 // Kill processes holding references first
335 ActivityManagerService ams = (ActivityManagerService)
336 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800337 for (int i = 0; i < size; i++) {
338 UnmountCallBack ucb = mForceUnmounts.get(i);
339 String path = ucb.path;
340 boolean done = false;
341 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800342 done = true;
343 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800344 int pids[] = getStorageUsers(path);
345 if (pids == null || pids.length == 0) {
346 done = true;
347 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800348 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700349 ams.killPids(pids, "unmount media");
350 // Confirm if file references have been freed.
351 pids = getStorageUsers(path);
352 if (pids == null || pids.length == 0) {
353 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354 }
355 }
356 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700357 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
358 // Retry again
359 Slog.i(TAG, "Retrying to kill storage users again");
360 mHandler.sendMessageDelayed(
361 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
362 ucb.retries++),
363 RETRY_UNMOUNT_DELAY);
364 } else {
365 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
366 Slog.i(TAG, "Failed to unmount media inspite of " +
367 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
368 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800369 sizeArr[sizeArrN++] = i;
370 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
371 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 }
373 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800374 // Remove already processed elements from list.
375 for (int i = (sizeArrN-1); i >= 0; i--) {
376 mForceUnmounts.remove(sizeArr[i]);
377 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800378 break;
379 }
380 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700381 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800382 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800383 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 break;
385 }
386 }
387 }
388 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400389 final private HandlerThread mHandlerThread;
390 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800391
San Mehat207e5382010-02-04 20:46:54 -0800392 private void waitForReady() {
393 while (mReady == false) {
394 for (int retries = 5; retries > 0; retries--) {
395 if (mReady) {
396 return;
397 }
398 SystemClock.sleep(1000);
399 }
San Mehata5078592010-03-25 09:36:54 -0700400 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800401 }
San Mehat1f6301e2010-01-07 22:40:27 -0800402 }
Kenny Root02c87302010-07-01 08:10:18 -0700403
San Mehat207e5382010-02-04 20:46:54 -0800404 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800406 String action = intent.getAction();
407
408 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800409 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800410
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800411 /*
412 * In the simulator, we need to broadcast a volume mounted event
413 * to make the media scanner run.
414 */
415 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
416 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
417 return;
418 }
San Mehatfafb0412010-02-18 19:40:04 -0800419 new Thread() {
420 public void run() {
421 try {
422 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700423 String state = getVolumeState(path);
424
425 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800426 int rc = doMountVolume(path);
427 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700428 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800429 }
San Mehat6a254402010-03-22 10:21:00 -0700430 } else if (state.equals(Environment.MEDIA_SHARED)) {
431 /*
432 * Bootstrap UMS enabled state since vold indicates
433 * the volume is shared (runtime restart while ums enabled)
434 */
435 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800436 }
San Mehat6a254402010-03-22 10:21:00 -0700437
San Mehat6a965af22010-02-24 17:47:30 -0800438 /*
San Mehat6a254402010-03-22 10:21:00 -0700439 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800440 * now that we're up.
441 */
442 if (mSendUmsConnectedOnBoot) {
443 sendUmsIntent(true);
444 mSendUmsConnectedOnBoot = false;
445 }
San Mehatfafb0412010-02-18 19:40:04 -0800446 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700447 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800448 }
San Mehat207e5382010-02-04 20:46:54 -0800449 }
San Mehatfafb0412010-02-18 19:40:04 -0800450 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452 }
453 };
454
San Mehat4270e1e2010-01-29 05:32:19 -0800455 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
456 final IMountServiceListener mListener;
457
458 MountServiceBinderListener(IMountServiceListener listener) {
459 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700460
San Mehat91c77612010-01-07 10:39:41 -0800461 }
462
San Mehat4270e1e2010-01-29 05:32:19 -0800463 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700464 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700465 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800466 mListeners.remove(this);
467 mListener.asBinder().unlinkToDeath(this, 0);
468 }
469 }
470 }
471
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800472 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800473 // TODO: Add support for multiple share methods
474 if (!method.equals("ums")) {
475 throw new IllegalArgumentException(String.format("Method %s not supported", method));
476 }
477
San Mehat4270e1e2010-01-29 05:32:19 -0800478 try {
479 mConnector.doCommand(String.format(
480 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
481 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700482 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800483 }
San Mehat4270e1e2010-01-29 05:32:19 -0800484 }
485
San Mehat207e5382010-02-04 20:46:54 -0800486 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800487 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700488 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800489 return;
490 }
San Mehatb1043402010-02-05 08:26:50 -0800491
492 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700493 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800494 return;
495 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800496 // Update state on PackageManager
497 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700498 mPms.updateExternalMediaStatus(false, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800499 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700500 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800501 }
Kenny Root38cf8862010-09-26 14:18:51 -0700502
503 // Remove all OBB mappings and listeners from this path
504 synchronized (mObbMounts) {
505 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
506
507 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
508 while (i.hasNext()) {
509 final Entry<String, ObbState> obbEntry = i.next();
510
511 // If this entry's source file is in the volume path that got
512 // unmounted, remove it because it's no longer valid.
513 if (obbEntry.getKey().startsWith(path)) {
514 obbStatesToRemove.add(obbEntry.getValue());
515 }
516 }
517
518 for (final ObbState obbState : obbStatesToRemove) {
519 removeObbState(obbState);
520
521 try {
522 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
523 } catch (RemoteException e) {
524 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
525 + obbState.filename);
526 }
527 }
528 }
529
San Mehat4270e1e2010-01-29 05:32:19 -0800530 String oldState = mLegacyState;
531 mLegacyState = state;
532
533 synchronized (mListeners) {
534 for (int i = mListeners.size() -1; i >= 0; i--) {
535 MountServiceBinderListener bl = mListeners.get(i);
536 try {
San Mehatb1043402010-02-05 08:26:50 -0800537 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800538 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700539 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800540 mListeners.remove(i);
541 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700542 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800543 }
544 }
545 }
546 }
547
548 /**
549 *
550 * Callback from NativeDaemonConnector
551 */
552 public void onDaemonConnected() {
553 /*
554 * Since we'll be calling back into the NativeDaemonConnector,
555 * we need to do our work in a new thread.
556 */
557 new Thread() {
558 public void run() {
559 /**
560 * Determine media state and UMS detection status
561 */
562 String path = Environment.getExternalStorageDirectory().getPath();
563 String state = Environment.MEDIA_REMOVED;
564
565 try {
566 String[] vols = mConnector.doListCommand(
567 "volume list", VoldResponseCode.VolumeListResult);
568 for (String volstr : vols) {
569 String[] tok = volstr.split(" ");
570 // FMT: <label> <mountpoint> <state>
571 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700572 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800573 "Skipping unknown volume '%s'",tok[1]));
574 continue;
575 }
576 int st = Integer.parseInt(tok[2]);
577 if (st == VolumeState.NoMedia) {
578 state = Environment.MEDIA_REMOVED;
579 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800580 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800581 } else if (st == VolumeState.Mounted) {
582 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700583 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800584 } else if (st == VolumeState.Shared) {
585 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700586 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800587 } else {
588 throw new Exception(String.format("Unexpected state %d", st));
589 }
590 }
591 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700592 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800593 updatePublicVolumeState(path, state);
594 }
595 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700596 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800597 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
598 }
599
600 try {
San Mehat207e5382010-02-04 20:46:54 -0800601 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800602 notifyShareAvailabilityChange("ums", avail);
603 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700604 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800605 }
San Mehat207e5382010-02-04 20:46:54 -0800606 /*
607 * Now that we've done our initialization, release
608 * the hounds!
609 */
610 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800611 }
612 }.start();
613 }
614
615 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800616 * Callback from NativeDaemonConnector
617 */
618 public boolean onEvent(int code, String raw, String[] cooked) {
619 Intent in = null;
620
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800621 if (DEBUG_EVENTS) {
622 StringBuilder builder = new StringBuilder();
623 builder.append("onEvent::");
624 builder.append(" raw= " + raw);
625 if (cooked != null) {
626 builder.append(" cooked = " );
627 for (String str : cooked) {
628 builder.append(" " + str);
629 }
630 }
San Mehata5078592010-03-25 09:36:54 -0700631 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800632 }
San Mehat4270e1e2010-01-29 05:32:19 -0800633 if (code == VoldResponseCode.VolumeStateChange) {
634 /*
635 * One of the volumes we're managing has changed state.
636 * Format: "NNN Volume <label> <path> state changed
637 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
638 */
639 notifyVolumeStateChange(
640 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
641 Integer.parseInt(cooked[10]));
642 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
643 // FMT: NNN Share method <method> now <available|unavailable>
644 boolean avail = false;
645 if (cooked[5].equals("available")) {
646 avail = true;
647 }
648 notifyShareAvailabilityChange(cooked[3], avail);
649 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
650 (code == VoldResponseCode.VolumeDiskRemoved) ||
651 (code == VoldResponseCode.VolumeBadRemoval)) {
652 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
653 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
654 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
655 final String label = cooked[2];
656 final String path = cooked[3];
657 int major = -1;
658 int minor = -1;
659
660 try {
661 String devComp = cooked[6].substring(1, cooked[6].length() -1);
662 String[] devTok = devComp.split(":");
663 major = Integer.parseInt(devTok[0]);
664 minor = Integer.parseInt(devTok[1]);
665 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700666 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800667 }
668
San Mehat4270e1e2010-01-29 05:32:19 -0800669 if (code == VoldResponseCode.VolumeDiskInserted) {
670 new Thread() {
671 public void run() {
672 try {
673 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800674 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700675 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800676 }
677 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700678 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800679 }
680 }
681 }.start();
682 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
683 /*
684 * This event gets trumped if we're already in BAD_REMOVAL state
685 */
686 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
687 return true;
688 }
689 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700690 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800691 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
692 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
693 mContext.sendBroadcast(in);
694
San Mehata5078592010-03-25 09:36:54 -0700695 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800696 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
697 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
698 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700699 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800700 /* Send the media unmounted event first */
701 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
702 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
703 mContext.sendBroadcast(in);
704
San Mehata5078592010-03-25 09:36:54 -0700705 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800706 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
707 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
708 } else {
San Mehata5078592010-03-25 09:36:54 -0700709 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800710 }
711 } else {
712 return false;
713 }
714
715 if (in != null) {
716 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400717 }
718 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800719 }
720
San Mehat207e5382010-02-04 20:46:54 -0800721 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800722 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700723 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800724
725 Intent in = null;
726
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500727 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700728 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500729 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
730 Uri.parse("file://" + path)));
731 }
732
San Mehat4270e1e2010-01-29 05:32:19 -0800733 if (newState == VolumeState.Init) {
734 } else if (newState == VolumeState.NoMedia) {
735 // NoMedia is handled via Disk Remove events
736 } else if (newState == VolumeState.Idle) {
737 /*
738 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
739 * if we're in the process of enabling UMS
740 */
741 if (!vs.equals(
742 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
743 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800744 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700745 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800746 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
747 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
748 }
749 } else if (newState == VolumeState.Pending) {
750 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700751 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
753 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
754 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700755 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800756 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800757 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
758 in.putExtra("read-only", false);
759 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800760 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
761 } else if (newState == VolumeState.Formatting) {
762 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700763 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800764 /* Send the media unmounted event first */
765 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
766 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
767 mContext.sendBroadcast(in);
768
San Mehata5078592010-03-25 09:36:54 -0700769 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800770 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
771 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700772 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800773 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700774 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800775 return;
776 } else {
San Mehata5078592010-03-25 09:36:54 -0700777 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800778 }
779
780 if (in != null) {
781 mContext.sendBroadcast(in);
782 }
783 }
784
San Mehat207e5382010-02-04 20:46:54 -0800785 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700786 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700787 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700788 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700789 } catch (NativeDaemonConnectorException ex) {
790 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
791 return false;
792 }
San Mehat207e5382010-02-04 20:46:54 -0800793
794 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700795 String[] tok = line.split(" ");
796 if (tok.length < 3) {
797 Slog.e(TAG, "Malformed response to share status " + method);
798 return false;
799 }
800
San Mehat207e5382010-02-04 20:46:54 -0800801 int code;
802 try {
803 code = Integer.parseInt(tok[0]);
804 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700805 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800806 return false;
807 }
808 if (code == VoldResponseCode.ShareStatusResult) {
809 if (tok[2].equals("available"))
810 return true;
811 return false;
812 } else {
San Mehata5078592010-03-25 09:36:54 -0700813 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800814 return false;
815 }
816 }
San Mehata5078592010-03-25 09:36:54 -0700817 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800818 return false;
819 }
820
821 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800822 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800823
San Mehata5078592010-03-25 09:36:54 -0700824 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800825 try {
826 mConnector.doCommand(String.format("volume mount %s", path));
827 } catch (NativeDaemonConnectorException e) {
828 /*
829 * Mount failed for some reason
830 */
831 Intent in = null;
832 int code = e.getCode();
833 if (code == VoldResponseCode.OpFailedNoMedia) {
834 /*
835 * Attempt to mount but no media inserted
836 */
San Mehatb1043402010-02-05 08:26:50 -0800837 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800838 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700839 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800840 /*
841 * Media is blank or does not contain a supported filesystem
842 */
843 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
844 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800845 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800846 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700847 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800848 /*
849 * Volume consistency check failed
850 */
851 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
852 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800853 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800854 } else {
San Mehatb1043402010-02-05 08:26:50 -0800855 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800856 }
857
858 /*
859 * Send broadcast intent (if required for the failure)
860 */
861 if (in != null) {
862 mContext.sendBroadcast(in);
863 }
864 }
865
866 return rc;
867 }
868
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800869 /*
870 * If force is not set, we do not unmount if there are
871 * processes holding references to the volume about to be unmounted.
872 * If force is set, all the processes holding references need to be
873 * killed via the ActivityManager before actually unmounting the volume.
874 * This might even take a while and might be retried after timed delays
875 * to make sure we dont end up in an instable state and kill some core
876 * processes.
877 */
San Mehatd9709982010-02-18 11:43:03 -0800878 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800879 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800880 return VoldResponseCode.OpFailedVolNotMounted;
881 }
Kenny Rootaa485402010-09-14 14:49:41 -0700882
883 /*
884 * Force a GC to make sure AssetManagers in other threads of the
885 * system_server are cleaned up. We have to do this since AssetManager
886 * instances are kept as a WeakReference and it's possible we have files
887 * open on the external storage.
888 */
889 Runtime.getRuntime().gc();
890
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800891 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700892 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800893 try {
San Mehatd9709982010-02-18 11:43:03 -0800894 mConnector.doCommand(String.format(
895 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700896 // We unmounted the volume. None of the asec containers are available now.
897 synchronized (mAsecMountSet) {
898 mAsecMountSet.clear();
899 }
San Mehatb1043402010-02-05 08:26:50 -0800900 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800901 } catch (NativeDaemonConnectorException e) {
902 // Don't worry about mismatch in PackageManager since the
903 // call back will handle the status changes any way.
904 int code = e.getCode();
905 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800906 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800907 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
908 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800909 } else {
San Mehatb1043402010-02-05 08:26:50 -0800910 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800911 }
912 }
913 }
914
915 private int doFormatVolume(String path) {
916 try {
917 String cmd = String.format("volume format %s", path);
918 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800919 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800920 } catch (NativeDaemonConnectorException e) {
921 int code = e.getCode();
922 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800923 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800924 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800925 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800926 } else {
San Mehatb1043402010-02-05 08:26:50 -0800927 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800928 }
929 }
930 }
931
San Mehatb1043402010-02-05 08:26:50 -0800932 private boolean doGetVolumeShared(String path, String method) {
933 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700934 ArrayList<String> rsp;
935
936 try {
937 rsp = mConnector.doCommand(cmd);
938 } catch (NativeDaemonConnectorException ex) {
939 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
940 return false;
941 }
San Mehatb1043402010-02-05 08:26:50 -0800942
943 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700944 String[] tok = line.split(" ");
945 if (tok.length < 3) {
946 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
947 return false;
948 }
949
San Mehatb1043402010-02-05 08:26:50 -0800950 int code;
951 try {
952 code = Integer.parseInt(tok[0]);
953 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700954 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800955 return false;
956 }
957 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700958 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800959 } else {
San Mehata5078592010-03-25 09:36:54 -0700960 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800961 return false;
962 }
963 }
San Mehata5078592010-03-25 09:36:54 -0700964 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800965 return false;
966 }
967
San Mehat207e5382010-02-04 20:46:54 -0800968 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800969 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700970 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800971 return;
972 }
973
974 synchronized (mListeners) {
975 for (int i = mListeners.size() -1; i >= 0; i--) {
976 MountServiceBinderListener bl = mListeners.get(i);
977 try {
San Mehatb1043402010-02-05 08:26:50 -0800978 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800979 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700980 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800981 mListeners.remove(i);
982 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700983 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800984 }
985 }
986 }
987
San Mehat207e5382010-02-04 20:46:54 -0800988 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800989 sendUmsIntent(avail);
990 } else {
991 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800992 }
San Mehat2fe718a2010-03-11 12:01:49 -0800993
994 final String path = Environment.getExternalStorageDirectory().getPath();
995 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
996 /*
997 * USB mass storage disconnected while enabled
998 */
999 new Thread() {
1000 public void run() {
1001 try {
1002 int rc;
San Mehata5078592010-03-25 09:36:54 -07001003 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001004 doShareUnshareVolume(path, "ums", false);
1005 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001006 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001007 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1008 path, rc));
1009 }
1010 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001011 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001012 }
1013 }
1014 }.start();
1015 }
San Mehat4270e1e2010-01-29 05:32:19 -08001016 }
1017
San Mehat6a965af22010-02-24 17:47:30 -08001018 private void sendUmsIntent(boolean c) {
1019 mContext.sendBroadcast(
1020 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1021 }
1022
San Mehat207e5382010-02-04 20:46:54 -08001023 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001024 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1025 throw new SecurityException(String.format("Requires %s permission", perm));
1026 }
1027 }
1028
1029 /**
San Mehat207e5382010-02-04 20:46:54 -08001030 * Constructs a new MountService instance
1031 *
1032 * @param context Binder context for this service
1033 */
1034 public MountService(Context context) {
1035 mContext = context;
1036
San Mehat207e5382010-02-04 20:46:54 -08001037 // XXX: This will go away soon in favor of IMountServiceObserver
1038 mPms = (PackageManagerService) ServiceManager.getService("package");
1039
1040 mContext.registerReceiver(mBroadcastReceiver,
1041 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1042
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001043 mHandlerThread = new HandlerThread("MountService");
1044 mHandlerThread.start();
1045 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1046
Kenny Roota02b8b02010-08-05 16:14:17 -07001047 // Add OBB Action Handler to MountService thread.
1048 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1049
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001050 /*
1051 * Vold does not run in the simulator, so pretend the connector thread
1052 * ran and did its thing.
1053 */
1054 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1055 mReady = true;
1056 mUmsEnabling = true;
1057 return;
1058 }
1059
Kenny Root305bcbf2010-09-03 07:56:38 -07001060 /*
1061 * Create the connection to vold with a maximum queue of twice the
1062 * amount of containers we'd ever expect to have. This keeps an
1063 * "asec list" from blocking a thread repeatedly.
1064 */
1065 mConnector = new NativeDaemonConnector(this, "vold",
1066 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001067 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001068 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001069 thread.start();
1070 }
1071
1072 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001073 * Exposed API calls below here
1074 */
1075
1076 public void registerListener(IMountServiceListener listener) {
1077 synchronized (mListeners) {
1078 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1079 try {
1080 listener.asBinder().linkToDeath(bl, 0);
1081 mListeners.add(bl);
1082 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001083 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001084 }
1085 }
1086 }
1087
1088 public void unregisterListener(IMountServiceListener listener) {
1089 synchronized (mListeners) {
1090 for(MountServiceBinderListener bl : mListeners) {
1091 if (bl.mListener == listener) {
1092 mListeners.remove(mListeners.indexOf(bl));
1093 return;
1094 }
1095 }
1096 }
1097 }
1098
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001099 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001100 validatePermission(android.Manifest.permission.SHUTDOWN);
1101
San Mehata5078592010-03-25 09:36:54 -07001102 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001103
1104 String path = Environment.getExternalStorageDirectory().getPath();
1105 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001106
1107 if (state.equals(Environment.MEDIA_SHARED)) {
1108 /*
1109 * If the media is currently shared, unshare it.
1110 * XXX: This is still dangerous!. We should not
1111 * be rebooting at *all* if UMS is enabled, since
1112 * the UMS host could have dirty FAT cache entries
1113 * yet to flush.
1114 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001115 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001116 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1117 /*
1118 * If the media is being checked, then we need to wait for
1119 * it to complete before being able to proceed.
1120 */
1121 // XXX: @hackbod - Should we disable the ANR timer here?
1122 int retries = 30;
1123 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1124 try {
1125 Thread.sleep(1000);
1126 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001127 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001128 break;
1129 }
1130 state = Environment.getExternalStorageState();
1131 }
1132 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001133 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001134 }
1135 }
1136
1137 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001138 // Post a unmount message.
1139 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1140 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001141 }
1142 }
1143
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001144 private boolean getUmsEnabling() {
1145 synchronized (mListeners) {
1146 return mUmsEnabling;
1147 }
1148 }
1149
1150 private void setUmsEnabling(boolean enable) {
1151 synchronized (mListeners) {
1152 mUmsEnabling = true;
1153 }
1154 }
1155
San Mehatb1043402010-02-05 08:26:50 -08001156 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001157 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001158
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001159 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001160 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001161 }
San Mehatb1043402010-02-05 08:26:50 -08001162 return doGetShareMethodAvailable("ums");
1163 }
1164
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001165 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001166 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001167 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001168
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001169 // TODO: Add support for multiple share methods
1170
1171 /*
1172 * If the volume is mounted and we're enabling then unmount it
1173 */
1174 String path = Environment.getExternalStorageDirectory().getPath();
1175 String vs = getVolumeState(path);
1176 String method = "ums";
1177 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1178 // Override for isUsbMassStorageEnabled()
1179 setUmsEnabling(enable);
1180 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1181 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1182 // Clear override
1183 setUmsEnabling(false);
1184 }
1185 /*
1186 * If we disabled UMS then mount the volume
1187 */
1188 if (!enable) {
1189 doShareUnshareVolume(path, method, enable);
1190 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001191 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001192 " after disabling share method " + method);
1193 /*
1194 * Even though the mount failed, the unshare didn't so don't indicate an error.
1195 * The mountVolume() call will have set the storage state and sent the necessary
1196 * broadcasts.
1197 */
1198 }
1199 }
San Mehatb1043402010-02-05 08:26:50 -08001200 }
1201
1202 public boolean isUsbMassStorageEnabled() {
1203 waitForReady();
1204 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
San Mehat4270e1e2010-01-29 05:32:19 -08001206
San Mehat7fd0fee2009-12-17 07:12:23 -08001207 /**
1208 * @return state of the volume at the specified mount point
1209 */
San Mehat4270e1e2010-01-29 05:32:19 -08001210 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001211 /*
1212 * XXX: Until we have multiple volume discovery, just hardwire
1213 * this to /sdcard
1214 */
1215 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001216 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001217 throw new IllegalArgumentException();
1218 }
1219
1220 return mLegacyState;
1221 }
1222
San Mehat4270e1e2010-01-29 05:32:19 -08001223 public int mountVolume(String path) {
1224 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001225
San Mehat207e5382010-02-04 20:46:54 -08001226 waitForReady();
1227 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
1229
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001230 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001231 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001232 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001234 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001235 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001236 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1237 Environment.MEDIA_REMOVED.equals(volState) ||
1238 Environment.MEDIA_SHARED.equals(volState) ||
1239 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1240 // Media already unmounted or cannot be unmounted.
1241 // TODO return valid return code when adding observer call back.
1242 return;
1243 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001244 UnmountCallBack ucb = new UnmountCallBack(path, force);
1245 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 }
1247
San Mehat4270e1e2010-01-29 05:32:19 -08001248 public int formatVolume(String path) {
1249 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001250 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001251
San Mehat207e5382010-02-04 20:46:54 -08001252 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
1254
San Mehatc1b4ce92010-02-16 17:13:03 -08001255 public int []getStorageUsers(String path) {
1256 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1257 waitForReady();
1258 try {
1259 String[] r = mConnector.doListCommand(
1260 String.format("storage users %s", path),
1261 VoldResponseCode.StorageUsersListResult);
1262 // FMT: <pid> <process name>
1263 int[] data = new int[r.length];
1264 for (int i = 0; i < r.length; i++) {
1265 String []tok = r[i].split(" ");
1266 try {
1267 data[i] = Integer.parseInt(tok[0]);
1268 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001269 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001270 return new int[0];
1271 }
1272 }
1273 return data;
1274 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001275 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001276 return new int[0];
1277 }
1278 }
1279
San Mehatb1043402010-02-05 08:26:50 -08001280 private void warnOnNotMounted() {
1281 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001282 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001283 }
1284 }
1285
San Mehat4270e1e2010-01-29 05:32:19 -08001286 public String[] getSecureContainerList() {
1287 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001288 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001289 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001290
San Mehat4270e1e2010-01-29 05:32:19 -08001291 try {
1292 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1293 } catch (NativeDaemonConnectorException e) {
1294 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
1296 }
San Mehat36972292010-01-06 11:06:32 -08001297
San Mehat4270e1e2010-01-29 05:32:19 -08001298 public int createSecureContainer(String id, int sizeMb, String fstype,
1299 String key, int ownerUid) {
1300 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001301 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001302 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001303
San Mehatb1043402010-02-05 08:26:50 -08001304 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001305 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1306 try {
1307 mConnector.doCommand(cmd);
1308 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001309 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001310 }
San Mehata181b212010-02-11 06:50:20 -08001311
1312 if (rc == StorageResultCode.OperationSucceeded) {
1313 synchronized (mAsecMountSet) {
1314 mAsecMountSet.add(id);
1315 }
1316 }
San Mehat4270e1e2010-01-29 05:32:19 -08001317 return rc;
San Mehat36972292010-01-06 11:06:32 -08001318 }
1319
San Mehat4270e1e2010-01-29 05:32:19 -08001320 public int finalizeSecureContainer(String id) {
1321 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001322 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001323
San Mehatb1043402010-02-05 08:26:50 -08001324 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001325 try {
1326 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001327 /*
1328 * Finalization does a remount, so no need
1329 * to update mAsecMountSet
1330 */
San Mehat4270e1e2010-01-29 05:32:19 -08001331 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001332 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001333 }
San Mehat4270e1e2010-01-29 05:32:19 -08001334 return rc;
San Mehat36972292010-01-06 11:06:32 -08001335 }
1336
San Mehatd9709982010-02-18 11:43:03 -08001337 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001338 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001339 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001340 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001341
Kenny Rootaa485402010-09-14 14:49:41 -07001342 /*
1343 * Force a GC to make sure AssetManagers in other threads of the
1344 * system_server are cleaned up. We have to do this since AssetManager
1345 * instances are kept as a WeakReference and it's possible we have files
1346 * open on the external storage.
1347 */
1348 Runtime.getRuntime().gc();
1349
San Mehatb1043402010-02-05 08:26:50 -08001350 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001351 try {
San Mehatd9709982010-02-18 11:43:03 -08001352 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001353 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001354 int code = e.getCode();
1355 if (code == VoldResponseCode.OpFailedStorageBusy) {
1356 rc = StorageResultCode.OperationFailedStorageBusy;
1357 } else {
1358 rc = StorageResultCode.OperationFailedInternalError;
1359 }
San Mehat02735bc2010-01-26 15:18:08 -08001360 }
San Mehata181b212010-02-11 06:50:20 -08001361
1362 if (rc == StorageResultCode.OperationSucceeded) {
1363 synchronized (mAsecMountSet) {
1364 if (mAsecMountSet.contains(id)) {
1365 mAsecMountSet.remove(id);
1366 }
1367 }
1368 }
1369
San Mehat4270e1e2010-01-29 05:32:19 -08001370 return rc;
San Mehat36972292010-01-06 11:06:32 -08001371 }
1372
San Mehat4270e1e2010-01-29 05:32:19 -08001373 public int mountSecureContainer(String id, String key, int ownerUid) {
1374 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001375 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001376 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001377
San Mehata181b212010-02-11 06:50:20 -08001378 synchronized (mAsecMountSet) {
1379 if (mAsecMountSet.contains(id)) {
1380 return StorageResultCode.OperationFailedStorageMounted;
1381 }
1382 }
1383
San Mehatb1043402010-02-05 08:26:50 -08001384 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001385 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1386 try {
1387 mConnector.doCommand(cmd);
1388 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001389 int code = e.getCode();
1390 if (code != VoldResponseCode.OpFailedStorageBusy) {
1391 rc = StorageResultCode.OperationFailedInternalError;
1392 }
San Mehat02735bc2010-01-26 15:18:08 -08001393 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001394
1395 if (rc == StorageResultCode.OperationSucceeded) {
1396 synchronized (mAsecMountSet) {
1397 mAsecMountSet.add(id);
1398 }
1399 }
San Mehat4270e1e2010-01-29 05:32:19 -08001400 return rc;
San Mehat36972292010-01-06 11:06:32 -08001401 }
1402
San Mehatd9709982010-02-18 11:43:03 -08001403 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001404 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001405 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001406 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001407
San Mehat6cdd9c02010-02-09 14:45:20 -08001408 synchronized (mAsecMountSet) {
1409 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001410 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001411 }
1412 }
1413
Kenny Rootaa485402010-09-14 14:49:41 -07001414 /*
1415 * Force a GC to make sure AssetManagers in other threads of the
1416 * system_server are cleaned up. We have to do this since AssetManager
1417 * instances are kept as a WeakReference and it's possible we have files
1418 * open on the external storage.
1419 */
1420 Runtime.getRuntime().gc();
1421
San Mehatb1043402010-02-05 08:26:50 -08001422 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001423 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001424 try {
1425 mConnector.doCommand(cmd);
1426 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001427 int code = e.getCode();
1428 if (code == VoldResponseCode.OpFailedStorageBusy) {
1429 rc = StorageResultCode.OperationFailedStorageBusy;
1430 } else {
1431 rc = StorageResultCode.OperationFailedInternalError;
1432 }
San Mehat02735bc2010-01-26 15:18:08 -08001433 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001434
1435 if (rc == StorageResultCode.OperationSucceeded) {
1436 synchronized (mAsecMountSet) {
1437 mAsecMountSet.remove(id);
1438 }
1439 }
San Mehat4270e1e2010-01-29 05:32:19 -08001440 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001441 }
1442
San Mehat6cdd9c02010-02-09 14:45:20 -08001443 public boolean isSecureContainerMounted(String id) {
1444 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1445 waitForReady();
1446 warnOnNotMounted();
1447
1448 synchronized (mAsecMountSet) {
1449 return mAsecMountSet.contains(id);
1450 }
1451 }
1452
San Mehat4270e1e2010-01-29 05:32:19 -08001453 public int renameSecureContainer(String oldId, String newId) {
1454 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001455 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001456 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001457
San Mehata181b212010-02-11 06:50:20 -08001458 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001459 /*
1460 * Because a mounted container has active internal state which cannot be
1461 * changed while active, we must ensure both ids are not currently mounted.
1462 */
1463 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001464 return StorageResultCode.OperationFailedStorageMounted;
1465 }
1466 }
1467
San Mehatb1043402010-02-05 08:26:50 -08001468 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001469 String cmd = String.format("asec rename %s %s", oldId, newId);
1470 try {
1471 mConnector.doCommand(cmd);
1472 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001473 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001474 }
San Mehata181b212010-02-11 06:50:20 -08001475
San Mehat4270e1e2010-01-29 05:32:19 -08001476 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001477 }
1478
San Mehat4270e1e2010-01-29 05:32:19 -08001479 public String getSecureContainerPath(String id) {
1480 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001481 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001482 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001483
San Mehat2d66cef2010-03-23 11:12:52 -07001484 try {
1485 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1486 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001487 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001488 if (code != VoldResponseCode.AsecPathResult) {
1489 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1490 }
1491 return tok[1];
1492 } catch (NativeDaemonConnectorException e) {
1493 int code = e.getCode();
1494 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1495 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001496 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001497 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001498 }
1499 }
San Mehat22dd86e2010-01-12 12:21:18 -08001500 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001501
1502 public void finishMediaUpdate() {
1503 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1504 }
Kenny Root02c87302010-07-01 08:10:18 -07001505
Kenny Roota02b8b02010-08-05 16:14:17 -07001506 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1507 if (callerUid == android.os.Process.SYSTEM_UID) {
1508 return true;
1509 }
1510
Kenny Root02c87302010-07-01 08:10:18 -07001511 if (packageName == null) {
1512 return false;
1513 }
1514
1515 final int packageUid = mPms.getPackageUid(packageName);
1516
1517 if (DEBUG_OBB) {
1518 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1519 packageUid + ", callerUid = " + callerUid);
1520 }
1521
1522 return callerUid == packageUid;
1523 }
1524
1525 public String getMountedObbPath(String filename) {
1526 waitForReady();
1527 warnOnNotMounted();
1528
Kenny Root02c87302010-07-01 08:10:18 -07001529 try {
1530 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1531 String []tok = rsp.get(0).split(" ");
1532 int code = Integer.parseInt(tok[0]);
1533 if (code != VoldResponseCode.AsecPathResult) {
1534 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1535 }
1536 return tok[1];
1537 } catch (NativeDaemonConnectorException e) {
1538 int code = e.getCode();
1539 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001540 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001541 } else {
1542 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1543 }
1544 }
1545 }
1546
1547 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001548 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001549 final ObbState obbState = mObbPathToStateMap.get(filename);
1550 if (obbState != null) {
1551 synchronized (obbState) {
1552 return obbState.mounted;
1553 }
1554 }
Kenny Root02c87302010-07-01 08:10:18 -07001555 }
Kenny Root38cf8862010-09-26 14:18:51 -07001556 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001557 }
1558
Kenny Roota02b8b02010-08-05 16:14:17 -07001559 public void mountObb(String filename, String key, IObbActionListener token) {
Kenny Root02c87302010-07-01 08:10:18 -07001560 waitForReady();
1561 warnOnNotMounted();
1562
Kenny Rootf1121dc2010-09-29 07:30:53 -07001563 if (filename == null) {
1564 throw new IllegalArgumentException("filename cannot be null");
1565 } else if (token == null) {
1566 throw new IllegalArgumentException("token cannot be null");
1567 }
1568
Kenny Roota02b8b02010-08-05 16:14:17 -07001569 final ObbState obbState;
1570
1571 synchronized (mObbMounts) {
1572 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001573 try {
1574 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1575 } catch (RemoteException e) {
1576 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1577 }
1578 return;
Kenny Root02c87302010-07-01 08:10:18 -07001579 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001580
Kenny Roota02b8b02010-08-05 16:14:17 -07001581 final int callerUid = Binder.getCallingUid();
Kenny Root27358a62010-09-29 19:27:20 -07001582
1583 final Integer uidUsage = mObbUidUsage.get(callerUid);
1584 if (uidUsage != null && uidUsage > MAX_OBBS) {
1585 throw new IllegalStateException("Maximum number of OBBs mounted!");
1586 }
1587
Kenny Roota02b8b02010-08-05 16:14:17 -07001588 obbState = new ObbState(filename, token, callerUid);
1589 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001590 }
1591
Kenny Root02c87302010-07-01 08:10:18 -07001592 try {
Kenny Roota02b8b02010-08-05 16:14:17 -07001593 token.asBinder().linkToDeath(obbState, 0);
1594 } catch (RemoteException rex) {
1595 Slog.e(TAG, "Failed to link to listener death");
Kenny Root02c87302010-07-01 08:10:18 -07001596 }
1597
Kenny Root38cf8862010-09-26 14:18:51 -07001598 ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001599 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1600
1601 if (DEBUG_OBB)
1602 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001603 }
1604
Kenny Roota02b8b02010-08-05 16:14:17 -07001605 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001606 if (filename == null) {
1607 throw new IllegalArgumentException("filename cannot be null");
1608 } else if (token == null) {
1609 throw new IllegalArgumentException("token cannot be null");
1610 }
1611
Kenny Roota02b8b02010-08-05 16:14:17 -07001612 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001613
Kenny Roota02b8b02010-08-05 16:14:17 -07001614 synchronized (mObbMounts) {
1615 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001616 try {
1617 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1618 } catch (RemoteException e) {
1619 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1620 }
1621 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001622 }
Kenny Root38cf8862010-09-26 14:18:51 -07001623
Kenny Roota02b8b02010-08-05 16:14:17 -07001624 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001625
1626 if (Binder.getCallingUid() != obbState.callerUid) {
1627 throw new SecurityException("caller UID does not match original mount caller UID");
1628 } else if (!token.asBinder().equals(obbState.token.asBinder())) {
1629 throw new SecurityException("caller does not match original mount caller");
1630 }
Kenny Root02c87302010-07-01 08:10:18 -07001631 }
1632
Kenny Root38cf8862010-09-26 14:18:51 -07001633 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001634 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001635
Kenny Roota02b8b02010-08-05 16:14:17 -07001636 if (DEBUG_OBB)
1637 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1638 }
1639
1640 private void addObbState(ObbState obbState) {
1641 synchronized (mObbMounts) {
Kenny Root05105f72010-09-22 17:29:43 -07001642 List<ObbState> obbStates = mObbMounts.get(obbState.token);
1643 if (obbStates == null) {
1644 obbStates = new ArrayList<ObbState>();
1645 mObbMounts.put(obbState.token, obbStates);
1646 }
1647 obbStates.add(obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001648 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Root27358a62010-09-29 19:27:20 -07001649
1650 // Track the number of OBBs used by this UID.
1651 final int uid = obbState.callerUid;
1652 final Integer uidUsage = mObbUidUsage.get(uid);
1653 if (uidUsage == null) {
1654 mObbUidUsage.put(uid, 1);
1655 } else {
1656 mObbUidUsage.put(uid, uidUsage + 1);
1657 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001658 }
1659 }
1660
1661 private void removeObbState(ObbState obbState) {
1662 synchronized (mObbMounts) {
Kenny Root05105f72010-09-22 17:29:43 -07001663 final List<ObbState> obbStates = mObbMounts.get(obbState.token);
1664 if (obbStates != null) {
1665 obbStates.remove(obbState);
1666 }
1667 if (obbStates == null || obbStates.isEmpty()) {
1668 mObbMounts.remove(obbState.token);
1669 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001670 mObbPathToStateMap.remove(obbState.filename);
Kenny Root27358a62010-09-29 19:27:20 -07001671
1672 // Track the number of OBBs used by this UID.
1673 final int uid = obbState.callerUid;
1674 final Integer uidUsage = mObbUidUsage.get(uid);
1675 if (uidUsage == null) {
1676 Slog.e(TAG, "Called removeObbState for UID that isn't in map: " + uid);
1677 } else {
1678 final int newUsage = uidUsage - 1;
1679 if (newUsage == 0) {
1680 mObbUidUsage.remove(uid);
1681 } else {
1682 mObbUidUsage.put(uid, newUsage);
1683 }
1684 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001685 }
1686 }
1687
Kenny Root38cf8862010-09-26 14:18:51 -07001688 private void replaceObbState(ObbState oldObbState, ObbState newObbState) {
1689 synchronized (mObbMounts) {
1690 removeObbState(oldObbState);
1691 addObbState(newObbState);
1692 }
1693 }
1694
Kenny Roota02b8b02010-08-05 16:14:17 -07001695 private class ObbActionHandler extends Handler {
1696 private boolean mBound = false;
1697 private List<ObbAction> mActions = new LinkedList<ObbAction>();
1698
1699 ObbActionHandler(Looper l) {
1700 super(l);
1701 }
1702
1703 @Override
1704 public void handleMessage(Message msg) {
1705 switch (msg.what) {
1706 case OBB_RUN_ACTION: {
1707 ObbAction action = (ObbAction) msg.obj;
1708
1709 if (DEBUG_OBB)
1710 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1711
1712 // If a bind was already initiated we don't really
1713 // need to do anything. The pending install
1714 // will be processed later on.
1715 if (!mBound) {
1716 // If this is the only one pending we might
1717 // have to bind to the service again.
1718 if (!connectToService()) {
1719 Slog.e(TAG, "Failed to bind to media container service");
1720 action.handleError();
1721 return;
1722 } else {
1723 // Once we bind to the service, the first
1724 // pending request will be processed.
1725 mActions.add(action);
1726 }
1727 } else {
1728 // Already bound to the service. Just make
1729 // sure we trigger off processing the first request.
1730 if (mActions.size() == 0) {
1731 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1732 }
1733
1734 mActions.add(action);
1735 }
1736 break;
1737 }
1738 case OBB_MCS_BOUND: {
1739 if (DEBUG_OBB)
1740 Slog.i(TAG, "OBB_MCS_BOUND");
1741 if (msg.obj != null) {
1742 mContainerService = (IMediaContainerService) msg.obj;
1743 }
1744 if (mContainerService == null) {
1745 // Something seriously wrong. Bail out
1746 Slog.e(TAG, "Cannot bind to media container service");
1747 for (ObbAction action : mActions) {
1748 // Indicate service bind error
1749 action.handleError();
1750 }
1751 mActions.clear();
1752 } else if (mActions.size() > 0) {
1753 ObbAction action = mActions.get(0);
1754 if (action != null) {
1755 action.execute(this);
1756 }
1757 } else {
1758 // Should never happen ideally.
1759 Slog.w(TAG, "Empty queue");
1760 }
1761 break;
1762 }
1763 case OBB_MCS_RECONNECT: {
1764 if (DEBUG_OBB)
1765 Slog.i(TAG, "OBB_MCS_RECONNECT");
1766 if (mActions.size() > 0) {
1767 if (mBound) {
1768 disconnectService();
1769 }
1770 if (!connectToService()) {
1771 Slog.e(TAG, "Failed to bind to media container service");
1772 for (ObbAction action : mActions) {
1773 // Indicate service bind error
1774 action.handleError();
1775 }
1776 mActions.clear();
1777 }
1778 }
1779 break;
1780 }
1781 case OBB_MCS_UNBIND: {
1782 if (DEBUG_OBB)
1783 Slog.i(TAG, "OBB_MCS_UNBIND");
1784
1785 // Delete pending install
1786 if (mActions.size() > 0) {
1787 mActions.remove(0);
1788 }
1789 if (mActions.size() == 0) {
1790 if (mBound) {
1791 disconnectService();
1792 }
1793 } else {
1794 // There are more pending requests in queue.
1795 // Just post MCS_BOUND message to trigger processing
1796 // of next pending install.
1797 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1798 }
1799 break;
1800 }
1801 case OBB_MCS_GIVE_UP: {
1802 if (DEBUG_OBB)
1803 Slog.i(TAG, "OBB_MCS_GIVE_UP");
1804 mActions.remove(0);
1805 break;
1806 }
1807 }
1808 }
1809
1810 private boolean connectToService() {
1811 if (DEBUG_OBB)
1812 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1813
1814 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1815 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1816 mBound = true;
1817 return true;
1818 }
1819 return false;
1820 }
1821
1822 private void disconnectService() {
1823 mContainerService = null;
1824 mBound = false;
1825 mContext.unbindService(mDefContainerConn);
1826 }
1827 }
1828
1829 abstract class ObbAction {
1830 private static final int MAX_RETRIES = 3;
1831 private int mRetries;
1832
1833 ObbState mObbState;
1834
1835 ObbAction(ObbState obbState) {
1836 mObbState = obbState;
1837 }
1838
1839 public void execute(ObbActionHandler handler) {
1840 try {
1841 if (DEBUG_OBB)
1842 Slog.i(TAG, "Starting to execute action: " + this.toString());
1843 mRetries++;
1844 if (mRetries > MAX_RETRIES) {
1845 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
1846 mObbActionHandler.sendEmptyMessage(OBB_MCS_GIVE_UP);
1847 handleError();
1848 return;
1849 } else {
1850 handleExecute();
1851 if (DEBUG_OBB)
1852 Slog.i(TAG, "Posting install MCS_UNBIND");
1853 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1854 }
1855 } catch (RemoteException e) {
1856 if (DEBUG_OBB)
1857 Slog.i(TAG, "Posting install MCS_RECONNECT");
1858 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1859 } catch (Exception e) {
1860 if (DEBUG_OBB)
1861 Slog.d(TAG, "Error handling OBB action", e);
1862 handleError();
1863 }
1864 }
1865
Kenny Root05105f72010-09-22 17:29:43 -07001866 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001867 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001868
1869 protected ObbInfo getObbInfo() throws IOException {
1870 ObbInfo obbInfo;
1871 try {
1872 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1873 } catch (RemoteException e) {
1874 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1875 + mObbState.filename);
1876 obbInfo = null;
1877 }
1878 if (obbInfo == null) {
1879 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1880 }
1881 return obbInfo;
1882 }
1883
1884 protected void sendNewStatusOrIgnore(String filename, String status) {
1885 try {
1886 mObbState.token.onObbResult(filename, status);
1887 } catch (RemoteException e) {
1888 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1889 }
1890 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001891 }
1892
1893 class MountObbAction extends ObbAction {
1894 private String mKey;
1895
1896 MountObbAction(ObbState obbState, String key) {
1897 super(obbState);
1898 mKey = key;
1899 }
1900
Kenny Root38cf8862010-09-26 14:18:51 -07001901 public void handleExecute() throws IOException {
1902 final ObbInfo obbInfo = getObbInfo();
1903
1904 /*
1905 * If someone tried to trick us with some weird characters, rectify
1906 * it here.
1907 */
1908 if (!mObbState.filename.equals(obbInfo.filename)) {
1909 if (DEBUG_OBB)
1910 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1911 + obbInfo.filename);
1912
1913 synchronized (mObbMounts) {
1914 /*
1915 * If the real filename is already mounted, discard this
1916 * state and notify the caller that the OBB is already
1917 * mounted.
1918 */
1919 if (isObbMounted(obbInfo.filename)) {
1920 if (DEBUG_OBB)
1921 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1922
1923 removeObbState(mObbState);
1924 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1925 return;
1926 }
1927
1928 /*
1929 * It's not already mounted, so we have to replace the state
1930 * with the state containing the actual filename.
1931 */
1932 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1933 mObbState.callerUid);
1934 replaceObbState(mObbState, newObbState);
1935 mObbState = newObbState;
1936 }
Kenny Root05105f72010-09-22 17:29:43 -07001937 }
1938
Kenny Roota02b8b02010-08-05 16:14:17 -07001939 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1940 throw new IllegalArgumentException("Caller package does not match OBB file");
1941 }
1942
1943 if (mKey == null) {
1944 mKey = "none";
1945 }
1946
Kenny Root38cf8862010-09-26 14:18:51 -07001947 boolean mounted = false;
1948 int rc;
1949 synchronized (mObbState) {
1950 if (mObbState.mounted) {
1951 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1952 return;
1953 }
1954
1955 rc = StorageResultCode.OperationSucceeded;
1956 String cmd = String.format("obb mount %s %s %d", mObbState.filename, mKey,
1957 mObbState.callerUid);
1958 try {
1959 mConnector.doCommand(cmd);
1960 } catch (NativeDaemonConnectorException e) {
1961 int code = e.getCode();
1962 if (code != VoldResponseCode.OpFailedStorageBusy) {
1963 rc = StorageResultCode.OperationFailedInternalError;
1964 }
1965 }
1966
1967 if (rc == StorageResultCode.OperationSucceeded) {
1968 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07001969 }
1970 }
1971
Kenny Root38cf8862010-09-26 14:18:51 -07001972 if (mounted) {
1973 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001974 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001975 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001976
1977 // We didn't succeed, so remove this from the mount-set.
1978 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07001979
Kenny Root38cf8862010-09-26 14:18:51 -07001980 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001981 }
1982 }
1983
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 public void handleError() {
1985 removeObbState(mObbState);
1986
Kenny Root38cf8862010-09-26 14:18:51 -07001987 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07001988 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001989
1990 @Override
1991 public String toString() {
1992 StringBuilder sb = new StringBuilder();
1993 sb.append("MountObbAction{");
1994 sb.append("filename=");
1995 sb.append(mObbState.filename);
1996 sb.append(",callerUid=");
1997 sb.append(mObbState.callerUid);
1998 sb.append(",token=");
1999 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2000 sb.append('}');
2001 return sb.toString();
2002 }
2003 }
2004
2005 class UnmountObbAction extends ObbAction {
2006 private boolean mForceUnmount;
2007
2008 UnmountObbAction(ObbState obbState, boolean force) {
2009 super(obbState);
2010 mForceUnmount = force;
2011 }
2012
Kenny Root38cf8862010-09-26 14:18:51 -07002013 public void handleExecute() throws IOException {
2014 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002015
Kenny Root38cf8862010-09-26 14:18:51 -07002016 /*
2017 * If someone tried to trick us with some weird characters, rectify
2018 * it here.
2019 */
2020 synchronized (mObbMounts) {
2021 if (!isObbMounted(obbInfo.filename)) {
2022 removeObbState(mObbState);
2023 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2024 return;
2025 }
2026
2027 if (!mObbState.filename.equals(obbInfo.filename)) {
2028 removeObbState(mObbState);
2029 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002030 }
2031 }
2032
Kenny Root38cf8862010-09-26 14:18:51 -07002033 boolean unmounted = false;
2034 synchronized (mObbState) {
2035 if (!mObbState.mounted) {
2036 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2037 return;
2038 }
2039
2040 int rc = StorageResultCode.OperationSucceeded;
2041 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2042 (mForceUnmount ? " force" : ""));
2043 try {
2044 mConnector.doCommand(cmd);
2045 } catch (NativeDaemonConnectorException e) {
2046 int code = e.getCode();
2047 if (code == VoldResponseCode.OpFailedStorageBusy) {
2048 rc = StorageResultCode.OperationFailedStorageBusy;
2049 } else {
2050 rc = StorageResultCode.OperationFailedInternalError;
2051 }
2052 }
2053
2054 if (rc == StorageResultCode.OperationSucceeded) {
2055 mObbState.mounted = false;
2056 unmounted = true;
2057 }
2058 }
2059
2060 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002061 removeObbState(mObbState);
2062
Kenny Root38cf8862010-09-26 14:18:51 -07002063 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002064 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002065 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002066 }
2067 }
2068
2069 public void handleError() {
2070 removeObbState(mObbState);
2071
Kenny Root38cf8862010-09-26 14:18:51 -07002072 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002073 }
2074
2075 @Override
2076 public String toString() {
2077 StringBuilder sb = new StringBuilder();
2078 sb.append("UnmountObbAction{");
2079 sb.append("filename=");
2080 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2081 sb.append(",force=");
2082 sb.append(mForceUnmount);
2083 sb.append(",callerUid=");
2084 sb.append(mObbState.callerUid);
2085 sb.append(",token=");
2086 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
2087 sb.append('}');
2088 return sb.toString();
2089 }
Kenny Root02c87302010-07-01 08:10:18 -07002090 }
Kenny Root38cf8862010-09-26 14:18:51 -07002091
2092 @Override
2093 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2094 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2095 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2096 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2097 + " without permission " + android.Manifest.permission.DUMP);
2098 return;
2099 }
2100
2101 pw.println(" mObbMounts:");
2102
2103 synchronized (mObbMounts) {
2104 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2105
2106 for (final List<ObbState> obbStates : obbStateLists) {
2107 for (final ObbState obbState : obbStates) {
2108 pw.print(" "); pw.println(obbState.toString());
2109 }
2110 }
2111 }
2112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113}
2114