blob: 32ab1542c3df2ff5d0439549d648beaf6adb761d [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
552 private final BroadcastReceiver mBootReceiver = new BroadcastReceiver() {
Jason parks5af0b912010-11-29 09:05:25 -0600553 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700555 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
556 if (userId == -1) return;
557 final UserHandle user = new UserHandle(userId);
San Mehat91c77612010-01-07 10:39:41 -0800558
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700559 Slog.d(TAG, "BOOT_COMPLETED for " + user);
San Mehat22dd86e2010-01-12 12:21:18 -0800560
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700561 // Broadcast mounted volumes to newly booted user. This kicks off
562 // media scanner when a user becomes active.
563 synchronized (mVolumesLock) {
564 for (StorageVolume volume : mVolumes) {
565 final UserHandle owner = volume.getOwner();
566 final boolean ownerMatch = owner == null
567 || owner.getIdentifier() == user.getIdentifier();
San Mehat6a254402010-03-22 10:21:00 -0700568
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700569 final String state = mVolumeStates.get(volume.getPath());
Mike Lockwood84338c42011-04-05 10:05:47 -0400570
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700571 if (ownerMatch && (Environment.MEDIA_MOUNTED.equals(state)
572 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))) {
573 sendStorageIntent(Intent.ACTION_MEDIA_MOUNTED, volume, user);
San Mehat207e5382010-02-04 20:46:54 -0800574 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577 }
578 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700579
580 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
581 @Override
582 public void onReceive(Context context, Intent intent) {
583 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
584 if (userId == -1) return;
585 final UserHandle user = new UserHandle(userId);
586
587 final String action = intent.getAction();
588 if (Intent.ACTION_USER_ADDED.equals(action)) {
589 synchronized (mVolumesLock) {
590 createEmulatedVolumeForUserLocked(user);
591 }
592
593 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
594 synchronized (mVolumesLock) {
595 final List<StorageVolume> toRemove = Lists.newArrayList();
596 for (StorageVolume volume : mVolumes) {
597 if (user.equals(volume.getOwner())) {
598 toRemove.add(volume);
599 }
600 }
601 for (StorageVolume volume : toRemove) {
602 removeVolumeLocked(volume);
603 }
604 }
605 }
606 }
607 };
608
609 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
610 @Override
611 public void onReceive(Context context, Intent intent) {
612 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
613 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
614 notifyShareAvailabilityChange(available);
615 }
616 };
617
San Mehat4270e1e2010-01-29 05:32:19 -0800618 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
619 final IMountServiceListener mListener;
620
621 MountServiceBinderListener(IMountServiceListener listener) {
622 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700623
San Mehat91c77612010-01-07 10:39:41 -0800624 }
625
San Mehat4270e1e2010-01-29 05:32:19 -0800626 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700627 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700628 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800629 mListeners.remove(this);
630 mListener.asBinder().unlinkToDeath(this, 0);
631 }
632 }
633 }
634
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800635 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800636 // TODO: Add support for multiple share methods
637 if (!method.equals("ums")) {
638 throw new IllegalArgumentException(String.format("Method %s not supported", method));
639 }
640
San Mehat4270e1e2010-01-29 05:32:19 -0800641 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800642 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800643 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700644 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800645 }
San Mehat4270e1e2010-01-29 05:32:19 -0800646 }
647
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700648 private void updatePublicVolumeState(StorageVolume volume, String state) {
649 final String path = volume.getPath();
650 final String oldState;
651 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400652 oldState = mVolumeStates.put(path, state);
653 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700654
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400655 if (state.equals(oldState)) {
656 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
657 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800658 return;
659 }
San Mehatb1043402010-02-05 08:26:50 -0800660
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400661 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700662
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700663 // Tell PackageManager about changes to primary volume state, but only
664 // when not emulated.
665 if (volume.isPrimary() && !volume.isEmulated()) {
666 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
667 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400668
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700669 /*
670 * Some OBBs might have been unmounted when this volume was
671 * unmounted, so send a message to the handler to let it know to
672 * remove those from the list of mounted OBBS.
673 */
674 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
675 OBB_FLUSH_MOUNT_STATE, path));
676 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
677 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400678 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800679 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700680
San Mehat4270e1e2010-01-29 05:32:19 -0800681 synchronized (mListeners) {
682 for (int i = mListeners.size() -1; i >= 0; i--) {
683 MountServiceBinderListener bl = mListeners.get(i);
684 try {
San Mehatb1043402010-02-05 08:26:50 -0800685 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800686 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700687 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800688 mListeners.remove(i);
689 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700690 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800691 }
692 }
693 }
694 }
695
696 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800697 * Callback from NativeDaemonConnector
698 */
699 public void onDaemonConnected() {
700 /*
701 * Since we'll be calling back into the NativeDaemonConnector,
702 * we need to do our work in a new thread.
703 */
Kenny Root51a573c2012-05-17 13:30:28 -0700704 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600705 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800706 public void run() {
707 /**
708 * Determine media state and UMS detection status
709 */
San Mehat4270e1e2010-01-29 05:32:19 -0800710 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800711 final String[] vols = NativeDaemonEvent.filterMessageList(
712 mConnector.executeForList("volume", "list"),
713 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800714 for (String volstr : vols) {
715 String[] tok = volstr.split(" ");
716 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400717 String path = tok[1];
718 String state = Environment.MEDIA_REMOVED;
719
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700720 final StorageVolume volume;
721 synchronized (mVolumesLock) {
722 volume = mVolumesByPath.get(path);
723 }
724
San Mehat4270e1e2010-01-29 05:32:19 -0800725 int st = Integer.parseInt(tok[2]);
726 if (st == VolumeState.NoMedia) {
727 state = Environment.MEDIA_REMOVED;
728 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800729 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800730 } else if (st == VolumeState.Mounted) {
731 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700732 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800733 } else if (st == VolumeState.Shared) {
734 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700735 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800736 } else {
737 throw new Exception(String.format("Unexpected state %d", st));
738 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400739
740 if (state != null) {
741 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700742 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400743 }
San Mehat4270e1e2010-01-29 05:32:19 -0800744 }
745 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700746 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700747 final StorageVolume primary = getPrimaryPhysicalVolume();
748 if (primary != null) {
749 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
750 }
San Mehat4270e1e2010-01-29 05:32:19 -0800751 }
752
San Mehat207e5382010-02-04 20:46:54 -0800753 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600754 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800755 * the hounds!
756 */
Kenny Root51a573c2012-05-17 13:30:28 -0700757 mConnectedSignal.countDown();
758 mConnectedSignal = null;
759
760 // Let package manager load internal ASECs.
761 mPms.scanAvailableAsecs();
762
763 // Notify people waiting for ASECs to be scanned that it's done.
764 mAsecsScanned.countDown();
765 mAsecsScanned = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800766 }
767 }.start();
768 }
769
770 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800771 * Callback from NativeDaemonConnector
772 */
773 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800774 if (DEBUG_EVENTS) {
775 StringBuilder builder = new StringBuilder();
776 builder.append("onEvent::");
777 builder.append(" raw= " + raw);
778 if (cooked != null) {
779 builder.append(" cooked = " );
780 for (String str : cooked) {
781 builder.append(" " + str);
782 }
783 }
San Mehata5078592010-03-25 09:36:54 -0700784 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800785 }
San Mehat4270e1e2010-01-29 05:32:19 -0800786 if (code == VoldResponseCode.VolumeStateChange) {
787 /*
788 * One of the volumes we're managing has changed state.
789 * Format: "NNN Volume <label> <path> state changed
790 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
791 */
792 notifyVolumeStateChange(
793 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
794 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800795 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
796 (code == VoldResponseCode.VolumeDiskRemoved) ||
797 (code == VoldResponseCode.VolumeBadRemoval)) {
798 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
799 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
800 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400801 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800802 final String label = cooked[2];
803 final String path = cooked[3];
804 int major = -1;
805 int minor = -1;
806
807 try {
808 String devComp = cooked[6].substring(1, cooked[6].length() -1);
809 String[] devTok = devComp.split(":");
810 major = Integer.parseInt(devTok[0]);
811 minor = Integer.parseInt(devTok[1]);
812 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700813 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800814 }
815
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700816 final StorageVolume volume;
817 final String state;
818 synchronized (mVolumesLock) {
819 volume = mVolumesByPath.get(path);
820 state = mVolumeStates.get(path);
821 }
822
San Mehat4270e1e2010-01-29 05:32:19 -0800823 if (code == VoldResponseCode.VolumeDiskInserted) {
824 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600825 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800826 public void run() {
827 try {
828 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800829 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800831 }
832 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700833 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800834 }
835 }
836 }.start();
837 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
838 /*
839 * This event gets trumped if we're already in BAD_REMOVAL state
840 */
841 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
842 return true;
843 }
844 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700845 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700846 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
847 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800848
San Mehata5078592010-03-25 09:36:54 -0700849 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700850 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400851 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800852 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700853 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800854 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700855 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400856 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800857
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700859 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400860 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800861 } else {
San Mehata5078592010-03-25 09:36:54 -0700862 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800863 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400864
865 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700866 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400867 }
San Mehat4270e1e2010-01-29 05:32:19 -0800868 } else {
869 return false;
870 }
871
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400872 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800873 }
874
San Mehat207e5382010-02-04 20:46:54 -0800875 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700876 final StorageVolume volume;
877 final String state;
878 synchronized (mVolumesLock) {
879 volume = mVolumesByPath.get(path);
880 state = getVolumeState(path);
881 }
882
883 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800884
Mike Lockwooda5250c92011-05-23 13:44:04 -0400885 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800886
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500887 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700888 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700889 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500890 }
891
San Mehat4270e1e2010-01-29 05:32:19 -0800892 if (newState == VolumeState.Init) {
893 } else if (newState == VolumeState.NoMedia) {
894 // NoMedia is handled via Disk Remove events
895 } else if (newState == VolumeState.Idle) {
896 /*
897 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
898 * if we're in the process of enabling UMS
899 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700900 if (!state.equals(
901 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
902 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800903 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700904 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700905 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400906 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800907 }
908 } else if (newState == VolumeState.Pending) {
909 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700910 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700911 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400912 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800913 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700914 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700915 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400916 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800917 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400918 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800919 } else if (newState == VolumeState.Formatting) {
920 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700921 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800922 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700923 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
924 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800925
San Mehata5078592010-03-25 09:36:54 -0700926 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700927 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400928 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700929 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800930 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700931 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800932 return;
933 } else {
San Mehata5078592010-03-25 09:36:54 -0700934 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800935 }
936
Mike Lockwooda5250c92011-05-23 13:44:04 -0400937 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700938 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800939 }
940 }
941
San Mehat207e5382010-02-04 20:46:54 -0800942 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800943 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800944
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700945 final StorageVolume volume;
946 synchronized (mVolumesLock) {
947 volume = mVolumesByPath.get(path);
948 }
949
San Mehata5078592010-03-25 09:36:54 -0700950 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800951 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800952 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800953 } catch (NativeDaemonConnectorException e) {
954 /*
955 * Mount failed for some reason
956 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400957 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800958 int code = e.getCode();
959 if (code == VoldResponseCode.OpFailedNoMedia) {
960 /*
961 * Attempt to mount but no media inserted
962 */
San Mehatb1043402010-02-05 08:26:50 -0800963 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800964 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700965 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800966 /*
967 * Media is blank or does not contain a supported filesystem
968 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700969 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400970 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800971 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800972 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700973 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800974 /*
975 * Volume consistency check failed
976 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700977 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400978 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800979 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800980 } else {
San Mehatb1043402010-02-05 08:26:50 -0800981 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800982 }
983
984 /*
985 * Send broadcast intent (if required for the failure)
986 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400987 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700988 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800989 }
990 }
991
992 return rc;
993 }
994
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800995 /*
996 * If force is not set, we do not unmount if there are
997 * processes holding references to the volume about to be unmounted.
998 * If force is set, all the processes holding references need to be
999 * killed via the ActivityManager before actually unmounting the volume.
1000 * This might even take a while and might be retried after timed delays
1001 * to make sure we dont end up in an instable state and kill some core
1002 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001003 * If removeEncryption is set, force is implied, and the system will remove any encryption
1004 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001005 */
Ben Komalo13c71972011-09-07 16:35:56 -07001006 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001007 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001008 return VoldResponseCode.OpFailedVolNotMounted;
1009 }
Kenny Rootaa485402010-09-14 14:49:41 -07001010
1011 /*
1012 * Force a GC to make sure AssetManagers in other threads of the
1013 * system_server are cleaned up. We have to do this since AssetManager
1014 * instances are kept as a WeakReference and it's possible we have files
1015 * open on the external storage.
1016 */
1017 Runtime.getRuntime().gc();
1018
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001019 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001020 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001021 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001022 final Command cmd = new Command("volume", "unmount", path);
1023 if (removeEncryption) {
1024 cmd.appendArg("force_and_revert");
1025 } else if (force) {
1026 cmd.appendArg("force");
1027 }
1028 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001029 // We unmounted the volume. None of the asec containers are available now.
1030 synchronized (mAsecMountSet) {
1031 mAsecMountSet.clear();
1032 }
San Mehatb1043402010-02-05 08:26:50 -08001033 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001034 } catch (NativeDaemonConnectorException e) {
1035 // Don't worry about mismatch in PackageManager since the
1036 // call back will handle the status changes any way.
1037 int code = e.getCode();
1038 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001039 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001040 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1041 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001042 } else {
San Mehatb1043402010-02-05 08:26:50 -08001043 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001044 }
1045 }
1046 }
1047
1048 private int doFormatVolume(String path) {
1049 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001050 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001051 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001052 } catch (NativeDaemonConnectorException e) {
1053 int code = e.getCode();
1054 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001055 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001056 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001057 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001058 } else {
San Mehatb1043402010-02-05 08:26:50 -08001059 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001060 }
1061 }
1062 }
1063
San Mehatb1043402010-02-05 08:26:50 -08001064 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001065 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001066 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001067 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001068 } catch (NativeDaemonConnectorException ex) {
1069 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1070 return false;
1071 }
San Mehatb1043402010-02-05 08:26:50 -08001072
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001073 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1074 return event.getMessage().endsWith("enabled");
1075 } else {
1076 return false;
San Mehatb1043402010-02-05 08:26:50 -08001077 }
San Mehatb1043402010-02-05 08:26:50 -08001078 }
1079
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001080 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001081 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001082 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001083 for (int i = mListeners.size() -1; i >= 0; i--) {
1084 MountServiceBinderListener bl = mListeners.get(i);
1085 try {
San Mehatb1043402010-02-05 08:26:50 -08001086 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001087 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001088 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001089 mListeners.remove(i);
1090 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001091 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001092 }
1093 }
1094 }
1095
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001096 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001097 sendUmsIntent(avail);
1098 } else {
1099 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001100 }
San Mehat2fe718a2010-03-11 12:01:49 -08001101
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001102 final StorageVolume primary = getPrimaryPhysicalVolume();
1103 if (avail == false && primary != null
1104 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1105 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001106 /*
1107 * USB mass storage disconnected while enabled
1108 */
1109 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001110 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001111 public void run() {
1112 try {
1113 int rc;
San Mehata5078592010-03-25 09:36:54 -07001114 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001115 doShareUnshareVolume(path, "ums", false);
1116 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001117 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001118 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1119 path, rc));
1120 }
1121 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001122 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001123 }
1124 }
1125 }.start();
1126 }
San Mehat4270e1e2010-01-29 05:32:19 -08001127 }
1128
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001129 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1130 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1131 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1132 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1133 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001134 }
1135
San Mehat6a965af22010-02-24 17:47:30 -08001136 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001137 mContext.sendBroadcastAsUser(
1138 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1139 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001140 }
1141
San Mehat207e5382010-02-04 20:46:54 -08001142 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001143 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1144 throw new SecurityException(String.format("Requires %s permission", perm));
1145 }
1146 }
1147
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001148 // Storage list XML tags
1149 private static final String TAG_STORAGE_LIST = "StorageList";
1150 private static final String TAG_STORAGE = "storage";
1151
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001152 private void readStorageListLocked() {
1153 mVolumes.clear();
1154 mVolumeStates.clear();
1155
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001156 Resources resources = mContext.getResources();
1157
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001158 int id = com.android.internal.R.xml.storage_list;
1159 XmlResourceParser parser = resources.getXml(id);
1160 AttributeSet attrs = Xml.asAttributeSet(parser);
1161
1162 try {
1163 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1164 while (true) {
1165 XmlUtils.nextElement(parser);
1166
1167 String element = parser.getName();
1168 if (element == null) break;
1169
1170 if (TAG_STORAGE.equals(element)) {
1171 TypedArray a = resources.obtainAttributes(attrs,
1172 com.android.internal.R.styleable.Storage);
1173
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001174 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001175 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001176 int descriptionId = a.getResourceId(
1177 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001178 CharSequence description = a.getText(
1179 com.android.internal.R.styleable.Storage_storageDescription);
1180 boolean primary = a.getBoolean(
1181 com.android.internal.R.styleable.Storage_primary, false);
1182 boolean removable = a.getBoolean(
1183 com.android.internal.R.styleable.Storage_removable, false);
1184 boolean emulated = a.getBoolean(
1185 com.android.internal.R.styleable.Storage_emulated, false);
1186 int mtpReserve = a.getInt(
1187 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001188 boolean allowMassStorage = a.getBoolean(
1189 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001190 // resource parser does not support longs, so XML value is in megabytes
1191 long maxFileSize = a.getInt(
1192 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001193
1194 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1195 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001196 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001197 " allowMassStorage: " + allowMassStorage +
1198 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001199
1200 if (emulated) {
1201 // For devices with emulated storage, we create separate
1202 // volumes for each known user.
1203 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1204 true, mtpReserve, false, maxFileSize, null);
1205
1206 final UserManagerService userManager = UserManagerService.getInstance();
1207 for (UserInfo user : userManager.getUsers()) {
1208 createEmulatedVolumeForUserLocked(user.getUserHandle());
1209 }
1210
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001211 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001212 if (path == null || description == null) {
1213 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001214 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001215 final StorageVolume volume = new StorageVolume(new File(path),
1216 descriptionId, primary, removable, emulated, mtpReserve,
1217 allowMassStorage, maxFileSize, null);
1218 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001219 }
1220 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001221
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001222 a.recycle();
1223 }
1224 }
1225 } catch (XmlPullParserException e) {
1226 throw new RuntimeException(e);
1227 } catch (IOException e) {
1228 throw new RuntimeException(e);
1229 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001230 // Compute storage ID for each physical volume; emulated storage is
1231 // always 0 when defined.
1232 int index = isExternalStorageEmulated() ? 1 : 0;
1233 for (StorageVolume volume : mVolumes) {
1234 if (!volume.isEmulated()) {
1235 volume.setStorageId(index++);
1236 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001237 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001238 parser.close();
1239 }
1240 }
1241
San Mehat4270e1e2010-01-29 05:32:19 -08001242 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001243 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1244 * using {@link #mEmulatedTemplate} as template.
1245 */
1246 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1247 if (mEmulatedTemplate == null) {
1248 throw new IllegalStateException("Missing emulated volume multi-user template");
1249 }
1250
1251 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1252 final File path = userEnv.getExternalStorageDirectory();
1253 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1254 volume.setStorageId(0);
1255 addVolumeLocked(volume);
1256
1257 if (mSystemReady) {
1258 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1259 } else {
1260 // Place stub status for early callers to find
1261 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1262 }
1263 }
1264
1265 private void addVolumeLocked(StorageVolume volume) {
1266 Slog.d(TAG, "addVolumeLocked() " + volume);
1267 mVolumes.add(volume);
1268 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1269 if (existing != null) {
1270 throw new IllegalStateException(
1271 "Volume at " + volume.getPath() + " already exists: " + existing);
1272 }
1273 }
1274
1275 private void removeVolumeLocked(StorageVolume volume) {
1276 Slog.d(TAG, "removeVolumeLocked() " + volume);
1277 mVolumes.remove(volume);
1278 mVolumesByPath.remove(volume.getPath());
1279 mVolumeStates.remove(volume.getPath());
1280 }
1281
1282 private StorageVolume getPrimaryPhysicalVolume() {
1283 synchronized (mVolumesLock) {
1284 for (StorageVolume volume : mVolumes) {
1285 if (volume.isPrimary() && !volume.isEmulated()) {
1286 return volume;
1287 }
1288 }
1289 }
1290 return null;
1291 }
1292
1293 /**
San Mehat207e5382010-02-04 20:46:54 -08001294 * Constructs a new MountService instance
1295 *
1296 * @param context Binder context for this service
1297 */
1298 public MountService(Context context) {
1299 mContext = context;
1300
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001301 synchronized (mVolumesLock) {
1302 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001303 }
1304
San Mehat207e5382010-02-04 20:46:54 -08001305 // XXX: This will go away soon in favor of IMountServiceObserver
1306 mPms = (PackageManagerService) ServiceManager.getService("package");
1307
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001308 mHandlerThread = new HandlerThread("MountService");
1309 mHandlerThread.start();
1310 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1311
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001312 // Watch for user boot completion
1313 mContext.registerReceiverAsUser(mBootReceiver, UserHandle.ALL,
1314 new IntentFilter(Intent.ACTION_BOOT_COMPLETED), null, mHandler);
1315
1316 // Watch for user changes
1317 final IntentFilter userFilter = new IntentFilter();
1318 userFilter.addAction(Intent.ACTION_USER_ADDED);
1319 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1320 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1321
1322 // Watch for USB changes on primary volume
1323 final StorageVolume primary = getPrimaryPhysicalVolume();
1324 if (primary != null && primary.allowMassStorage()) {
1325 mContext.registerReceiver(
1326 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1327 }
1328
Kenny Roota02b8b02010-08-05 16:14:17 -07001329 // Add OBB Action Handler to MountService thread.
1330 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1331
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001332 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001333 * Create the connection to vold with a maximum queue of twice the
1334 * amount of containers we'd ever expect to have. This keeps an
1335 * "asec list" from blocking a thread repeatedly.
1336 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001337 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001338
Kenny Root305bcbf2010-09-03 07:56:38 -07001339 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001340 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001341
Kenny Root07714d42011-08-17 17:49:28 -07001342 // Add ourself to the Watchdog monitors if enabled.
1343 if (WATCHDOG_ENABLE) {
1344 Watchdog.getInstance().addMonitor(this);
1345 }
San Mehat207e5382010-02-04 20:46:54 -08001346 }
1347
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001348 public void systemReady() {
1349 mSystemReady = true;
1350 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1351 }
1352
San Mehat207e5382010-02-04 20:46:54 -08001353 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001354 * Exposed API calls below here
1355 */
1356
1357 public void registerListener(IMountServiceListener listener) {
1358 synchronized (mListeners) {
1359 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1360 try {
1361 listener.asBinder().linkToDeath(bl, 0);
1362 mListeners.add(bl);
1363 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001364 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001365 }
1366 }
1367 }
1368
1369 public void unregisterListener(IMountServiceListener listener) {
1370 synchronized (mListeners) {
1371 for(MountServiceBinderListener bl : mListeners) {
1372 if (bl.mListener == listener) {
1373 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001374 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001375 return;
1376 }
1377 }
1378 }
1379 }
1380
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001381 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001382 validatePermission(android.Manifest.permission.SHUTDOWN);
1383
San Mehata5078592010-03-25 09:36:54 -07001384 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001385 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001386 for (String path : mVolumeStates.keySet()) {
1387 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001388
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001389 if (state.equals(Environment.MEDIA_SHARED)) {
1390 /*
1391 * If the media is currently shared, unshare it.
1392 * XXX: This is still dangerous!. We should not
1393 * be rebooting at *all* if UMS is enabled, since
1394 * the UMS host could have dirty FAT cache entries
1395 * yet to flush.
1396 */
1397 setUsbMassStorageEnabled(false);
1398 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1399 /*
1400 * If the media is being checked, then we need to wait for
1401 * it to complete before being able to proceed.
1402 */
1403 // XXX: @hackbod - Should we disable the ANR timer here?
1404 int retries = 30;
1405 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1406 try {
1407 Thread.sleep(1000);
1408 } catch (InterruptedException iex) {
1409 Slog.e(TAG, "Interrupted while waiting for media", iex);
1410 break;
1411 }
1412 state = Environment.getExternalStorageState();
1413 }
1414 if (retries == 0) {
1415 Slog.e(TAG, "Timed out waiting for media to check");
1416 }
San Mehat91c77612010-01-07 10:39:41 -08001417 }
San Mehat91c77612010-01-07 10:39:41 -08001418
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001419 if (state.equals(Environment.MEDIA_MOUNTED)) {
1420 // Post a unmount message.
1421 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1422 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1423 } else if (observer != null) {
1424 /*
1425 * Observer is waiting for onShutDownComplete when we are done.
1426 * Since nothing will be done send notification directly so shutdown
1427 * sequence can continue.
1428 */
1429 try {
1430 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1431 } catch (RemoteException e) {
1432 Slog.w(TAG, "RemoteException when shutting down");
1433 }
1434 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001435 }
San Mehat4270e1e2010-01-29 05:32:19 -08001436 }
1437 }
1438
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001439 private boolean getUmsEnabling() {
1440 synchronized (mListeners) {
1441 return mUmsEnabling;
1442 }
1443 }
1444
1445 private void setUmsEnabling(boolean enable) {
1446 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001447 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001448 }
1449 }
1450
San Mehatb1043402010-02-05 08:26:50 -08001451 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001452 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001453
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001454 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001455 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001456 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001457 synchronized (mListeners) {
1458 return mUmsAvailable;
1459 }
San Mehatb1043402010-02-05 08:26:50 -08001460 }
1461
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001462 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001463 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001464 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001465
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001466 final StorageVolume primary = getPrimaryPhysicalVolume();
1467 if (primary == null) return;
1468
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001469 // TODO: Add support for multiple share methods
1470
1471 /*
1472 * If the volume is mounted and we're enabling then unmount it
1473 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001474 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001475 String vs = getVolumeState(path);
1476 String method = "ums";
1477 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1478 // Override for isUsbMassStorageEnabled()
1479 setUmsEnabling(enable);
1480 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1481 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1482 // Clear override
1483 setUmsEnabling(false);
1484 }
1485 /*
1486 * If we disabled UMS then mount the volume
1487 */
1488 if (!enable) {
1489 doShareUnshareVolume(path, method, enable);
1490 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001491 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001492 " after disabling share method " + method);
1493 /*
1494 * Even though the mount failed, the unshare didn't so don't indicate an error.
1495 * The mountVolume() call will have set the storage state and sent the necessary
1496 * broadcasts.
1497 */
1498 }
1499 }
San Mehatb1043402010-02-05 08:26:50 -08001500 }
1501
1502 public boolean isUsbMassStorageEnabled() {
1503 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001504
1505 final StorageVolume primary = getPrimaryPhysicalVolume();
1506 if (primary != null) {
1507 return doGetVolumeShared(primary.getPath(), "ums");
1508 } else {
1509 return false;
1510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001512
San Mehat7fd0fee2009-12-17 07:12:23 -08001513 /**
1514 * @return state of the volume at the specified mount point
1515 */
San Mehat4270e1e2010-01-29 05:32:19 -08001516 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001517 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001518 String state = mVolumeStates.get(mountPoint);
1519 if (state == null) {
1520 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001521 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1522 state = Environment.MEDIA_REMOVED;
1523 } else {
1524 throw new IllegalArgumentException();
1525 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001526 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001527
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001528 return state;
1529 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001530 }
1531
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001532 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001533 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001534 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001535 }
1536
San Mehat4270e1e2010-01-29 05:32:19 -08001537 public int mountVolume(String path) {
1538 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001539
San Mehat207e5382010-02-04 20:46:54 -08001540 waitForReady();
1541 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543
Ben Komalo13c71972011-09-07 16:35:56 -07001544 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001545 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001546 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001548 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001549 if (DEBUG_UNMOUNT) {
1550 Slog.i(TAG, "Unmounting " + path
1551 + " force = " + force
1552 + " removeEncryption = " + removeEncryption);
1553 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001554 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1555 Environment.MEDIA_REMOVED.equals(volState) ||
1556 Environment.MEDIA_SHARED.equals(volState) ||
1557 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1558 // Media already unmounted or cannot be unmounted.
1559 // TODO return valid return code when adding observer call back.
1560 return;
1561 }
Ben Komalo13c71972011-09-07 16:35:56 -07001562 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001563 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
San Mehat4270e1e2010-01-29 05:32:19 -08001566 public int formatVolume(String path) {
1567 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001568 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001569
San Mehat207e5382010-02-04 20:46:54 -08001570 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001573 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001574 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1575 waitForReady();
1576 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001577 final String[] r = NativeDaemonEvent.filterMessageList(
1578 mConnector.executeForList("storage", "users", path),
1579 VoldResponseCode.StorageUsersListResult);
1580
San Mehatc1b4ce92010-02-16 17:13:03 -08001581 // FMT: <pid> <process name>
1582 int[] data = new int[r.length];
1583 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001584 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001585 try {
1586 data[i] = Integer.parseInt(tok[0]);
1587 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001588 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001589 return new int[0];
1590 }
1591 }
1592 return data;
1593 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001594 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001595 return new int[0];
1596 }
1597 }
1598
San Mehatb1043402010-02-05 08:26:50 -08001599 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001600 final StorageVolume primary = getPrimaryPhysicalVolume();
1601 if (primary != null
1602 && Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()))) {
San Mehata5078592010-03-25 09:36:54 -07001603 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
San Mehatb1043402010-02-05 08:26:50 -08001604 }
1605 }
1606
San Mehat4270e1e2010-01-29 05:32:19 -08001607 public String[] getSecureContainerList() {
1608 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001609 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001610 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001611
San Mehat4270e1e2010-01-29 05:32:19 -08001612 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001613 return NativeDaemonEvent.filterMessageList(
1614 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001615 } catch (NativeDaemonConnectorException e) {
1616 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618 }
San Mehat36972292010-01-06 11:06:32 -08001619
Kenny Root6dceb882012-04-12 14:23:49 -07001620 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1621 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001622 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001623 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001624 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001625
San Mehatb1043402010-02-05 08:26:50 -08001626 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001627 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001628 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1629 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001630 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001631 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001632 }
San Mehata181b212010-02-11 06:50:20 -08001633
1634 if (rc == StorageResultCode.OperationSucceeded) {
1635 synchronized (mAsecMountSet) {
1636 mAsecMountSet.add(id);
1637 }
1638 }
San Mehat4270e1e2010-01-29 05:32:19 -08001639 return rc;
San Mehat36972292010-01-06 11:06:32 -08001640 }
1641
San Mehat4270e1e2010-01-29 05:32:19 -08001642 public int finalizeSecureContainer(String id) {
1643 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001644 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001645
San Mehatb1043402010-02-05 08:26:50 -08001646 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001647 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001648 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001649 /*
1650 * Finalization does a remount, so no need
1651 * to update mAsecMountSet
1652 */
San Mehat4270e1e2010-01-29 05:32:19 -08001653 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001654 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001655 }
San Mehat4270e1e2010-01-29 05:32:19 -08001656 return rc;
San Mehat36972292010-01-06 11:06:32 -08001657 }
1658
Kenny Root6dceb882012-04-12 14:23:49 -07001659 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1660 validatePermission(android.Manifest.permission.ASEC_CREATE);
1661 warnOnNotMounted();
1662
1663 int rc = StorageResultCode.OperationSucceeded;
1664 try {
1665 mConnector.execute("asec", "fixperms", id, gid, filename);
1666 /*
1667 * Fix permissions does a remount, so no need to update
1668 * mAsecMountSet
1669 */
1670 } catch (NativeDaemonConnectorException e) {
1671 rc = StorageResultCode.OperationFailedInternalError;
1672 }
1673 return rc;
1674 }
1675
San Mehatd9709982010-02-18 11:43:03 -08001676 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001677 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001678 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001679 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001680
Kenny Rootaa485402010-09-14 14:49:41 -07001681 /*
1682 * Force a GC to make sure AssetManagers in other threads of the
1683 * system_server are cleaned up. We have to do this since AssetManager
1684 * instances are kept as a WeakReference and it's possible we have files
1685 * open on the external storage.
1686 */
1687 Runtime.getRuntime().gc();
1688
San Mehatb1043402010-02-05 08:26:50 -08001689 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001690 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001691 final Command cmd = new Command("asec", "destroy", id);
1692 if (force) {
1693 cmd.appendArg("force");
1694 }
1695 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001696 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001697 int code = e.getCode();
1698 if (code == VoldResponseCode.OpFailedStorageBusy) {
1699 rc = StorageResultCode.OperationFailedStorageBusy;
1700 } else {
1701 rc = StorageResultCode.OperationFailedInternalError;
1702 }
San Mehat02735bc2010-01-26 15:18:08 -08001703 }
San Mehata181b212010-02-11 06:50:20 -08001704
1705 if (rc == StorageResultCode.OperationSucceeded) {
1706 synchronized (mAsecMountSet) {
1707 if (mAsecMountSet.contains(id)) {
1708 mAsecMountSet.remove(id);
1709 }
1710 }
1711 }
1712
San Mehat4270e1e2010-01-29 05:32:19 -08001713 return rc;
San Mehat36972292010-01-06 11:06:32 -08001714 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001715
San Mehat4270e1e2010-01-29 05:32:19 -08001716 public int mountSecureContainer(String id, String key, int ownerUid) {
1717 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001718 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001719 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001720
San Mehata181b212010-02-11 06:50:20 -08001721 synchronized (mAsecMountSet) {
1722 if (mAsecMountSet.contains(id)) {
1723 return StorageResultCode.OperationFailedStorageMounted;
1724 }
1725 }
1726
San Mehatb1043402010-02-05 08:26:50 -08001727 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001728 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001729 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001730 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001731 int code = e.getCode();
1732 if (code != VoldResponseCode.OpFailedStorageBusy) {
1733 rc = StorageResultCode.OperationFailedInternalError;
1734 }
San Mehat02735bc2010-01-26 15:18:08 -08001735 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001736
1737 if (rc == StorageResultCode.OperationSucceeded) {
1738 synchronized (mAsecMountSet) {
1739 mAsecMountSet.add(id);
1740 }
1741 }
San Mehat4270e1e2010-01-29 05:32:19 -08001742 return rc;
San Mehat36972292010-01-06 11:06:32 -08001743 }
1744
San Mehatd9709982010-02-18 11:43:03 -08001745 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001746 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001747 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001748 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001749
San Mehat6cdd9c02010-02-09 14:45:20 -08001750 synchronized (mAsecMountSet) {
1751 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001752 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001753 }
1754 }
1755
Kenny Rootaa485402010-09-14 14:49:41 -07001756 /*
1757 * Force a GC to make sure AssetManagers in other threads of the
1758 * system_server are cleaned up. We have to do this since AssetManager
1759 * instances are kept as a WeakReference and it's possible we have files
1760 * open on the external storage.
1761 */
1762 Runtime.getRuntime().gc();
1763
San Mehatb1043402010-02-05 08:26:50 -08001764 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001765 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001766 final Command cmd = new Command("asec", "unmount", id);
1767 if (force) {
1768 cmd.appendArg("force");
1769 }
1770 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001771 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001772 int code = e.getCode();
1773 if (code == VoldResponseCode.OpFailedStorageBusy) {
1774 rc = StorageResultCode.OperationFailedStorageBusy;
1775 } else {
1776 rc = StorageResultCode.OperationFailedInternalError;
1777 }
San Mehat02735bc2010-01-26 15:18:08 -08001778 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001779
1780 if (rc == StorageResultCode.OperationSucceeded) {
1781 synchronized (mAsecMountSet) {
1782 mAsecMountSet.remove(id);
1783 }
1784 }
San Mehat4270e1e2010-01-29 05:32:19 -08001785 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001786 }
1787
San Mehat6cdd9c02010-02-09 14:45:20 -08001788 public boolean isSecureContainerMounted(String id) {
1789 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1790 waitForReady();
1791 warnOnNotMounted();
1792
1793 synchronized (mAsecMountSet) {
1794 return mAsecMountSet.contains(id);
1795 }
1796 }
1797
San Mehat4270e1e2010-01-29 05:32:19 -08001798 public int renameSecureContainer(String oldId, String newId) {
1799 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001800 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001801 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001802
San Mehata181b212010-02-11 06:50:20 -08001803 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001804 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001805 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001806 * changed while active, we must ensure both ids are not currently mounted.
1807 */
1808 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001809 return StorageResultCode.OperationFailedStorageMounted;
1810 }
1811 }
1812
San Mehatb1043402010-02-05 08:26:50 -08001813 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001814 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001815 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001816 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001817 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001818 }
San Mehata181b212010-02-11 06:50:20 -08001819
San Mehat4270e1e2010-01-29 05:32:19 -08001820 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001821 }
1822
San Mehat4270e1e2010-01-29 05:32:19 -08001823 public String getSecureContainerPath(String id) {
1824 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001825 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001826 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001827
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001828 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001829 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001830 event = mConnector.execute("asec", "path", id);
1831 event.checkCode(VoldResponseCode.AsecPathResult);
1832 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001833 } catch (NativeDaemonConnectorException e) {
1834 int code = e.getCode();
1835 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001836 Slog.i(TAG, String.format("Container '%s' not found", id));
1837 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001838 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001839 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001840 }
1841 }
San Mehat22dd86e2010-01-12 12:21:18 -08001842 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001843
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001844 public String getSecureContainerFilesystemPath(String id) {
1845 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1846 waitForReady();
1847 warnOnNotMounted();
1848
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001849 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001850 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001851 event = mConnector.execute("asec", "fspath", id);
1852 event.checkCode(VoldResponseCode.AsecPathResult);
1853 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001854 } catch (NativeDaemonConnectorException e) {
1855 int code = e.getCode();
1856 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1857 Slog.i(TAG, String.format("Container '%s' not found", id));
1858 return null;
1859 } else {
1860 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1861 }
1862 }
1863 }
1864
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001865 public void finishMediaUpdate() {
1866 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1867 }
Kenny Root02c87302010-07-01 08:10:18 -07001868
Kenny Roota02b8b02010-08-05 16:14:17 -07001869 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1870 if (callerUid == android.os.Process.SYSTEM_UID) {
1871 return true;
1872 }
1873
Kenny Root02c87302010-07-01 08:10:18 -07001874 if (packageName == null) {
1875 return false;
1876 }
1877
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001878 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001879
1880 if (DEBUG_OBB) {
1881 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1882 packageUid + ", callerUid = " + callerUid);
1883 }
1884
1885 return callerUid == packageUid;
1886 }
1887
1888 public String getMountedObbPath(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001889 if (filename == null) {
1890 throw new IllegalArgumentException("filename cannot be null");
1891 }
1892
Kenny Root02c87302010-07-01 08:10:18 -07001893 waitForReady();
1894 warnOnNotMounted();
1895
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001896 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001897 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001898 event = mConnector.execute("obb", "path", filename);
1899 event.checkCode(VoldResponseCode.AsecPathResult);
1900 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001901 } catch (NativeDaemonConnectorException e) {
1902 int code = e.getCode();
1903 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001904 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001905 } else {
1906 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1907 }
1908 }
1909 }
1910
1911 public boolean isObbMounted(String filename) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07001912 if (filename == null) {
1913 throw new IllegalArgumentException("filename cannot be null");
Kenny Root02c87302010-07-01 08:10:18 -07001914 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07001915
1916 synchronized (mObbMounts) {
1917 return mObbPathToStateMap.containsKey(filename);
1918 }
Kenny Root02c87302010-07-01 08:10:18 -07001919 }
1920
Kenny Rootaf9d6672010-10-08 09:21:39 -07001921 public void mountObb(String filename, String key, IObbActionListener token, int nonce)
Kenny Root735de3b2010-09-30 14:11:39 -07001922 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001923 if (filename == null) {
1924 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001925 }
1926
1927 if (token == null) {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001928 throw new IllegalArgumentException("token cannot be null");
1929 }
1930
Kenny Rootaf9d6672010-10-08 09:21:39 -07001931 final int callerUid = Binder.getCallingUid();
1932 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1933 final ObbAction action = new MountObbAction(obbState, key);
Kenny Roota02b8b02010-08-05 16:14:17 -07001934 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1935
1936 if (DEBUG_OBB)
1937 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001938 }
1939
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940 public void unmountObb(String filename, boolean force, IObbActionListener token, int nonce)
1941 throws RemoteException {
Kenny Rootf1121dc2010-09-29 07:30:53 -07001942 if (filename == null) {
1943 throw new IllegalArgumentException("filename cannot be null");
Kenny Rootf1121dc2010-09-29 07:30:53 -07001944 }
1945
Kenny Rootaf9d6672010-10-08 09:21:39 -07001946 final int callerUid = Binder.getCallingUid();
1947 final ObbState obbState = new ObbState(filename, callerUid, token, nonce);
1948 final ObbAction action = new UnmountObbAction(obbState, force);
Kenny Roota02b8b02010-08-05 16:14:17 -07001949 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001950
Kenny Roota02b8b02010-08-05 16:14:17 -07001951 if (DEBUG_OBB)
1952 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1953 }
1954
Ben Komalo444eca22011-09-01 15:17:44 -07001955 @Override
1956 public int getEncryptionState() {
1957 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1958 "no permission to access the crypt keeper");
1959
1960 waitForReady();
1961
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001962 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001963 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001964 event = mConnector.execute("cryptfs", "cryptocomplete");
1965 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001966 } catch (NumberFormatException e) {
1967 // Bad result - unexpected.
1968 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1969 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1970 } catch (NativeDaemonConnectorException e) {
1971 // Something bad happened.
1972 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1973 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1974 }
1975 }
1976
1977 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001978 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001979 if (TextUtils.isEmpty(password)) {
1980 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001981 }
1982
Jason parks8888c592011-01-20 22:46:41 -06001983 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1984 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001985
1986 waitForReady();
1987
1988 if (DEBUG_EVENTS) {
1989 Slog.i(TAG, "decrypting storage...");
1990 }
1991
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001992 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001993 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001994 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001995
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001996 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001997 if (code == 0) {
1998 // Decrypt was successful. Post a delayed message before restarting in order
1999 // to let the UI to clear itself
2000 mHandler.postDelayed(new Runnable() {
2001 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002002 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002003 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002004 } catch (NativeDaemonConnectorException e) {
2005 Slog.e(TAG, "problem executing in background", e);
2006 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002007 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002008 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002009 }
2010
2011 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002012 } catch (NativeDaemonConnectorException e) {
2013 // Decryption failed
2014 return e.getCode();
2015 }
Jason parks5af0b912010-11-29 09:05:25 -06002016 }
2017
Jason parks56aa5322011-01-07 09:01:15 -06002018 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002019 if (TextUtils.isEmpty(password)) {
2020 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002021 }
2022
Jason parks8888c592011-01-20 22:46:41 -06002023 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2024 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002025
2026 waitForReady();
2027
2028 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002029 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002030 }
2031
2032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002033 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002034 } catch (NativeDaemonConnectorException e) {
2035 // Encryption failed
2036 return e.getCode();
2037 }
2038
2039 return 0;
2040 }
2041
Jason parksf7b3cd42011-01-27 09:28:25 -06002042 public int changeEncryptionPassword(String password) {
2043 if (TextUtils.isEmpty(password)) {
2044 throw new IllegalArgumentException("password cannot be empty");
2045 }
2046
2047 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2048 "no permission to access the crypt keeper");
2049
2050 waitForReady();
2051
2052 if (DEBUG_EVENTS) {
2053 Slog.i(TAG, "changing encryption password...");
2054 }
2055
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002056 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002057 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002058 event = mConnector.execute("cryptfs", "changepw", password);
2059 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002060 } catch (NativeDaemonConnectorException e) {
2061 // Encryption failed
2062 return e.getCode();
2063 }
2064 }
2065
Christopher Tate32418be2011-10-10 13:51:12 -07002066 /**
2067 * Validate a user-supplied password string with cryptfs
2068 */
2069 @Override
2070 public int verifyEncryptionPassword(String password) throws RemoteException {
2071 // Only the system process is permitted to validate passwords
2072 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2073 throw new SecurityException("no permission to access the crypt keeper");
2074 }
2075
2076 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2077 "no permission to access the crypt keeper");
2078
2079 if (TextUtils.isEmpty(password)) {
2080 throw new IllegalArgumentException("password cannot be empty");
2081 }
2082
2083 waitForReady();
2084
2085 if (DEBUG_EVENTS) {
2086 Slog.i(TAG, "validating encryption password...");
2087 }
2088
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002089 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002090 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002091 event = mConnector.execute("cryptfs", "verifypw", password);
2092 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2093 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002094 } catch (NativeDaemonConnectorException e) {
2095 // Encryption failed
2096 return e.getCode();
2097 }
2098 }
2099
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002100 @Override
2101 public StorageVolume[] getVolumeList() {
2102 final int callingUserId = UserHandle.getCallingUserId();
2103 final boolean accessAll = (mContext.checkPermission(
2104 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2105 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2106
2107 synchronized (mVolumesLock) {
2108 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2109 for (StorageVolume volume : mVolumes) {
2110 final UserHandle owner = volume.getOwner();
2111 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2112 if (accessAll || ownerMatch) {
2113 filtered.add(volume);
2114 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002115 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002116 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002117 }
2118 }
2119
Kenny Rootaf9d6672010-10-08 09:21:39 -07002120 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2121 final IBinder binder = obbState.getBinder();
2122 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002123
Kenny Rootaf9d6672010-10-08 09:21:39 -07002124 if (obbStates == null) {
2125 obbStates = new ArrayList<ObbState>();
2126 mObbMounts.put(binder, obbStates);
2127 } else {
2128 for (final ObbState o : obbStates) {
2129 if (o.filename.equals(obbState.filename)) {
2130 throw new IllegalStateException("Attempt to add ObbState twice. "
2131 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002132 }
2133 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002134 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002135
2136 obbStates.add(obbState);
2137 try {
2138 obbState.link();
2139 } catch (RemoteException e) {
2140 /*
2141 * The binder died before we could link it, so clean up our state
2142 * and return failure.
2143 */
2144 obbStates.remove(obbState);
2145 if (obbStates.isEmpty()) {
2146 mObbMounts.remove(binder);
2147 }
2148
2149 // Rethrow the error so mountObb can get it
2150 throw e;
2151 }
2152
2153 mObbPathToStateMap.put(obbState.filename, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002154 }
2155
Kenny Rootaf9d6672010-10-08 09:21:39 -07002156 private void removeObbStateLocked(ObbState obbState) {
2157 final IBinder binder = obbState.getBinder();
2158 final List<ObbState> obbStates = mObbMounts.get(binder);
2159 if (obbStates != null) {
2160 if (obbStates.remove(obbState)) {
2161 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002162 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002163 if (obbStates.isEmpty()) {
2164 mObbMounts.remove(binder);
2165 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002166 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002167
Kenny Rootaf9d6672010-10-08 09:21:39 -07002168 mObbPathToStateMap.remove(obbState.filename);
Kenny Root38cf8862010-09-26 14:18:51 -07002169 }
2170
Kenny Roota02b8b02010-08-05 16:14:17 -07002171 private class ObbActionHandler extends Handler {
2172 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002173 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002174
2175 ObbActionHandler(Looper l) {
2176 super(l);
2177 }
2178
2179 @Override
2180 public void handleMessage(Message msg) {
2181 switch (msg.what) {
2182 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002183 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002184
2185 if (DEBUG_OBB)
2186 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2187
2188 // If a bind was already initiated we don't really
2189 // need to do anything. The pending install
2190 // will be processed later on.
2191 if (!mBound) {
2192 // If this is the only one pending we might
2193 // have to bind to the service again.
2194 if (!connectToService()) {
2195 Slog.e(TAG, "Failed to bind to media container service");
2196 action.handleError();
2197 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002198 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002199 }
Kenny Root735de3b2010-09-30 14:11:39 -07002200
Kenny Root735de3b2010-09-30 14:11:39 -07002201 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002202 break;
2203 }
2204 case OBB_MCS_BOUND: {
2205 if (DEBUG_OBB)
2206 Slog.i(TAG, "OBB_MCS_BOUND");
2207 if (msg.obj != null) {
2208 mContainerService = (IMediaContainerService) msg.obj;
2209 }
2210 if (mContainerService == null) {
2211 // Something seriously wrong. Bail out
2212 Slog.e(TAG, "Cannot bind to media container service");
2213 for (ObbAction action : mActions) {
2214 // Indicate service bind error
2215 action.handleError();
2216 }
2217 mActions.clear();
2218 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002219 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002220 if (action != null) {
2221 action.execute(this);
2222 }
2223 } else {
2224 // Should never happen ideally.
2225 Slog.w(TAG, "Empty queue");
2226 }
2227 break;
2228 }
2229 case OBB_MCS_RECONNECT: {
2230 if (DEBUG_OBB)
2231 Slog.i(TAG, "OBB_MCS_RECONNECT");
2232 if (mActions.size() > 0) {
2233 if (mBound) {
2234 disconnectService();
2235 }
2236 if (!connectToService()) {
2237 Slog.e(TAG, "Failed to bind to media container service");
2238 for (ObbAction action : mActions) {
2239 // Indicate service bind error
2240 action.handleError();
2241 }
2242 mActions.clear();
2243 }
2244 }
2245 break;
2246 }
2247 case OBB_MCS_UNBIND: {
2248 if (DEBUG_OBB)
2249 Slog.i(TAG, "OBB_MCS_UNBIND");
2250
2251 // Delete pending install
2252 if (mActions.size() > 0) {
2253 mActions.remove(0);
2254 }
2255 if (mActions.size() == 0) {
2256 if (mBound) {
2257 disconnectService();
2258 }
2259 } else {
2260 // There are more pending requests in queue.
2261 // Just post MCS_BOUND message to trigger processing
2262 // of next pending install.
2263 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2264 }
2265 break;
2266 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002267 case OBB_FLUSH_MOUNT_STATE: {
2268 final String path = (String) msg.obj;
2269
2270 if (DEBUG_OBB)
2271 Slog.i(TAG, "Flushing all OBB state for path " + path);
2272
2273 synchronized (mObbMounts) {
2274 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2275
2276 final Iterator<Entry<String, ObbState>> i =
2277 mObbPathToStateMap.entrySet().iterator();
2278 while (i.hasNext()) {
2279 final Entry<String, ObbState> obbEntry = i.next();
2280
2281 /*
2282 * If this entry's source file is in the volume path
2283 * that got unmounted, remove it because it's no
2284 * longer valid.
2285 */
2286 if (obbEntry.getKey().startsWith(path)) {
2287 obbStatesToRemove.add(obbEntry.getValue());
2288 }
2289 }
2290
2291 for (final ObbState obbState : obbStatesToRemove) {
2292 if (DEBUG_OBB)
2293 Slog.i(TAG, "Removing state for " + obbState.filename);
2294
2295 removeObbStateLocked(obbState);
2296
2297 try {
2298 obbState.token.onObbResult(obbState.filename, obbState.nonce,
2299 OnObbStateChangeListener.UNMOUNTED);
2300 } catch (RemoteException e) {
2301 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
2302 + obbState.filename);
2303 }
2304 }
2305 }
2306 break;
2307 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002308 }
2309 }
2310
2311 private boolean connectToService() {
2312 if (DEBUG_OBB)
2313 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2314
2315 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2316 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2317 mBound = true;
2318 return true;
2319 }
2320 return false;
2321 }
2322
2323 private void disconnectService() {
2324 mContainerService = null;
2325 mBound = false;
2326 mContext.unbindService(mDefContainerConn);
2327 }
2328 }
2329
2330 abstract class ObbAction {
2331 private static final int MAX_RETRIES = 3;
2332 private int mRetries;
2333
2334 ObbState mObbState;
2335
2336 ObbAction(ObbState obbState) {
2337 mObbState = obbState;
2338 }
2339
2340 public void execute(ObbActionHandler handler) {
2341 try {
2342 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002343 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002344 mRetries++;
2345 if (mRetries > MAX_RETRIES) {
2346 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002347 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002348 handleError();
2349 return;
2350 } else {
2351 handleExecute();
2352 if (DEBUG_OBB)
2353 Slog.i(TAG, "Posting install MCS_UNBIND");
2354 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2355 }
2356 } catch (RemoteException e) {
2357 if (DEBUG_OBB)
2358 Slog.i(TAG, "Posting install MCS_RECONNECT");
2359 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2360 } catch (Exception e) {
2361 if (DEBUG_OBB)
2362 Slog.d(TAG, "Error handling OBB action", e);
2363 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002364 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002365 }
2366 }
2367
Kenny Root05105f72010-09-22 17:29:43 -07002368 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002369 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002370
2371 protected ObbInfo getObbInfo() throws IOException {
2372 ObbInfo obbInfo;
2373 try {
2374 obbInfo = mContainerService.getObbInfo(mObbState.filename);
2375 } catch (RemoteException e) {
2376 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
2377 + mObbState.filename);
2378 obbInfo = null;
2379 }
2380 if (obbInfo == null) {
2381 throw new IOException("Couldn't read OBB file: " + mObbState.filename);
2382 }
2383 return obbInfo;
2384 }
2385
Kenny Rootaf9d6672010-10-08 09:21:39 -07002386 protected void sendNewStatusOrIgnore(int status) {
2387 if (mObbState == null || mObbState.token == null) {
2388 return;
2389 }
2390
Kenny Root38cf8862010-09-26 14:18:51 -07002391 try {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002392 mObbState.token.onObbResult(mObbState.filename, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002393 } catch (RemoteException e) {
2394 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2395 }
2396 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002397 }
2398
2399 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002400 private final String mKey;
Kenny Roota02b8b02010-08-05 16:14:17 -07002401
2402 MountObbAction(ObbState obbState, String key) {
2403 super(obbState);
2404 mKey = key;
2405 }
2406
Jason parks5af0b912010-11-29 09:05:25 -06002407 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002408 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409 waitForReady();
2410 warnOnNotMounted();
2411
Kenny Root38cf8862010-09-26 14:18:51 -07002412 final ObbInfo obbInfo = getObbInfo();
2413
Kenny Roota02b8b02010-08-05 16:14:17 -07002414 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mObbState.callerUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002415 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2416 + " which is owned by " + obbInfo.packageName);
2417 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2418 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002419 }
2420
Kenny Rootaf9d6672010-10-08 09:21:39 -07002421 final boolean isMounted;
2422 synchronized (mObbMounts) {
2423 isMounted = mObbPathToStateMap.containsKey(obbInfo.filename);
2424 }
2425 if (isMounted) {
2426 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2427 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2428 return;
2429 }
2430
2431 /*
2432 * The filename passed in might not be the canonical name, so just
2433 * set the filename to the canonicalized version.
2434 */
2435 mObbState.filename = obbInfo.filename;
2436
2437 final String hashedKey;
2438 if (mKey == null) {
2439 hashedKey = "none";
2440 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002442 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2443
2444 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2445 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2446 SecretKey key = factory.generateSecret(ks);
2447 BigInteger bi = new BigInteger(key.getEncoded());
2448 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002449 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002450 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2451 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2452 return;
2453 } catch (InvalidKeySpecException e) {
2454 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2455 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002456 return;
2457 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002458 }
Kenny Root38cf8862010-09-26 14:18:51 -07002459
Kenny Rootaf9d6672010-10-08 09:21:39 -07002460 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002461 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002462 mConnector.execute(
2463 "obb", "mount", mObbState.filename, hashedKey, mObbState.callerUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002464 } catch (NativeDaemonConnectorException e) {
2465 int code = e.getCode();
2466 if (code != VoldResponseCode.OpFailedStorageBusy) {
2467 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002468 }
2469 }
2470
Kenny Rootaf9d6672010-10-08 09:21:39 -07002471 if (rc == StorageResultCode.OperationSucceeded) {
2472 if (DEBUG_OBB)
2473 Slog.d(TAG, "Successfully mounted OBB " + mObbState.filename);
2474
2475 synchronized (mObbMounts) {
2476 addObbStateLocked(mObbState);
2477 }
2478
2479 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002480 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002481 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002482
Kenny Rootaf9d6672010-10-08 09:21:39 -07002483 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002484 }
2485 }
2486
Jason parks5af0b912010-11-29 09:05:25 -06002487 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002488 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002489 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002490 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002491
2492 @Override
2493 public String toString() {
2494 StringBuilder sb = new StringBuilder();
2495 sb.append("MountObbAction{");
2496 sb.append("filename=");
2497 sb.append(mObbState.filename);
2498 sb.append(",callerUid=");
2499 sb.append(mObbState.callerUid);
2500 sb.append(",token=");
2501 sb.append(mObbState.token != null ? mObbState.token.toString() : "NULL");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002502 sb.append(",binder=");
2503 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002504 sb.append('}');
2505 return sb.toString();
2506 }
2507 }
2508
2509 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002510 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002511
2512 UnmountObbAction(ObbState obbState, boolean force) {
2513 super(obbState);
2514 mForceUnmount = force;
2515 }
2516
Jason parks5af0b912010-11-29 09:05:25 -06002517 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002518 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002519 waitForReady();
2520 warnOnNotMounted();
2521
Kenny Root38cf8862010-09-26 14:18:51 -07002522 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002523
Kenny Rootaf9d6672010-10-08 09:21:39 -07002524 final ObbState obbState;
Kenny Root38cf8862010-09-26 14:18:51 -07002525 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002526 obbState = mObbPathToStateMap.get(obbInfo.filename);
2527 }
Kenny Root38cf8862010-09-26 14:18:51 -07002528
Kenny Rootaf9d6672010-10-08 09:21:39 -07002529 if (obbState == null) {
2530 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2531 return;
2532 }
2533
2534 if (obbState.callerUid != mObbState.callerUid) {
2535 Slog.w(TAG, "Permission denied attempting to unmount OBB " + obbInfo.filename
2536 + " (owned by " + obbInfo.packageName + ")");
2537 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2538 return;
2539 }
2540
2541 mObbState.filename = obbInfo.filename;
2542
2543 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002545 final Command cmd = new Command("obb", "unmount", mObbState.filename);
2546 if (mForceUnmount) {
2547 cmd.appendArg("force");
2548 }
2549 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002550 } catch (NativeDaemonConnectorException e) {
2551 int code = e.getCode();
2552 if (code == VoldResponseCode.OpFailedStorageBusy) {
2553 rc = StorageResultCode.OperationFailedStorageBusy;
2554 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2555 // If it's not mounted then we've already won.
2556 rc = StorageResultCode.OperationSucceeded;
2557 } else {
2558 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002559 }
2560 }
2561
Kenny Rootaf9d6672010-10-08 09:21:39 -07002562 if (rc == StorageResultCode.OperationSucceeded) {
2563 synchronized (mObbMounts) {
2564 removeObbStateLocked(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002565 }
2566
Kenny Rootaf9d6672010-10-08 09:21:39 -07002567 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002568 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002569 Slog.w(TAG, "Could not mount OBB: " + mObbState.filename);
2570 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002571 }
2572 }
2573
Jason parks5af0b912010-11-29 09:05:25 -06002574 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002575 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002577 }
2578
2579 @Override
2580 public String toString() {
2581 StringBuilder sb = new StringBuilder();
2582 sb.append("UnmountObbAction{");
2583 sb.append("filename=");
2584 sb.append(mObbState.filename != null ? mObbState.filename : "null");
2585 sb.append(",force=");
2586 sb.append(mForceUnmount);
2587 sb.append(",callerUid=");
2588 sb.append(mObbState.callerUid);
2589 sb.append(",token=");
2590 sb.append(mObbState.token != null ? mObbState.token.toString() : "null");
Kenny Root735de3b2010-09-30 14:11:39 -07002591 sb.append(",binder=");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002592 sb.append(mObbState.token != null ? mObbState.getBinder().toString() : "null");
Kenny Roota02b8b02010-08-05 16:14:17 -07002593 sb.append('}');
2594 return sb.toString();
2595 }
Kenny Root02c87302010-07-01 08:10:18 -07002596 }
Kenny Root38cf8862010-09-26 14:18:51 -07002597
2598 @Override
2599 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2600 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2601 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2602 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2603 + " without permission " + android.Manifest.permission.DUMP);
2604 return;
2605 }
2606
Kenny Root38cf8862010-09-26 14:18:51 -07002607 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002608 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002609
Kenny Rootaf9d6672010-10-08 09:21:39 -07002610 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2611 while (binders.hasNext()) {
2612 Entry<IBinder, List<ObbState>> e = binders.next();
2613 pw.print(" Key="); pw.println(e.getKey().toString());
2614 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002615 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002616 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002617 }
2618 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002619
2620 pw.println("");
2621 pw.println(" mObbPathToStateMap:");
2622 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2623 while (maps.hasNext()) {
2624 final Entry<String, ObbState> e = maps.next();
2625 pw.print(" "); pw.print(e.getKey());
2626 pw.print(" -> "); pw.println(e.getValue().toString());
2627 }
Kenny Root38cf8862010-09-26 14:18:51 -07002628 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002629
2630 pw.println("");
2631
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002632 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002633 pw.println(" mVolumes:");
2634
2635 final int N = mVolumes.size();
2636 for (int i = 0; i < N; i++) {
2637 final StorageVolume v = mVolumes.get(i);
2638 pw.print(" ");
2639 pw.println(v.toString());
2640 }
2641 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002642
2643 pw.println();
2644 pw.println(" mConnection:");
2645 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002648 /** {@inheritDoc} */
2649 public void monitor() {
2650 if (mConnector != null) {
2651 mConnector.monitor();
2652 }
2653 }
2654}