blob: 775f5c87d6a2d487964595e94093af514c56e275 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Kenny Root735de3b2010-09-30 14:11:39 -070020import com.android.internal.util.HexDump;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070047import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.StorageResultCode;
Kenny Root735de3b2010-09-30 14:11:39 -070049import android.security.MessageDigest;
San Mehata5078592010-03-25 09:36:54 -070050import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070051
Kenny Root38cf8862010-09-26 14:18:51 -070052import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070053import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070054import java.io.PrintWriter;
Kenny Root735de3b2010-09-30 14:11:39 -070055import java.security.NoSuchAlgorithmException;
San Mehat22dd86e2010-01-12 12:21:18 -080056import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080058import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070059import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.LinkedList;
61import java.util.List;
62import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
San Mehatb1043402010-02-05 08:26:50 -080066 * MountService implements back-end services for platform storage
67 * management.
68 * @hide - Applications should use android.os.storage.StorageManager
69 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 */
San Mehat22dd86e2010-01-12 12:21:18 -080071class MountService extends IMountService.Stub
72 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080073 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080074 private static final boolean DEBUG_UNMOUNT = false;
75 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070076 private static final boolean DEBUG_OBB = true;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "MountService";
79
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String VOLD_TAG = "VoldConnector";
81
San Mehat4270e1e2010-01-29 05:32:19 -080082 /*
83 * Internal vold volume state constants
84 */
San Mehat7fd0fee2009-12-17 07:12:23 -080085 class VolumeState {
86 public static final int Init = -1;
87 public static final int NoMedia = 0;
88 public static final int Idle = 1;
89 public static final int Pending = 2;
90 public static final int Checking = 3;
91 public static final int Mounted = 4;
92 public static final int Unmounting = 5;
93 public static final int Formatting = 6;
94 public static final int Shared = 7;
95 public static final int SharedMnt = 8;
96 }
97
San Mehat4270e1e2010-01-29 05:32:19 -080098 /*
99 * Internal vold response code constants
100 */
San Mehat22dd86e2010-01-12 12:21:18 -0800101 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800102 /*
103 * 100 series - Requestion action was initiated; expect another reply
104 * before proceeding with a new command.
105 */
San Mehat22dd86e2010-01-12 12:21:18 -0800106 public static final int VolumeListResult = 110;
107 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800108 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800109
San Mehat4270e1e2010-01-29 05:32:19 -0800110 /*
111 * 200 series - Requestion action has been successfully completed.
112 */
113 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800114 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800115 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800116
San Mehat4270e1e2010-01-29 05:32:19 -0800117 /*
118 * 400 series - Command was accepted, but the requested action
119 * did not take place.
120 */
121 public static final int OpFailedNoMedia = 401;
122 public static final int OpFailedMediaBlank = 402;
123 public static final int OpFailedMediaCorrupt = 403;
124 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800125 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700126 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800127
128 /*
129 * 600 series - Unsolicited broadcasts.
130 */
San Mehat22dd86e2010-01-12 12:21:18 -0800131 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800132 public static final int ShareAvailabilityChange = 620;
133 public static final int VolumeDiskInserted = 630;
134 public static final int VolumeDiskRemoved = 631;
135 public static final int VolumeBadRemoval = 632;
136 }
137
San Mehat4270e1e2010-01-29 05:32:19 -0800138 private Context mContext;
139 private NativeDaemonConnector mConnector;
140 private String mLegacyState = Environment.MEDIA_REMOVED;
141 private PackageManagerService mPms;
142 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800143 // Used as a lock for methods that register/unregister listeners.
144 final private ArrayList<MountServiceBinderListener> mListeners =
145 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800146 private boolean mBooted = false;
147 private boolean mReady = false;
148 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800149
San Mehat6cdd9c02010-02-09 14:45:20 -0800150 /**
151 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800152 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800153 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800154 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800155
Kenny Root02c87302010-07-01 08:10:18 -0700156 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700157 * Mounted OBB tracking information. Used to track the current state of all
158 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700159 */
Kenny Root735de3b2010-09-30 14:11:39 -0700160 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, 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 {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700164 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700165 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700166 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700167 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700168 this.token = token;
169 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700170 }
171
172 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700173 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700174
175 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700176 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700177
Kenny Rootaf9d6672010-10-08 09:21:39 -0700178 // Token of remote Binder caller
179 final IObbActionListener token;
180
181 // Identifier to pass back to the token
182 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700183
Kenny Root735de3b2010-09-30 14:11:39 -0700184 public IBinder getBinder() {
185 return token.asBinder();
186 }
187
Kenny Roota02b8b02010-08-05 16:14:17 -0700188 @Override
189 public void binderDied() {
190 ObbAction action = new UnmountObbAction(this, true);
191 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700192 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700193
Kenny Root5919ac62010-10-05 09:49:40 -0700194 public void link() throws RemoteException {
195 getBinder().linkToDeath(this, 0);
196 }
197
198 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700199 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700200 }
Kenny Root38cf8862010-09-26 14:18:51 -0700201
202 @Override
203 public String toString() {
204 StringBuilder sb = new StringBuilder("ObbState{");
205 sb.append("filename=");
206 sb.append(filename);
207 sb.append(",token=");
208 sb.append(token.toString());
209 sb.append(",callerUid=");
210 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700211 sb.append('}');
212 return sb.toString();
213 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700214 }
215
216 // OBB Action Handler
217 final private ObbActionHandler mObbActionHandler;
218
219 // OBB action handler messages
220 private static final int OBB_RUN_ACTION = 1;
221 private static final int OBB_MCS_BOUND = 2;
222 private static final int OBB_MCS_UNBIND = 3;
223 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700224 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700225
226 /*
227 * Default Container Service information
228 */
229 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
230 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
231
232 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
233
234 class DefaultContainerConnection implements ServiceConnection {
235 public void onServiceConnected(ComponentName name, IBinder service) {
236 if (DEBUG_OBB)
237 Slog.i(TAG, "onServiceConnected");
238 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
239 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
240 }
241
242 public void onServiceDisconnected(ComponentName name) {
243 if (DEBUG_OBB)
244 Slog.i(TAG, "onServiceDisconnected");
245 }
246 };
247
248 // Used in the ObbActionHandler
249 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700250
251 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800252 private static final int H_UNMOUNT_PM_UPDATE = 1;
253 private static final int H_UNMOUNT_PM_DONE = 2;
254 private static final int H_UNMOUNT_MS = 3;
255 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
256 private static final int MAX_UNMOUNT_RETRIES = 4;
257
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800258 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700259 final String path;
260 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800261 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800262
263 UnmountCallBack(String path, boolean force) {
264 retries = 0;
265 this.path = path;
266 this.force = force;
267 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800268
269 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700270 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800271 doUnmountVolume(path, true);
272 }
273 }
274
275 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700276 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800277
278 UmsEnableCallBack(String path, String method, boolean force) {
279 super(path, force);
280 this.method = method;
281 }
282
283 @Override
284 void handleFinished() {
285 super.handleFinished();
286 doShareUnshareVolume(path, method, true);
287 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800288 }
289
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800290 class ShutdownCallBack extends UnmountCallBack {
291 IMountShutdownObserver observer;
292 ShutdownCallBack(String path, IMountShutdownObserver observer) {
293 super(path, true);
294 this.observer = observer;
295 }
296
297 @Override
298 void handleFinished() {
299 int ret = doUnmountVolume(path, true);
300 if (observer != null) {
301 try {
302 observer.onShutDownComplete(ret);
303 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700304 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800305 }
306 }
307 }
308 }
309
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400310 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800311 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700312 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800313
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400314 MountServiceHandler(Looper l) {
315 super(l);
316 }
317
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800318 public void handleMessage(Message msg) {
319 switch (msg.what) {
320 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700321 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800322 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
323 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700324 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800325 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700326 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700327 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700328 mUpdatingStatus = true;
329 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800330 }
331 break;
332 }
333 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700334 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700335 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700336 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800337 int size = mForceUnmounts.size();
338 int sizeArr[] = new int[size];
339 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700340 // Kill processes holding references first
341 ActivityManagerService ams = (ActivityManagerService)
342 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800343 for (int i = 0; i < size; i++) {
344 UnmountCallBack ucb = mForceUnmounts.get(i);
345 String path = ucb.path;
346 boolean done = false;
347 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800348 done = true;
349 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800350 int pids[] = getStorageUsers(path);
351 if (pids == null || pids.length == 0) {
352 done = true;
353 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800354 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700355 ams.killPids(pids, "unmount media");
356 // Confirm if file references have been freed.
357 pids = getStorageUsers(path);
358 if (pids == null || pids.length == 0) {
359 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 }
361 }
362 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700363 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
364 // Retry again
365 Slog.i(TAG, "Retrying to kill storage users again");
366 mHandler.sendMessageDelayed(
367 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
368 ucb.retries++),
369 RETRY_UNMOUNT_DELAY);
370 } else {
371 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
372 Slog.i(TAG, "Failed to unmount media inspite of " +
373 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
374 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800375 sizeArr[sizeArrN++] = i;
376 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
377 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800378 }
379 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 // Remove already processed elements from list.
381 for (int i = (sizeArrN-1); i >= 0; i--) {
382 mForceUnmounts.remove(sizeArr[i]);
383 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 break;
385 }
386 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700387 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800388 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800389 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800390 break;
391 }
392 }
393 }
394 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400395 final private HandlerThread mHandlerThread;
396 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800397
San Mehat207e5382010-02-04 20:46:54 -0800398 private void waitForReady() {
399 while (mReady == false) {
400 for (int retries = 5; retries > 0; retries--) {
401 if (mReady) {
402 return;
403 }
404 SystemClock.sleep(1000);
405 }
San Mehata5078592010-03-25 09:36:54 -0700406 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800407 }
San Mehat1f6301e2010-01-07 22:40:27 -0800408 }
Kenny Root02c87302010-07-01 08:10:18 -0700409
San Mehat207e5382010-02-04 20:46:54 -0800410 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800412 String action = intent.getAction();
413
414 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800415 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800416
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800417 /*
418 * In the simulator, we need to broadcast a volume mounted event
419 * to make the media scanner run.
420 */
421 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
422 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
423 return;
424 }
San Mehatfafb0412010-02-18 19:40:04 -0800425 new Thread() {
426 public void run() {
427 try {
428 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700429 String state = getVolumeState(path);
430
431 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800432 int rc = doMountVolume(path);
433 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700434 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800435 }
San Mehat6a254402010-03-22 10:21:00 -0700436 } else if (state.equals(Environment.MEDIA_SHARED)) {
437 /*
438 * Bootstrap UMS enabled state since vold indicates
439 * the volume is shared (runtime restart while ums enabled)
440 */
441 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800442 }
San Mehat6a254402010-03-22 10:21:00 -0700443
San Mehat6a965af22010-02-24 17:47:30 -0800444 /*
San Mehat6a254402010-03-22 10:21:00 -0700445 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800446 * now that we're up.
447 */
448 if (mSendUmsConnectedOnBoot) {
449 sendUmsIntent(true);
450 mSendUmsConnectedOnBoot = false;
451 }
San Mehatfafb0412010-02-18 19:40:04 -0800452 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700453 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800454 }
San Mehat207e5382010-02-04 20:46:54 -0800455 }
San Mehatfafb0412010-02-18 19:40:04 -0800456 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
458 }
459 };
460
San Mehat4270e1e2010-01-29 05:32:19 -0800461 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
462 final IMountServiceListener mListener;
463
464 MountServiceBinderListener(IMountServiceListener listener) {
465 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700466
San Mehat91c77612010-01-07 10:39:41 -0800467 }
468
San Mehat4270e1e2010-01-29 05:32:19 -0800469 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700470 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700471 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800472 mListeners.remove(this);
473 mListener.asBinder().unlinkToDeath(this, 0);
474 }
475 }
476 }
477
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800478 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800479 // TODO: Add support for multiple share methods
480 if (!method.equals("ums")) {
481 throw new IllegalArgumentException(String.format("Method %s not supported", method));
482 }
483
San Mehat4270e1e2010-01-29 05:32:19 -0800484 try {
485 mConnector.doCommand(String.format(
486 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
487 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700488 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800489 }
San Mehat4270e1e2010-01-29 05:32:19 -0800490 }
491
San Mehat207e5382010-02-04 20:46:54 -0800492 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800493 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700494 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800495 return;
496 }
San Mehatb1043402010-02-05 08:26:50 -0800497
498 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700499 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800500 return;
501 }
Kenny Rootaf9d6672010-10-08 09:21:39 -0700502
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800503 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700504 // Tell the package manager the media is gone.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700505 mPms.updateExternalMediaStatus(false, false);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700506
507 /*
508 * Some OBBs might have been unmounted when this volume was
509 * unmounted, so send a message to the handler to let it know to
510 * remove those from the list of mounted OBBS.
511 */
512 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_FLUSH_MOUNT_STATE,
513 path));
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800514 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700515 // Tell the package manager the media is available for use.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700516 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800517 }
Kenny Root38cf8862010-09-26 14:18:51 -0700518
San Mehat4270e1e2010-01-29 05:32:19 -0800519 String oldState = mLegacyState;
520 mLegacyState = state;
521
522 synchronized (mListeners) {
523 for (int i = mListeners.size() -1; i >= 0; i--) {
524 MountServiceBinderListener bl = mListeners.get(i);
525 try {
San Mehatb1043402010-02-05 08:26:50 -0800526 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800527 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700528 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800529 mListeners.remove(i);
530 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700531 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800532 }
533 }
534 }
535 }
536
537 /**
538 *
539 * Callback from NativeDaemonConnector
540 */
541 public void onDaemonConnected() {
542 /*
543 * Since we'll be calling back into the NativeDaemonConnector,
544 * we need to do our work in a new thread.
545 */
546 new Thread() {
547 public void run() {
548 /**
549 * Determine media state and UMS detection status
550 */
551 String path = Environment.getExternalStorageDirectory().getPath();
552 String state = Environment.MEDIA_REMOVED;
553
554 try {
555 String[] vols = mConnector.doListCommand(
556 "volume list", VoldResponseCode.VolumeListResult);
557 for (String volstr : vols) {
558 String[] tok = volstr.split(" ");
559 // FMT: <label> <mountpoint> <state>
560 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700561 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800562 "Skipping unknown volume '%s'",tok[1]));
563 continue;
564 }
565 int st = Integer.parseInt(tok[2]);
566 if (st == VolumeState.NoMedia) {
567 state = Environment.MEDIA_REMOVED;
568 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800569 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800570 } else if (st == VolumeState.Mounted) {
571 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700572 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800573 } else if (st == VolumeState.Shared) {
574 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700575 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800576 } else {
577 throw new Exception(String.format("Unexpected state %d", st));
578 }
579 }
580 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700581 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800582 updatePublicVolumeState(path, state);
583 }
584 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700585 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800586 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
587 }
588
589 try {
San Mehat207e5382010-02-04 20:46:54 -0800590 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800591 notifyShareAvailabilityChange("ums", avail);
592 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700593 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800594 }
San Mehat207e5382010-02-04 20:46:54 -0800595 /*
596 * Now that we've done our initialization, release
597 * the hounds!
598 */
599 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800600 }
601 }.start();
602 }
603
604 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800605 * Callback from NativeDaemonConnector
606 */
607 public boolean onEvent(int code, String raw, String[] cooked) {
608 Intent in = null;
609
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800610 if (DEBUG_EVENTS) {
611 StringBuilder builder = new StringBuilder();
612 builder.append("onEvent::");
613 builder.append(" raw= " + raw);
614 if (cooked != null) {
615 builder.append(" cooked = " );
616 for (String str : cooked) {
617 builder.append(" " + str);
618 }
619 }
San Mehata5078592010-03-25 09:36:54 -0700620 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800621 }
San Mehat4270e1e2010-01-29 05:32:19 -0800622 if (code == VoldResponseCode.VolumeStateChange) {
623 /*
624 * One of the volumes we're managing has changed state.
625 * Format: "NNN Volume <label> <path> state changed
626 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
627 */
628 notifyVolumeStateChange(
629 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
630 Integer.parseInt(cooked[10]));
631 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
632 // FMT: NNN Share method <method> now <available|unavailable>
633 boolean avail = false;
634 if (cooked[5].equals("available")) {
635 avail = true;
636 }
637 notifyShareAvailabilityChange(cooked[3], avail);
638 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
639 (code == VoldResponseCode.VolumeDiskRemoved) ||
640 (code == VoldResponseCode.VolumeBadRemoval)) {
641 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
642 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
643 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
644 final String label = cooked[2];
645 final String path = cooked[3];
646 int major = -1;
647 int minor = -1;
648
649 try {
650 String devComp = cooked[6].substring(1, cooked[6].length() -1);
651 String[] devTok = devComp.split(":");
652 major = Integer.parseInt(devTok[0]);
653 minor = Integer.parseInt(devTok[1]);
654 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700655 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800656 }
657
San Mehat4270e1e2010-01-29 05:32:19 -0800658 if (code == VoldResponseCode.VolumeDiskInserted) {
659 new Thread() {
660 public void run() {
661 try {
662 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800663 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700664 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800665 }
666 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700667 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800668 }
669 }
670 }.start();
671 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
672 /*
673 * This event gets trumped if we're already in BAD_REMOVAL state
674 */
675 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
676 return true;
677 }
678 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700679 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800680 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
681 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
682 mContext.sendBroadcast(in);
683
San Mehata5078592010-03-25 09:36:54 -0700684 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800685 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
686 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
687 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700688 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800689 /* Send the media unmounted event first */
690 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
691 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
692 mContext.sendBroadcast(in);
693
San Mehata5078592010-03-25 09:36:54 -0700694 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800695 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
696 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
697 } else {
San Mehata5078592010-03-25 09:36:54 -0700698 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800699 }
700 } else {
701 return false;
702 }
703
704 if (in != null) {
705 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400706 }
707 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800708 }
709
San Mehat207e5382010-02-04 20:46:54 -0800710 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800711 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700712 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800713
714 Intent in = null;
715
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500716 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700717 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500718 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
719 Uri.parse("file://" + path)));
720 }
721
San Mehat4270e1e2010-01-29 05:32:19 -0800722 if (newState == VolumeState.Init) {
723 } else if (newState == VolumeState.NoMedia) {
724 // NoMedia is handled via Disk Remove events
725 } else if (newState == VolumeState.Idle) {
726 /*
727 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
728 * if we're in the process of enabling UMS
729 */
730 if (!vs.equals(
731 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
732 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800733 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700734 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800735 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
736 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
737 }
738 } else if (newState == VolumeState.Pending) {
739 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700740 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800741 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
742 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
743 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700744 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800745 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800746 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
747 in.putExtra("read-only", false);
748 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800749 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
750 } else if (newState == VolumeState.Formatting) {
751 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700752 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800753 /* Send the media unmounted event first */
754 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
755 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
756 mContext.sendBroadcast(in);
757
San Mehata5078592010-03-25 09:36:54 -0700758 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800759 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
760 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700761 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800762 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700763 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800764 return;
765 } else {
San Mehata5078592010-03-25 09:36:54 -0700766 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800767 }
768
769 if (in != null) {
770 mContext.sendBroadcast(in);
771 }
772 }
773
San Mehat207e5382010-02-04 20:46:54 -0800774 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700775 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700776 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700777 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700778 } catch (NativeDaemonConnectorException ex) {
779 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
780 return false;
781 }
San Mehat207e5382010-02-04 20:46:54 -0800782
783 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700784 String[] tok = line.split(" ");
785 if (tok.length < 3) {
786 Slog.e(TAG, "Malformed response to share status " + method);
787 return false;
788 }
789
San Mehat207e5382010-02-04 20:46:54 -0800790 int code;
791 try {
792 code = Integer.parseInt(tok[0]);
793 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700794 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800795 return false;
796 }
797 if (code == VoldResponseCode.ShareStatusResult) {
798 if (tok[2].equals("available"))
799 return true;
800 return false;
801 } else {
San Mehata5078592010-03-25 09:36:54 -0700802 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800803 return false;
804 }
805 }
San Mehata5078592010-03-25 09:36:54 -0700806 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800807 return false;
808 }
809
810 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800811 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800812
San Mehata5078592010-03-25 09:36:54 -0700813 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800814 try {
815 mConnector.doCommand(String.format("volume mount %s", path));
816 } catch (NativeDaemonConnectorException e) {
817 /*
818 * Mount failed for some reason
819 */
820 Intent in = null;
821 int code = e.getCode();
822 if (code == VoldResponseCode.OpFailedNoMedia) {
823 /*
824 * Attempt to mount but no media inserted
825 */
San Mehatb1043402010-02-05 08:26:50 -0800826 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800827 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700828 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800829 /*
830 * Media is blank or does not contain a supported filesystem
831 */
832 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
833 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800834 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800835 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700836 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800837 /*
838 * Volume consistency check failed
839 */
840 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
841 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800842 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800843 } else {
San Mehatb1043402010-02-05 08:26:50 -0800844 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800845 }
846
847 /*
848 * Send broadcast intent (if required for the failure)
849 */
850 if (in != null) {
851 mContext.sendBroadcast(in);
852 }
853 }
854
855 return rc;
856 }
857
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800858 /*
859 * If force is not set, we do not unmount if there are
860 * processes holding references to the volume about to be unmounted.
861 * If force is set, all the processes holding references need to be
862 * killed via the ActivityManager before actually unmounting the volume.
863 * This might even take a while and might be retried after timed delays
864 * to make sure we dont end up in an instable state and kill some core
865 * processes.
866 */
San Mehatd9709982010-02-18 11:43:03 -0800867 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800868 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800869 return VoldResponseCode.OpFailedVolNotMounted;
870 }
Kenny Rootaa485402010-09-14 14:49:41 -0700871
872 /*
873 * Force a GC to make sure AssetManagers in other threads of the
874 * system_server are cleaned up. We have to do this since AssetManager
875 * instances are kept as a WeakReference and it's possible we have files
876 * open on the external storage.
877 */
878 Runtime.getRuntime().gc();
879
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800880 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700881 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800882 try {
San Mehatd9709982010-02-18 11:43:03 -0800883 mConnector.doCommand(String.format(
884 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700885 // We unmounted the volume. None of the asec containers are available now.
886 synchronized (mAsecMountSet) {
887 mAsecMountSet.clear();
888 }
San Mehatb1043402010-02-05 08:26:50 -0800889 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800890 } catch (NativeDaemonConnectorException e) {
891 // Don't worry about mismatch in PackageManager since the
892 // call back will handle the status changes any way.
893 int code = e.getCode();
894 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800895 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800896 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
897 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800898 } else {
San Mehatb1043402010-02-05 08:26:50 -0800899 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800900 }
901 }
902 }
903
904 private int doFormatVolume(String path) {
905 try {
906 String cmd = String.format("volume format %s", path);
907 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800908 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800909 } catch (NativeDaemonConnectorException e) {
910 int code = e.getCode();
911 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800912 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800913 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800914 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800915 } else {
San Mehatb1043402010-02-05 08:26:50 -0800916 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800917 }
918 }
919 }
920
San Mehatb1043402010-02-05 08:26:50 -0800921 private boolean doGetVolumeShared(String path, String method) {
922 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700923 ArrayList<String> rsp;
924
925 try {
926 rsp = mConnector.doCommand(cmd);
927 } catch (NativeDaemonConnectorException ex) {
928 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
929 return false;
930 }
San Mehatb1043402010-02-05 08:26:50 -0800931
932 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700933 String[] tok = line.split(" ");
934 if (tok.length < 3) {
935 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
936 return false;
937 }
938
San Mehatb1043402010-02-05 08:26:50 -0800939 int code;
940 try {
941 code = Integer.parseInt(tok[0]);
942 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700943 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800944 return false;
945 }
946 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700947 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800948 } else {
San Mehata5078592010-03-25 09:36:54 -0700949 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800950 return false;
951 }
952 }
San Mehata5078592010-03-25 09:36:54 -0700953 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800954 return false;
955 }
956
San Mehat207e5382010-02-04 20:46:54 -0800957 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800958 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700959 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800960 return;
961 }
962
963 synchronized (mListeners) {
964 for (int i = mListeners.size() -1; i >= 0; i--) {
965 MountServiceBinderListener bl = mListeners.get(i);
966 try {
San Mehatb1043402010-02-05 08:26:50 -0800967 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800968 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800970 mListeners.remove(i);
971 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700972 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800973 }
974 }
975 }
976
San Mehat207e5382010-02-04 20:46:54 -0800977 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -0800978 sendUmsIntent(avail);
979 } else {
980 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -0800981 }
San Mehat2fe718a2010-03-11 12:01:49 -0800982
983 final String path = Environment.getExternalStorageDirectory().getPath();
984 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
985 /*
986 * USB mass storage disconnected while enabled
987 */
988 new Thread() {
989 public void run() {
990 try {
991 int rc;
San Mehata5078592010-03-25 09:36:54 -0700992 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -0800993 doShareUnshareVolume(path, "ums", false);
994 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700995 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -0800996 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
997 path, rc));
998 }
999 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001000 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001001 }
1002 }
1003 }.start();
1004 }
San Mehat4270e1e2010-01-29 05:32:19 -08001005 }
1006
San Mehat6a965af22010-02-24 17:47:30 -08001007 private void sendUmsIntent(boolean c) {
1008 mContext.sendBroadcast(
1009 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1010 }
1011
San Mehat207e5382010-02-04 20:46:54 -08001012 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001013 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1014 throw new SecurityException(String.format("Requires %s permission", perm));
1015 }
1016 }
1017
1018 /**
San Mehat207e5382010-02-04 20:46:54 -08001019 * Constructs a new MountService instance
1020 *
1021 * @param context Binder context for this service
1022 */
1023 public MountService(Context context) {
1024 mContext = context;
1025
San Mehat207e5382010-02-04 20:46:54 -08001026 // XXX: This will go away soon in favor of IMountServiceObserver
1027 mPms = (PackageManagerService) ServiceManager.getService("package");
1028
1029 mContext.registerReceiver(mBroadcastReceiver,
1030 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1031
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001032 mHandlerThread = new HandlerThread("MountService");
1033 mHandlerThread.start();
1034 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1035
Kenny Roota02b8b02010-08-05 16:14:17 -07001036 // Add OBB Action Handler to MountService thread.
1037 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1038
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001039 /*
1040 * Vold does not run in the simulator, so pretend the connector thread
1041 * ran and did its thing.
1042 */
1043 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1044 mReady = true;
1045 mUmsEnabling = true;
1046 return;
1047 }
1048
Kenny Root305bcbf2010-09-03 07:56:38 -07001049 /*
1050 * Create the connection to vold with a maximum queue of twice the
1051 * amount of containers we'd ever expect to have. This keeps an
1052 * "asec list" from blocking a thread repeatedly.
1053 */
1054 mConnector = new NativeDaemonConnector(this, "vold",
1055 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001056 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001057 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001058 thread.start();
1059 }
1060
1061 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001062 * Exposed API calls below here
1063 */
1064
1065 public void registerListener(IMountServiceListener listener) {
1066 synchronized (mListeners) {
1067 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1068 try {
1069 listener.asBinder().linkToDeath(bl, 0);
1070 mListeners.add(bl);
1071 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001072 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001073 }
1074 }
1075 }
1076
1077 public void unregisterListener(IMountServiceListener listener) {
1078 synchronized (mListeners) {
1079 for(MountServiceBinderListener bl : mListeners) {
1080 if (bl.mListener == listener) {
1081 mListeners.remove(mListeners.indexOf(bl));
1082 return;
1083 }
1084 }
1085 }
1086 }
1087
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001088 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001089 validatePermission(android.Manifest.permission.SHUTDOWN);
1090
San Mehata5078592010-03-25 09:36:54 -07001091 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001092
1093 String path = Environment.getExternalStorageDirectory().getPath();
1094 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001095
1096 if (state.equals(Environment.MEDIA_SHARED)) {
1097 /*
1098 * If the media is currently shared, unshare it.
1099 * XXX: This is still dangerous!. We should not
1100 * be rebooting at *all* if UMS is enabled, since
1101 * the UMS host could have dirty FAT cache entries
1102 * yet to flush.
1103 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001104 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001105 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1106 /*
1107 * If the media is being checked, then we need to wait for
1108 * it to complete before being able to proceed.
1109 */
1110 // XXX: @hackbod - Should we disable the ANR timer here?
1111 int retries = 30;
1112 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1113 try {
1114 Thread.sleep(1000);
1115 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001116 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001117 break;
1118 }
1119 state = Environment.getExternalStorageState();
1120 }
1121 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001122 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001123 }
1124 }
1125
1126 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001127 // Post a unmount message.
1128 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1129 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001130 }
1131 }
1132
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001133 private boolean getUmsEnabling() {
1134 synchronized (mListeners) {
1135 return mUmsEnabling;
1136 }
1137 }
1138
1139 private void setUmsEnabling(boolean enable) {
1140 synchronized (mListeners) {
1141 mUmsEnabling = true;
1142 }
1143 }
1144
San Mehatb1043402010-02-05 08:26:50 -08001145 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001146 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001147
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001148 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001149 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001150 }
San Mehatb1043402010-02-05 08:26:50 -08001151 return doGetShareMethodAvailable("ums");
1152 }
1153
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001154 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001155 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001156 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001157
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001158 // TODO: Add support for multiple share methods
1159
1160 /*
1161 * If the volume is mounted and we're enabling then unmount it
1162 */
1163 String path = Environment.getExternalStorageDirectory().getPath();
1164 String vs = getVolumeState(path);
1165 String method = "ums";
1166 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1167 // Override for isUsbMassStorageEnabled()
1168 setUmsEnabling(enable);
1169 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1170 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1171 // Clear override
1172 setUmsEnabling(false);
1173 }
1174 /*
1175 * If we disabled UMS then mount the volume
1176 */
1177 if (!enable) {
1178 doShareUnshareVolume(path, method, enable);
1179 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001180 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001181 " after disabling share method " + method);
1182 /*
1183 * Even though the mount failed, the unshare didn't so don't indicate an error.
1184 * The mountVolume() call will have set the storage state and sent the necessary
1185 * broadcasts.
1186 */
1187 }
1188 }
San Mehatb1043402010-02-05 08:26:50 -08001189 }
1190
1191 public boolean isUsbMassStorageEnabled() {
1192 waitForReady();
1193 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
San Mehat4270e1e2010-01-29 05:32:19 -08001195
San Mehat7fd0fee2009-12-17 07:12:23 -08001196 /**
1197 * @return state of the volume at the specified mount point
1198 */
San Mehat4270e1e2010-01-29 05:32:19 -08001199 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001200 /*
1201 * XXX: Until we have multiple volume discovery, just hardwire
1202 * this to /sdcard
1203 */
1204 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001205 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001206 throw new IllegalArgumentException();
1207 }
1208
1209 return mLegacyState;
1210 }
1211
San Mehat4270e1e2010-01-29 05:32:19 -08001212 public int mountVolume(String path) {
1213 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001214
San Mehat207e5382010-02-04 20:46:54 -08001215 waitForReady();
1216 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001219 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001220 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001221 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001223 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001224 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001225 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1226 Environment.MEDIA_REMOVED.equals(volState) ||
1227 Environment.MEDIA_SHARED.equals(volState) ||
1228 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1229 // Media already unmounted or cannot be unmounted.
1230 // TODO return valid return code when adding observer call back.
1231 return;
1232 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001233 UnmountCallBack ucb = new UnmountCallBack(path, force);
1234 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236
San Mehat4270e1e2010-01-29 05:32:19 -08001237 public int formatVolume(String path) {
1238 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001239 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001240
San Mehat207e5382010-02-04 20:46:54 -08001241 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
1243
San Mehatc1b4ce92010-02-16 17:13:03 -08001244 public int []getStorageUsers(String path) {
1245 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1246 waitForReady();
1247 try {
1248 String[] r = mConnector.doListCommand(
1249 String.format("storage users %s", path),
1250 VoldResponseCode.StorageUsersListResult);
1251 // FMT: <pid> <process name>
1252 int[] data = new int[r.length];
1253 for (int i = 0; i < r.length; i++) {
1254 String []tok = r[i].split(" ");
1255 try {
1256 data[i] = Integer.parseInt(tok[0]);
1257 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001258 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001259 return new int[0];
1260 }
1261 }
1262 return data;
1263 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001264 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001265 return new int[0];
1266 }
1267 }
1268
San Mehatb1043402010-02-05 08:26:50 -08001269 private void warnOnNotMounted() {
1270 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001271 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001272 }
1273 }
1274
San Mehat4270e1e2010-01-29 05:32:19 -08001275 public String[] getSecureContainerList() {
1276 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001277 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001278 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001279
San Mehat4270e1e2010-01-29 05:32:19 -08001280 try {
1281 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1282 } catch (NativeDaemonConnectorException e) {
1283 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285 }
San Mehat36972292010-01-06 11:06:32 -08001286
San Mehat4270e1e2010-01-29 05:32:19 -08001287 public int createSecureContainer(String id, int sizeMb, String fstype,
1288 String key, int ownerUid) {
1289 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001290 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001291 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001292
San Mehatb1043402010-02-05 08:26:50 -08001293 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001294 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1295 try {
1296 mConnector.doCommand(cmd);
1297 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001298 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001299 }
San Mehata181b212010-02-11 06:50:20 -08001300
1301 if (rc == StorageResultCode.OperationSucceeded) {
1302 synchronized (mAsecMountSet) {
1303 mAsecMountSet.add(id);
1304 }
1305 }
San Mehat4270e1e2010-01-29 05:32:19 -08001306 return rc;
San Mehat36972292010-01-06 11:06:32 -08001307 }
1308
San Mehat4270e1e2010-01-29 05:32:19 -08001309 public int finalizeSecureContainer(String id) {
1310 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001311 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001312
San Mehatb1043402010-02-05 08:26:50 -08001313 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001314 try {
1315 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001316 /*
1317 * Finalization does a remount, so no need
1318 * to update mAsecMountSet
1319 */
San Mehat4270e1e2010-01-29 05:32:19 -08001320 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001321 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001322 }
San Mehat4270e1e2010-01-29 05:32:19 -08001323 return rc;
San Mehat36972292010-01-06 11:06:32 -08001324 }
1325
San Mehatd9709982010-02-18 11:43:03 -08001326 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001327 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001328 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001329 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001330
Kenny Rootaa485402010-09-14 14:49:41 -07001331 /*
1332 * Force a GC to make sure AssetManagers in other threads of the
1333 * system_server are cleaned up. We have to do this since AssetManager
1334 * instances are kept as a WeakReference and it's possible we have files
1335 * open on the external storage.
1336 */
1337 Runtime.getRuntime().gc();
1338
San Mehatb1043402010-02-05 08:26:50 -08001339 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001340 try {
San Mehatd9709982010-02-18 11:43:03 -08001341 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001342 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001343 int code = e.getCode();
1344 if (code == VoldResponseCode.OpFailedStorageBusy) {
1345 rc = StorageResultCode.OperationFailedStorageBusy;
1346 } else {
1347 rc = StorageResultCode.OperationFailedInternalError;
1348 }
San Mehat02735bc2010-01-26 15:18:08 -08001349 }
San Mehata181b212010-02-11 06:50:20 -08001350
1351 if (rc == StorageResultCode.OperationSucceeded) {
1352 synchronized (mAsecMountSet) {
1353 if (mAsecMountSet.contains(id)) {
1354 mAsecMountSet.remove(id);
1355 }
1356 }
1357 }
1358
San Mehat4270e1e2010-01-29 05:32:19 -08001359 return rc;
San Mehat36972292010-01-06 11:06:32 -08001360 }
1361
San Mehat4270e1e2010-01-29 05:32:19 -08001362 public int mountSecureContainer(String id, String key, int ownerUid) {
1363 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001364 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001365 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001366
San Mehata181b212010-02-11 06:50:20 -08001367 synchronized (mAsecMountSet) {
1368 if (mAsecMountSet.contains(id)) {
1369 return StorageResultCode.OperationFailedStorageMounted;
1370 }
1371 }
1372
San Mehatb1043402010-02-05 08:26:50 -08001373 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001374 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1375 try {
1376 mConnector.doCommand(cmd);
1377 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001378 int code = e.getCode();
1379 if (code != VoldResponseCode.OpFailedStorageBusy) {
1380 rc = StorageResultCode.OperationFailedInternalError;
1381 }
San Mehat02735bc2010-01-26 15:18:08 -08001382 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001383
1384 if (rc == StorageResultCode.OperationSucceeded) {
1385 synchronized (mAsecMountSet) {
1386 mAsecMountSet.add(id);
1387 }
1388 }
San Mehat4270e1e2010-01-29 05:32:19 -08001389 return rc;
San Mehat36972292010-01-06 11:06:32 -08001390 }
1391
San Mehatd9709982010-02-18 11:43:03 -08001392 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001393 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001394 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001395 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001396
San Mehat6cdd9c02010-02-09 14:45:20 -08001397 synchronized (mAsecMountSet) {
1398 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001399 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001400 }
1401 }
1402
Kenny Rootaa485402010-09-14 14:49:41 -07001403 /*
1404 * Force a GC to make sure AssetManagers in other threads of the
1405 * system_server are cleaned up. We have to do this since AssetManager
1406 * instances are kept as a WeakReference and it's possible we have files
1407 * open on the external storage.
1408 */
1409 Runtime.getRuntime().gc();
1410
San Mehatb1043402010-02-05 08:26:50 -08001411 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001412 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001413 try {
1414 mConnector.doCommand(cmd);
1415 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001416 int code = e.getCode();
1417 if (code == VoldResponseCode.OpFailedStorageBusy) {
1418 rc = StorageResultCode.OperationFailedStorageBusy;
1419 } else {
1420 rc = StorageResultCode.OperationFailedInternalError;
1421 }
San Mehat02735bc2010-01-26 15:18:08 -08001422 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001423
1424 if (rc == StorageResultCode.OperationSucceeded) {
1425 synchronized (mAsecMountSet) {
1426 mAsecMountSet.remove(id);
1427 }
1428 }
San Mehat4270e1e2010-01-29 05:32:19 -08001429 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001430 }
1431
San Mehat6cdd9c02010-02-09 14:45:20 -08001432 public boolean isSecureContainerMounted(String id) {
1433 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1434 waitForReady();
1435 warnOnNotMounted();
1436
1437 synchronized (mAsecMountSet) {
1438 return mAsecMountSet.contains(id);
1439 }
1440 }
1441
San Mehat4270e1e2010-01-29 05:32:19 -08001442 public int renameSecureContainer(String oldId, String newId) {
1443 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001444 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001445 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001446
San Mehata181b212010-02-11 06:50:20 -08001447 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001448 /*
1449 * Because a mounted container has active internal state which cannot be
1450 * changed while active, we must ensure both ids are not currently mounted.
1451 */
1452 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001453 return StorageResultCode.OperationFailedStorageMounted;
1454 }
1455 }
1456
San Mehatb1043402010-02-05 08:26:50 -08001457 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001458 String cmd = String.format("asec rename %s %s", oldId, newId);
1459 try {
1460 mConnector.doCommand(cmd);
1461 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001462 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001463 }
San Mehata181b212010-02-11 06:50:20 -08001464
San Mehat4270e1e2010-01-29 05:32:19 -08001465 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001466 }
1467
San Mehat4270e1e2010-01-29 05:32:19 -08001468 public String getSecureContainerPath(String id) {
1469 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001470 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001471 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001472
San Mehat2d66cef2010-03-23 11:12:52 -07001473 try {
1474 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1475 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001476 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001477 if (code != VoldResponseCode.AsecPathResult) {
1478 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1479 }
1480 return tok[1];
1481 } catch (NativeDaemonConnectorException e) {
1482 int code = e.getCode();
1483 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1484 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001485 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001486 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001487 }
1488 }
San Mehat22dd86e2010-01-12 12:21:18 -08001489 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001490
1491 public void finishMediaUpdate() {
1492 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1493 }
Kenny Root02c87302010-07-01 08:10:18 -07001494
Kenny Roota02b8b02010-08-05 16:14:17 -07001495 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1496 if (callerUid == android.os.Process.SYSTEM_UID) {
1497 return true;
1498 }
1499
Kenny Root02c87302010-07-01 08:10:18 -07001500 if (packageName == null) {
1501 return false;
1502 }
1503
1504 final int packageUid = mPms.getPackageUid(packageName);
1505
1506 if (DEBUG_OBB) {
1507 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1508 packageUid + ", callerUid = " + callerUid);
1509 }
1510
1511 return callerUid == packageUid;
1512 }
1513
1514 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001515 if (filename == null) {
1516 throw new IllegalArgumentException("filename cannot be null");
1517 }
1518
Kenny Root02c87302010-07-01 08:10:18 -07001519 waitForReady();
1520 warnOnNotMounted();
1521
Kenny Root02c87302010-07-01 08:10:18 -07001522 try {
1523 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1524 String []tok = rsp.get(0).split(" ");
1525 int code = Integer.parseInt(tok[0]);
1526 if (code != VoldResponseCode.AsecPathResult) {
1527 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1528 }
1529 return tok[1];
1530 } catch (NativeDaemonConnectorException e) {
1531 int code = e.getCode();
1532 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001533 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001534 } else {
1535 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1536 }
1537 }
1538 }
1539
1540 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001541 if (filename == null) {
1542 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001543 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001544
1545 synchronized (mObbMounts) {
1546 return mObbPathToStateMap.containsKey(filename);
1547 }
Kenny Root02c87302010-07-01 08:10:18 -07001548 }
1549
Kenny Rootaf9d6672010-10-08 09:21:39 -07001550 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001551 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001552 if (filename == null) {
1553 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001554 }
1555
1556 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001557 throw new IllegalArgumentException("token cannot be null");
1558 }
1559
Kenny Rootaf9d6672010-10-08 09:21:39 -07001560 final int callerUid = Binder.getCallingUid();
1561 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1562 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001563 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1564
1565 if (DEBUG_OBB)
1566 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001567 }
1568
Kenny Rootaf9d6672010-10-08 09:21:39 -07001569 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1570 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001571 if (filename == null) {
1572 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001573 }
1574
Kenny Rootaf9d6672010-10-08 09:21:39 -07001575 final int callerUid = Binder.getCallingUid();
1576 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1577 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001578 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001579
Kenny Roota02b8b02010-08-05 16:14:17 -07001580 if (DEBUG_OBB)
1581 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1582 }
1583
Kenny Rootaf9d6672010-10-08 09:21:39 -07001584 private void addObbStateLocked(ObbState obbState) throws RemoteException {
1585 final IBinder binder = obbState.getBinder();
1586 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07001587
Kenny Rootaf9d6672010-10-08 09:21:39 -07001588 if (obbStates == null) {
1589 obbStates = new ArrayList<ObbState>();
1590 mObbMounts.put(binder, obbStates);
1591 } else {
1592 for (final ObbState o : obbStates) {
1593 if (o.filename.equals(obbState.filename)) {
1594 throw new IllegalStateException("Attempt to add ObbState twice. "
1595 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07001596 }
1597 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001598 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001599
1600 obbStates.add(obbState);
1601 try {
1602 obbState.link();
1603 } catch (RemoteException e) {
1604 /*
1605 * The binder died before we could link it, so clean up our state
1606 * and return failure.
1607 */
1608 obbStates.remove(obbState);
1609 if (obbStates.isEmpty()) {
1610 mObbMounts.remove(binder);
1611 }
1612
1613 // Rethrow the error so mountObb can get it
1614 throw e;
1615 }
1616
1617 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07001618 }
1619
Kenny Rootaf9d6672010-10-08 09:21:39 -07001620 private void removeObbStateLocked(ObbState obbState) {
1621 final IBinder binder = obbState.getBinder();
1622 final List<ObbState> obbStates = mObbMounts.get(binder);
1623 if (obbStates != null) {
1624 if (obbStates.remove(obbState)) {
1625 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07001626 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001627 if (obbStates.isEmpty()) {
1628 mObbMounts.remove(binder);
1629 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001630 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001631
Kenny Rootaf9d6672010-10-08 09:21:39 -07001632 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07001633 }
1634
Kenny Roota02b8b02010-08-05 16:14:17 -07001635 private class ObbActionHandler extends Handler {
1636 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07001637 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07001638
1639 ObbActionHandler(Looper l) {
1640 super(l);
1641 }
1642
1643 @Override
1644 public void handleMessage(Message msg) {
1645 switch (msg.what) {
1646 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07001647 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07001648
1649 if (DEBUG_OBB)
1650 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1651
1652 // If a bind was already initiated we don't really
1653 // need to do anything. The pending install
1654 // will be processed later on.
1655 if (!mBound) {
1656 // If this is the only one pending we might
1657 // have to bind to the service again.
1658 if (!connectToService()) {
1659 Slog.e(TAG, "Failed to bind to media container service");
1660 action.handleError();
1661 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001662 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001663 }
Kenny Root735de3b2010-09-30 14:11:39 -07001664
Kenny Root735de3b2010-09-30 14:11:39 -07001665 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001666 break;
1667 }
1668 case OBB_MCS_BOUND: {
1669 if (DEBUG_OBB)
1670 Slog.i(TAG, "OBB_MCS_BOUND");
1671 if (msg.obj != null) {
1672 mContainerService = (IMediaContainerService) msg.obj;
1673 }
1674 if (mContainerService == null) {
1675 // Something seriously wrong. Bail out
1676 Slog.e(TAG, "Cannot bind to media container service");
1677 for (ObbAction action : mActions) {
1678 // Indicate service bind error
1679 action.handleError();
1680 }
1681 mActions.clear();
1682 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07001683 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07001684 if (action != null) {
1685 action.execute(this);
1686 }
1687 } else {
1688 // Should never happen ideally.
1689 Slog.w(TAG, "Empty queue");
1690 }
1691 break;
1692 }
1693 case OBB_MCS_RECONNECT: {
1694 if (DEBUG_OBB)
1695 Slog.i(TAG, "OBB_MCS_RECONNECT");
1696 if (mActions.size() > 0) {
1697 if (mBound) {
1698 disconnectService();
1699 }
1700 if (!connectToService()) {
1701 Slog.e(TAG, "Failed to bind to media container service");
1702 for (ObbAction action : mActions) {
1703 // Indicate service bind error
1704 action.handleError();
1705 }
1706 mActions.clear();
1707 }
1708 }
1709 break;
1710 }
1711 case OBB_MCS_UNBIND: {
1712 if (DEBUG_OBB)
1713 Slog.i(TAG, "OBB_MCS_UNBIND");
1714
1715 // Delete pending install
1716 if (mActions.size() > 0) {
1717 mActions.remove(0);
1718 }
1719 if (mActions.size() == 0) {
1720 if (mBound) {
1721 disconnectService();
1722 }
1723 } else {
1724 // There are more pending requests in queue.
1725 // Just post MCS_BOUND message to trigger processing
1726 // of next pending install.
1727 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1728 }
1729 break;
1730 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001731 case OBB_FLUSH_MOUNT_STATE: {
1732 final String path = (String) msg.obj;
1733
1734 if (DEBUG_OBB)
1735 Slog.i(TAG, "Flushing all OBB state for path " + path);
1736
1737 synchronized (mObbMounts) {
1738 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
1739
1740 final Iterator<Entry<String, ObbState>> i =
1741 mObbPathToStateMap.entrySet().iterator();
1742 while (i.hasNext()) {
1743 final Entry<String, ObbState> obbEntry = i.next();
1744
1745 /*
1746 * If this entry's source file is in the volume path
1747 * that got unmounted, remove it because it's no
1748 * longer valid.
1749 */
1750 if (obbEntry.getKey().startsWith(path)) {
1751 obbStatesToRemove.add(obbEntry.getValue());
1752 }
1753 }
1754
1755 for (final ObbState obbState : obbStatesToRemove) {
1756 if (DEBUG_OBB)
1757 Slog.i(TAG, "Removing state for " + obbState.filename);
1758
1759 removeObbStateLocked(obbState);
1760
1761 try {
1762 obbState.token.onObbResult(obbState.filename, obbState.nonce,
1763 OnObbStateChangeListener.UNMOUNTED);
1764 } catch (RemoteException e) {
1765 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
1766 + obbState.filename);
1767 }
1768 }
1769 }
1770 break;
1771 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001772 }
1773 }
1774
1775 private boolean connectToService() {
1776 if (DEBUG_OBB)
1777 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1778
1779 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1780 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1781 mBound = true;
1782 return true;
1783 }
1784 return false;
1785 }
1786
1787 private void disconnectService() {
1788 mContainerService = null;
1789 mBound = false;
1790 mContext.unbindService(mDefContainerConn);
1791 }
1792 }
1793
1794 abstract class ObbAction {
1795 private static final int MAX_RETRIES = 3;
1796 private int mRetries;
1797
1798 ObbState mObbState;
1799
1800 ObbAction(ObbState obbState) {
1801 mObbState = obbState;
1802 }
1803
1804 public void execute(ObbActionHandler handler) {
1805 try {
1806 if (DEBUG_OBB)
1807 Slog.i(TAG, "Starting to execute action: " + this.toString());
1808 mRetries++;
1809 if (mRetries > MAX_RETRIES) {
1810 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07001811 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001812 handleError();
1813 return;
1814 } else {
1815 handleExecute();
1816 if (DEBUG_OBB)
1817 Slog.i(TAG, "Posting install MCS_UNBIND");
1818 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1819 }
1820 } catch (RemoteException e) {
1821 if (DEBUG_OBB)
1822 Slog.i(TAG, "Posting install MCS_RECONNECT");
1823 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1824 } catch (Exception e) {
1825 if (DEBUG_OBB)
1826 Slog.d(TAG, "Error handling OBB action", e);
1827 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001828 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001829 }
1830 }
1831
Kenny Root05105f72010-09-22 17:29:43 -07001832 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001833 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001834
1835 protected ObbInfo getObbInfo() throws IOException {
1836 ObbInfo obbInfo;
1837 try {
1838 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1839 } catch (RemoteException e) {
1840 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1841 + mObbState.filename);
1842 obbInfo = null;
1843 }
1844 if (obbInfo == null) {
1845 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1846 }
1847 return obbInfo;
1848 }
1849
Kenny Rootaf9d6672010-10-08 09:21:39 -07001850 protected void sendNewStatusOrIgnore(int status) {
1851 if (mObbState == null || mObbState.token == null) {
1852 return;
1853 }
1854
Kenny Root38cf8862010-09-26 14:18:51 -07001855 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001856 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07001857 } catch (RemoteException e) {
1858 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1859 }
1860 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001861 }
1862
1863 class MountObbAction extends ObbAction {
1864 private String mKey;
1865
1866 MountObbAction(ObbState obbState, String key) {
1867 super(obbState);
1868 mKey = key;
1869 }
1870
Kenny Root735de3b2010-09-30 14:11:39 -07001871 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001872 waitForReady();
1873 warnOnNotMounted();
1874
Kenny Root38cf8862010-09-26 14:18:51 -07001875 final ObbInfo obbInfo = getObbInfo();
1876
Kenny Roota02b8b02010-08-05 16:14:17 -07001877 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001878 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
1879 + " which is owned by " + obbInfo.packageName);
1880 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
1881 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001882 }
1883
Kenny Rootaf9d6672010-10-08 09:21:39 -07001884 final boolean isMounted;
1885 synchronized (mObbMounts) {
1886 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
1887 }
1888 if (isMounted) {
1889 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
1890 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
1891 return;
1892 }
1893
1894 /*
1895 * The filename passed in might not be the canonical name, so just
1896 * set the filename to the canonicalized version.
1897 */
1898 mObbState.filename = obbInfo.filename;
1899
1900 final String hashedKey;
1901 if (mKey == null) {
1902 hashedKey = "none";
1903 } else {
1904 final MessageDigest md;
1905 try {
1906 md = MessageDigest.getInstance("MD5");
1907 } catch (NoSuchAlgorithmException e) {
1908 Slog.e(TAG, "Could not load MD5 algorithm", e);
1909 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
Kenny Root38cf8862010-09-26 14:18:51 -07001910 return;
1911 }
1912
Kenny Rootaf9d6672010-10-08 09:21:39 -07001913 hashedKey = HexDump.toHexString(md.digest(mKey.getBytes()));
1914 }
Kenny Root38cf8862010-09-26 14:18:51 -07001915
Kenny Rootaf9d6672010-10-08 09:21:39 -07001916 int rc = StorageResultCode.OperationSucceeded;
1917 String cmd = String.format("obb mount %s %s %d", mObbState.filename, hashedKey,
1918 mObbState.callerUid);
1919 try {
1920 mConnector.doCommand(cmd);
1921 } catch (NativeDaemonConnectorException e) {
1922 int code = e.getCode();
1923 if (code != VoldResponseCode.OpFailedStorageBusy) {
1924 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07001925 }
1926 }
1927
Kenny Rootaf9d6672010-10-08 09:21:39 -07001928 if (rc == StorageResultCode.OperationSucceeded) {
1929 if (DEBUG_OBB)
1930 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
1931
1932 synchronized (mObbMounts) {
1933 addObbStateLocked(mObbState);
1934 }
1935
1936 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07001937 } else {
Kenny Root05105f72010-09-22 17:29:43 -07001938 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07001939
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07001941 }
1942 }
1943
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001945 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07001946 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001947
1948 @Override
1949 public String toString() {
1950 StringBuilder sb = new StringBuilder();
1951 sb.append("MountObbAction{");
1952 sb.append("filename=");
1953 sb.append(mObbState.filename);
1954 sb.append(",callerUid=");
1955 sb.append(mObbState.callerUid);
1956 sb.append(",token=");
1957 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001958 sb.append(",binder=");
1959 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07001960 sb.append('}');
1961 return sb.toString();
1962 }
1963 }
1964
1965 class UnmountObbAction extends ObbAction {
1966 private boolean mForceUnmount;
1967
1968 UnmountObbAction(ObbState obbState, boolean force) {
1969 super(obbState);
1970 mForceUnmount = force;
1971 }
1972
Kenny Root38cf8862010-09-26 14:18:51 -07001973 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001974 waitForReady();
1975 warnOnNotMounted();
1976
Kenny Root38cf8862010-09-26 14:18:51 -07001977 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07001978
Kenny Rootaf9d6672010-10-08 09:21:39 -07001979 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07001980 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001981 obbState = mObbPathToStateMap.get(obbInfo.filename);
1982 }
Kenny Root38cf8862010-09-26 14:18:51 -07001983
Kenny Rootaf9d6672010-10-08 09:21:39 -07001984 if (obbState == null) {
1985 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
1986 return;
1987 }
1988
1989 if (obbState.callerUid != mObbState.callerUid) {
1990 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
1991 + " (owned by " + obbInfo.packageName + ")");
1992 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
1993 return;
1994 }
1995
1996 mObbState.filename = obbInfo.filename;
1997
1998 int rc = StorageResultCode.OperationSucceeded;
1999 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2000 (mForceUnmount ? " force" : ""));
2001 try {
2002 mConnector.doCommand(cmd);
2003 } catch (NativeDaemonConnectorException e) {
2004 int code = e.getCode();
2005 if (code == VoldResponseCode.OpFailedStorageBusy) {
2006 rc = StorageResultCode.OperationFailedStorageBusy;
2007 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2008 // If it's not mounted then we've already won.
2009 rc = StorageResultCode.OperationSucceeded;
2010 } else {
2011 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002012 }
2013 }
2014
Kenny Rootaf9d6672010-10-08 09:21:39 -07002015 if (rc == StorageResultCode.OperationSucceeded) {
2016 synchronized (mObbMounts) {
2017 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002018 }
2019
Kenny Rootaf9d6672010-10-08 09:21:39 -07002020 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002021 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002022 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2023 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002024 }
2025 }
2026
2027 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002028 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002029 }
2030
2031 @Override
2032 public String toString() {
2033 StringBuilder sb = new StringBuilder();
2034 sb.append("UnmountObbAction{");
2035 sb.append("filename=");
2036 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2037 sb.append(",force=");
2038 sb.append(mForceUnmount);
2039 sb.append(",callerUid=");
2040 sb.append(mObbState.callerUid);
2041 sb.append(",token=");
2042 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002043 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002044 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002045 sb.append('}');
2046 return sb.toString();
2047 }
Kenny Root02c87302010-07-01 08:10:18 -07002048 }
Kenny Root38cf8862010-09-26 14:18:51 -07002049
2050 @Override
2051 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2052 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2053 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2054 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2055 + " without permission " + android.Manifest.permission.DUMP);
2056 return;
2057 }
2058
Kenny Root38cf8862010-09-26 14:18:51 -07002059 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002060 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002061
Kenny Rootaf9d6672010-10-08 09:21:39 -07002062 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2063 while (binders.hasNext()) {
2064 Entry<IBinder, List<ObbState>> e = binders.next();
2065 pw.print(" Key="); pw.println(e.getKey().toString());
2066 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002067 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002068 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002069 }
2070 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002071
2072 pw.println("");
2073 pw.println(" mObbPathToStateMap:");
2074 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2075 while (maps.hasNext()) {
2076 final Entry<String, ObbState> e = maps.next();
2077 pw.print(" "); pw.print(e.getKey());
2078 pw.print(" -> "); pw.println(e.getValue().toString());
2079 }
Kenny Root38cf8862010-09-26 14:18:51 -07002080 }
2081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082}
2083