blob: 06f9c41e707d25cdd8d5141ecdfe0674880a7e23 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Kenny Roota02b8b02010-08-05 16:14:17 -070019import com.android.internal.app.IMediaContainerService;
Kenny Root735de3b2010-09-30 14:11:39 -070020import com.android.internal.util.HexDump;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080021import com.android.server.am.ActivityManagerService;
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070032import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070033import android.os.Environment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080034import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040035import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070036import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040037import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080038import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080039import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080040import android.os.ServiceManager;
San Mehat207e5382010-02-04 20:46:54 -080041import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemProperties;
Kenny Roota02b8b02010-08-05 16:14:17 -070043import android.os.storage.IMountService;
44import android.os.storage.IMountServiceListener;
45import android.os.storage.IMountShutdownObserver;
46import android.os.storage.IObbActionListener;
47import android.os.storage.StorageResultCode;
Kenny Root735de3b2010-09-30 14:11:39 -070048import android.security.MessageDigest;
San Mehata5078592010-03-25 09:36:54 -070049import android.util.Slog;
Kenny Roota02b8b02010-08-05 16:14:17 -070050
Kenny Root38cf8862010-09-26 14:18:51 -070051import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070052import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070053import java.io.PrintWriter;
Kenny Root735de3b2010-09-30 14:11:39 -070054import java.security.NoSuchAlgorithmException;
San Mehat22dd86e2010-01-12 12:21:18 -080055import java.util.ArrayList;
Kenny Root38cf8862010-09-26 14:18:51 -070056import java.util.Collection;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080058import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070059import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070060import java.util.LinkedList;
61import java.util.List;
62import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070063import java.util.Map.Entry;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065/**
San Mehatb1043402010-02-05 08:26:50 -080066 * MountService implements back-end services for platform storage
67 * management.
68 * @hide - Applications should use android.os.storage.StorageManager
69 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 */
San Mehat22dd86e2010-01-12 12:21:18 -080071class MountService extends IMountService.Stub
72 implements INativeDaemonConnectorCallbacks {
San Mehatb1043402010-02-05 08:26:50 -080073 private static final boolean LOCAL_LOGD = false;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -080074 private static final boolean DEBUG_UNMOUNT = false;
75 private static final boolean DEBUG_EVENTS = false;
Kenny Root02c87302010-07-01 08:10:18 -070076 private static final boolean DEBUG_OBB = true;
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "MountService";
79
Kenny Root305bcbf2010-09-03 07:56:38 -070080 private static final String VOLD_TAG = "VoldConnector";
81
Kenny Root27358a62010-09-29 19:27:20 -070082 protected static final int MAX_OBBS = 8;
83
San Mehat4270e1e2010-01-29 05:32:19 -080084 /*
85 * Internal vold volume state constants
86 */
San Mehat7fd0fee2009-12-17 07:12:23 -080087 class VolumeState {
88 public static final int Init = -1;
89 public static final int NoMedia = 0;
90 public static final int Idle = 1;
91 public static final int Pending = 2;
92 public static final int Checking = 3;
93 public static final int Mounted = 4;
94 public static final int Unmounting = 5;
95 public static final int Formatting = 6;
96 public static final int Shared = 7;
97 public static final int SharedMnt = 8;
98 }
99
San Mehat4270e1e2010-01-29 05:32:19 -0800100 /*
101 * Internal vold response code constants
102 */
San Mehat22dd86e2010-01-12 12:21:18 -0800103 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800104 /*
105 * 100 series - Requestion action was initiated; expect another reply
106 * before proceeding with a new command.
107 */
San Mehat22dd86e2010-01-12 12:21:18 -0800108 public static final int VolumeListResult = 110;
109 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800110 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800111
San Mehat4270e1e2010-01-29 05:32:19 -0800112 /*
113 * 200 series - Requestion action has been successfully completed.
114 */
115 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800116 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800117 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800118
San Mehat4270e1e2010-01-29 05:32:19 -0800119 /*
120 * 400 series - Command was accepted, but the requested action
121 * did not take place.
122 */
123 public static final int OpFailedNoMedia = 401;
124 public static final int OpFailedMediaBlank = 402;
125 public static final int OpFailedMediaCorrupt = 403;
126 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800127 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700128 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800129
130 /*
131 * 600 series - Unsolicited broadcasts.
132 */
San Mehat22dd86e2010-01-12 12:21:18 -0800133 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800134 public static final int ShareAvailabilityChange = 620;
135 public static final int VolumeDiskInserted = 630;
136 public static final int VolumeDiskRemoved = 631;
137 public static final int VolumeBadRemoval = 632;
138 }
139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 private Context mContext;
141 private NativeDaemonConnector mConnector;
142 private String mLegacyState = Environment.MEDIA_REMOVED;
143 private PackageManagerService mPms;
144 private boolean mUmsEnabling;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800145 // Used as a lock for methods that register/unregister listeners.
146 final private ArrayList<MountServiceBinderListener> mListeners =
147 new ArrayList<MountServiceBinderListener>();
San Mehat6a965af22010-02-24 17:47:30 -0800148 private boolean mBooted = false;
149 private boolean mReady = false;
150 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800151
San Mehat6cdd9c02010-02-09 14:45:20 -0800152 /**
153 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800154 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800155 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800156 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800157
Kenny Root02c87302010-07-01 08:10:18 -0700158 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700159 * Mounted OBB tracking information. Used to track the current state of all
160 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700161 */
Kenny Root27358a62010-09-29 19:27:20 -0700162 final private Map<Integer, Integer> mObbUidUsage = new HashMap<Integer, Integer>();
Kenny Root735de3b2010-09-30 14:11:39 -0700163 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700164 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
165
166 class ObbState implements IBinder.DeathRecipient {
Kenny Root735de3b2010-09-30 14:11:39 -0700167 public ObbState(String filename, IObbActionListener token, int callerUid)
168 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700169 this.filename = filename;
170 this.token = token;
171 this.callerUid = callerUid;
172 mounted = false;
173 }
174
175 // OBB source filename
Kenny Root05105f72010-09-22 17:29:43 -0700176 final String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700177
178 // Token of remote Binder caller
Kenny Root05105f72010-09-22 17:29:43 -0700179 final IObbActionListener token;
Kenny Roota02b8b02010-08-05 16:14:17 -0700180
181 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700182 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700183
184 // Whether this is mounted currently.
185 boolean mounted;
186
Kenny Root735de3b2010-09-30 14:11:39 -0700187 public IBinder getBinder() {
188 return token.asBinder();
189 }
190
Kenny Roota02b8b02010-08-05 16:14:17 -0700191 @Override
192 public void binderDied() {
193 ObbAction action = new UnmountObbAction(this, true);
194 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700195 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700196
Kenny Root5919ac62010-10-05 09:49:40 -0700197 public void link() throws RemoteException {
198 getBinder().linkToDeath(this, 0);
199 }
200
201 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700202 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700203 }
Kenny Root38cf8862010-09-26 14:18:51 -0700204
205 @Override
206 public String toString() {
207 StringBuilder sb = new StringBuilder("ObbState{");
208 sb.append("filename=");
209 sb.append(filename);
210 sb.append(",token=");
211 sb.append(token.toString());
212 sb.append(",callerUid=");
213 sb.append(callerUid);
214 sb.append(",mounted=");
215 sb.append(mounted);
216 sb.append('}');
217 return sb.toString();
218 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700219 }
220
221 // OBB Action Handler
222 final private ObbActionHandler mObbActionHandler;
223
224 // OBB action handler messages
225 private static final int OBB_RUN_ACTION = 1;
226 private static final int OBB_MCS_BOUND = 2;
227 private static final int OBB_MCS_UNBIND = 3;
228 private static final int OBB_MCS_RECONNECT = 4;
229 private static final int OBB_MCS_GIVE_UP = 5;
230
231 /*
232 * Default Container Service information
233 */
234 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
235 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
236
237 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
238
239 class DefaultContainerConnection implements ServiceConnection {
240 public void onServiceConnected(ComponentName name, IBinder service) {
241 if (DEBUG_OBB)
242 Slog.i(TAG, "onServiceConnected");
243 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
244 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
245 }
246
247 public void onServiceDisconnected(ComponentName name) {
248 if (DEBUG_OBB)
249 Slog.i(TAG, "onServiceDisconnected");
250 }
251 };
252
253 // Used in the ObbActionHandler
254 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700255
256 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800257 private static final int H_UNMOUNT_PM_UPDATE = 1;
258 private static final int H_UNMOUNT_PM_DONE = 2;
259 private static final int H_UNMOUNT_MS = 3;
260 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
261 private static final int MAX_UNMOUNT_RETRIES = 4;
262
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800263 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700264 final String path;
265 final boolean force;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800266 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800267
268 UnmountCallBack(String path, boolean force) {
269 retries = 0;
270 this.path = path;
271 this.force = force;
272 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800273
274 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700275 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800276 doUnmountVolume(path, true);
277 }
278 }
279
280 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700281 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800282
283 UmsEnableCallBack(String path, String method, boolean force) {
284 super(path, force);
285 this.method = method;
286 }
287
288 @Override
289 void handleFinished() {
290 super.handleFinished();
291 doShareUnshareVolume(path, method, true);
292 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800293 }
294
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800295 class ShutdownCallBack extends UnmountCallBack {
296 IMountShutdownObserver observer;
297 ShutdownCallBack(String path, IMountShutdownObserver observer) {
298 super(path, true);
299 this.observer = observer;
300 }
301
302 @Override
303 void handleFinished() {
304 int ret = doUnmountVolume(path, true);
305 if (observer != null) {
306 try {
307 observer.onShutDownComplete(ret);
308 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700309 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800310 }
311 }
312 }
313 }
314
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400315 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800316 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700317 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800318
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400319 MountServiceHandler(Looper l) {
320 super(l);
321 }
322
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800323 public void handleMessage(Message msg) {
324 switch (msg.what) {
325 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700326 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800327 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
328 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700329 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800330 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700331 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700332 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700333 mUpdatingStatus = true;
334 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800335 }
336 break;
337 }
338 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700339 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700340 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700341 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800342 int size = mForceUnmounts.size();
343 int sizeArr[] = new int[size];
344 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700345 // Kill processes holding references first
346 ActivityManagerService ams = (ActivityManagerService)
347 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800348 for (int i = 0; i < size; i++) {
349 UnmountCallBack ucb = mForceUnmounts.get(i);
350 String path = ucb.path;
351 boolean done = false;
352 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 done = true;
354 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800355 int pids[] = getStorageUsers(path);
356 if (pids == null || pids.length == 0) {
357 done = true;
358 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800359 // Eliminate system process here?
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700360 ams.killPids(pids, "unmount media");
361 // Confirm if file references have been freed.
362 pids = getStorageUsers(path);
363 if (pids == null || pids.length == 0) {
364 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 }
366 }
367 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700368 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
369 // Retry again
370 Slog.i(TAG, "Retrying to kill storage users again");
371 mHandler.sendMessageDelayed(
372 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
373 ucb.retries++),
374 RETRY_UNMOUNT_DELAY);
375 } else {
376 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
377 Slog.i(TAG, "Failed to unmount media inspite of " +
378 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
379 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 sizeArr[sizeArrN++] = i;
381 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
382 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800383 }
384 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800385 // Remove already processed elements from list.
386 for (int i = (sizeArrN-1); i >= 0; i--) {
387 mForceUnmounts.remove(sizeArr[i]);
388 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800389 break;
390 }
391 case H_UNMOUNT_MS : {
San Mehata5078592010-03-25 09:36:54 -0700392 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800393 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800394 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800395 break;
396 }
397 }
398 }
399 };
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400400 final private HandlerThread mHandlerThread;
401 final private Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402
San Mehat207e5382010-02-04 20:46:54 -0800403 private void waitForReady() {
404 while (mReady == false) {
405 for (int retries = 5; retries > 0; retries--) {
406 if (mReady) {
407 return;
408 }
409 SystemClock.sleep(1000);
410 }
San Mehata5078592010-03-25 09:36:54 -0700411 Slog.w(TAG, "Waiting too long for mReady!");
San Mehat207e5382010-02-04 20:46:54 -0800412 }
San Mehat1f6301e2010-01-07 22:40:27 -0800413 }
Kenny Root02c87302010-07-01 08:10:18 -0700414
San Mehat207e5382010-02-04 20:46:54 -0800415 private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 public void onReceive(Context context, Intent intent) {
San Mehat91c77612010-01-07 10:39:41 -0800417 String action = intent.getAction();
418
419 if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
San Mehat207e5382010-02-04 20:46:54 -0800420 mBooted = true;
San Mehat22dd86e2010-01-12 12:21:18 -0800421
Marco Nelissenc34ebce2010-02-18 13:39:41 -0800422 /*
423 * In the simulator, we need to broadcast a volume mounted event
424 * to make the media scanner run.
425 */
426 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
427 notifyVolumeStateChange(null, "/sdcard", VolumeState.NoMedia, VolumeState.Mounted);
428 return;
429 }
San Mehatfafb0412010-02-18 19:40:04 -0800430 new Thread() {
431 public void run() {
432 try {
433 String path = Environment.getExternalStorageDirectory().getPath();
San Mehat6a254402010-03-22 10:21:00 -0700434 String state = getVolumeState(path);
435
436 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
San Mehatfafb0412010-02-18 19:40:04 -0800437 int rc = doMountVolume(path);
438 if (rc != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700439 Slog.e(TAG, String.format("Boot-time mount failed (%d)", rc));
San Mehatfafb0412010-02-18 19:40:04 -0800440 }
San Mehat6a254402010-03-22 10:21:00 -0700441 } else if (state.equals(Environment.MEDIA_SHARED)) {
442 /*
443 * Bootstrap UMS enabled state since vold indicates
444 * the volume is shared (runtime restart while ums enabled)
445 */
446 notifyVolumeStateChange(null, path, VolumeState.NoMedia, VolumeState.Shared);
San Mehatfafb0412010-02-18 19:40:04 -0800447 }
San Mehat6a254402010-03-22 10:21:00 -0700448
San Mehat6a965af22010-02-24 17:47:30 -0800449 /*
San Mehat6a254402010-03-22 10:21:00 -0700450 * If UMS was connected on boot, send the connected event
San Mehat6a965af22010-02-24 17:47:30 -0800451 * now that we're up.
452 */
453 if (mSendUmsConnectedOnBoot) {
454 sendUmsIntent(true);
455 mSendUmsConnectedOnBoot = false;
456 }
San Mehatfafb0412010-02-18 19:40:04 -0800457 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700458 Slog.e(TAG, "Boot-time mount exception", ex);
San Mehatfafb0412010-02-18 19:40:04 -0800459 }
San Mehat207e5382010-02-04 20:46:54 -0800460 }
San Mehatfafb0412010-02-18 19:40:04 -0800461 }.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
463 }
464 };
465
San Mehat4270e1e2010-01-29 05:32:19 -0800466 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
467 final IMountServiceListener mListener;
468
469 MountServiceBinderListener(IMountServiceListener listener) {
470 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700471
San Mehat91c77612010-01-07 10:39:41 -0800472 }
473
San Mehat4270e1e2010-01-29 05:32:19 -0800474 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700475 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700476 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800477 mListeners.remove(this);
478 mListener.asBinder().unlinkToDeath(this, 0);
479 }
480 }
481 }
482
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800483 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800484 // TODO: Add support for multiple share methods
485 if (!method.equals("ums")) {
486 throw new IllegalArgumentException(String.format("Method %s not supported", method));
487 }
488
San Mehat4270e1e2010-01-29 05:32:19 -0800489 try {
490 mConnector.doCommand(String.format(
491 "volume %sshare %s %s", (enable ? "" : "un"), path, method));
492 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700493 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800494 }
San Mehat4270e1e2010-01-29 05:32:19 -0800495 }
496
San Mehat207e5382010-02-04 20:46:54 -0800497 private void updatePublicVolumeState(String path, String state) {
San Mehat4270e1e2010-01-29 05:32:19 -0800498 if (!path.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -0700499 Slog.w(TAG, "Multiple volumes not currently supported");
San Mehat4270e1e2010-01-29 05:32:19 -0800500 return;
501 }
San Mehatb1043402010-02-05 08:26:50 -0800502
503 if (mLegacyState.equals(state)) {
San Mehata5078592010-03-25 09:36:54 -0700504 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s)", mLegacyState, state));
San Mehatb1043402010-02-05 08:26:50 -0800505 return;
506 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800507 // Update state on PackageManager
508 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700509 mPms.updateExternalMediaStatus(false, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800510 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700511 mPms.updateExternalMediaStatus(true, false);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800512 }
Kenny Root38cf8862010-09-26 14:18:51 -0700513
514 // Remove all OBB mappings and listeners from this path
515 synchronized (mObbMounts) {
516 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
517
518 final Iterator<Entry<String, ObbState>> i = mObbPathToStateMap.entrySet().iterator();
519 while (i.hasNext()) {
520 final Entry<String, ObbState> obbEntry = i.next();
521
522 // If this entry's source file is in the volume path that got
523 // unmounted, remove it because it's no longer valid.
524 if (obbEntry.getKey().startsWith(path)) {
525 obbStatesToRemove.add(obbEntry.getValue());
526 }
527 }
528
529 for (final ObbState obbState : obbStatesToRemove) {
530 removeObbState(obbState);
531
532 try {
533 obbState.token.onObbResult(obbState.filename, Environment.MEDIA_UNMOUNTED);
534 } catch (RemoteException e) {
535 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
536 + obbState.filename);
537 }
538 }
539 }
540
San Mehat4270e1e2010-01-29 05:32:19 -0800541 String oldState = mLegacyState;
542 mLegacyState = state;
543
544 synchronized (mListeners) {
545 for (int i = mListeners.size() -1; i >= 0; i--) {
546 MountServiceBinderListener bl = mListeners.get(i);
547 try {
San Mehatb1043402010-02-05 08:26:50 -0800548 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800549 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700550 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800551 mListeners.remove(i);
552 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700553 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800554 }
555 }
556 }
557 }
558
559 /**
560 *
561 * Callback from NativeDaemonConnector
562 */
563 public void onDaemonConnected() {
564 /*
565 * Since we'll be calling back into the NativeDaemonConnector,
566 * we need to do our work in a new thread.
567 */
568 new Thread() {
569 public void run() {
570 /**
571 * Determine media state and UMS detection status
572 */
573 String path = Environment.getExternalStorageDirectory().getPath();
574 String state = Environment.MEDIA_REMOVED;
575
576 try {
577 String[] vols = mConnector.doListCommand(
578 "volume list", VoldResponseCode.VolumeListResult);
579 for (String volstr : vols) {
580 String[] tok = volstr.split(" ");
581 // FMT: <label> <mountpoint> <state>
582 if (!tok[1].equals(path)) {
San Mehata5078592010-03-25 09:36:54 -0700583 Slog.w(TAG, String.format(
San Mehat4270e1e2010-01-29 05:32:19 -0800584 "Skipping unknown volume '%s'",tok[1]));
585 continue;
586 }
587 int st = Integer.parseInt(tok[2]);
588 if (st == VolumeState.NoMedia) {
589 state = Environment.MEDIA_REMOVED;
590 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800591 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800592 } else if (st == VolumeState.Mounted) {
593 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700594 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800595 } else if (st == VolumeState.Shared) {
596 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700597 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800598 } else {
599 throw new Exception(String.format("Unexpected state %d", st));
600 }
601 }
602 if (state != null) {
San Mehata5078592010-03-25 09:36:54 -0700603 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800604 updatePublicVolumeState(path, state);
605 }
606 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700607 Slog.e(TAG, "Error processing initial volume state", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800608 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
609 }
610
611 try {
San Mehat207e5382010-02-04 20:46:54 -0800612 boolean avail = doGetShareMethodAvailable("ums");
San Mehat4270e1e2010-01-29 05:32:19 -0800613 notifyShareAvailabilityChange("ums", avail);
614 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700615 Slog.w(TAG, "Failed to get share availability");
San Mehat4270e1e2010-01-29 05:32:19 -0800616 }
San Mehat207e5382010-02-04 20:46:54 -0800617 /*
618 * Now that we've done our initialization, release
619 * the hounds!
620 */
621 mReady = true;
San Mehat4270e1e2010-01-29 05:32:19 -0800622 }
623 }.start();
624 }
625
626 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800627 * Callback from NativeDaemonConnector
628 */
629 public boolean onEvent(int code, String raw, String[] cooked) {
630 Intent in = null;
631
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800632 if (DEBUG_EVENTS) {
633 StringBuilder builder = new StringBuilder();
634 builder.append("onEvent::");
635 builder.append(" raw= " + raw);
636 if (cooked != null) {
637 builder.append(" cooked = " );
638 for (String str : cooked) {
639 builder.append(" " + str);
640 }
641 }
San Mehata5078592010-03-25 09:36:54 -0700642 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800643 }
San Mehat4270e1e2010-01-29 05:32:19 -0800644 if (code == VoldResponseCode.VolumeStateChange) {
645 /*
646 * One of the volumes we're managing has changed state.
647 * Format: "NNN Volume <label> <path> state changed
648 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
649 */
650 notifyVolumeStateChange(
651 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
652 Integer.parseInt(cooked[10]));
653 } else if (code == VoldResponseCode.ShareAvailabilityChange) {
654 // FMT: NNN Share method <method> now <available|unavailable>
655 boolean avail = false;
656 if (cooked[5].equals("available")) {
657 avail = true;
658 }
659 notifyShareAvailabilityChange(cooked[3], avail);
660 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
661 (code == VoldResponseCode.VolumeDiskRemoved) ||
662 (code == VoldResponseCode.VolumeBadRemoval)) {
663 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
664 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
665 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
666 final String label = cooked[2];
667 final String path = cooked[3];
668 int major = -1;
669 int minor = -1;
670
671 try {
672 String devComp = cooked[6].substring(1, cooked[6].length() -1);
673 String[] devTok = devComp.split(":");
674 major = Integer.parseInt(devTok[0]);
675 minor = Integer.parseInt(devTok[1]);
676 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700677 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800678 }
679
San Mehat4270e1e2010-01-29 05:32:19 -0800680 if (code == VoldResponseCode.VolumeDiskInserted) {
681 new Thread() {
682 public void run() {
683 try {
684 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800685 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700686 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800687 }
688 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700689 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800690 }
691 }
692 }.start();
693 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
694 /*
695 * This event gets trumped if we're already in BAD_REMOVAL state
696 */
697 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
698 return true;
699 }
700 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700701 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800702 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
703 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
704 mContext.sendBroadcast(in);
705
San Mehata5078592010-03-25 09:36:54 -0700706 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
San Mehat4270e1e2010-01-29 05:32:19 -0800707 updatePublicVolumeState(path, Environment.MEDIA_REMOVED);
708 in = new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://" + path));
709 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700710 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800711 /* Send the media unmounted event first */
712 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
713 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
714 mContext.sendBroadcast(in);
715
San Mehata5078592010-03-25 09:36:54 -0700716 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
San Mehat4270e1e2010-01-29 05:32:19 -0800717 updatePublicVolumeState(path, Environment.MEDIA_BAD_REMOVAL);
718 in = new Intent(Intent.ACTION_MEDIA_BAD_REMOVAL, Uri.parse("file://" + path));
719 } else {
San Mehata5078592010-03-25 09:36:54 -0700720 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800721 }
722 } else {
723 return false;
724 }
725
726 if (in != null) {
727 mContext.sendBroadcast(in);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400728 }
729 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800730 }
731
San Mehat207e5382010-02-04 20:46:54 -0800732 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
San Mehat4270e1e2010-01-29 05:32:19 -0800733 String vs = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -0700734 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChanged::" + vs);
San Mehat4270e1e2010-01-29 05:32:19 -0800735
736 Intent in = null;
737
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500738 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700739 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500740 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_UNSHARED,
741 Uri.parse("file://" + path)));
742 }
743
San Mehat4270e1e2010-01-29 05:32:19 -0800744 if (newState == VolumeState.Init) {
745 } else if (newState == VolumeState.NoMedia) {
746 // NoMedia is handled via Disk Remove events
747 } else if (newState == VolumeState.Idle) {
748 /*
749 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
750 * if we're in the process of enabling UMS
751 */
752 if (!vs.equals(
753 Environment.MEDIA_BAD_REMOVAL) && !vs.equals(
754 Environment.MEDIA_NOFS) && !vs.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800755 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700756 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
San Mehat4270e1e2010-01-29 05:32:19 -0800757 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
758 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
759 }
760 } else if (newState == VolumeState.Pending) {
761 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700762 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
San Mehat4270e1e2010-01-29 05:32:19 -0800763 updatePublicVolumeState(path, Environment.MEDIA_CHECKING);
764 in = new Intent(Intent.ACTION_MEDIA_CHECKING, Uri.parse("file://" + path));
765 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700766 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800767 updatePublicVolumeState(path, Environment.MEDIA_MOUNTED);
San Mehat4270e1e2010-01-29 05:32:19 -0800768 in = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + path));
769 in.putExtra("read-only", false);
770 } else if (newState == VolumeState.Unmounting) {
San Mehat4270e1e2010-01-29 05:32:19 -0800771 in = new Intent(Intent.ACTION_MEDIA_EJECT, Uri.parse("file://" + path));
772 } else if (newState == VolumeState.Formatting) {
773 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700774 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800775 /* Send the media unmounted event first */
776 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTED);
777 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTED, Uri.parse("file://" + path));
778 mContext.sendBroadcast(in);
779
San Mehata5078592010-03-25 09:36:54 -0700780 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
San Mehat4270e1e2010-01-29 05:32:19 -0800781 updatePublicVolumeState(path, Environment.MEDIA_SHARED);
782 in = new Intent(Intent.ACTION_MEDIA_SHARED, Uri.parse("file://" + path));
San Mehata5078592010-03-25 09:36:54 -0700783 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800784 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700785 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800786 return;
787 } else {
San Mehata5078592010-03-25 09:36:54 -0700788 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800789 }
790
791 if (in != null) {
792 mContext.sendBroadcast(in);
793 }
794 }
795
San Mehat207e5382010-02-04 20:46:54 -0800796 private boolean doGetShareMethodAvailable(String method) {
Kenny Root85fb2062010-06-01 20:50:21 -0700797 ArrayList<String> rsp;
Kenny Roota80ce062010-06-01 13:23:53 -0700798 try {
Kenny Root85fb2062010-06-01 20:50:21 -0700799 rsp = mConnector.doCommand("share status " + method);
Kenny Roota80ce062010-06-01 13:23:53 -0700800 } catch (NativeDaemonConnectorException ex) {
801 Slog.e(TAG, "Failed to determine whether share method " + method + " is available.");
802 return false;
803 }
San Mehat207e5382010-02-04 20:46:54 -0800804
805 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700806 String[] tok = line.split(" ");
807 if (tok.length < 3) {
808 Slog.e(TAG, "Malformed response to share status " + method);
809 return false;
810 }
811
San Mehat207e5382010-02-04 20:46:54 -0800812 int code;
813 try {
814 code = Integer.parseInt(tok[0]);
815 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700816 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehat207e5382010-02-04 20:46:54 -0800817 return false;
818 }
819 if (code == VoldResponseCode.ShareStatusResult) {
820 if (tok[2].equals("available"))
821 return true;
822 return false;
823 } else {
San Mehata5078592010-03-25 09:36:54 -0700824 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehat207e5382010-02-04 20:46:54 -0800825 return false;
826 }
827 }
San Mehata5078592010-03-25 09:36:54 -0700828 Slog.e(TAG, "Got an empty response");
San Mehat207e5382010-02-04 20:46:54 -0800829 return false;
830 }
831
832 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800833 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800834
San Mehata5078592010-03-25 09:36:54 -0700835 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800836 try {
837 mConnector.doCommand(String.format("volume mount %s", path));
838 } catch (NativeDaemonConnectorException e) {
839 /*
840 * Mount failed for some reason
841 */
842 Intent in = null;
843 int code = e.getCode();
844 if (code == VoldResponseCode.OpFailedNoMedia) {
845 /*
846 * Attempt to mount but no media inserted
847 */
San Mehatb1043402010-02-05 08:26:50 -0800848 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800849 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700850 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800851 /*
852 * Media is blank or does not contain a supported filesystem
853 */
854 updatePublicVolumeState(path, Environment.MEDIA_NOFS);
855 in = new Intent(Intent.ACTION_MEDIA_NOFS, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800856 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800857 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800859 /*
860 * Volume consistency check failed
861 */
862 updatePublicVolumeState(path, Environment.MEDIA_UNMOUNTABLE);
863 in = new Intent(Intent.ACTION_MEDIA_UNMOUNTABLE, Uri.parse("file://" + path));
San Mehatb1043402010-02-05 08:26:50 -0800864 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800865 } else {
San Mehatb1043402010-02-05 08:26:50 -0800866 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800867 }
868
869 /*
870 * Send broadcast intent (if required for the failure)
871 */
872 if (in != null) {
873 mContext.sendBroadcast(in);
874 }
875 }
876
877 return rc;
878 }
879
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800880 /*
881 * If force is not set, we do not unmount if there are
882 * processes holding references to the volume about to be unmounted.
883 * If force is set, all the processes holding references need to be
884 * killed via the ActivityManager before actually unmounting the volume.
885 * This might even take a while and might be retried after timed delays
886 * to make sure we dont end up in an instable state and kill some core
887 * processes.
888 */
San Mehatd9709982010-02-18 11:43:03 -0800889 private int doUnmountVolume(String path, boolean force) {
San Mehat59443a62010-02-09 13:28:45 -0800890 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800891 return VoldResponseCode.OpFailedVolNotMounted;
892 }
Kenny Rootaa485402010-09-14 14:49:41 -0700893
894 /*
895 * Force a GC to make sure AssetManagers in other threads of the
896 * system_server are cleaned up. We have to do this since AssetManager
897 * instances are kept as a WeakReference and it's possible we have files
898 * open on the external storage.
899 */
900 Runtime.getRuntime().gc();
901
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800902 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700903 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800904 try {
San Mehatd9709982010-02-18 11:43:03 -0800905 mConnector.doCommand(String.format(
906 "volume unmount %s%s", path, (force ? " force" : "")));
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700907 // We unmounted the volume. None of the asec containers are available now.
908 synchronized (mAsecMountSet) {
909 mAsecMountSet.clear();
910 }
San Mehatb1043402010-02-05 08:26:50 -0800911 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800912 } catch (NativeDaemonConnectorException e) {
913 // Don't worry about mismatch in PackageManager since the
914 // call back will handle the status changes any way.
915 int code = e.getCode();
916 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -0800917 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -0800918 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
919 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -0800920 } else {
San Mehatb1043402010-02-05 08:26:50 -0800921 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800922 }
923 }
924 }
925
926 private int doFormatVolume(String path) {
927 try {
928 String cmd = String.format("volume format %s", path);
929 mConnector.doCommand(cmd);
San Mehatb1043402010-02-05 08:26:50 -0800930 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800931 } catch (NativeDaemonConnectorException e) {
932 int code = e.getCode();
933 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -0800934 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800935 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -0800936 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800937 } else {
San Mehatb1043402010-02-05 08:26:50 -0800938 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800939 }
940 }
941 }
942
San Mehatb1043402010-02-05 08:26:50 -0800943 private boolean doGetVolumeShared(String path, String method) {
944 String cmd = String.format("volume shared %s %s", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -0700945 ArrayList<String> rsp;
946
947 try {
948 rsp = mConnector.doCommand(cmd);
949 } catch (NativeDaemonConnectorException ex) {
950 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
951 return false;
952 }
San Mehatb1043402010-02-05 08:26:50 -0800953
954 for (String line : rsp) {
Kenny Roota80ce062010-06-01 13:23:53 -0700955 String[] tok = line.split(" ");
956 if (tok.length < 3) {
957 Slog.e(TAG, "Malformed response to volume shared " + path + " " + method + " command");
958 return false;
959 }
960
San Mehatb1043402010-02-05 08:26:50 -0800961 int code;
962 try {
963 code = Integer.parseInt(tok[0]);
964 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -0700965 Slog.e(TAG, String.format("Error parsing code %s", tok[0]));
San Mehatb1043402010-02-05 08:26:50 -0800966 return false;
967 }
968 if (code == VoldResponseCode.ShareEnabledResult) {
Kenny Roota80ce062010-06-01 13:23:53 -0700969 return "enabled".equals(tok[2]);
San Mehatb1043402010-02-05 08:26:50 -0800970 } else {
San Mehata5078592010-03-25 09:36:54 -0700971 Slog.e(TAG, String.format("Unexpected response code %d", code));
San Mehatb1043402010-02-05 08:26:50 -0800972 return false;
973 }
974 }
San Mehata5078592010-03-25 09:36:54 -0700975 Slog.e(TAG, "Got an empty response");
San Mehatb1043402010-02-05 08:26:50 -0800976 return false;
977 }
978
San Mehat207e5382010-02-04 20:46:54 -0800979 private void notifyShareAvailabilityChange(String method, final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -0800980 if (!method.equals("ums")) {
San Mehata5078592010-03-25 09:36:54 -0700981 Slog.w(TAG, "Ignoring unsupported share method {" + method + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800982 return;
983 }
984
985 synchronized (mListeners) {
986 for (int i = mListeners.size() -1; i >= 0; i--) {
987 MountServiceBinderListener bl = mListeners.get(i);
988 try {
San Mehatb1043402010-02-05 08:26:50 -0800989 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -0800990 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700991 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800992 mListeners.remove(i);
993 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700994 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800995 }
996 }
997 }
998
San Mehat207e5382010-02-04 20:46:54 -0800999 if (mBooted == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001000 sendUmsIntent(avail);
1001 } else {
1002 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001003 }
San Mehat2fe718a2010-03-11 12:01:49 -08001004
1005 final String path = Environment.getExternalStorageDirectory().getPath();
1006 if (avail == false && getVolumeState(path).equals(Environment.MEDIA_SHARED)) {
1007 /*
1008 * USB mass storage disconnected while enabled
1009 */
1010 new Thread() {
1011 public void run() {
1012 try {
1013 int rc;
San Mehata5078592010-03-25 09:36:54 -07001014 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001015 doShareUnshareVolume(path, "ums", false);
1016 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001017 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001018 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1019 path, rc));
1020 }
1021 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001022 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001023 }
1024 }
1025 }.start();
1026 }
San Mehat4270e1e2010-01-29 05:32:19 -08001027 }
1028
San Mehat6a965af22010-02-24 17:47:30 -08001029 private void sendUmsIntent(boolean c) {
1030 mContext.sendBroadcast(
1031 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)));
1032 }
1033
San Mehat207e5382010-02-04 20:46:54 -08001034 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001035 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1036 throw new SecurityException(String.format("Requires %s permission", perm));
1037 }
1038 }
1039
1040 /**
San Mehat207e5382010-02-04 20:46:54 -08001041 * Constructs a new MountService instance
1042 *
1043 * @param context Binder context for this service
1044 */
1045 public MountService(Context context) {
1046 mContext = context;
1047
San Mehat207e5382010-02-04 20:46:54 -08001048 // XXX: This will go away soon in favor of IMountServiceObserver
1049 mPms = (PackageManagerService) ServiceManager.getService("package");
1050
1051 mContext.registerReceiver(mBroadcastReceiver,
1052 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, null);
1053
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001054 mHandlerThread = new HandlerThread("MountService");
1055 mHandlerThread.start();
1056 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1057
Kenny Roota02b8b02010-08-05 16:14:17 -07001058 // Add OBB Action Handler to MountService thread.
1059 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1060
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001061 /*
1062 * Vold does not run in the simulator, so pretend the connector thread
1063 * ran and did its thing.
1064 */
1065 if ("simulator".equals(SystemProperties.get("ro.product.device"))) {
1066 mReady = true;
1067 mUmsEnabling = true;
1068 return;
1069 }
1070
Kenny Root305bcbf2010-09-03 07:56:38 -07001071 /*
1072 * Create the connection to vold with a maximum queue of twice the
1073 * amount of containers we'd ever expect to have. This keeps an
1074 * "asec list" from blocking a thread repeatedly.
1075 */
1076 mConnector = new NativeDaemonConnector(this, "vold",
1077 PackageManagerService.MAX_CONTAINERS * 2, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001078 mReady = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07001079 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001080 thread.start();
1081 }
1082
1083 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001084 * Exposed API calls below here
1085 */
1086
1087 public void registerListener(IMountServiceListener listener) {
1088 synchronized (mListeners) {
1089 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1090 try {
1091 listener.asBinder().linkToDeath(bl, 0);
1092 mListeners.add(bl);
1093 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001094 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001095 }
1096 }
1097 }
1098
1099 public void unregisterListener(IMountServiceListener listener) {
1100 synchronized (mListeners) {
1101 for(MountServiceBinderListener bl : mListeners) {
1102 if (bl.mListener == listener) {
1103 mListeners.remove(mListeners.indexOf(bl));
1104 return;
1105 }
1106 }
1107 }
1108 }
1109
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001110 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001111 validatePermission(android.Manifest.permission.SHUTDOWN);
1112
San Mehata5078592010-03-25 09:36:54 -07001113 Slog.i(TAG, "Shutting down");
San Mehat4270e1e2010-01-29 05:32:19 -08001114
1115 String path = Environment.getExternalStorageDirectory().getPath();
1116 String state = getVolumeState(path);
San Mehat91c77612010-01-07 10:39:41 -08001117
1118 if (state.equals(Environment.MEDIA_SHARED)) {
1119 /*
1120 * If the media is currently shared, unshare it.
1121 * XXX: This is still dangerous!. We should not
1122 * be rebooting at *all* if UMS is enabled, since
1123 * the UMS host could have dirty FAT cache entries
1124 * yet to flush.
1125 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001126 setUsbMassStorageEnabled(false);
San Mehat91c77612010-01-07 10:39:41 -08001127 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1128 /*
1129 * If the media is being checked, then we need to wait for
1130 * it to complete before being able to proceed.
1131 */
1132 // XXX: @hackbod - Should we disable the ANR timer here?
1133 int retries = 30;
1134 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1135 try {
1136 Thread.sleep(1000);
1137 } catch (InterruptedException iex) {
San Mehata5078592010-03-25 09:36:54 -07001138 Slog.e(TAG, "Interrupted while waiting for media", iex);
San Mehat91c77612010-01-07 10:39:41 -08001139 break;
1140 }
1141 state = Environment.getExternalStorageState();
1142 }
1143 if (retries == 0) {
San Mehata5078592010-03-25 09:36:54 -07001144 Slog.e(TAG, "Timed out waiting for media to check");
San Mehat91c77612010-01-07 10:39:41 -08001145 }
1146 }
1147
1148 if (state.equals(Environment.MEDIA_MOUNTED)) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001149 // Post a unmount message.
1150 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1151 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
San Mehat4270e1e2010-01-29 05:32:19 -08001152 }
1153 }
1154
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001155 private boolean getUmsEnabling() {
1156 synchronized (mListeners) {
1157 return mUmsEnabling;
1158 }
1159 }
1160
1161 private void setUmsEnabling(boolean enable) {
1162 synchronized (mListeners) {
1163 mUmsEnabling = true;
1164 }
1165 }
1166
San Mehatb1043402010-02-05 08:26:50 -08001167 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001168 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001169
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001170 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001171 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001172 }
San Mehatb1043402010-02-05 08:26:50 -08001173 return doGetShareMethodAvailable("ums");
1174 }
1175
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001176 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001177 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001178 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001179
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001180 // TODO: Add support for multiple share methods
1181
1182 /*
1183 * If the volume is mounted and we're enabling then unmount it
1184 */
1185 String path = Environment.getExternalStorageDirectory().getPath();
1186 String vs = getVolumeState(path);
1187 String method = "ums";
1188 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1189 // Override for isUsbMassStorageEnabled()
1190 setUmsEnabling(enable);
1191 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1192 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1193 // Clear override
1194 setUmsEnabling(false);
1195 }
1196 /*
1197 * If we disabled UMS then mount the volume
1198 */
1199 if (!enable) {
1200 doShareUnshareVolume(path, method, enable);
1201 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001202 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001203 " after disabling share method " + method);
1204 /*
1205 * Even though the mount failed, the unshare didn't so don't indicate an error.
1206 * The mountVolume() call will have set the storage state and sent the necessary
1207 * broadcasts.
1208 */
1209 }
1210 }
San Mehatb1043402010-02-05 08:26:50 -08001211 }
1212
1213 public boolean isUsbMassStorageEnabled() {
1214 waitForReady();
1215 return doGetVolumeShared(Environment.getExternalStorageDirectory().getPath(), "ums");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
San Mehat4270e1e2010-01-29 05:32:19 -08001217
San Mehat7fd0fee2009-12-17 07:12:23 -08001218 /**
1219 * @return state of the volume at the specified mount point
1220 */
San Mehat4270e1e2010-01-29 05:32:19 -08001221 public String getVolumeState(String mountPoint) {
San Mehat7fd0fee2009-12-17 07:12:23 -08001222 /*
1223 * XXX: Until we have multiple volume discovery, just hardwire
1224 * this to /sdcard
1225 */
1226 if (!mountPoint.equals(Environment.getExternalStorageDirectory().getPath())) {
San Mehata5078592010-03-25 09:36:54 -07001227 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
San Mehat7fd0fee2009-12-17 07:12:23 -08001228 throw new IllegalArgumentException();
1229 }
1230
1231 return mLegacyState;
1232 }
1233
San Mehat4270e1e2010-01-29 05:32:19 -08001234 public int mountVolume(String path) {
1235 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001236
San Mehat207e5382010-02-04 20:46:54 -08001237 waitForReady();
1238 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
1240
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001241 public void unmountVolume(String path, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001242 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001243 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001245 String volState = getVolumeState(path);
San Mehata5078592010-03-25 09:36:54 -07001246 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path + " force = " + force);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001247 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1248 Environment.MEDIA_REMOVED.equals(volState) ||
1249 Environment.MEDIA_SHARED.equals(volState) ||
1250 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1251 // Media already unmounted or cannot be unmounted.
1252 // TODO return valid return code when adding observer call back.
1253 return;
1254 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001255 UnmountCallBack ucb = new UnmountCallBack(path, force);
1256 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258
San Mehat4270e1e2010-01-29 05:32:19 -08001259 public int formatVolume(String path) {
1260 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001261 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001262
San Mehat207e5382010-02-04 20:46:54 -08001263 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
1265
San Mehatc1b4ce92010-02-16 17:13:03 -08001266 public int []getStorageUsers(String path) {
1267 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1268 waitForReady();
1269 try {
1270 String[] r = mConnector.doListCommand(
1271 String.format("storage users %s", path),
1272 VoldResponseCode.StorageUsersListResult);
1273 // FMT: <pid> <process name>
1274 int[] data = new int[r.length];
1275 for (int i = 0; i < r.length; i++) {
1276 String []tok = r[i].split(" ");
1277 try {
1278 data[i] = Integer.parseInt(tok[0]);
1279 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001280 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001281 return new int[0];
1282 }
1283 }
1284 return data;
1285 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001286 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001287 return new int[0];
1288 }
1289 }
1290
San Mehatb1043402010-02-05 08:26:50 -08001291 private void warnOnNotMounted() {
1292 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
San Mehata5078592010-03-25 09:36:54 -07001293 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001294 }
1295 }
1296
San Mehat4270e1e2010-01-29 05:32:19 -08001297 public String[] getSecureContainerList() {
1298 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001299 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001300 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001301
San Mehat4270e1e2010-01-29 05:32:19 -08001302 try {
1303 return mConnector.doListCommand("asec list", VoldResponseCode.AsecListResult);
1304 } catch (NativeDaemonConnectorException e) {
1305 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 }
1307 }
San Mehat36972292010-01-06 11:06:32 -08001308
San Mehat4270e1e2010-01-29 05:32:19 -08001309 public int createSecureContainer(String id, int sizeMb, String fstype,
1310 String key, int ownerUid) {
1311 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001312 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001313 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001314
San Mehatb1043402010-02-05 08:26:50 -08001315 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001316 String cmd = String.format("asec create %s %d %s %s %d", id, sizeMb, fstype, key, ownerUid);
1317 try {
1318 mConnector.doCommand(cmd);
1319 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001320 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001321 }
San Mehata181b212010-02-11 06:50:20 -08001322
1323 if (rc == StorageResultCode.OperationSucceeded) {
1324 synchronized (mAsecMountSet) {
1325 mAsecMountSet.add(id);
1326 }
1327 }
San Mehat4270e1e2010-01-29 05:32:19 -08001328 return rc;
San Mehat36972292010-01-06 11:06:32 -08001329 }
1330
San Mehat4270e1e2010-01-29 05:32:19 -08001331 public int finalizeSecureContainer(String id) {
1332 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001333 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001334
San Mehatb1043402010-02-05 08:26:50 -08001335 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001336 try {
1337 mConnector.doCommand(String.format("asec finalize %s", id));
San Mehata181b212010-02-11 06:50:20 -08001338 /*
1339 * Finalization does a remount, so no need
1340 * to update mAsecMountSet
1341 */
San Mehat4270e1e2010-01-29 05:32:19 -08001342 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001343 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001344 }
San Mehat4270e1e2010-01-29 05:32:19 -08001345 return rc;
San Mehat36972292010-01-06 11:06:32 -08001346 }
1347
San Mehatd9709982010-02-18 11:43:03 -08001348 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001349 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001350 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001351 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001352
Kenny Rootaa485402010-09-14 14:49:41 -07001353 /*
1354 * Force a GC to make sure AssetManagers in other threads of the
1355 * system_server are cleaned up. We have to do this since AssetManager
1356 * instances are kept as a WeakReference and it's possible we have files
1357 * open on the external storage.
1358 */
1359 Runtime.getRuntime().gc();
1360
San Mehatb1043402010-02-05 08:26:50 -08001361 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001362 try {
San Mehatd9709982010-02-18 11:43:03 -08001363 mConnector.doCommand(String.format("asec destroy %s%s", id, (force ? " force" : "")));
San Mehat4270e1e2010-01-29 05:32:19 -08001364 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001365 int code = e.getCode();
1366 if (code == VoldResponseCode.OpFailedStorageBusy) {
1367 rc = StorageResultCode.OperationFailedStorageBusy;
1368 } else {
1369 rc = StorageResultCode.OperationFailedInternalError;
1370 }
San Mehat02735bc2010-01-26 15:18:08 -08001371 }
San Mehata181b212010-02-11 06:50:20 -08001372
1373 if (rc == StorageResultCode.OperationSucceeded) {
1374 synchronized (mAsecMountSet) {
1375 if (mAsecMountSet.contains(id)) {
1376 mAsecMountSet.remove(id);
1377 }
1378 }
1379 }
1380
San Mehat4270e1e2010-01-29 05:32:19 -08001381 return rc;
San Mehat36972292010-01-06 11:06:32 -08001382 }
1383
San Mehat4270e1e2010-01-29 05:32:19 -08001384 public int mountSecureContainer(String id, String key, int ownerUid) {
1385 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001386 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001387 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001388
San Mehata181b212010-02-11 06:50:20 -08001389 synchronized (mAsecMountSet) {
1390 if (mAsecMountSet.contains(id)) {
1391 return StorageResultCode.OperationFailedStorageMounted;
1392 }
1393 }
1394
San Mehatb1043402010-02-05 08:26:50 -08001395 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001396 String cmd = String.format("asec mount %s %s %d", id, key, ownerUid);
1397 try {
1398 mConnector.doCommand(cmd);
1399 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001400 int code = e.getCode();
1401 if (code != VoldResponseCode.OpFailedStorageBusy) {
1402 rc = StorageResultCode.OperationFailedInternalError;
1403 }
San Mehat02735bc2010-01-26 15:18:08 -08001404 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001405
1406 if (rc == StorageResultCode.OperationSucceeded) {
1407 synchronized (mAsecMountSet) {
1408 mAsecMountSet.add(id);
1409 }
1410 }
San Mehat4270e1e2010-01-29 05:32:19 -08001411 return rc;
San Mehat36972292010-01-06 11:06:32 -08001412 }
1413
San Mehatd9709982010-02-18 11:43:03 -08001414 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001415 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001416 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001417 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001418
San Mehat6cdd9c02010-02-09 14:45:20 -08001419 synchronized (mAsecMountSet) {
1420 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001421 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001422 }
1423 }
1424
Kenny Rootaa485402010-09-14 14:49:41 -07001425 /*
1426 * Force a GC to make sure AssetManagers in other threads of the
1427 * system_server are cleaned up. We have to do this since AssetManager
1428 * instances are kept as a WeakReference and it's possible we have files
1429 * open on the external storage.
1430 */
1431 Runtime.getRuntime().gc();
1432
San Mehatb1043402010-02-05 08:26:50 -08001433 int rc = StorageResultCode.OperationSucceeded;
San Mehatd9709982010-02-18 11:43:03 -08001434 String cmd = String.format("asec unmount %s%s", id, (force ? " force" : ""));
San Mehat4270e1e2010-01-29 05:32:19 -08001435 try {
1436 mConnector.doCommand(cmd);
1437 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001438 int code = e.getCode();
1439 if (code == VoldResponseCode.OpFailedStorageBusy) {
1440 rc = StorageResultCode.OperationFailedStorageBusy;
1441 } else {
1442 rc = StorageResultCode.OperationFailedInternalError;
1443 }
San Mehat02735bc2010-01-26 15:18:08 -08001444 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001445
1446 if (rc == StorageResultCode.OperationSucceeded) {
1447 synchronized (mAsecMountSet) {
1448 mAsecMountSet.remove(id);
1449 }
1450 }
San Mehat4270e1e2010-01-29 05:32:19 -08001451 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001452 }
1453
San Mehat6cdd9c02010-02-09 14:45:20 -08001454 public boolean isSecureContainerMounted(String id) {
1455 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1456 waitForReady();
1457 warnOnNotMounted();
1458
1459 synchronized (mAsecMountSet) {
1460 return mAsecMountSet.contains(id);
1461 }
1462 }
1463
San Mehat4270e1e2010-01-29 05:32:19 -08001464 public int renameSecureContainer(String oldId, String newId) {
1465 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001466 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001467 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001468
San Mehata181b212010-02-11 06:50:20 -08001469 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001470 /*
1471 * Because a mounted container has active internal state which cannot be
1472 * changed while active, we must ensure both ids are not currently mounted.
1473 */
1474 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001475 return StorageResultCode.OperationFailedStorageMounted;
1476 }
1477 }
1478
San Mehatb1043402010-02-05 08:26:50 -08001479 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001480 String cmd = String.format("asec rename %s %s", oldId, newId);
1481 try {
1482 mConnector.doCommand(cmd);
1483 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001484 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001485 }
San Mehata181b212010-02-11 06:50:20 -08001486
San Mehat4270e1e2010-01-29 05:32:19 -08001487 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001488 }
1489
San Mehat4270e1e2010-01-29 05:32:19 -08001490 public String getSecureContainerPath(String id) {
1491 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001492 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001493 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001494
San Mehat2d66cef2010-03-23 11:12:52 -07001495 try {
1496 ArrayList<String> rsp = mConnector.doCommand(String.format("asec path %s", id));
1497 String []tok = rsp.get(0).split(" ");
San Mehat22dd86e2010-01-12 12:21:18 -08001498 int code = Integer.parseInt(tok[0]);
San Mehat2d66cef2010-03-23 11:12:52 -07001499 if (code != VoldResponseCode.AsecPathResult) {
1500 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1501 }
1502 return tok[1];
1503 } catch (NativeDaemonConnectorException e) {
1504 int code = e.getCode();
1505 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1506 throw new IllegalArgumentException(String.format("Container '%s' not found", id));
San Mehat22dd86e2010-01-12 12:21:18 -08001507 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001508 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001509 }
1510 }
San Mehat22dd86e2010-01-12 12:21:18 -08001511 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001512
1513 public void finishMediaUpdate() {
1514 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1515 }
Kenny Root02c87302010-07-01 08:10:18 -07001516
Kenny Roota02b8b02010-08-05 16:14:17 -07001517 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1518 if (callerUid == android.os.Process.SYSTEM_UID) {
1519 return true;
1520 }
1521
Kenny Root02c87302010-07-01 08:10:18 -07001522 if (packageName == null) {
1523 return false;
1524 }
1525
1526 final int packageUid = mPms.getPackageUid(packageName);
1527
1528 if (DEBUG_OBB) {
1529 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1530 packageUid + ", callerUid = " + callerUid);
1531 }
1532
1533 return callerUid == packageUid;
1534 }
1535
1536 public String getMountedObbPath(String filename) {
1537 waitForReady();
1538 warnOnNotMounted();
1539
Kenny Root02c87302010-07-01 08:10:18 -07001540 try {
1541 ArrayList<String> rsp = mConnector.doCommand(String.format("obb path %s", filename));
1542 String []tok = rsp.get(0).split(" ");
1543 int code = Integer.parseInt(tok[0]);
1544 if (code != VoldResponseCode.AsecPathResult) {
1545 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1546 }
1547 return tok[1];
1548 } catch (NativeDaemonConnectorException e) {
1549 int code = e.getCode();
1550 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001551 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001552 } else {
1553 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1554 }
1555 }
1556 }
1557
1558 public boolean isObbMounted(String filename) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001559 synchronized (mObbMounts) {
Kenny Root38cf8862010-09-26 14:18:51 -07001560 final ObbState obbState = mObbPathToStateMap.get(filename);
1561 if (obbState != null) {
1562 synchronized (obbState) {
1563 return obbState.mounted;
1564 }
1565 }
Kenny Root02c87302010-07-01 08:10:18 -07001566 }
Kenny Root38cf8862010-09-26 14:18:51 -07001567 return false;
Kenny Root02c87302010-07-01 08:10:18 -07001568 }
1569
Kenny Root735de3b2010-09-30 14:11:39 -07001570 public void mountObb(String filename, String key, IObbActionListener token)
1571 throws RemoteException {
Kenny Root02c87302010-07-01 08:10:18 -07001572 waitForReady();
1573 warnOnNotMounted();
1574
Kenny Rootf1121dc2010-09-29 07:30:53 -07001575 if (filename == null) {
1576 throw new IllegalArgumentException("filename cannot be null");
1577 } else if (token == null) {
1578 throw new IllegalArgumentException("token cannot be null");
1579 }
1580
Kenny Roota02b8b02010-08-05 16:14:17 -07001581 final ObbState obbState;
1582
1583 synchronized (mObbMounts) {
1584 if (isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001585 try {
1586 token.onObbResult(filename, Environment.MEDIA_MOUNTED);
1587 } catch (RemoteException e) {
1588 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1589 }
1590 return;
Kenny Root02c87302010-07-01 08:10:18 -07001591 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001592
Kenny Roota02b8b02010-08-05 16:14:17 -07001593 final int callerUid = Binder.getCallingUid();
Kenny Root27358a62010-09-29 19:27:20 -07001594
1595 final Integer uidUsage = mObbUidUsage.get(callerUid);
1596 if (uidUsage != null && uidUsage > MAX_OBBS) {
1597 throw new IllegalStateException("Maximum number of OBBs mounted!");
1598 }
1599
Kenny Roota02b8b02010-08-05 16:14:17 -07001600 obbState = new ObbState(filename, token, callerUid);
1601 addObbState(obbState);
Kenny Root02c87302010-07-01 08:10:18 -07001602 }
1603
Kenny Root29423912010-10-01 08:37:20 -07001604 String hashedKey = null;
1605 if (key != null) {
1606 final MessageDigest md;
Kenny Root735de3b2010-09-30 14:11:39 -07001607 try {
Kenny Root29423912010-10-01 08:37:20 -07001608 md = MessageDigest.getInstance("MD5");
1609 } catch (NoSuchAlgorithmException e) {
1610 Slog.e(TAG, "Could not load MD5 algorithm", e);
1611 try {
1612 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1613 } catch (RemoteException e1) {
1614 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1615 }
1616 return;
Kenny Root735de3b2010-09-30 14:11:39 -07001617 }
Kenny Root02c87302010-07-01 08:10:18 -07001618
Kenny Root29423912010-10-01 08:37:20 -07001619 hashedKey = HexDump.toHexString(md.digest(key.getBytes()));
1620 }
Kenny Root735de3b2010-09-30 14:11:39 -07001621
1622 ObbAction action = new MountObbAction(obbState, hashedKey);
Kenny Roota02b8b02010-08-05 16:14:17 -07001623 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1624
1625 if (DEBUG_OBB)
1626 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001627 }
1628
Kenny Roota02b8b02010-08-05 16:14:17 -07001629 public void unmountObb(String filename, boolean force, IObbActionListener token) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001630 if (filename == null) {
1631 throw new IllegalArgumentException("filename cannot be null");
1632 } else if (token == null) {
1633 throw new IllegalArgumentException("token cannot be null");
1634 }
1635
Kenny Roota02b8b02010-08-05 16:14:17 -07001636 final ObbState obbState;
Kenny Root02c87302010-07-01 08:10:18 -07001637
Kenny Roota02b8b02010-08-05 16:14:17 -07001638 synchronized (mObbMounts) {
1639 if (!isObbMounted(filename)) {
Kenny Root38cf8862010-09-26 14:18:51 -07001640 try {
1641 token.onObbResult(filename, Environment.MEDIA_UNMOUNTED);
1642 } catch (RemoteException e) {
1643 Slog.d(TAG, "Could not send unmount notification for: " + filename);
1644 }
1645 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001646 }
Kenny Root38cf8862010-09-26 14:18:51 -07001647
Kenny Roota02b8b02010-08-05 16:14:17 -07001648 obbState = mObbPathToStateMap.get(filename);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001649
1650 if (Binder.getCallingUid() != obbState.callerUid) {
1651 throw new SecurityException("caller UID does not match original mount caller UID");
Kenny Root735de3b2010-09-30 14:11:39 -07001652 } else if (!token.asBinder().equals(obbState.getBinder())) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001653 throw new SecurityException("caller does not match original mount caller");
1654 }
Kenny Root02c87302010-07-01 08:10:18 -07001655 }
1656
Kenny Root38cf8862010-09-26 14:18:51 -07001657 ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001658 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001659
Kenny Roota02b8b02010-08-05 16:14:17 -07001660 if (DEBUG_OBB)
1661 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1662 }
1663
Kenny Root5919ac62010-10-05 09:49:40 -07001664 private void addObbState(ObbState obbState) throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -07001665 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001666 final IBinder binder = obbState.getBinder();
1667 List<ObbState> obbStates = mObbMounts.get(binder);
1668 final boolean unique;
1669
Kenny Root05105f72010-09-22 17:29:43 -07001670 if (obbStates == null) {
1671 obbStates = new ArrayList<ObbState>();
Kenny Root5919ac62010-10-05 09:49:40 -07001672 mObbMounts.put(binder, obbStates);
1673 unique = true;
1674 } else {
1675 unique = obbStates.contains(obbState);
Kenny Root05105f72010-09-22 17:29:43 -07001676 }
Kenny Root5919ac62010-10-05 09:49:40 -07001677
1678 if (unique) {
1679 obbStates.add(obbState);
1680 try {
1681 obbState.link();
1682 } catch (RemoteException e) {
1683 /*
1684 * The binder died before we could link it, so clean up our
1685 * state and return failure.
1686 */
1687 obbStates.remove(obbState);
1688 if (obbStates.isEmpty()) {
1689 mObbMounts.remove(binder);
1690 }
1691
1692 // Rethrow the error so mountObb can get it
1693 throw e;
1694 }
1695 }
1696
Kenny Roota02b8b02010-08-05 16:14:17 -07001697 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Root27358a62010-09-29 19:27:20 -07001698
1699 // Track the number of OBBs used by this UID.
1700 final int uid = obbState.callerUid;
1701 final Integer uidUsage = mObbUidUsage.get(uid);
1702 if (uidUsage == null) {
1703 mObbUidUsage.put(uid, 1);
1704 } else {
1705 mObbUidUsage.put(uid, uidUsage + 1);
1706 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001707 }
1708 }
1709
1710 private void removeObbState(ObbState obbState) {
1711 synchronized (mObbMounts) {
Kenny Root5919ac62010-10-05 09:49:40 -07001712 final IBinder binder = obbState.getBinder();
1713 final List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root05105f72010-09-22 17:29:43 -07001714 if (obbStates != null) {
Kenny Root5919ac62010-10-05 09:49:40 -07001715 if (obbStates.remove(obbState)) {
1716 obbState.unlink();
1717 }
1718 if (obbStates.isEmpty()) {
1719 mObbMounts.remove(binder);
1720 }
Kenny Root05105f72010-09-22 17:29:43 -07001721 }
Kenny Root5919ac62010-10-05 09:49:40 -07001722
Kenny Roota02b8b02010-08-05 16:14:17 -07001723 mObbPathToStateMap.remove(obbState.filename);
Kenny Root27358a62010-09-29 19:27:20 -07001724
1725 // Track the number of OBBs used by this UID.
1726 final int uid = obbState.callerUid;
1727 final Integer uidUsage = mObbUidUsage.get(uid);
1728 if (uidUsage == null) {
1729 Slog.e(TAG, "Called removeObbState for UID that isn't in map: " + uid);
1730 } else {
1731 final int newUsage = uidUsage - 1;
1732 if (newUsage == 0) {
1733 mObbUidUsage.remove(uid);
1734 } else {
1735 mObbUidUsage.put(uid, newUsage);
1736 }
1737 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001738 }
1739 }
1740
Kenny Root5919ac62010-10-05 09:49:40 -07001741 private void replaceObbState(ObbState oldObbState, ObbState newObbState) throws RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001742 synchronized (mObbMounts) {
1743 removeObbState(oldObbState);
1744 addObbState(newObbState);
1745 }
1746 }
1747
Kenny Roota02b8b02010-08-05 16:14:17 -07001748 private class ObbActionHandler extends Handler {
1749 private boolean mBound = false;
1750 private List<ObbAction> mActions = new LinkedList<ObbAction>();
1751
1752 ObbActionHandler(Looper l) {
1753 super(l);
1754 }
1755
1756 @Override
1757 public void handleMessage(Message msg) {
1758 switch (msg.what) {
1759 case OBB_RUN_ACTION: {
1760 ObbAction action = (ObbAction) msg.obj;
1761
1762 if (DEBUG_OBB)
1763 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
1764
1765 // If a bind was already initiated we don't really
1766 // need to do anything. The pending install
1767 // will be processed later on.
1768 if (!mBound) {
1769 // If this is the only one pending we might
1770 // have to bind to the service again.
1771 if (!connectToService()) {
1772 Slog.e(TAG, "Failed to bind to media container service");
1773 action.handleError();
1774 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07001775 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001776 }
Kenny Root735de3b2010-09-30 14:11:39 -07001777
Kenny Root735de3b2010-09-30 14:11:39 -07001778 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07001779 break;
1780 }
1781 case OBB_MCS_BOUND: {
1782 if (DEBUG_OBB)
1783 Slog.i(TAG, "OBB_MCS_BOUND");
1784 if (msg.obj != null) {
1785 mContainerService = (IMediaContainerService) msg.obj;
1786 }
1787 if (mContainerService == null) {
1788 // Something seriously wrong. Bail out
1789 Slog.e(TAG, "Cannot bind to media container service");
1790 for (ObbAction action : mActions) {
1791 // Indicate service bind error
1792 action.handleError();
1793 }
1794 mActions.clear();
1795 } else if (mActions.size() > 0) {
1796 ObbAction action = mActions.get(0);
1797 if (action != null) {
1798 action.execute(this);
1799 }
1800 } else {
1801 // Should never happen ideally.
1802 Slog.w(TAG, "Empty queue");
1803 }
1804 break;
1805 }
1806 case OBB_MCS_RECONNECT: {
1807 if (DEBUG_OBB)
1808 Slog.i(TAG, "OBB_MCS_RECONNECT");
1809 if (mActions.size() > 0) {
1810 if (mBound) {
1811 disconnectService();
1812 }
1813 if (!connectToService()) {
1814 Slog.e(TAG, "Failed to bind to media container service");
1815 for (ObbAction action : mActions) {
1816 // Indicate service bind error
1817 action.handleError();
1818 }
1819 mActions.clear();
1820 }
1821 }
1822 break;
1823 }
1824 case OBB_MCS_UNBIND: {
1825 if (DEBUG_OBB)
1826 Slog.i(TAG, "OBB_MCS_UNBIND");
1827
1828 // Delete pending install
1829 if (mActions.size() > 0) {
1830 mActions.remove(0);
1831 }
1832 if (mActions.size() == 0) {
1833 if (mBound) {
1834 disconnectService();
1835 }
1836 } else {
1837 // There are more pending requests in queue.
1838 // Just post MCS_BOUND message to trigger processing
1839 // of next pending install.
1840 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
1841 }
1842 break;
1843 }
1844 case OBB_MCS_GIVE_UP: {
1845 if (DEBUG_OBB)
1846 Slog.i(TAG, "OBB_MCS_GIVE_UP");
1847 mActions.remove(0);
Kenny Root17eb6fb2010-10-06 15:02:52 -07001848 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001849 break;
1850 }
1851 }
1852 }
1853
1854 private boolean connectToService() {
1855 if (DEBUG_OBB)
1856 Slog.i(TAG, "Trying to bind to DefaultContainerService");
1857
1858 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1859 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
1860 mBound = true;
1861 return true;
1862 }
1863 return false;
1864 }
1865
1866 private void disconnectService() {
1867 mContainerService = null;
1868 mBound = false;
1869 mContext.unbindService(mDefContainerConn);
1870 }
1871 }
1872
1873 abstract class ObbAction {
1874 private static final int MAX_RETRIES = 3;
1875 private int mRetries;
1876
1877 ObbState mObbState;
1878
1879 ObbAction(ObbState obbState) {
1880 mObbState = obbState;
1881 }
1882
1883 public void execute(ObbActionHandler handler) {
1884 try {
1885 if (DEBUG_OBB)
1886 Slog.i(TAG, "Starting to execute action: " + this.toString());
1887 mRetries++;
1888 if (mRetries > MAX_RETRIES) {
1889 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
1890 mObbActionHandler.sendEmptyMessage(OBB_MCS_GIVE_UP);
1891 handleError();
1892 return;
1893 } else {
1894 handleExecute();
1895 if (DEBUG_OBB)
1896 Slog.i(TAG, "Posting install MCS_UNBIND");
1897 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
1898 }
1899 } catch (RemoteException e) {
1900 if (DEBUG_OBB)
1901 Slog.i(TAG, "Posting install MCS_RECONNECT");
1902 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
1903 } catch (Exception e) {
1904 if (DEBUG_OBB)
1905 Slog.d(TAG, "Error handling OBB action", e);
1906 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07001907 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07001908 }
1909 }
1910
Kenny Root05105f72010-09-22 17:29:43 -07001911 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07001912 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07001913
1914 protected ObbInfo getObbInfo() throws IOException {
1915 ObbInfo obbInfo;
1916 try {
1917 obbInfo = mContainerService.getObbInfo(mObbState.filename);
1918 } catch (RemoteException e) {
1919 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
1920 + mObbState.filename);
1921 obbInfo = null;
1922 }
1923 if (obbInfo == null) {
1924 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
1925 }
1926 return obbInfo;
1927 }
1928
1929 protected void sendNewStatusOrIgnore(String filename, String status) {
1930 try {
1931 mObbState.token.onObbResult(filename, status);
1932 } catch (RemoteException e) {
1933 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
1934 }
1935 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001936 }
1937
1938 class MountObbAction extends ObbAction {
1939 private String mKey;
1940
1941 MountObbAction(ObbState obbState, String key) {
1942 super(obbState);
1943 mKey = key;
1944 }
1945
Kenny Root735de3b2010-09-30 14:11:39 -07001946 public void handleExecute() throws IOException, RemoteException {
Kenny Root38cf8862010-09-26 14:18:51 -07001947 final ObbInfo obbInfo = getObbInfo();
1948
1949 /*
1950 * If someone tried to trick us with some weird characters, rectify
1951 * it here.
1952 */
1953 if (!mObbState.filename.equals(obbInfo.filename)) {
1954 if (DEBUG_OBB)
1955 Slog.i(TAG, "OBB filename " + mObbState.filename + " is actually "
1956 + obbInfo.filename);
1957
1958 synchronized (mObbMounts) {
1959 /*
1960 * If the real filename is already mounted, discard this
1961 * state and notify the caller that the OBB is already
1962 * mounted.
1963 */
1964 if (isObbMounted(obbInfo.filename)) {
1965 if (DEBUG_OBB)
1966 Slog.i(TAG, "OBB already mounted as " + obbInfo.filename);
1967
1968 removeObbState(mObbState);
1969 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_MOUNTED);
1970 return;
1971 }
1972
1973 /*
1974 * It's not already mounted, so we have to replace the state
1975 * with the state containing the actual filename.
1976 */
1977 ObbState newObbState = new ObbState(obbInfo.filename, mObbState.token,
1978 mObbState.callerUid);
1979 replaceObbState(mObbState, newObbState);
1980 mObbState = newObbState;
1981 }
Kenny Root05105f72010-09-22 17:29:43 -07001982 }
1983
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
1985 throw new IllegalArgumentException("Caller package does not match OBB file");
1986 }
1987
Kenny Root38cf8862010-09-26 14:18:51 -07001988 boolean mounted = false;
1989 int rc;
1990 synchronized (mObbState) {
1991 if (mObbState.mounted) {
1992 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
1993 return;
1994 }
1995
1996 rc = StorageResultCode.OperationSucceeded;
Kenny Root12ffd9b2010-10-01 12:56:59 -07001997 String cmd = String.format("obb mount %s %s %d", mObbState.filename,
1998 mKey != null ? mKey : "none",
Kenny Root38cf8862010-09-26 14:18:51 -07001999 mObbState.callerUid);
2000 try {
2001 mConnector.doCommand(cmd);
2002 } catch (NativeDaemonConnectorException e) {
2003 int code = e.getCode();
2004 if (code != VoldResponseCode.OpFailedStorageBusy) {
2005 rc = StorageResultCode.OperationFailedInternalError;
2006 }
2007 }
2008
2009 if (rc == StorageResultCode.OperationSucceeded) {
2010 mObbState.mounted = mounted = true;
Kenny Roota02b8b02010-08-05 16:14:17 -07002011 }
2012 }
2013
Kenny Root38cf8862010-09-26 14:18:51 -07002014 if (mounted) {
2015 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002016 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002017 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002018
2019 // We didn't succeed, so remove this from the mount-set.
2020 removeObbState(mObbState);
Kenny Root05105f72010-09-22 17:29:43 -07002021
Kenny Root38cf8862010-09-26 14:18:51 -07002022 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002023 }
2024 }
2025
Kenny Roota02b8b02010-08-05 16:14:17 -07002026 public void handleError() {
2027 removeObbState(mObbState);
2028
Kenny Root38cf8862010-09-26 14:18:51 -07002029 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Root02c87302010-07-01 08:10:18 -07002030 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002031
2032 @Override
2033 public String toString() {
2034 StringBuilder sb = new StringBuilder();
2035 sb.append("MountObbAction{");
2036 sb.append("filename=");
2037 sb.append(mObbState.filename);
2038 sb.append(",callerUid=");
2039 sb.append(mObbState.callerUid);
2040 sb.append(",token=");
2041 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
2042 sb.append('}');
2043 return sb.toString();
2044 }
2045 }
2046
2047 class UnmountObbAction extends ObbAction {
2048 private boolean mForceUnmount;
2049
2050 UnmountObbAction(ObbState obbState, boolean force) {
2051 super(obbState);
2052 mForceUnmount = force;
2053 }
2054
Kenny Root38cf8862010-09-26 14:18:51 -07002055 public void handleExecute() throws IOException {
2056 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002057
Kenny Root38cf8862010-09-26 14:18:51 -07002058 /*
2059 * If someone tried to trick us with some weird characters, rectify
2060 * it here.
2061 */
2062 synchronized (mObbMounts) {
2063 if (!isObbMounted(obbInfo.filename)) {
2064 removeObbState(mObbState);
2065 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
2066 return;
2067 }
2068
2069 if (!mObbState.filename.equals(obbInfo.filename)) {
2070 removeObbState(mObbState);
2071 mObbState = mObbPathToStateMap.get(obbInfo.filename);
Kenny Roota02b8b02010-08-05 16:14:17 -07002072 }
2073 }
2074
Kenny Root38cf8862010-09-26 14:18:51 -07002075 boolean unmounted = false;
2076 synchronized (mObbState) {
2077 if (!mObbState.mounted) {
2078 sendNewStatusOrIgnore(obbInfo.filename, Environment.MEDIA_UNMOUNTED);
2079 return;
2080 }
2081
2082 int rc = StorageResultCode.OperationSucceeded;
2083 String cmd = String.format("obb unmount %s%s", mObbState.filename,
2084 (mForceUnmount ? " force" : ""));
2085 try {
2086 mConnector.doCommand(cmd);
2087 } catch (NativeDaemonConnectorException e) {
2088 int code = e.getCode();
2089 if (code == VoldResponseCode.OpFailedStorageBusy) {
2090 rc = StorageResultCode.OperationFailedStorageBusy;
Kenny Root4da02392010-09-30 17:58:41 -07002091 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2092 // If it's not mounted then we've already won.
2093 rc = StorageResultCode.OperationSucceeded;
Kenny Root38cf8862010-09-26 14:18:51 -07002094 } else {
2095 rc = StorageResultCode.OperationFailedInternalError;
2096 }
2097 }
2098
2099 if (rc == StorageResultCode.OperationSucceeded) {
2100 mObbState.mounted = false;
2101 unmounted = true;
2102 }
2103 }
2104
2105 if (unmounted) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002106 removeObbState(mObbState);
2107
Kenny Root38cf8862010-09-26 14:18:51 -07002108 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002109 } else {
Kenny Root38cf8862010-09-26 14:18:51 -07002110 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_MOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002111 }
2112 }
2113
2114 public void handleError() {
2115 removeObbState(mObbState);
2116
Kenny Root38cf8862010-09-26 14:18:51 -07002117 sendNewStatusOrIgnore(mObbState.filename, Environment.MEDIA_BAD_REMOVAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002118 }
2119
2120 @Override
2121 public String toString() {
2122 StringBuilder sb = new StringBuilder();
2123 sb.append("UnmountObbAction{");
2124 sb.append("filename=");
2125 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2126 sb.append(",force=");
2127 sb.append(mForceUnmount);
2128 sb.append(",callerUid=");
2129 sb.append(mObbState.callerUid);
2130 sb.append(",token=");
2131 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002132 sb.append(",binder=");
2133 sb.append(mObbState.getBinder().toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002134 sb.append('}');
2135 return sb.toString();
2136 }
Kenny Root02c87302010-07-01 08:10:18 -07002137 }
Kenny Root38cf8862010-09-26 14:18:51 -07002138
2139 @Override
2140 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2141 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2142 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2143 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2144 + " without permission " + android.Manifest.permission.DUMP);
2145 return;
2146 }
2147
2148 pw.println(" mObbMounts:");
2149
2150 synchronized (mObbMounts) {
2151 final Collection<List<ObbState>> obbStateLists = mObbMounts.values();
2152
2153 for (final List<ObbState> obbStates : obbStateLists) {
2154 for (final ObbState obbState : obbStates) {
2155 pw.print(" "); pw.println(obbState.toString());
2156 }
2157 }
2158 }
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160}
2161