blob: fe2f8d8896a2eca3ee6afe07dda3f0cb039bf782 [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
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040040import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070041import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080043import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080044import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080045import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.IMountService;
49import android.os.storage.IMountServiceListener;
50import android.os.storage.IMountShutdownObserver;
51import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070052import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070053import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070054import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060055import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070057import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.Xml;
59
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070060import com.android.internal.app.IMediaContainerService;
61import com.android.internal.util.XmlUtils;
62import com.android.server.NativeDaemonConnector.Command;
63import com.android.server.am.ActivityManagerService;
64import com.android.server.pm.PackageManagerService;
65import com.android.server.pm.UserManagerService;
66import com.google.android.collect.Lists;
67import com.google.android.collect.Maps;
68
Mike Lockwood2f6a3882011-05-09 19:08:06 -070069import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070070
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070071import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070072import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070073import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070074import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070075import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070076import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070077import java.security.spec.InvalidKeySpecException;
78import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080079import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070080import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080081import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070082import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070083import java.util.LinkedList;
84import java.util.List;
85import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070086import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070087import java.util.concurrent.CountDownLatch;
88import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Kenny Root3b1abba2010-10-13 15:00:07 -070090import javax.crypto.SecretKey;
91import javax.crypto.SecretKeyFactory;
92import javax.crypto.spec.PBEKeySpec;
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094/**
San Mehatb1043402010-02-05 08:26:50 -080095 * MountService implements back-end services for platform storage
96 * management.
97 * @hide - Applications should use android.os.storage.StorageManager
98 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700100class MountService extends IMountService.Stub
101 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600102
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700103 // TODO: listen for user creation/deletion
104
105 private static final boolean LOCAL_LOGD = true;
106 private static final boolean DEBUG_UNMOUNT = true;
107 private static final boolean DEBUG_EVENTS = true;
Kenny Rootb7db2722011-01-25 16:39:35 -0800108 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700109
Kenny Root07714d42011-08-17 17:49:28 -0700110 // Disable this since it messes up long-running cryptfs operations.
111 private static final boolean WATCHDOG_ENABLE = false;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private static final String TAG = "MountService";
114
Kenny Root305bcbf2010-09-03 07:56:38 -0700115 private static final String VOLD_TAG = "VoldConnector";
116
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700117 /** Maximum number of ASEC containers allowed to be mounted. */
118 private static final int MAX_CONTAINERS = 250;
119
San Mehat4270e1e2010-01-29 05:32:19 -0800120 /*
121 * Internal vold volume state constants
122 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800123 class VolumeState {
124 public static final int Init = -1;
125 public static final int NoMedia = 0;
126 public static final int Idle = 1;
127 public static final int Pending = 2;
128 public static final int Checking = 3;
129 public static final int Mounted = 4;
130 public static final int Unmounting = 5;
131 public static final int Formatting = 6;
132 public static final int Shared = 7;
133 public static final int SharedMnt = 8;
134 }
135
San Mehat4270e1e2010-01-29 05:32:19 -0800136 /*
137 * Internal vold response code constants
138 */
San Mehat22dd86e2010-01-12 12:21:18 -0800139 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800140 /*
141 * 100 series - Requestion action was initiated; expect another reply
142 * before proceeding with a new command.
143 */
San Mehat22dd86e2010-01-12 12:21:18 -0800144 public static final int VolumeListResult = 110;
145 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800146 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800147
San Mehat4270e1e2010-01-29 05:32:19 -0800148 /*
149 * 200 series - Requestion action has been successfully completed.
150 */
151 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800152 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800153 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800154
San Mehat4270e1e2010-01-29 05:32:19 -0800155 /*
156 * 400 series - Command was accepted, but the requested action
157 * did not take place.
158 */
159 public static final int OpFailedNoMedia = 401;
160 public static final int OpFailedMediaBlank = 402;
161 public static final int OpFailedMediaCorrupt = 403;
162 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800163 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700164 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800165
166 /*
167 * 600 series - Unsolicited broadcasts.
168 */
San Mehat22dd86e2010-01-12 12:21:18 -0800169 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800170 public static final int VolumeDiskInserted = 630;
171 public static final int VolumeDiskRemoved = 631;
172 public static final int VolumeBadRemoval = 632;
173 }
174
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700175 private Context mContext;
176 private NativeDaemonConnector mConnector;
177
178 private final Object mVolumesLock = new Object();
179
180 /** When defined, base template for user-specific {@link StorageVolume}. */
181 private StorageVolume mEmulatedTemplate;
182
183 // @GuardedBy("mVolumesLock")
184 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
185 /** Map from path to {@link StorageVolume} */
186 // @GuardedBy("mVolumesLock")
187 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
188 /** Map from path to state */
189 // @GuardedBy("mVolumesLock")
190 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
191
192 private volatile boolean mSystemReady = false;
193
San Mehat4270e1e2010-01-29 05:32:19 -0800194 private PackageManagerService mPms;
195 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700196 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800197 // Used as a lock for methods that register/unregister listeners.
198 final private ArrayList<MountServiceBinderListener> mListeners =
199 new ArrayList<MountServiceBinderListener>();
Kenny Root51a573c2012-05-17 13:30:28 -0700200 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
201 private CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800202 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800203
San Mehat6cdd9c02010-02-09 14:45:20 -0800204 /**
205 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800206 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800207 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800208 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800209
Kenny Root02c87302010-07-01 08:10:18 -0700210 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700211 * The size of the crypto algorithm key in bits for OBB files. Currently
212 * Twofish is used which takes 128-bit keys.
213 */
214 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
215
216 /**
217 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
218 * 1024 is reasonably secure and not too slow.
219 */
220 private static final int PBKDF2_HASH_ROUNDS = 1024;
221
222 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700223 * Mounted OBB tracking information. Used to track the current state of all
224 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700225 */
Kenny Root735de3b2010-09-30 14:11:39 -0700226 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Kenny Roota02b8b02010-08-05 16:14:17 -0700227 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
228
229 class ObbState implements IBinder.DeathRecipient {
Kenny Rootaf9d6672010-10-08 09:21:39 -0700230 public ObbState(String filename, int callerUid, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -0700231 throws RemoteException {
Kenny Roota02b8b02010-08-05 16:14:17 -0700232 this.filename = filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700233 this.callerUid = callerUid;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700234 this.token = token;
235 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700236 }
237
238 // OBB source filename
Kenny Rootaf9d6672010-10-08 09:21:39 -0700239 String filename;
Kenny Roota02b8b02010-08-05 16:14:17 -0700240
241 // Binder.callingUid()
Kenny Root05105f72010-09-22 17:29:43 -0700242 final public int callerUid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700243
Kenny Rootaf9d6672010-10-08 09:21:39 -0700244 // Token of remote Binder caller
245 final IObbActionListener token;
246
247 // Identifier to pass back to the token
248 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700249
Kenny Root735de3b2010-09-30 14:11:39 -0700250 public IBinder getBinder() {
251 return token.asBinder();
252 }
253
Kenny Roota02b8b02010-08-05 16:14:17 -0700254 @Override
255 public void binderDied() {
256 ObbAction action = new UnmountObbAction(this, true);
257 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700258 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700259
Kenny Root5919ac62010-10-05 09:49:40 -0700260 public void link() throws RemoteException {
261 getBinder().linkToDeath(this, 0);
262 }
263
264 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700265 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700266 }
Kenny Root38cf8862010-09-26 14:18:51 -0700267
268 @Override
269 public String toString() {
270 StringBuilder sb = new StringBuilder("ObbState{");
271 sb.append("filename=");
272 sb.append(filename);
273 sb.append(",token=");
274 sb.append(token.toString());
275 sb.append(",callerUid=");
276 sb.append(callerUid);
Kenny Root38cf8862010-09-26 14:18:51 -0700277 sb.append('}');
278 return sb.toString();
279 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700280 }
281
282 // OBB Action Handler
283 final private ObbActionHandler mObbActionHandler;
284
285 // OBB action handler messages
286 private static final int OBB_RUN_ACTION = 1;
287 private static final int OBB_MCS_BOUND = 2;
288 private static final int OBB_MCS_UNBIND = 3;
289 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700290 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700291
292 /*
293 * Default Container Service information
294 */
295 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
296 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
297
298 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
299
300 class DefaultContainerConnection implements ServiceConnection {
301 public void onServiceConnected(ComponentName name, IBinder service) {
302 if (DEBUG_OBB)
303 Slog.i(TAG, "onServiceConnected");
304 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
305 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
306 }
307
308 public void onServiceDisconnected(ComponentName name) {
309 if (DEBUG_OBB)
310 Slog.i(TAG, "onServiceDisconnected");
311 }
312 };
313
314 // Used in the ObbActionHandler
315 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700316
317 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800318 private static final int H_UNMOUNT_PM_UPDATE = 1;
319 private static final int H_UNMOUNT_PM_DONE = 2;
320 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700321 private static final int H_SYSTEM_READY = 4;
322
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800323 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
324 private static final int MAX_UNMOUNT_RETRIES = 4;
325
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800326 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700327 final String path;
328 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700329 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800330 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800331
Ben Komalo13c71972011-09-07 16:35:56 -0700332 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800333 retries = 0;
334 this.path = path;
335 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700336 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800337 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800338
339 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700340 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700341 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800342 }
343 }
344
345 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700346 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800347
348 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700349 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800350 this.method = method;
351 }
352
353 @Override
354 void handleFinished() {
355 super.handleFinished();
356 doShareUnshareVolume(path, method, true);
357 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800358 }
359
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800360 class ShutdownCallBack extends UnmountCallBack {
361 IMountShutdownObserver observer;
362 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700363 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800364 this.observer = observer;
365 }
366
367 @Override
368 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700369 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800370 if (observer != null) {
371 try {
372 observer.onShutDownComplete(ret);
373 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700374 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800375 }
376 }
377 }
378 }
379
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400380 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800381 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700382 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400384 MountServiceHandler(Looper l) {
385 super(l);
386 }
387
Jason parks5af0b912010-11-29 09:05:25 -0600388 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800389 public void handleMessage(Message msg) {
390 switch (msg.what) {
391 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700392 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800393 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
394 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700395 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800396 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700397 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700398 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700399 mUpdatingStatus = true;
400 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 }
402 break;
403 }
404 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700405 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700406 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700407 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800408 int size = mForceUnmounts.size();
409 int sizeArr[] = new int[size];
410 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700411 // Kill processes holding references first
412 ActivityManagerService ams = (ActivityManagerService)
413 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800414 for (int i = 0; i < size; i++) {
415 UnmountCallBack ucb = mForceUnmounts.get(i);
416 String path = ucb.path;
417 boolean done = false;
418 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800419 done = true;
420 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800421 int pids[] = getStorageUsers(path);
422 if (pids == null || pids.length == 0) {
423 done = true;
424 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800425 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800426 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700427 // Confirm if file references have been freed.
428 pids = getStorageUsers(path);
429 if (pids == null || pids.length == 0) {
430 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800431 }
432 }
433 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700434 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
435 // Retry again
436 Slog.i(TAG, "Retrying to kill storage users again");
437 mHandler.sendMessageDelayed(
438 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
439 ucb.retries++),
440 RETRY_UNMOUNT_DELAY);
441 } else {
442 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
443 Slog.i(TAG, "Failed to unmount media inspite of " +
444 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
445 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800446 sizeArr[sizeArrN++] = i;
447 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
448 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800449 }
450 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800451 // Remove already processed elements from list.
452 for (int i = (sizeArrN-1); i >= 0; i--) {
453 mForceUnmounts.remove(sizeArr[i]);
454 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800455 break;
456 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700457 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700458 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800459 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800460 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800461 break;
462 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700463 case H_SYSTEM_READY: {
464 try {
465 handleSystemReady();
466 } catch (Exception ex) {
467 Slog.e(TAG, "Boot-time mount exception", ex);
468 }
469 break;
470 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800471 }
472 }
473 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700474
475 private final HandlerThread mHandlerThread;
476 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800477
Kenny Root51a573c2012-05-17 13:30:28 -0700478 void waitForAsecScan() {
479 waitForLatch(mAsecsScanned);
480 }
481
San Mehat207e5382010-02-04 20:46:54 -0800482 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700483 waitForLatch(mConnectedSignal);
484 }
485
486 private void waitForLatch(CountDownLatch latch) {
487 if (latch == null) {
488 return;
489 }
490
491 for (;;) {
492 try {
493 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800494 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700495 } else {
496 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
497 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800498 }
Kenny Root51a573c2012-05-17 13:30:28 -0700499 } catch (InterruptedException e) {
500 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800501 }
San Mehat207e5382010-02-04 20:46:54 -0800502 }
San Mehat1f6301e2010-01-07 22:40:27 -0800503 }
Kenny Root02c87302010-07-01 08:10:18 -0700504
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700505 private void handleSystemReady() {
506 // Snapshot current volume states since it's not safe to call into vold
507 // while holding locks.
508 final HashMap<String, String> snapshot;
509 synchronized (mVolumesLock) {
510 snapshot = new HashMap<String, String>(mVolumeStates);
511 }
512
513 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
514 final String path = entry.getKey();
515 final String state = entry.getValue();
516
517 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
518 int rc = doMountVolume(path);
519 if (rc != StorageResultCode.OperationSucceeded) {
520 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
521 rc));
522 }
523 } else if (state.equals(Environment.MEDIA_SHARED)) {
524 /*
525 * Bootstrap UMS enabled state since vold indicates
526 * the volume is shared (runtime restart while ums enabled)
527 */
528 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
529 VolumeState.Shared);
530 }
531 }
532
533 // Push mounted state for all emulated storage
534 synchronized (mVolumesLock) {
535 for (StorageVolume volume : mVolumes) {
536 if (volume.isEmulated()) {
537 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
538 }
539 }
540 }
541
542 /*
543 * If UMS was connected on boot, send the connected event
544 * now that we're up.
545 */
546 if (mSendUmsConnectedOnBoot) {
547 sendUmsIntent(true);
548 mSendUmsConnectedOnBoot = false;
549 }
550 }
551
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700552 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
553 @Override
554 public void onReceive(Context context, Intent intent) {
555 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
556 if (userId == -1) return;
557 final UserHandle user = new UserHandle(userId);
558
559 final String action = intent.getAction();
560 if (Intent.ACTION_USER_ADDED.equals(action)) {
561 synchronized (mVolumesLock) {
562 createEmulatedVolumeForUserLocked(user);
563 }
564
565 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
566 synchronized (mVolumesLock) {
567 final List<StorageVolume> toRemove = Lists.newArrayList();
568 for (StorageVolume volume : mVolumes) {
569 if (user.equals(volume.getOwner())) {
570 toRemove.add(volume);
571 }
572 }
573 for (StorageVolume volume : toRemove) {
574 removeVolumeLocked(volume);
575 }
576 }
577 }
578 }
579 };
580
581 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
582 @Override
583 public void onReceive(Context context, Intent intent) {
584 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
585 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
586 notifyShareAvailabilityChange(available);
587 }
588 };
589
San Mehat4270e1e2010-01-29 05:32:19 -0800590 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
591 final IMountServiceListener mListener;
592
593 MountServiceBinderListener(IMountServiceListener listener) {
594 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700595
San Mehat91c77612010-01-07 10:39:41 -0800596 }
597
San Mehat4270e1e2010-01-29 05:32:19 -0800598 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700599 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700600 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800601 mListeners.remove(this);
602 mListener.asBinder().unlinkToDeath(this, 0);
603 }
604 }
605 }
606
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800607 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800608 // TODO: Add support for multiple share methods
609 if (!method.equals("ums")) {
610 throw new IllegalArgumentException(String.format("Method %s not supported", method));
611 }
612
San Mehat4270e1e2010-01-29 05:32:19 -0800613 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800614 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800615 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700616 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800617 }
San Mehat4270e1e2010-01-29 05:32:19 -0800618 }
619
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700620 private void updatePublicVolumeState(StorageVolume volume, String state) {
621 final String path = volume.getPath();
622 final String oldState;
623 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400624 oldState = mVolumeStates.put(path, state);
625 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700626
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400627 if (state.equals(oldState)) {
628 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
629 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800630 return;
631 }
San Mehatb1043402010-02-05 08:26:50 -0800632
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400633 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700634
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700635 // Tell PackageManager about changes to primary volume state, but only
636 // when not emulated.
637 if (volume.isPrimary() && !volume.isEmulated()) {
638 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
639 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400640
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700641 /*
642 * Some OBBs might have been unmounted when this volume was
643 * unmounted, so send a message to the handler to let it know to
644 * remove those from the list of mounted OBBS.
645 */
646 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
647 OBB_FLUSH_MOUNT_STATE, path));
648 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
649 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400650 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800651 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700652
San Mehat4270e1e2010-01-29 05:32:19 -0800653 synchronized (mListeners) {
654 for (int i = mListeners.size() -1; i >= 0; i--) {
655 MountServiceBinderListener bl = mListeners.get(i);
656 try {
San Mehatb1043402010-02-05 08:26:50 -0800657 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800658 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700659 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800660 mListeners.remove(i);
661 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700662 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800663 }
664 }
665 }
666 }
667
668 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800669 * Callback from NativeDaemonConnector
670 */
671 public void onDaemonConnected() {
672 /*
673 * Since we'll be calling back into the NativeDaemonConnector,
674 * we need to do our work in a new thread.
675 */
Kenny Root51a573c2012-05-17 13:30:28 -0700676 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600677 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800678 public void run() {
679 /**
680 * Determine media state and UMS detection status
681 */
San Mehat4270e1e2010-01-29 05:32:19 -0800682 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800683 final String[] vols = NativeDaemonEvent.filterMessageList(
684 mConnector.executeForList("volume", "list"),
685 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800686 for (String volstr : vols) {
687 String[] tok = volstr.split(" ");
688 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400689 String path = tok[1];
690 String state = Environment.MEDIA_REMOVED;
691
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700692 final StorageVolume volume;
693 synchronized (mVolumesLock) {
694 volume = mVolumesByPath.get(path);
695 }
696
San Mehat4270e1e2010-01-29 05:32:19 -0800697 int st = Integer.parseInt(tok[2]);
698 if (st == VolumeState.NoMedia) {
699 state = Environment.MEDIA_REMOVED;
700 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800701 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800702 } else if (st == VolumeState.Mounted) {
703 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700704 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800705 } else if (st == VolumeState.Shared) {
706 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700707 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800708 } else {
709 throw new Exception(String.format("Unexpected state %d", st));
710 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400711
712 if (state != null) {
713 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700714 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400715 }
San Mehat4270e1e2010-01-29 05:32:19 -0800716 }
717 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700718 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700719 final StorageVolume primary = getPrimaryPhysicalVolume();
720 if (primary != null) {
721 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
722 }
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724
San Mehat207e5382010-02-04 20:46:54 -0800725 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600726 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800727 * the hounds!
728 */
Kenny Root51a573c2012-05-17 13:30:28 -0700729 mConnectedSignal.countDown();
730 mConnectedSignal = null;
731
732 // Let package manager load internal ASECs.
733 mPms.scanAvailableAsecs();
734
735 // Notify people waiting for ASECs to be scanned that it's done.
736 mAsecsScanned.countDown();
737 mAsecsScanned = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800738 }
739 }.start();
740 }
741
742 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800743 * Callback from NativeDaemonConnector
744 */
745 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800746 if (DEBUG_EVENTS) {
747 StringBuilder builder = new StringBuilder();
748 builder.append("onEvent::");
749 builder.append(" raw= " + raw);
750 if (cooked != null) {
751 builder.append(" cooked = " );
752 for (String str : cooked) {
753 builder.append(" " + str);
754 }
755 }
San Mehata5078592010-03-25 09:36:54 -0700756 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800757 }
San Mehat4270e1e2010-01-29 05:32:19 -0800758 if (code == VoldResponseCode.VolumeStateChange) {
759 /*
760 * One of the volumes we're managing has changed state.
761 * Format: "NNN Volume <label> <path> state changed
762 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
763 */
764 notifyVolumeStateChange(
765 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
766 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800767 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
768 (code == VoldResponseCode.VolumeDiskRemoved) ||
769 (code == VoldResponseCode.VolumeBadRemoval)) {
770 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
771 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
772 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400773 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800774 final String label = cooked[2];
775 final String path = cooked[3];
776 int major = -1;
777 int minor = -1;
778
779 try {
780 String devComp = cooked[6].substring(1, cooked[6].length() -1);
781 String[] devTok = devComp.split(":");
782 major = Integer.parseInt(devTok[0]);
783 minor = Integer.parseInt(devTok[1]);
784 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700785 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800786 }
787
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700788 final StorageVolume volume;
789 final String state;
790 synchronized (mVolumesLock) {
791 volume = mVolumesByPath.get(path);
792 state = mVolumeStates.get(path);
793 }
794
San Mehat4270e1e2010-01-29 05:32:19 -0800795 if (code == VoldResponseCode.VolumeDiskInserted) {
796 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600797 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800798 public void run() {
799 try {
800 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800801 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700802 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800803 }
804 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700805 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800806 }
807 }
808 }.start();
809 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
810 /*
811 * This event gets trumped if we're already in BAD_REMOVAL state
812 */
813 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
814 return true;
815 }
816 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700817 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700818 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
819 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800820
San Mehata5078592010-03-25 09:36:54 -0700821 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700822 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400823 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800824 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700825 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800826 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700827 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400828 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800829
San Mehata5078592010-03-25 09:36:54 -0700830 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700831 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400832 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800833 } else {
San Mehata5078592010-03-25 09:36:54 -0700834 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800835 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400836
837 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700838 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400839 }
San Mehat4270e1e2010-01-29 05:32:19 -0800840 } else {
841 return false;
842 }
843
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400844 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800845 }
846
San Mehat207e5382010-02-04 20:46:54 -0800847 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700848 final StorageVolume volume;
849 final String state;
850 synchronized (mVolumesLock) {
851 volume = mVolumesByPath.get(path);
852 state = getVolumeState(path);
853 }
854
855 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800856
Mike Lockwooda5250c92011-05-23 13:44:04 -0400857 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800858
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500859 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700860 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700861 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500862 }
863
San Mehat4270e1e2010-01-29 05:32:19 -0800864 if (newState == VolumeState.Init) {
865 } else if (newState == VolumeState.NoMedia) {
866 // NoMedia is handled via Disk Remove events
867 } else if (newState == VolumeState.Idle) {
868 /*
869 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
870 * if we're in the process of enabling UMS
871 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700872 if (!state.equals(
873 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
874 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800875 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700876 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700877 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400878 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800879 }
880 } else if (newState == VolumeState.Pending) {
881 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700882 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700883 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400884 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800885 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700886 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700887 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400888 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800889 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400890 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800891 } else if (newState == VolumeState.Formatting) {
892 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700893 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800894 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700895 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
896 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800897
San Mehata5078592010-03-25 09:36:54 -0700898 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700899 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400900 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700901 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800902 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700903 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800904 return;
905 } else {
San Mehata5078592010-03-25 09:36:54 -0700906 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800907 }
908
Mike Lockwooda5250c92011-05-23 13:44:04 -0400909 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700910 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800911 }
912 }
913
San Mehat207e5382010-02-04 20:46:54 -0800914 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800915 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800916
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700917 final StorageVolume volume;
918 synchronized (mVolumesLock) {
919 volume = mVolumesByPath.get(path);
920 }
921
San Mehata5078592010-03-25 09:36:54 -0700922 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800923 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800924 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800925 } catch (NativeDaemonConnectorException e) {
926 /*
927 * Mount failed for some reason
928 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400929 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800930 int code = e.getCode();
931 if (code == VoldResponseCode.OpFailedNoMedia) {
932 /*
933 * Attempt to mount but no media inserted
934 */
San Mehatb1043402010-02-05 08:26:50 -0800935 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800936 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700937 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800938 /*
939 * Media is blank or does not contain a supported filesystem
940 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700941 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400942 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800943 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800944 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700945 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800946 /*
947 * Volume consistency check failed
948 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700949 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400950 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800951 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800952 } else {
San Mehatb1043402010-02-05 08:26:50 -0800953 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800954 }
955
956 /*
957 * Send broadcast intent (if required for the failure)
958 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400959 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700960 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800961 }
962 }
963
964 return rc;
965 }
966
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800967 /*
968 * If force is not set, we do not unmount if there are
969 * processes holding references to the volume about to be unmounted.
970 * If force is set, all the processes holding references need to be
971 * killed via the ActivityManager before actually unmounting the volume.
972 * This might even take a while and might be retried after timed delays
973 * to make sure we dont end up in an instable state and kill some core
974 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700975 * If removeEncryption is set, force is implied, and the system will remove any encryption
976 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800977 */
Ben Komalo13c71972011-09-07 16:35:56 -0700978 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800979 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800980 return VoldResponseCode.OpFailedVolNotMounted;
981 }
Kenny Rootaa485402010-09-14 14:49:41 -0700982
983 /*
984 * Force a GC to make sure AssetManagers in other threads of the
985 * system_server are cleaned up. We have to do this since AssetManager
986 * instances are kept as a WeakReference and it's possible we have files
987 * open on the external storage.
988 */
989 Runtime.getRuntime().gc();
990
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800991 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700992 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800993 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800994 final Command cmd = new Command("volume", "unmount", path);
995 if (removeEncryption) {
996 cmd.appendArg("force_and_revert");
997 } else if (force) {
998 cmd.appendArg("force");
999 }
1000 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001001 // We unmounted the volume. None of the asec containers are available now.
1002 synchronized (mAsecMountSet) {
1003 mAsecMountSet.clear();
1004 }
San Mehatb1043402010-02-05 08:26:50 -08001005 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001006 } catch (NativeDaemonConnectorException e) {
1007 // Don't worry about mismatch in PackageManager since the
1008 // call back will handle the status changes any way.
1009 int code = e.getCode();
1010 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001011 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001012 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1013 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001014 } else {
San Mehatb1043402010-02-05 08:26:50 -08001015 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001016 }
1017 }
1018 }
1019
1020 private int doFormatVolume(String path) {
1021 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001022 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001023 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001024 } catch (NativeDaemonConnectorException e) {
1025 int code = e.getCode();
1026 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001027 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001028 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001029 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001030 } else {
San Mehatb1043402010-02-05 08:26:50 -08001031 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001032 }
1033 }
1034 }
1035
San Mehatb1043402010-02-05 08:26:50 -08001036 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001037 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001038 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001039 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001040 } catch (NativeDaemonConnectorException ex) {
1041 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1042 return false;
1043 }
San Mehatb1043402010-02-05 08:26:50 -08001044
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001045 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1046 return event.getMessage().endsWith("enabled");
1047 } else {
1048 return false;
San Mehatb1043402010-02-05 08:26:50 -08001049 }
San Mehatb1043402010-02-05 08:26:50 -08001050 }
1051
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001052 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001053 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001054 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001055 for (int i = mListeners.size() -1; i >= 0; i--) {
1056 MountServiceBinderListener bl = mListeners.get(i);
1057 try {
San Mehatb1043402010-02-05 08:26:50 -08001058 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001059 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001060 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001061 mListeners.remove(i);
1062 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001063 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001064 }
1065 }
1066 }
1067
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001068 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001069 sendUmsIntent(avail);
1070 } else {
1071 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001072 }
San Mehat2fe718a2010-03-11 12:01:49 -08001073
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001074 final StorageVolume primary = getPrimaryPhysicalVolume();
1075 if (avail == false && primary != null
1076 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1077 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001078 /*
1079 * USB mass storage disconnected while enabled
1080 */
1081 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001082 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001083 public void run() {
1084 try {
1085 int rc;
San Mehata5078592010-03-25 09:36:54 -07001086 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001087 doShareUnshareVolume(path, "ums", false);
1088 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001089 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001090 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1091 path, rc));
1092 }
1093 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001094 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001095 }
1096 }
1097 }.start();
1098 }
San Mehat4270e1e2010-01-29 05:32:19 -08001099 }
1100
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001101 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1102 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1103 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1104 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1105 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001106 }
1107
San Mehat6a965af22010-02-24 17:47:30 -08001108 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001109 mContext.sendBroadcastAsUser(
1110 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1111 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001112 }
1113
San Mehat207e5382010-02-04 20:46:54 -08001114 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001115 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1116 throw new SecurityException(String.format("Requires %s permission", perm));
1117 }
1118 }
1119
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001120 // Storage list XML tags
1121 private static final String TAG_STORAGE_LIST = "StorageList";
1122 private static final String TAG_STORAGE = "storage";
1123
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001124 private void readStorageListLocked() {
1125 mVolumes.clear();
1126 mVolumeStates.clear();
1127
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001128 Resources resources = mContext.getResources();
1129
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001130 int id = com.android.internal.R.xml.storage_list;
1131 XmlResourceParser parser = resources.getXml(id);
1132 AttributeSet attrs = Xml.asAttributeSet(parser);
1133
1134 try {
1135 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1136 while (true) {
1137 XmlUtils.nextElement(parser);
1138
1139 String element = parser.getName();
1140 if (element == null) break;
1141
1142 if (TAG_STORAGE.equals(element)) {
1143 TypedArray a = resources.obtainAttributes(attrs,
1144 com.android.internal.R.styleable.Storage);
1145
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001146 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001147 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001148 int descriptionId = a.getResourceId(
1149 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001150 CharSequence description = a.getText(
1151 com.android.internal.R.styleable.Storage_storageDescription);
1152 boolean primary = a.getBoolean(
1153 com.android.internal.R.styleable.Storage_primary, false);
1154 boolean removable = a.getBoolean(
1155 com.android.internal.R.styleable.Storage_removable, false);
1156 boolean emulated = a.getBoolean(
1157 com.android.internal.R.styleable.Storage_emulated, false);
1158 int mtpReserve = a.getInt(
1159 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001160 boolean allowMassStorage = a.getBoolean(
1161 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001162 // resource parser does not support longs, so XML value is in megabytes
1163 long maxFileSize = a.getInt(
1164 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001165
1166 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1167 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001168 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001169 " allowMassStorage: " + allowMassStorage +
1170 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001171
1172 if (emulated) {
1173 // For devices with emulated storage, we create separate
1174 // volumes for each known user.
1175 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1176 true, mtpReserve, false, maxFileSize, null);
1177
1178 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001179 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001180 createEmulatedVolumeForUserLocked(user.getUserHandle());
1181 }
1182
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001183 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001184 if (path == null || description == null) {
1185 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001186 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001187 final StorageVolume volume = new StorageVolume(new File(path),
1188 descriptionId, primary, removable, emulated, mtpReserve,
1189 allowMassStorage, maxFileSize, null);
1190 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001191 }
1192 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001193
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001194 a.recycle();
1195 }
1196 }
1197 } catch (XmlPullParserException e) {
1198 throw new RuntimeException(e);
1199 } catch (IOException e) {
1200 throw new RuntimeException(e);
1201 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001202 // Compute storage ID for each physical volume; emulated storage is
1203 // always 0 when defined.
1204 int index = isExternalStorageEmulated() ? 1 : 0;
1205 for (StorageVolume volume : mVolumes) {
1206 if (!volume.isEmulated()) {
1207 volume.setStorageId(index++);
1208 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001209 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001210 parser.close();
1211 }
1212 }
1213
San Mehat4270e1e2010-01-29 05:32:19 -08001214 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001215 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1216 * using {@link #mEmulatedTemplate} as template.
1217 */
1218 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1219 if (mEmulatedTemplate == null) {
1220 throw new IllegalStateException("Missing emulated volume multi-user template");
1221 }
1222
1223 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1224 final File path = userEnv.getExternalStorageDirectory();
1225 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1226 volume.setStorageId(0);
1227 addVolumeLocked(volume);
1228
1229 if (mSystemReady) {
1230 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1231 } else {
1232 // Place stub status for early callers to find
1233 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1234 }
1235 }
1236
1237 private void addVolumeLocked(StorageVolume volume) {
1238 Slog.d(TAG, "addVolumeLocked() " + volume);
1239 mVolumes.add(volume);
1240 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1241 if (existing != null) {
1242 throw new IllegalStateException(
1243 "Volume at " + volume.getPath() + " already exists: " + existing);
1244 }
1245 }
1246
1247 private void removeVolumeLocked(StorageVolume volume) {
1248 Slog.d(TAG, "removeVolumeLocked() " + volume);
1249 mVolumes.remove(volume);
1250 mVolumesByPath.remove(volume.getPath());
1251 mVolumeStates.remove(volume.getPath());
1252 }
1253
1254 private StorageVolume getPrimaryPhysicalVolume() {
1255 synchronized (mVolumesLock) {
1256 for (StorageVolume volume : mVolumes) {
1257 if (volume.isPrimary() && !volume.isEmulated()) {
1258 return volume;
1259 }
1260 }
1261 }
1262 return null;
1263 }
1264
1265 /**
San Mehat207e5382010-02-04 20:46:54 -08001266 * Constructs a new MountService instance
1267 *
1268 * @param context Binder context for this service
1269 */
1270 public MountService(Context context) {
1271 mContext = context;
1272
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001273 synchronized (mVolumesLock) {
1274 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001275 }
1276
San Mehat207e5382010-02-04 20:46:54 -08001277 // XXX: This will go away soon in favor of IMountServiceObserver
1278 mPms = (PackageManagerService) ServiceManager.getService("package");
1279
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001280 mHandlerThread = new HandlerThread("MountService");
1281 mHandlerThread.start();
1282 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1283
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001284 // Watch for user changes
1285 final IntentFilter userFilter = new IntentFilter();
1286 userFilter.addAction(Intent.ACTION_USER_ADDED);
1287 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1288 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1289
1290 // Watch for USB changes on primary volume
1291 final StorageVolume primary = getPrimaryPhysicalVolume();
1292 if (primary != null && primary.allowMassStorage()) {
1293 mContext.registerReceiver(
1294 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1295 }
1296
Kenny Roota02b8b02010-08-05 16:14:17 -07001297 // Add OBB Action Handler to MountService thread.
1298 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1299
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001300 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001301 * Create the connection to vold with a maximum queue of twice the
1302 * amount of containers we'd ever expect to have. This keeps an
1303 * "asec list" from blocking a thread repeatedly.
1304 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001305 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001306
Kenny Root305bcbf2010-09-03 07:56:38 -07001307 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001308 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001309
Kenny Root07714d42011-08-17 17:49:28 -07001310 // Add ourself to the Watchdog monitors if enabled.
1311 if (WATCHDOG_ENABLE) {
1312 Watchdog.getInstance().addMonitor(this);
1313 }
San Mehat207e5382010-02-04 20:46:54 -08001314 }
1315
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001316 public void systemReady() {
1317 mSystemReady = true;
1318 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1319 }
1320
San Mehat207e5382010-02-04 20:46:54 -08001321 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001322 * Exposed API calls below here
1323 */
1324
1325 public void registerListener(IMountServiceListener listener) {
1326 synchronized (mListeners) {
1327 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1328 try {
1329 listener.asBinder().linkToDeath(bl, 0);
1330 mListeners.add(bl);
1331 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001332 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001333 }
1334 }
1335 }
1336
1337 public void unregisterListener(IMountServiceListener listener) {
1338 synchronized (mListeners) {
1339 for(MountServiceBinderListener bl : mListeners) {
1340 if (bl.mListener == listener) {
1341 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001342 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001343 return;
1344 }
1345 }
1346 }
1347 }
1348
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001349 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001350 validatePermission(android.Manifest.permission.SHUTDOWN);
1351
San Mehata5078592010-03-25 09:36:54 -07001352 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001353 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001354 for (String path : mVolumeStates.keySet()) {
1355 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001356
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001357 if (state.equals(Environment.MEDIA_SHARED)) {
1358 /*
1359 * If the media is currently shared, unshare it.
1360 * XXX: This is still dangerous!. We should not
1361 * be rebooting at *all* if UMS is enabled, since
1362 * the UMS host could have dirty FAT cache entries
1363 * yet to flush.
1364 */
1365 setUsbMassStorageEnabled(false);
1366 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1367 /*
1368 * If the media is being checked, then we need to wait for
1369 * it to complete before being able to proceed.
1370 */
1371 // XXX: @hackbod - Should we disable the ANR timer here?
1372 int retries = 30;
1373 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1374 try {
1375 Thread.sleep(1000);
1376 } catch (InterruptedException iex) {
1377 Slog.e(TAG, "Interrupted while waiting for media", iex);
1378 break;
1379 }
1380 state = Environment.getExternalStorageState();
1381 }
1382 if (retries == 0) {
1383 Slog.e(TAG, "Timed out waiting for media to check");
1384 }
San Mehat91c77612010-01-07 10:39:41 -08001385 }
San Mehat91c77612010-01-07 10:39:41 -08001386
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001387 if (state.equals(Environment.MEDIA_MOUNTED)) {
1388 // Post a unmount message.
1389 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1390 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1391 } else if (observer != null) {
1392 /*
1393 * Observer is waiting for onShutDownComplete when we are done.
1394 * Since nothing will be done send notification directly so shutdown
1395 * sequence can continue.
1396 */
1397 try {
1398 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1399 } catch (RemoteException e) {
1400 Slog.w(TAG, "RemoteException when shutting down");
1401 }
1402 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001403 }
San Mehat4270e1e2010-01-29 05:32:19 -08001404 }
1405 }
1406
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001407 private boolean getUmsEnabling() {
1408 synchronized (mListeners) {
1409 return mUmsEnabling;
1410 }
1411 }
1412
1413 private void setUmsEnabling(boolean enable) {
1414 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001415 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001416 }
1417 }
1418
San Mehatb1043402010-02-05 08:26:50 -08001419 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001420 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001421
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001422 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001423 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001424 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001425 synchronized (mListeners) {
1426 return mUmsAvailable;
1427 }
San Mehatb1043402010-02-05 08:26:50 -08001428 }
1429
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001430 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001431 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001432 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001433
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001434 final StorageVolume primary = getPrimaryPhysicalVolume();
1435 if (primary == null) return;
1436
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001437 // TODO: Add support for multiple share methods
1438
1439 /*
1440 * If the volume is mounted and we're enabling then unmount it
1441 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001442 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001443 String vs = getVolumeState(path);
1444 String method = "ums";
1445 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1446 // Override for isUsbMassStorageEnabled()
1447 setUmsEnabling(enable);
1448 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1449 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1450 // Clear override
1451 setUmsEnabling(false);
1452 }
1453 /*
1454 * If we disabled UMS then mount the volume
1455 */
1456 if (!enable) {
1457 doShareUnshareVolume(path, method, enable);
1458 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001459 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001460 " after disabling share method " + method);
1461 /*
1462 * Even though the mount failed, the unshare didn't so don't indicate an error.
1463 * The mountVolume() call will have set the storage state and sent the necessary
1464 * broadcasts.
1465 */
1466 }
1467 }
San Mehatb1043402010-02-05 08:26:50 -08001468 }
1469
1470 public boolean isUsbMassStorageEnabled() {
1471 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001472
1473 final StorageVolume primary = getPrimaryPhysicalVolume();
1474 if (primary != null) {
1475 return doGetVolumeShared(primary.getPath(), "ums");
1476 } else {
1477 return false;
1478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001480
San Mehat7fd0fee2009-12-17 07:12:23 -08001481 /**
1482 * @return state of the volume at the specified mount point
1483 */
San Mehat4270e1e2010-01-29 05:32:19 -08001484 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001485 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001486 String state = mVolumeStates.get(mountPoint);
1487 if (state == null) {
1488 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001489 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1490 state = Environment.MEDIA_REMOVED;
1491 } else {
1492 throw new IllegalArgumentException();
1493 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001494 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001495
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001496 return state;
1497 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001498 }
1499
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001500 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001501 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001502 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001503 }
1504
San Mehat4270e1e2010-01-29 05:32:19 -08001505 public int mountVolume(String path) {
1506 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001507
San Mehat207e5382010-02-04 20:46:54 -08001508 waitForReady();
1509 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511
Ben Komalo13c71972011-09-07 16:35:56 -07001512 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001513 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001514 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001516 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001517 if (DEBUG_UNMOUNT) {
1518 Slog.i(TAG, "Unmounting " + path
1519 + " force = " + force
1520 + " removeEncryption = " + removeEncryption);
1521 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001522 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1523 Environment.MEDIA_REMOVED.equals(volState) ||
1524 Environment.MEDIA_SHARED.equals(volState) ||
1525 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1526 // Media already unmounted or cannot be unmounted.
1527 // TODO return valid return code when adding observer call back.
1528 return;
1529 }
Ben Komalo13c71972011-09-07 16:35:56 -07001530 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001531 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
1533
San Mehat4270e1e2010-01-29 05:32:19 -08001534 public int formatVolume(String path) {
1535 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001536 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001537
San Mehat207e5382010-02-04 20:46:54 -08001538 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001541 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001542 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1543 waitForReady();
1544 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001545 final String[] r = NativeDaemonEvent.filterMessageList(
1546 mConnector.executeForList("storage", "users", path),
1547 VoldResponseCode.StorageUsersListResult);
1548
San Mehatc1b4ce92010-02-16 17:13:03 -08001549 // FMT: <pid> <process name>
1550 int[] data = new int[r.length];
1551 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001552 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001553 try {
1554 data[i] = Integer.parseInt(tok[0]);
1555 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001556 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001557 return new int[0];
1558 }
1559 }
1560 return data;
1561 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001562 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001563 return new int[0];
1564 }
1565 }
1566
San Mehatb1043402010-02-05 08:26:50 -08001567 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001568 final StorageVolume primary = getPrimaryPhysicalVolume();
1569 if (primary != null
1570 && Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()))) {
San Mehata5078592010-03-25 09:36:54 -07001571 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001572 }
1573 }
1574
San Mehat4270e1e2010-01-29 05:32:19 -08001575 public String[] getSecureContainerList() {
1576 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001577 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001578 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001579
San Mehat4270e1e2010-01-29 05:32:19 -08001580 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001581 return NativeDaemonEvent.filterMessageList(
1582 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001583 } catch (NativeDaemonConnectorException e) {
1584 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 }
San Mehat36972292010-01-06 11:06:32 -08001587
Kenny Root6dceb882012-04-12 14:23:49 -07001588 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1589 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001590 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001591 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001592 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001593
San Mehatb1043402010-02-05 08:26:50 -08001594 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001595 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001596 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1597 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001598 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001599 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001600 }
San Mehata181b212010-02-11 06:50:20 -08001601
1602 if (rc == StorageResultCode.OperationSucceeded) {
1603 synchronized (mAsecMountSet) {
1604 mAsecMountSet.add(id);
1605 }
1606 }
San Mehat4270e1e2010-01-29 05:32:19 -08001607 return rc;
San Mehat36972292010-01-06 11:06:32 -08001608 }
1609
San Mehat4270e1e2010-01-29 05:32:19 -08001610 public int finalizeSecureContainer(String id) {
1611 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001612 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001613
San Mehatb1043402010-02-05 08:26:50 -08001614 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001615 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001616 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001617 /*
1618 * Finalization does a remount, so no need
1619 * to update mAsecMountSet
1620 */
San Mehat4270e1e2010-01-29 05:32:19 -08001621 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001622 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001623 }
San Mehat4270e1e2010-01-29 05:32:19 -08001624 return rc;
San Mehat36972292010-01-06 11:06:32 -08001625 }
1626
Kenny Root6dceb882012-04-12 14:23:49 -07001627 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1628 validatePermission(android.Manifest.permission.ASEC_CREATE);
1629 warnOnNotMounted();
1630
1631 int rc = StorageResultCode.OperationSucceeded;
1632 try {
1633 mConnector.execute("asec", "fixperms", id, gid, filename);
1634 /*
1635 * Fix permissions does a remount, so no need to update
1636 * mAsecMountSet
1637 */
1638 } catch (NativeDaemonConnectorException e) {
1639 rc = StorageResultCode.OperationFailedInternalError;
1640 }
1641 return rc;
1642 }
1643
San Mehatd9709982010-02-18 11:43:03 -08001644 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001645 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001646 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001647 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001648
Kenny Rootaa485402010-09-14 14:49:41 -07001649 /*
1650 * Force a GC to make sure AssetManagers in other threads of the
1651 * system_server are cleaned up. We have to do this since AssetManager
1652 * instances are kept as a WeakReference and it's possible we have files
1653 * open on the external storage.
1654 */
1655 Runtime.getRuntime().gc();
1656
San Mehatb1043402010-02-05 08:26:50 -08001657 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001658 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001659 final Command cmd = new Command("asec", "destroy", id);
1660 if (force) {
1661 cmd.appendArg("force");
1662 }
1663 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001664 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001665 int code = e.getCode();
1666 if (code == VoldResponseCode.OpFailedStorageBusy) {
1667 rc = StorageResultCode.OperationFailedStorageBusy;
1668 } else {
1669 rc = StorageResultCode.OperationFailedInternalError;
1670 }
San Mehat02735bc2010-01-26 15:18:08 -08001671 }
San Mehata181b212010-02-11 06:50:20 -08001672
1673 if (rc == StorageResultCode.OperationSucceeded) {
1674 synchronized (mAsecMountSet) {
1675 if (mAsecMountSet.contains(id)) {
1676 mAsecMountSet.remove(id);
1677 }
1678 }
1679 }
1680
San Mehat4270e1e2010-01-29 05:32:19 -08001681 return rc;
San Mehat36972292010-01-06 11:06:32 -08001682 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001683
San Mehat4270e1e2010-01-29 05:32:19 -08001684 public int mountSecureContainer(String id, String key, int ownerUid) {
1685 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001686 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001687 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001688
San Mehata181b212010-02-11 06:50:20 -08001689 synchronized (mAsecMountSet) {
1690 if (mAsecMountSet.contains(id)) {
1691 return StorageResultCode.OperationFailedStorageMounted;
1692 }
1693 }
1694
San Mehatb1043402010-02-05 08:26:50 -08001695 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001696 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001697 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001698 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001699 int code = e.getCode();
1700 if (code != VoldResponseCode.OpFailedStorageBusy) {
1701 rc = StorageResultCode.OperationFailedInternalError;
1702 }
San Mehat02735bc2010-01-26 15:18:08 -08001703 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001704
1705 if (rc == StorageResultCode.OperationSucceeded) {
1706 synchronized (mAsecMountSet) {
1707 mAsecMountSet.add(id);
1708 }
1709 }
San Mehat4270e1e2010-01-29 05:32:19 -08001710 return rc;
San Mehat36972292010-01-06 11:06:32 -08001711 }
1712
San Mehatd9709982010-02-18 11:43:03 -08001713 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001714 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001715 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001716 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001717
San Mehat6cdd9c02010-02-09 14:45:20 -08001718 synchronized (mAsecMountSet) {
1719 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001720 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001721 }
1722 }
1723
Kenny Rootaa485402010-09-14 14:49:41 -07001724 /*
1725 * Force a GC to make sure AssetManagers in other threads of the
1726 * system_server are cleaned up. We have to do this since AssetManager
1727 * instances are kept as a WeakReference and it's possible we have files
1728 * open on the external storage.
1729 */
1730 Runtime.getRuntime().gc();
1731
San Mehatb1043402010-02-05 08:26:50 -08001732 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001733 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001734 final Command cmd = new Command("asec", "unmount", id);
1735 if (force) {
1736 cmd.appendArg("force");
1737 }
1738 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001739 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001740 int code = e.getCode();
1741 if (code == VoldResponseCode.OpFailedStorageBusy) {
1742 rc = StorageResultCode.OperationFailedStorageBusy;
1743 } else {
1744 rc = StorageResultCode.OperationFailedInternalError;
1745 }
San Mehat02735bc2010-01-26 15:18:08 -08001746 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001747
1748 if (rc == StorageResultCode.OperationSucceeded) {
1749 synchronized (mAsecMountSet) {
1750 mAsecMountSet.remove(id);
1751 }
1752 }
San Mehat4270e1e2010-01-29 05:32:19 -08001753 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001754 }
1755
San Mehat6cdd9c02010-02-09 14:45:20 -08001756 public boolean isSecureContainerMounted(String id) {
1757 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1758 waitForReady();
1759 warnOnNotMounted();
1760
1761 synchronized (mAsecMountSet) {
1762 return mAsecMountSet.contains(id);
1763 }
1764 }
1765
San Mehat4270e1e2010-01-29 05:32:19 -08001766 public int renameSecureContainer(String oldId, String newId) {
1767 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001768 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001769 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001770
San Mehata181b212010-02-11 06:50:20 -08001771 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001772 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001773 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001774 * changed while active, we must ensure both ids are not currently mounted.
1775 */
1776 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001777 return StorageResultCode.OperationFailedStorageMounted;
1778 }
1779 }
1780
San Mehatb1043402010-02-05 08:26:50 -08001781 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001782 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001783 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001784 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001785 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001786 }
San Mehata181b212010-02-11 06:50:20 -08001787
San Mehat4270e1e2010-01-29 05:32:19 -08001788 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001789 }
1790
San Mehat4270e1e2010-01-29 05:32:19 -08001791 public String getSecureContainerPath(String id) {
1792 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001793 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001794 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001795
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001796 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001797 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001798 event = mConnector.execute("asec", "path", id);
1799 event.checkCode(VoldResponseCode.AsecPathResult);
1800 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001801 } catch (NativeDaemonConnectorException e) {
1802 int code = e.getCode();
1803 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001804 Slog.i(TAG, String.format("Container '%s' not found", id));
1805 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001806 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001807 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001808 }
1809 }
San Mehat22dd86e2010-01-12 12:21:18 -08001810 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001811
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001812 public String getSecureContainerFilesystemPath(String id) {
1813 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1814 waitForReady();
1815 warnOnNotMounted();
1816
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001817 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001818 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001819 event = mConnector.execute("asec", "fspath", id);
1820 event.checkCode(VoldResponseCode.AsecPathResult);
1821 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001822 } catch (NativeDaemonConnectorException e) {
1823 int code = e.getCode();
1824 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1825 Slog.i(TAG, String.format("Container '%s' not found", id));
1826 return null;
1827 } else {
1828 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1829 }
1830 }
1831 }
1832
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001833 public void finishMediaUpdate() {
1834 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1835 }
Kenny Root02c87302010-07-01 08:10:18 -07001836
Kenny Roota02b8b02010-08-05 16:14:17 -07001837 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1838 if (callerUid == android.os.Process.SYSTEM_UID) {
1839 return true;
1840 }
1841
Kenny Root02c87302010-07-01 08:10:18 -07001842 if (packageName == null) {
1843 return false;
1844 }
1845
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001846 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001847
1848 if (DEBUG_OBB) {
1849 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1850 packageUid + ", callerUid = " + callerUid);
1851 }
1852
1853 return callerUid == packageUid;
1854 }
1855
1856 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001857 if (filename == null) {
1858 throw new IllegalArgumentException("filename cannot be null");
1859 }
1860
Kenny Root02c87302010-07-01 08:10:18 -07001861 waitForReady();
1862 warnOnNotMounted();
1863
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001864 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001865 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001866 event = mConnector.execute("obb", "path", filename);
1867 event.checkCode(VoldResponseCode.AsecPathResult);
1868 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001869 } catch (NativeDaemonConnectorException e) {
1870 int code = e.getCode();
1871 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001872 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001873 } else {
1874 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1875 }
1876 }
1877 }
1878
1879 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001880 if (filename == null) {
1881 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001882 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001883
1884 synchronized (mObbMounts) {
1885 return mObbPathToStateMap.containsKey(filename);
1886 }
Kenny Root02c87302010-07-01 08:10:18 -07001887 }
1888
Kenny Rootaf9d6672010-10-08 09:21:39 -07001889 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001890 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001891 if (filename == null) {
1892 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001893 }
1894
1895 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001896 throw new IllegalArgumentException("token cannot be null");
1897 }
1898
Kenny Rootaf9d6672010-10-08 09:21:39 -07001899 final int callerUid = Binder.getCallingUid();
1900 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1901 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001902 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1903
1904 if (DEBUG_OBB)
1905 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001906 }
1907
Kenny Rootaf9d6672010-10-08 09:21:39 -07001908 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1909 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001910 if (filename == null) {
1911 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001912 }
1913
Kenny Rootaf9d6672010-10-08 09:21:39 -07001914 final int callerUid = Binder.getCallingUid();
1915 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1916 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001917 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001918
Kenny Roota02b8b02010-08-05 16:14:17 -07001919 if (DEBUG_OBB)
1920 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1921 }
1922
Ben Komalo444eca22011-09-01 15:17:44 -07001923 @Override
1924 public int getEncryptionState() {
1925 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1926 "no permission to access the crypt keeper");
1927
1928 waitForReady();
1929
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001930 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001931 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001932 event = mConnector.execute("cryptfs", "cryptocomplete");
1933 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001934 } catch (NumberFormatException e) {
1935 // Bad result - unexpected.
1936 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1937 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1938 } catch (NativeDaemonConnectorException e) {
1939 // Something bad happened.
1940 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1941 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1942 }
1943 }
1944
1945 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001946 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001947 if (TextUtils.isEmpty(password)) {
1948 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001949 }
1950
Jason parks8888c592011-01-20 22:46:41 -06001951 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1952 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001953
1954 waitForReady();
1955
1956 if (DEBUG_EVENTS) {
1957 Slog.i(TAG, "decrypting storage...");
1958 }
1959
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001960 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001961 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001962 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001963
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001964 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001965 if (code == 0) {
1966 // Decrypt was successful. Post a delayed message before restarting in order
1967 // to let the UI to clear itself
1968 mHandler.postDelayed(new Runnable() {
1969 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001970 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001971 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001972 } catch (NativeDaemonConnectorException e) {
1973 Slog.e(TAG, "problem executing in background", e);
1974 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001975 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001976 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06001977 }
1978
1979 return code;
Jason parks5af0b912010-11-29 09:05:25 -06001980 } catch (NativeDaemonConnectorException e) {
1981 // Decryption failed
1982 return e.getCode();
1983 }
Jason parks5af0b912010-11-29 09:05:25 -06001984 }
1985
Jason parks56aa5322011-01-07 09:01:15 -06001986 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001987 if (TextUtils.isEmpty(password)) {
1988 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06001989 }
1990
Jason parks8888c592011-01-20 22:46:41 -06001991 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1992 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06001993
1994 waitForReady();
1995
1996 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06001997 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06001998 }
1999
2000 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002001 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002002 } catch (NativeDaemonConnectorException e) {
2003 // Encryption failed
2004 return e.getCode();
2005 }
2006
2007 return 0;
2008 }
2009
Jason parksf7b3cd42011-01-27 09:28:25 -06002010 public int changeEncryptionPassword(String password) {
2011 if (TextUtils.isEmpty(password)) {
2012 throw new IllegalArgumentException("password cannot be empty");
2013 }
2014
2015 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2016 "no permission to access the crypt keeper");
2017
2018 waitForReady();
2019
2020 if (DEBUG_EVENTS) {
2021 Slog.i(TAG, "changing encryption password...");
2022 }
2023
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002024 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002025 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002026 event = mConnector.execute("cryptfs", "changepw", password);
2027 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002028 } catch (NativeDaemonConnectorException e) {
2029 // Encryption failed
2030 return e.getCode();
2031 }
2032 }
2033
Christopher Tate32418be2011-10-10 13:51:12 -07002034 /**
2035 * Validate a user-supplied password string with cryptfs
2036 */
2037 @Override
2038 public int verifyEncryptionPassword(String password) throws RemoteException {
2039 // Only the system process is permitted to validate passwords
2040 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2041 throw new SecurityException("no permission to access the crypt keeper");
2042 }
2043
2044 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2045 "no permission to access the crypt keeper");
2046
2047 if (TextUtils.isEmpty(password)) {
2048 throw new IllegalArgumentException("password cannot be empty");
2049 }
2050
2051 waitForReady();
2052
2053 if (DEBUG_EVENTS) {
2054 Slog.i(TAG, "validating encryption password...");
2055 }
2056
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002057 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002058 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002059 event = mConnector.execute("cryptfs", "verifypw", password);
2060 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2061 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002062 } catch (NativeDaemonConnectorException e) {
2063 // Encryption failed
2064 return e.getCode();
2065 }
2066 }
2067
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002068 @Override
2069 public StorageVolume[] getVolumeList() {
2070 final int callingUserId = UserHandle.getCallingUserId();
2071 final boolean accessAll = (mContext.checkPermission(
2072 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2073 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2074
2075 synchronized (mVolumesLock) {
2076 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2077 for (StorageVolume volume : mVolumes) {
2078 final UserHandle owner = volume.getOwner();
2079 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2080 if (accessAll || ownerMatch) {
2081 filtered.add(volume);
2082 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002083 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002084 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002085 }
2086 }
2087
Kenny Rootaf9d6672010-10-08 09:21:39 -07002088 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2089 final IBinder binder = obbState.getBinder();
2090 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002091
Kenny Rootaf9d6672010-10-08 09:21:39 -07002092 if (obbStates == null) {
2093 obbStates = new ArrayList<ObbState>();
2094 mObbMounts.put(binder, obbStates);
2095 } else {
2096 for (final ObbState o : obbStates) {
2097 if (o.filename.equals(obbState.filename)) {
2098 throw new IllegalStateException("Attempt to add ObbState twice. "
2099 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002100 }
2101 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002102 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002103
2104 obbStates.add(obbState);
2105 try {
2106 obbState.link();
2107 } catch (RemoteException e) {
2108 /*
2109 * The binder died before we could link it, so clean up our state
2110 * and return failure.
2111 */
2112 obbStates.remove(obbState);
2113 if (obbStates.isEmpty()) {
2114 mObbMounts.remove(binder);
2115 }
2116
2117 // Rethrow the error so mountObb can get it
2118 throw e;
2119 }
2120
2121 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002122 }
2123
Kenny Rootaf9d6672010-10-08 09:21:39 -07002124 private void removeObbStateLocked(ObbState obbState) {
2125 final IBinder binder = obbState.getBinder();
2126 final List<ObbState> obbStates = mObbMounts.get(binder);
2127 if (obbStates != null) {
2128 if (obbStates.remove(obbState)) {
2129 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002130 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002131 if (obbStates.isEmpty()) {
2132 mObbMounts.remove(binder);
2133 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002134 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002135
Kenny Rootaf9d6672010-10-08 09:21:39 -07002136 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07002137 }
2138
Kenny Roota02b8b02010-08-05 16:14:17 -07002139 private class ObbActionHandler extends Handler {
2140 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002141 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002142
2143 ObbActionHandler(Looper l) {
2144 super(l);
2145 }
2146
2147 @Override
2148 public void handleMessage(Message msg) {
2149 switch (msg.what) {
2150 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002151 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002152
2153 if (DEBUG_OBB)
2154 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2155
2156 // If a bind was already initiated we don't really
2157 // need to do anything. The pending install
2158 // will be processed later on.
2159 if (!mBound) {
2160 // If this is the only one pending we might
2161 // have to bind to the service again.
2162 if (!connectToService()) {
2163 Slog.e(TAG, "Failed to bind to media container service");
2164 action.handleError();
2165 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002166 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002167 }
Kenny Root735de3b2010-09-30 14:11:39 -07002168
Kenny Root735de3b2010-09-30 14:11:39 -07002169 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002170 break;
2171 }
2172 case OBB_MCS_BOUND: {
2173 if (DEBUG_OBB)
2174 Slog.i(TAG, "OBB_MCS_BOUND");
2175 if (msg.obj != null) {
2176 mContainerService = (IMediaContainerService) msg.obj;
2177 }
2178 if (mContainerService == null) {
2179 // Something seriously wrong. Bail out
2180 Slog.e(TAG, "Cannot bind to media container service");
2181 for (ObbAction action : mActions) {
2182 // Indicate service bind error
2183 action.handleError();
2184 }
2185 mActions.clear();
2186 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002187 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002188 if (action != null) {
2189 action.execute(this);
2190 }
2191 } else {
2192 // Should never happen ideally.
2193 Slog.w(TAG, "Empty queue");
2194 }
2195 break;
2196 }
2197 case OBB_MCS_RECONNECT: {
2198 if (DEBUG_OBB)
2199 Slog.i(TAG, "OBB_MCS_RECONNECT");
2200 if (mActions.size() > 0) {
2201 if (mBound) {
2202 disconnectService();
2203 }
2204 if (!connectToService()) {
2205 Slog.e(TAG, "Failed to bind to media container service");
2206 for (ObbAction action : mActions) {
2207 // Indicate service bind error
2208 action.handleError();
2209 }
2210 mActions.clear();
2211 }
2212 }
2213 break;
2214 }
2215 case OBB_MCS_UNBIND: {
2216 if (DEBUG_OBB)
2217 Slog.i(TAG, "OBB_MCS_UNBIND");
2218
2219 // Delete pending install
2220 if (mActions.size() > 0) {
2221 mActions.remove(0);
2222 }
2223 if (mActions.size() == 0) {
2224 if (mBound) {
2225 disconnectService();
2226 }
2227 } else {
2228 // There are more pending requests in queue.
2229 // Just post MCS_BOUND message to trigger processing
2230 // of next pending install.
2231 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2232 }
2233 break;
2234 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002235 case OBB_FLUSH_MOUNT_STATE: {
2236 final String path = (String) msg.obj;
2237
2238 if (DEBUG_OBB)
2239 Slog.i(TAG, "Flushing all OBB state for path " + path);
2240
2241 synchronized (mObbMounts) {
2242 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2243
2244 final Iterator<Entry<String, ObbState>> i =
2245 mObbPathToStateMap.entrySet().iterator();
2246 while (i.hasNext()) {
2247 final Entry<String, ObbState> obbEntry = i.next();
2248
2249 /*
2250 * If this entry's source file is in the volume path
2251 * that got unmounted, remove it because it's no
2252 * longer valid.
2253 */
2254 if (obbEntry.getKey().startsWith(path)) {
2255 obbStatesToRemove.add(obbEntry.getValue());
2256 }
2257 }
2258
2259 for (final ObbState obbState : obbStatesToRemove) {
2260 if (DEBUG_OBB)
2261 Slog.i(TAG, "Removing state for " + obbState.filename);
2262
2263 removeObbStateLocked(obbState);
2264
2265 try {
2266 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2267 OnObbStateChangeListener.UNMOUNTED);
2268 } catch (RemoteException e) {
2269 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2270 + obbState.filename);
2271 }
2272 }
2273 }
2274 break;
2275 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002276 }
2277 }
2278
2279 private boolean connectToService() {
2280 if (DEBUG_OBB)
2281 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2282
2283 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2284 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2285 mBound = true;
2286 return true;
2287 }
2288 return false;
2289 }
2290
2291 private void disconnectService() {
2292 mContainerService = null;
2293 mBound = false;
2294 mContext.unbindService(mDefContainerConn);
2295 }
2296 }
2297
2298 abstract class ObbAction {
2299 private static final int MAX_RETRIES = 3;
2300 private int mRetries;
2301
2302 ObbState mObbState;
2303
2304 ObbAction(ObbState obbState) {
2305 mObbState = obbState;
2306 }
2307
2308 public void execute(ObbActionHandler handler) {
2309 try {
2310 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002311 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002312 mRetries++;
2313 if (mRetries > MAX_RETRIES) {
2314 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002315 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002316 handleError();
2317 return;
2318 } else {
2319 handleExecute();
2320 if (DEBUG_OBB)
2321 Slog.i(TAG, "Posting install MCS_UNBIND");
2322 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2323 }
2324 } catch (RemoteException e) {
2325 if (DEBUG_OBB)
2326 Slog.i(TAG, "Posting install MCS_RECONNECT");
2327 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2328 } catch (Exception e) {
2329 if (DEBUG_OBB)
2330 Slog.d(TAG, "Error handling OBB action", e);
2331 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002332 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002333 }
2334 }
2335
Kenny Root05105f72010-09-22 17:29:43 -07002336 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002337 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002338
2339 protected ObbInfo getObbInfo() throws IOException {
2340 ObbInfo obbInfo;
2341 try {
2342 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2343 } catch (RemoteException e) {
2344 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2345 + mObbState.filename);
2346 obbInfo = null;
2347 }
2348 if (obbInfo == null) {
2349 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2350 }
2351 return obbInfo;
2352 }
2353
Kenny Rootaf9d6672010-10-08 09:21:39 -07002354 protected void sendNewStatusOrIgnore(int status) {
2355 if (mObbState == null || mObbState.token == null) {
2356 return;
2357 }
2358
Kenny Root38cf8862010-09-26 14:18:51 -07002359 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002360 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002361 } catch (RemoteException e) {
2362 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2363 }
2364 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002365 }
2366
2367 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002368 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002369
2370 MountObbAction(ObbState obbState, String key) {
2371 super(obbState);
2372 mKey = key;
2373 }
2374
Jason parks5af0b912010-11-29 09:05:25 -06002375 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002376 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002377 waitForReady();
2378 warnOnNotMounted();
2379
Kenny Root38cf8862010-09-26 14:18:51 -07002380 final ObbInfo obbInfo = getObbInfo();
2381
Kenny Roota02b8b02010-08-05 16:14:17 -07002382 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002383 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2384 + " which is owned by " + obbInfo.packageName);
2385 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2386 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002387 }
2388
Kenny Rootaf9d6672010-10-08 09:21:39 -07002389 final boolean isMounted;
2390 synchronized (mObbMounts) {
2391 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2392 }
2393 if (isMounted) {
2394 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2395 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2396 return;
2397 }
2398
2399 /*
2400 * The filename passed in might not be the canonical name, so just
2401 * set the filename to the canonicalized version.
2402 */
2403 mObbState.filename = obbInfo.filename;
2404
2405 final String hashedKey;
2406 if (mKey == null) {
2407 hashedKey = "none";
2408 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002410 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2411
2412 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2413 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2414 SecretKey key = factory.generateSecret(ks);
2415 BigInteger bi = new BigInteger(key.getEncoded());
2416 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002417 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002418 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2419 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2420 return;
2421 } catch (InvalidKeySpecException e) {
2422 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2423 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002424 return;
2425 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002426 }
Kenny Root38cf8862010-09-26 14:18:51 -07002427
Kenny Rootaf9d6672010-10-08 09:21:39 -07002428 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002429 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002430 mConnector.execute(
2431 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002432 } catch (NativeDaemonConnectorException e) {
2433 int code = e.getCode();
2434 if (code != VoldResponseCode.OpFailedStorageBusy) {
2435 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002436 }
2437 }
2438
Kenny Rootaf9d6672010-10-08 09:21:39 -07002439 if (rc == StorageResultCode.OperationSucceeded) {
2440 if (DEBUG_OBB)
2441 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2442
2443 synchronized (mObbMounts) {
2444 addObbStateLocked(mObbState);
2445 }
2446
2447 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002448 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002449 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002450
Kenny Rootaf9d6672010-10-08 09:21:39 -07002451 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002452 }
2453 }
2454
Jason parks5af0b912010-11-29 09:05:25 -06002455 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002456 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002457 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002458 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002459
2460 @Override
2461 public String toString() {
2462 StringBuilder sb = new StringBuilder();
2463 sb.append("MountObbAction{");
2464 sb.append("filename=");
2465 sb.append(mObbState.filename);
2466 sb.append(",callerUid=");
2467 sb.append(mObbState.callerUid);
2468 sb.append(",token=");
2469 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002470 sb.append(",binder=");
2471 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002472 sb.append('}');
2473 return sb.toString();
2474 }
2475 }
2476
2477 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002478 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002479
2480 UnmountObbAction(ObbState obbState, boolean force) {
2481 super(obbState);
2482 mForceUnmount = force;
2483 }
2484
Jason parks5af0b912010-11-29 09:05:25 -06002485 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002486 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002487 waitForReady();
2488 warnOnNotMounted();
2489
Kenny Root38cf8862010-09-26 14:18:51 -07002490 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002491
Kenny Rootaf9d6672010-10-08 09:21:39 -07002492 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002493 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002494 obbState = mObbPathToStateMap.get(obbInfo.filename);
2495 }
Kenny Root38cf8862010-09-26 14:18:51 -07002496
Kenny Rootaf9d6672010-10-08 09:21:39 -07002497 if (obbState == null) {
2498 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2499 return;
2500 }
2501
2502 if (obbState.callerUid != mObbState.callerUid) {
2503 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2504 + " (owned by " + obbInfo.packageName + ")");
2505 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2506 return;
2507 }
2508
2509 mObbState.filename = obbInfo.filename;
2510
2511 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002512 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002513 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2514 if (mForceUnmount) {
2515 cmd.appendArg("force");
2516 }
2517 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002518 } catch (NativeDaemonConnectorException e) {
2519 int code = e.getCode();
2520 if (code == VoldResponseCode.OpFailedStorageBusy) {
2521 rc = StorageResultCode.OperationFailedStorageBusy;
2522 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2523 // If it's not mounted then we've already won.
2524 rc = StorageResultCode.OperationSucceeded;
2525 } else {
2526 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002527 }
2528 }
2529
Kenny Rootaf9d6672010-10-08 09:21:39 -07002530 if (rc == StorageResultCode.OperationSucceeded) {
2531 synchronized (mObbMounts) {
2532 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002533 }
2534
Kenny Rootaf9d6672010-10-08 09:21:39 -07002535 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002536 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002537 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2538 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002539 }
2540 }
2541
Jason parks5af0b912010-11-29 09:05:25 -06002542 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002543 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002545 }
2546
2547 @Override
2548 public String toString() {
2549 StringBuilder sb = new StringBuilder();
2550 sb.append("UnmountObbAction{");
2551 sb.append("filename=");
2552 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2553 sb.append(",force=");
2554 sb.append(mForceUnmount);
2555 sb.append(",callerUid=");
2556 sb.append(mObbState.callerUid);
2557 sb.append(",token=");
2558 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002559 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002560 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002561 sb.append('}');
2562 return sb.toString();
2563 }
Kenny Root02c87302010-07-01 08:10:18 -07002564 }
Kenny Root38cf8862010-09-26 14:18:51 -07002565
2566 @Override
2567 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2568 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2569 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2570 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2571 + " without permission " + android.Manifest.permission.DUMP);
2572 return;
2573 }
2574
Kenny Root38cf8862010-09-26 14:18:51 -07002575 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002577
Kenny Rootaf9d6672010-10-08 09:21:39 -07002578 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2579 while (binders.hasNext()) {
2580 Entry<IBinder, List<ObbState>> e = binders.next();
2581 pw.print(" Key="); pw.println(e.getKey().toString());
2582 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002583 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002584 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002585 }
2586 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002587
2588 pw.println("");
2589 pw.println(" mObbPathToStateMap:");
2590 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2591 while (maps.hasNext()) {
2592 final Entry<String, ObbState> e = maps.next();
2593 pw.print(" "); pw.print(e.getKey());
2594 pw.print(" -> "); pw.println(e.getValue().toString());
2595 }
Kenny Root38cf8862010-09-26 14:18:51 -07002596 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002597
2598 pw.println("");
2599
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002600 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002601 pw.println(" mVolumes:");
2602
2603 final int N = mVolumes.size();
2604 for (int i = 0; i < N; i++) {
2605 final StorageVolume v = mVolumes.get(i);
2606 pw.print(" ");
2607 pw.println(v.toString());
2608 }
2609 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002610
2611 pw.println();
2612 pw.println(" mConnection:");
2613 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002616 /** {@inheritDoc} */
2617 public void monitor() {
2618 if (mConnector != null) {
2619 mConnector.monitor();
2620 }
2621 }
2622}