blob: f73a92be9694749d87bd75ac7eefdcbb380e3c15 [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;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070064import com.android.internal.app.IMediaContainerService;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070065import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070066import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070067import com.android.internal.util.XmlUtils;
68import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070069import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070070import com.android.server.am.ActivityManagerService;
71import com.android.server.pm.PackageManagerService;
72import com.android.server.pm.UserManagerService;
73import com.google.android.collect.Lists;
74import com.google.android.collect.Maps;
75
Mike Lockwood2f6a3882011-05-09 19:08:06 -070076import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070077
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070078import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070080import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070081import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070082import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070083import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070084import java.security.spec.InvalidKeySpecException;
85import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080086import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070087import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080088import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070089import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070090import java.util.LinkedList;
91import java.util.List;
92import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070093import java.util.Map.Entry;
Rickard Helldin5fb5df02014-02-07 09:35:04 +010094import java.util.concurrent.atomic.AtomicInteger;
Kenny Root51a573c2012-05-17 13:30:28 -070095import java.util.concurrent.CountDownLatch;
96import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Kenny Root3b1abba2010-10-13 15:00:07 -070098import javax.crypto.SecretKey;
99import javax.crypto.SecretKeyFactory;
100import javax.crypto.spec.PBEKeySpec;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102/**
San Mehatb1043402010-02-05 08:26:50 -0800103 * MountService implements back-end services for platform storage
104 * management.
105 * @hide - Applications should use android.os.storage.StorageManager
106 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700108class MountService extends IMountService.Stub
109 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600110
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700111 // TODO: listen for user creation/deletion
112
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800113 private static final boolean LOCAL_LOGD = false;
114 private static final boolean DEBUG_UNMOUNT = false;
115 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800116 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700117
Kenny Root07714d42011-08-17 17:49:28 -0700118 // Disable this since it messes up long-running cryptfs operations.
119 private static final boolean WATCHDOG_ENABLE = false;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private static final String TAG = "MountService";
122
Kenny Root305bcbf2010-09-03 07:56:38 -0700123 private static final String VOLD_TAG = "VoldConnector";
124
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700125 /** Maximum number of ASEC containers allowed to be mounted. */
126 private static final int MAX_CONTAINERS = 250;
127
San Mehat4270e1e2010-01-29 05:32:19 -0800128 /*
129 * Internal vold volume state constants
130 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800131 class VolumeState {
132 public static final int Init = -1;
133 public static final int NoMedia = 0;
134 public static final int Idle = 1;
135 public static final int Pending = 2;
136 public static final int Checking = 3;
137 public static final int Mounted = 4;
138 public static final int Unmounting = 5;
139 public static final int Formatting = 6;
140 public static final int Shared = 7;
141 public static final int SharedMnt = 8;
142 }
143
San Mehat4270e1e2010-01-29 05:32:19 -0800144 /*
145 * Internal vold response code constants
146 */
San Mehat22dd86e2010-01-12 12:21:18 -0800147 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800148 /*
149 * 100 series - Requestion action was initiated; expect another reply
150 * before proceeding with a new command.
151 */
San Mehat22dd86e2010-01-12 12:21:18 -0800152 public static final int VolumeListResult = 110;
153 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800154 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800155
San Mehat4270e1e2010-01-29 05:32:19 -0800156 /*
157 * 200 series - Requestion action has been successfully completed.
158 */
159 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800160 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800161 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800162
San Mehat4270e1e2010-01-29 05:32:19 -0800163 /*
164 * 400 series - Command was accepted, but the requested action
165 * did not take place.
166 */
167 public static final int OpFailedNoMedia = 401;
168 public static final int OpFailedMediaBlank = 402;
169 public static final int OpFailedMediaCorrupt = 403;
170 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800171 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700172 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800173
174 /*
175 * 600 series - Unsolicited broadcasts.
176 */
San Mehat22dd86e2010-01-12 12:21:18 -0800177 public static final int VolumeStateChange = 605;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700178 public static final int VolumeUuidChange = 613;
179 public static final int VolumeUserLabelChange = 614;
San Mehat22dd86e2010-01-12 12:21:18 -0800180 public static final int VolumeDiskInserted = 630;
181 public static final int VolumeDiskRemoved = 631;
182 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700183
184 /*
185 * 700 series - fstrim
186 */
187 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800188 }
189
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700190 private Context mContext;
191 private NativeDaemonConnector mConnector;
192
193 private final Object mVolumesLock = new Object();
194
195 /** When defined, base template for user-specific {@link StorageVolume}. */
196 private StorageVolume mEmulatedTemplate;
197
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700198 // TODO: separate storage volumes on per-user basis
199
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800200 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700201 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
202 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800203 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700204 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
205 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800206 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700207 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
208
209 private volatile boolean mSystemReady = false;
210
San Mehat4270e1e2010-01-29 05:32:19 -0800211 private PackageManagerService mPms;
212 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700213 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800214 // Used as a lock for methods that register/unregister listeners.
215 final private ArrayList<MountServiceBinderListener> mListeners =
216 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800217 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
218 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800219 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800220
San Mehat6cdd9c02010-02-09 14:45:20 -0800221 /**
222 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800223 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800224 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800225 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800226
Kenny Root02c87302010-07-01 08:10:18 -0700227 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700228 * The size of the crypto algorithm key in bits for OBB files. Currently
229 * Twofish is used which takes 128-bit keys.
230 */
231 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
232
233 /**
234 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
235 * 1024 is reasonably secure and not too slow.
236 */
237 private static final int PBKDF2_HASH_ROUNDS = 1024;
238
239 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700240 * Mounted OBB tracking information. Used to track the current state of all
241 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700242 */
Kenny Root735de3b2010-09-30 14:11:39 -0700243 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700244
245 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700246 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
247
248 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700249 public ObbState(String rawPath, String canonicalPath, int callingUid,
250 IObbActionListener token, int nonce) {
251 this.rawPath = rawPath;
252 this.canonicalPath = canonicalPath.toString();
253
254 final int userId = UserHandle.getUserId(callingUid);
255 this.ownerPath = buildObbPath(canonicalPath, userId, false);
256 this.voldPath = buildObbPath(canonicalPath, userId, true);
257
258 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700259 this.token = token;
260 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700261 }
262
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700263 final String rawPath;
264 final String canonicalPath;
265 final String ownerPath;
266 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700267
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700268 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700269
Kenny Rootaf9d6672010-10-08 09:21:39 -0700270 // Token of remote Binder caller
271 final IObbActionListener token;
272
273 // Identifier to pass back to the token
274 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700275
Kenny Root735de3b2010-09-30 14:11:39 -0700276 public IBinder getBinder() {
277 return token.asBinder();
278 }
279
Kenny Roota02b8b02010-08-05 16:14:17 -0700280 @Override
281 public void binderDied() {
282 ObbAction action = new UnmountObbAction(this, true);
283 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700284 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700285
Kenny Root5919ac62010-10-05 09:49:40 -0700286 public void link() throws RemoteException {
287 getBinder().linkToDeath(this, 0);
288 }
289
290 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700291 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700292 }
Kenny Root38cf8862010-09-26 14:18:51 -0700293
294 @Override
295 public String toString() {
296 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700297 sb.append("rawPath=").append(rawPath);
298 sb.append(",canonicalPath=").append(canonicalPath);
299 sb.append(",ownerPath=").append(ownerPath);
300 sb.append(",voldPath=").append(voldPath);
301 sb.append(",ownerGid=").append(ownerGid);
302 sb.append(",token=").append(token);
303 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700304 sb.append('}');
305 return sb.toString();
306 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700307 }
308
309 // OBB Action Handler
310 final private ObbActionHandler mObbActionHandler;
311
312 // OBB action handler messages
313 private static final int OBB_RUN_ACTION = 1;
314 private static final int OBB_MCS_BOUND = 2;
315 private static final int OBB_MCS_UNBIND = 3;
316 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700317 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700318
319 /*
320 * Default Container Service information
321 */
322 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
323 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
324
325 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
326
327 class DefaultContainerConnection implements ServiceConnection {
328 public void onServiceConnected(ComponentName name, IBinder service) {
329 if (DEBUG_OBB)
330 Slog.i(TAG, "onServiceConnected");
331 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
332 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
333 }
334
335 public void onServiceDisconnected(ComponentName name) {
336 if (DEBUG_OBB)
337 Slog.i(TAG, "onServiceDisconnected");
338 }
339 };
340
341 // Used in the ObbActionHandler
342 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700343
344 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800345 private static final int H_UNMOUNT_PM_UPDATE = 1;
346 private static final int H_UNMOUNT_PM_DONE = 2;
347 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700348 private static final int H_SYSTEM_READY = 4;
349
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
351 private static final int MAX_UNMOUNT_RETRIES = 4;
352
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700354 final String path;
355 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700356 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800357 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800358
Ben Komalo13c71972011-09-07 16:35:56 -0700359 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 retries = 0;
361 this.path = path;
362 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700363 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800364 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800365
366 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700367 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700368 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800369 }
370 }
371
372 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700373 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800374
375 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700376 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800377 this.method = method;
378 }
379
380 @Override
381 void handleFinished() {
382 super.handleFinished();
383 doShareUnshareVolume(path, method, true);
384 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800385 }
386
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 class ShutdownCallBack extends UnmountCallBack {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100388 MountShutdownLatch mMountShutdownLatch;
389 ShutdownCallBack(String path, final MountShutdownLatch mountShutdownLatch) {
Ben Komalo13c71972011-09-07 16:35:56 -0700390 super(path, true, false);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100391 mMountShutdownLatch = mountShutdownLatch;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 }
393
394 @Override
395 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700396 int ret = doUnmountVolume(path, true, removeEncryption);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100397 Slog.i(TAG, "Unmount completed: " + path + ", result code: " + ret);
398 mMountShutdownLatch.countDown();
399 }
400 }
401
402 static class MountShutdownLatch {
403 private IMountShutdownObserver mObserver;
404 private AtomicInteger mCount;
405
406 MountShutdownLatch(final IMountShutdownObserver observer, int count) {
407 mObserver = observer;
408 mCount = new AtomicInteger(count);
409 }
410
411 void countDown() {
412 boolean sendShutdown = false;
413 if (mCount.decrementAndGet() == 0) {
414 sendShutdown = true;
415 }
416 if (sendShutdown && mObserver != null) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800417 try {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100418 mObserver.onShutDownComplete(StorageResultCode.OperationSucceeded);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700420 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800421 }
422 }
423 }
424 }
425
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400426 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800427 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700428 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800429
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400430 MountServiceHandler(Looper l) {
431 super(l);
432 }
433
Jason parks5af0b912010-11-29 09:05:25 -0600434 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800435 public void handleMessage(Message msg) {
436 switch (msg.what) {
437 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700438 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
440 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700441 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800442 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700443 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700444 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700445 mUpdatingStatus = true;
446 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800447 }
448 break;
449 }
450 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700451 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700452 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700453 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800454 int size = mForceUnmounts.size();
455 int sizeArr[] = new int[size];
456 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700457 // Kill processes holding references first
458 ActivityManagerService ams = (ActivityManagerService)
459 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800460 for (int i = 0; i < size; i++) {
461 UnmountCallBack ucb = mForceUnmounts.get(i);
462 String path = ucb.path;
463 boolean done = false;
464 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800465 done = true;
466 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800467 int pids[] = getStorageUsers(path);
468 if (pids == null || pids.length == 0) {
469 done = true;
470 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800471 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800472 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700473 // Confirm if file references have been freed.
474 pids = getStorageUsers(path);
475 if (pids == null || pids.length == 0) {
476 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800477 }
478 }
479 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700480 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
481 // Retry again
482 Slog.i(TAG, "Retrying to kill storage users again");
483 mHandler.sendMessageDelayed(
484 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
485 ucb.retries++),
486 RETRY_UNMOUNT_DELAY);
487 } else {
488 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
489 Slog.i(TAG, "Failed to unmount media inspite of " +
490 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
491 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800492 sizeArr[sizeArrN++] = i;
493 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
494 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800495 }
496 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800497 // Remove already processed elements from list.
498 for (int i = (sizeArrN-1); i >= 0; i--) {
499 mForceUnmounts.remove(sizeArr[i]);
500 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800501 break;
502 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700503 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700504 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800505 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800506 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800507 break;
508 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700509 case H_SYSTEM_READY: {
510 try {
511 handleSystemReady();
512 } catch (Exception ex) {
513 Slog.e(TAG, "Boot-time mount exception", ex);
514 }
515 break;
516 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800517 }
518 }
519 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700520
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700521 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800522
Kenny Root51a573c2012-05-17 13:30:28 -0700523 void waitForAsecScan() {
524 waitForLatch(mAsecsScanned);
525 }
526
San Mehat207e5382010-02-04 20:46:54 -0800527 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700528 waitForLatch(mConnectedSignal);
529 }
530
531 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700532 for (;;) {
533 try {
534 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800535 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700536 } else {
537 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
538 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800539 }
Kenny Root51a573c2012-05-17 13:30:28 -0700540 } catch (InterruptedException e) {
541 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800542 }
San Mehat207e5382010-02-04 20:46:54 -0800543 }
San Mehat1f6301e2010-01-07 22:40:27 -0800544 }
Kenny Root02c87302010-07-01 08:10:18 -0700545
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700546 private void handleSystemReady() {
547 // Snapshot current volume states since it's not safe to call into vold
548 // while holding locks.
549 final HashMap<String, String> snapshot;
550 synchronized (mVolumesLock) {
551 snapshot = new HashMap<String, String>(mVolumeStates);
552 }
553
554 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
555 final String path = entry.getKey();
556 final String state = entry.getValue();
557
558 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
559 int rc = doMountVolume(path);
560 if (rc != StorageResultCode.OperationSucceeded) {
561 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
562 rc));
563 }
564 } else if (state.equals(Environment.MEDIA_SHARED)) {
565 /*
566 * Bootstrap UMS enabled state since vold indicates
567 * the volume is shared (runtime restart while ums enabled)
568 */
569 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
570 VolumeState.Shared);
571 }
572 }
573
574 // Push mounted state for all emulated storage
575 synchronized (mVolumesLock) {
576 for (StorageVolume volume : mVolumes) {
577 if (volume.isEmulated()) {
578 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
579 }
580 }
581 }
582
583 /*
584 * If UMS was connected on boot, send the connected event
585 * now that we're up.
586 */
587 if (mSendUmsConnectedOnBoot) {
588 sendUmsIntent(true);
589 mSendUmsConnectedOnBoot = false;
590 }
591 }
592
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700593 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
594 @Override
595 public void onReceive(Context context, Intent intent) {
596 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
597 if (userId == -1) return;
598 final UserHandle user = new UserHandle(userId);
599
600 final String action = intent.getAction();
601 if (Intent.ACTION_USER_ADDED.equals(action)) {
602 synchronized (mVolumesLock) {
603 createEmulatedVolumeForUserLocked(user);
604 }
605
606 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
607 synchronized (mVolumesLock) {
608 final List<StorageVolume> toRemove = Lists.newArrayList();
609 for (StorageVolume volume : mVolumes) {
610 if (user.equals(volume.getOwner())) {
611 toRemove.add(volume);
612 }
613 }
614 for (StorageVolume volume : toRemove) {
615 removeVolumeLocked(volume);
616 }
617 }
618 }
619 }
620 };
621
622 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
623 @Override
624 public void onReceive(Context context, Intent intent) {
625 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
626 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
627 notifyShareAvailabilityChange(available);
628 }
629 };
630
Svetoslava7452ee2013-03-20 12:06:59 -0700631 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
632 @Override
633 public void onReceive(Context context, Intent intent) {
634 waitForReady();
635 String action = intent.getAction();
636 // Since fstrim will be run on a daily basis we do not expect
637 // fstrim to be too long, so it is not interruptible. We will
638 // implement interruption only in case we see issues.
639 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
640 try {
641 // This method runs on the handler thread,
642 // so it is safe to directly call into vold.
643 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700644 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700645 } catch (NativeDaemonConnectorException ndce) {
646 Slog.e(TAG, "Failed to run fstrim!");
647 }
648 }
649 }
650 };
651
San Mehat4270e1e2010-01-29 05:32:19 -0800652 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
653 final IMountServiceListener mListener;
654
655 MountServiceBinderListener(IMountServiceListener listener) {
656 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700657
San Mehat91c77612010-01-07 10:39:41 -0800658 }
659
San Mehat4270e1e2010-01-29 05:32:19 -0800660 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700661 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700662 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800663 mListeners.remove(this);
664 mListener.asBinder().unlinkToDeath(this, 0);
665 }
666 }
667 }
668
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800669 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800670 // TODO: Add support for multiple share methods
671 if (!method.equals("ums")) {
672 throw new IllegalArgumentException(String.format("Method %s not supported", method));
673 }
674
San Mehat4270e1e2010-01-29 05:32:19 -0800675 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800676 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800677 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700678 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800679 }
San Mehat4270e1e2010-01-29 05:32:19 -0800680 }
681
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700682 private void updatePublicVolumeState(StorageVolume volume, String state) {
683 final String path = volume.getPath();
684 final String oldState;
685 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400686 oldState = mVolumeStates.put(path, state);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700687 volume.setState(state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400688 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700689
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400690 if (state.equals(oldState)) {
691 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
692 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800693 return;
694 }
San Mehatb1043402010-02-05 08:26:50 -0800695
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400696 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700697
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700698 // Tell PackageManager about changes to primary volume state, but only
699 // when not emulated.
700 if (volume.isPrimary() && !volume.isEmulated()) {
701 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
702 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400703
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700704 /*
705 * Some OBBs might have been unmounted when this volume was
706 * unmounted, so send a message to the handler to let it know to
707 * remove those from the list of mounted OBBS.
708 */
709 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
710 OBB_FLUSH_MOUNT_STATE, path));
711 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
712 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400713 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800714 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700715
San Mehat4270e1e2010-01-29 05:32:19 -0800716 synchronized (mListeners) {
717 for (int i = mListeners.size() -1; i >= 0; i--) {
718 MountServiceBinderListener bl = mListeners.get(i);
719 try {
San Mehatb1043402010-02-05 08:26:50 -0800720 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800721 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700722 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800723 mListeners.remove(i);
724 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700725 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800726 }
727 }
728 }
729 }
730
731 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800732 * Callback from NativeDaemonConnector
733 */
734 public void onDaemonConnected() {
735 /*
736 * Since we'll be calling back into the NativeDaemonConnector,
737 * we need to do our work in a new thread.
738 */
Kenny Root51a573c2012-05-17 13:30:28 -0700739 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600740 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800741 public void run() {
742 /**
743 * Determine media state and UMS detection status
744 */
San Mehat4270e1e2010-01-29 05:32:19 -0800745 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800746 final String[] vols = NativeDaemonEvent.filterMessageList(
747 mConnector.executeForList("volume", "list"),
748 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800749 for (String volstr : vols) {
750 String[] tok = volstr.split(" ");
751 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400752 String path = tok[1];
753 String state = Environment.MEDIA_REMOVED;
754
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700755 final StorageVolume volume;
756 synchronized (mVolumesLock) {
757 volume = mVolumesByPath.get(path);
758 }
759
San Mehat4270e1e2010-01-29 05:32:19 -0800760 int st = Integer.parseInt(tok[2]);
761 if (st == VolumeState.NoMedia) {
762 state = Environment.MEDIA_REMOVED;
763 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800764 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800765 } else if (st == VolumeState.Mounted) {
766 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700767 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800768 } else if (st == VolumeState.Shared) {
769 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700770 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800771 } else {
772 throw new Exception(String.format("Unexpected state %d", st));
773 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400774
775 if (state != null) {
776 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700777 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400778 }
San Mehat4270e1e2010-01-29 05:32:19 -0800779 }
780 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700781 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700782 final StorageVolume primary = getPrimaryPhysicalVolume();
783 if (primary != null) {
784 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
785 }
San Mehat4270e1e2010-01-29 05:32:19 -0800786 }
787
San Mehat207e5382010-02-04 20:46:54 -0800788 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600789 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800790 * the hounds!
791 */
Kenny Root51a573c2012-05-17 13:30:28 -0700792 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700793
794 // Let package manager load internal ASECs.
795 mPms.scanAvailableAsecs();
796
797 // Notify people waiting for ASECs to be scanned that it's done.
798 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800799 }
800 }.start();
801 }
802
803 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800804 * Callback from NativeDaemonConnector
805 */
806 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800807 if (DEBUG_EVENTS) {
808 StringBuilder builder = new StringBuilder();
809 builder.append("onEvent::");
810 builder.append(" raw= " + raw);
811 if (cooked != null) {
812 builder.append(" cooked = " );
813 for (String str : cooked) {
814 builder.append(" " + str);
815 }
816 }
San Mehata5078592010-03-25 09:36:54 -0700817 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800818 }
San Mehat4270e1e2010-01-29 05:32:19 -0800819 if (code == VoldResponseCode.VolumeStateChange) {
820 /*
821 * One of the volumes we're managing has changed state.
822 * Format: "NNN Volume <label> <path> state changed
823 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
824 */
825 notifyVolumeStateChange(
826 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
827 Integer.parseInt(cooked[10]));
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700828 } else if (code == VoldResponseCode.VolumeUuidChange) {
829 // Format: nnn <label> <path> <uuid>
830 final String path = cooked[2];
831 final String uuid = (cooked.length > 3) ? cooked[3] : null;
832
833 final StorageVolume vol = mVolumesByPath.get(path);
834 if (vol != null) {
835 vol.setUuid(uuid);
836 }
837
838 } else if (code == VoldResponseCode.VolumeUserLabelChange) {
839 // Format: nnn <label> <path> <label>
840 final String path = cooked[2];
841 final String userLabel = (cooked.length > 3) ? cooked[3] : null;
842
843 final StorageVolume vol = mVolumesByPath.get(path);
844 if (vol != null) {
845 vol.setUserLabel(userLabel);
846 }
847
San Mehat4270e1e2010-01-29 05:32:19 -0800848 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
849 (code == VoldResponseCode.VolumeDiskRemoved) ||
850 (code == VoldResponseCode.VolumeBadRemoval)) {
851 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
852 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
853 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400854 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800855 final String label = cooked[2];
856 final String path = cooked[3];
857 int major = -1;
858 int minor = -1;
859
860 try {
861 String devComp = cooked[6].substring(1, cooked[6].length() -1);
862 String[] devTok = devComp.split(":");
863 major = Integer.parseInt(devTok[0]);
864 minor = Integer.parseInt(devTok[1]);
865 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700866 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800867 }
868
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700869 final StorageVolume volume;
870 final String state;
871 synchronized (mVolumesLock) {
872 volume = mVolumesByPath.get(path);
873 state = mVolumeStates.get(path);
874 }
875
San Mehat4270e1e2010-01-29 05:32:19 -0800876 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700877 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600878 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800879 public void run() {
880 try {
881 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800882 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700883 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800884 }
885 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700886 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800887 }
888 }
889 }.start();
890 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
891 /*
892 * This event gets trumped if we're already in BAD_REMOVAL state
893 */
894 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
895 return true;
896 }
897 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700898 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700899 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Johan Redestig0464c072014-01-18 22:46:56 +0100900 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800901
San Mehata5078592010-03-25 09:36:54 -0700902 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700903 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400904 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800905 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700906 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800907 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700908 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200909 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800910
San Mehata5078592010-03-25 09:36:54 -0700911 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700912 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400913 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700914 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700915 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800916 } else {
San Mehata5078592010-03-25 09:36:54 -0700917 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800918 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400919
920 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700921 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400922 }
San Mehat4270e1e2010-01-29 05:32:19 -0800923 } else {
924 return false;
925 }
926
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400927 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800928 }
929
San Mehat207e5382010-02-04 20:46:54 -0800930 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700931 final StorageVolume volume;
932 final String state;
933 synchronized (mVolumesLock) {
934 volume = mVolumesByPath.get(path);
935 state = getVolumeState(path);
936 }
937
938 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800939
Mike Lockwooda5250c92011-05-23 13:44:04 -0400940 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800941
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500942 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700943 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700944 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500945 }
946
San Mehat4270e1e2010-01-29 05:32:19 -0800947 if (newState == VolumeState.Init) {
948 } else if (newState == VolumeState.NoMedia) {
949 // NoMedia is handled via Disk Remove events
950 } else if (newState == VolumeState.Idle) {
951 /*
952 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
953 * if we're in the process of enabling UMS
954 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700955 if (!state.equals(
956 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
957 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800958 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700959 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700960 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400961 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800962 }
963 } else if (newState == VolumeState.Pending) {
964 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700965 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700966 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400967 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800968 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700969 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700970 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400971 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800972 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400973 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800974 } else if (newState == VolumeState.Formatting) {
975 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700976 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800977 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700978 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
979 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800980
San Mehata5078592010-03-25 09:36:54 -0700981 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700982 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400983 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700984 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800985 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700986 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800987 return;
988 } else {
San Mehata5078592010-03-25 09:36:54 -0700989 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800990 }
991
Mike Lockwooda5250c92011-05-23 13:44:04 -0400992 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700993 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800994 }
995 }
996
San Mehat207e5382010-02-04 20:46:54 -0800997 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800998 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800999
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001000 final StorageVolume volume;
1001 synchronized (mVolumesLock) {
1002 volume = mVolumesByPath.get(path);
1003 }
1004
San Mehata5078592010-03-25 09:36:54 -07001005 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -08001006 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001007 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -08001008 } catch (NativeDaemonConnectorException e) {
1009 /*
1010 * Mount failed for some reason
1011 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001012 String action = null;
San Mehat207e5382010-02-04 20:46:54 -08001013 int code = e.getCode();
1014 if (code == VoldResponseCode.OpFailedNoMedia) {
1015 /*
1016 * Attempt to mount but no media inserted
1017 */
San Mehatb1043402010-02-05 08:26:50 -08001018 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001019 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -07001020 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -08001021 /*
1022 * Media is blank or does not contain a supported filesystem
1023 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001024 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001025 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -08001026 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -08001027 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -07001028 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -08001029 /*
1030 * Volume consistency check failed
1031 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001032 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001033 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -08001034 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001035 } else {
San Mehatb1043402010-02-05 08:26:50 -08001036 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001037 }
1038
1039 /*
1040 * Send broadcast intent (if required for the failure)
1041 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001042 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001043 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001044 }
1045 }
1046
1047 return rc;
1048 }
1049
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001050 /*
1051 * If force is not set, we do not unmount if there are
1052 * processes holding references to the volume about to be unmounted.
1053 * If force is set, all the processes holding references need to be
1054 * killed via the ActivityManager before actually unmounting the volume.
1055 * This might even take a while and might be retried after timed delays
1056 * to make sure we dont end up in an instable state and kill some core
1057 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001058 * If removeEncryption is set, force is implied, and the system will remove any encryption
1059 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001060 */
Ben Komalo13c71972011-09-07 16:35:56 -07001061 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001062 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001063 return VoldResponseCode.OpFailedVolNotMounted;
1064 }
Kenny Rootaa485402010-09-14 14:49:41 -07001065
1066 /*
1067 * Force a GC to make sure AssetManagers in other threads of the
1068 * system_server are cleaned up. We have to do this since AssetManager
1069 * instances are kept as a WeakReference and it's possible we have files
1070 * open on the external storage.
1071 */
1072 Runtime.getRuntime().gc();
1073
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001074 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001075 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001076 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001077 final Command cmd = new Command("volume", "unmount", path);
1078 if (removeEncryption) {
1079 cmd.appendArg("force_and_revert");
1080 } else if (force) {
1081 cmd.appendArg("force");
1082 }
1083 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001084 // We unmounted the volume. None of the asec containers are available now.
1085 synchronized (mAsecMountSet) {
1086 mAsecMountSet.clear();
1087 }
San Mehatb1043402010-02-05 08:26:50 -08001088 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001089 } catch (NativeDaemonConnectorException e) {
1090 // Don't worry about mismatch in PackageManager since the
1091 // call back will handle the status changes any way.
1092 int code = e.getCode();
1093 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001094 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001095 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1096 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001097 } else {
San Mehatb1043402010-02-05 08:26:50 -08001098 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001099 }
1100 }
1101 }
1102
1103 private int doFormatVolume(String path) {
1104 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001105 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001106 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001107 } catch (NativeDaemonConnectorException e) {
1108 int code = e.getCode();
1109 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001110 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001111 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001112 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001113 } else {
San Mehatb1043402010-02-05 08:26:50 -08001114 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001115 }
1116 }
1117 }
1118
San Mehatb1043402010-02-05 08:26:50 -08001119 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001120 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001121 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001122 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001123 } catch (NativeDaemonConnectorException ex) {
1124 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1125 return false;
1126 }
San Mehatb1043402010-02-05 08:26:50 -08001127
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001128 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1129 return event.getMessage().endsWith("enabled");
1130 } else {
1131 return false;
San Mehatb1043402010-02-05 08:26:50 -08001132 }
San Mehatb1043402010-02-05 08:26:50 -08001133 }
1134
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001135 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001136 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001137 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001138 for (int i = mListeners.size() -1; i >= 0; i--) {
1139 MountServiceBinderListener bl = mListeners.get(i);
1140 try {
San Mehatb1043402010-02-05 08:26:50 -08001141 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001142 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001143 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001144 mListeners.remove(i);
1145 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001146 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001147 }
1148 }
1149 }
1150
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001151 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001152 sendUmsIntent(avail);
1153 } else {
1154 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001155 }
San Mehat2fe718a2010-03-11 12:01:49 -08001156
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001157 final StorageVolume primary = getPrimaryPhysicalVolume();
1158 if (avail == false && primary != null
1159 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1160 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001161 /*
1162 * USB mass storage disconnected while enabled
1163 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001164 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001165 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001166 public void run() {
1167 try {
1168 int rc;
San Mehata5078592010-03-25 09:36:54 -07001169 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001170 doShareUnshareVolume(path, "ums", false);
1171 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001172 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001173 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1174 path, rc));
1175 }
1176 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001177 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001178 }
1179 }
1180 }.start();
1181 }
San Mehat4270e1e2010-01-29 05:32:19 -08001182 }
1183
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001184 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1185 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1186 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
Johan Redestig0464c072014-01-18 22:46:56 +01001187 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001188 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1189 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001190 }
1191
San Mehat6a965af22010-02-24 17:47:30 -08001192 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001193 mContext.sendBroadcastAsUser(
1194 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1195 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001196 }
1197
San Mehat207e5382010-02-04 20:46:54 -08001198 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001199 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1200 throw new SecurityException(String.format("Requires %s permission", perm));
1201 }
1202 }
1203
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001204 // Storage list XML tags
1205 private static final String TAG_STORAGE_LIST = "StorageList";
1206 private static final String TAG_STORAGE = "storage";
1207
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001208 private void readStorageListLocked() {
1209 mVolumes.clear();
1210 mVolumeStates.clear();
1211
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001212 Resources resources = mContext.getResources();
1213
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001214 int id = com.android.internal.R.xml.storage_list;
1215 XmlResourceParser parser = resources.getXml(id);
1216 AttributeSet attrs = Xml.asAttributeSet(parser);
1217
1218 try {
1219 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1220 while (true) {
1221 XmlUtils.nextElement(parser);
1222
1223 String element = parser.getName();
1224 if (element == null) break;
1225
1226 if (TAG_STORAGE.equals(element)) {
1227 TypedArray a = resources.obtainAttributes(attrs,
1228 com.android.internal.R.styleable.Storage);
1229
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001230 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001231 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001232 int descriptionId = a.getResourceId(
1233 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001234 CharSequence description = a.getText(
1235 com.android.internal.R.styleable.Storage_storageDescription);
1236 boolean primary = a.getBoolean(
1237 com.android.internal.R.styleable.Storage_primary, false);
1238 boolean removable = a.getBoolean(
1239 com.android.internal.R.styleable.Storage_removable, false);
1240 boolean emulated = a.getBoolean(
1241 com.android.internal.R.styleable.Storage_emulated, false);
1242 int mtpReserve = a.getInt(
1243 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001244 boolean allowMassStorage = a.getBoolean(
1245 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001246 // resource parser does not support longs, so XML value is in megabytes
1247 long maxFileSize = a.getInt(
1248 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001249
1250 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1251 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001252 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001253 " allowMassStorage: " + allowMassStorage +
1254 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001255
1256 if (emulated) {
1257 // For devices with emulated storage, we create separate
1258 // volumes for each known user.
1259 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1260 true, mtpReserve, false, maxFileSize, null);
1261
1262 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001263 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001264 createEmulatedVolumeForUserLocked(user.getUserHandle());
1265 }
1266
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001267 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001268 if (path == null || description == null) {
1269 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001270 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001271 final StorageVolume volume = new StorageVolume(new File(path),
1272 descriptionId, primary, removable, emulated, mtpReserve,
1273 allowMassStorage, maxFileSize, null);
1274 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001275
1276 // Until we hear otherwise, treat as unmounted
1277 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001278 volume.setState(Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001279 }
1280 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001281
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001282 a.recycle();
1283 }
1284 }
1285 } catch (XmlPullParserException e) {
1286 throw new RuntimeException(e);
1287 } catch (IOException e) {
1288 throw new RuntimeException(e);
1289 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001290 // Compute storage ID for each physical volume; emulated storage is
1291 // always 0 when defined.
1292 int index = isExternalStorageEmulated() ? 1 : 0;
1293 for (StorageVolume volume : mVolumes) {
1294 if (!volume.isEmulated()) {
1295 volume.setStorageId(index++);
1296 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001297 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001298 parser.close();
1299 }
1300 }
1301
San Mehat4270e1e2010-01-29 05:32:19 -08001302 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001303 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1304 * using {@link #mEmulatedTemplate} as template.
1305 */
1306 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1307 if (mEmulatedTemplate == null) {
1308 throw new IllegalStateException("Missing emulated volume multi-user template");
1309 }
1310
1311 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1312 final File path = userEnv.getExternalStorageDirectory();
1313 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1314 volume.setStorageId(0);
1315 addVolumeLocked(volume);
1316
1317 if (mSystemReady) {
1318 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1319 } else {
1320 // Place stub status for early callers to find
1321 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001322 volume.setState(Environment.MEDIA_MOUNTED);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001323 }
1324 }
1325
1326 private void addVolumeLocked(StorageVolume volume) {
1327 Slog.d(TAG, "addVolumeLocked() " + volume);
1328 mVolumes.add(volume);
1329 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1330 if (existing != null) {
1331 throw new IllegalStateException(
1332 "Volume at " + volume.getPath() + " already exists: " + existing);
1333 }
1334 }
1335
1336 private void removeVolumeLocked(StorageVolume volume) {
1337 Slog.d(TAG, "removeVolumeLocked() " + volume);
1338 mVolumes.remove(volume);
1339 mVolumesByPath.remove(volume.getPath());
1340 mVolumeStates.remove(volume.getPath());
1341 }
1342
1343 private StorageVolume getPrimaryPhysicalVolume() {
1344 synchronized (mVolumesLock) {
1345 for (StorageVolume volume : mVolumes) {
1346 if (volume.isPrimary() && !volume.isEmulated()) {
1347 return volume;
1348 }
1349 }
1350 }
1351 return null;
1352 }
1353
1354 /**
San Mehat207e5382010-02-04 20:46:54 -08001355 * Constructs a new MountService instance
1356 *
1357 * @param context Binder context for this service
1358 */
1359 public MountService(Context context) {
1360 mContext = context;
1361
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001362 synchronized (mVolumesLock) {
1363 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001364 }
1365
San Mehat207e5382010-02-04 20:46:54 -08001366 // XXX: This will go away soon in favor of IMountServiceObserver
1367 mPms = (PackageManagerService) ServiceManager.getService("package");
1368
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001369 HandlerThread hthread = new HandlerThread(TAG);
1370 hthread.start();
1371 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001372
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001373 // Watch for user changes
1374 final IntentFilter userFilter = new IntentFilter();
1375 userFilter.addAction(Intent.ACTION_USER_ADDED);
1376 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1377 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1378
1379 // Watch for USB changes on primary volume
1380 final StorageVolume primary = getPrimaryPhysicalVolume();
1381 if (primary != null && primary.allowMassStorage()) {
1382 mContext.registerReceiver(
1383 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1384 }
1385
Svetoslava7452ee2013-03-20 12:06:59 -07001386 // Watch for idle maintenance changes
1387 IntentFilter idleMaintenanceFilter = new IntentFilter();
1388 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1389 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1390 idleMaintenanceFilter, null, mHandler);
1391
Kenny Roota02b8b02010-08-05 16:14:17 -07001392 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001393 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001394
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001395 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001396 * Create the connection to vold with a maximum queue of twice the
1397 * amount of containers we'd ever expect to have. This keeps an
1398 * "asec list" from blocking a thread repeatedly.
1399 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001400 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001401
Kenny Root305bcbf2010-09-03 07:56:38 -07001402 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001403 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001404
Kenny Root07714d42011-08-17 17:49:28 -07001405 // Add ourself to the Watchdog monitors if enabled.
1406 if (WATCHDOG_ENABLE) {
1407 Watchdog.getInstance().addMonitor(this);
1408 }
San Mehat207e5382010-02-04 20:46:54 -08001409 }
1410
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001411 public void systemReady() {
1412 mSystemReady = true;
1413 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1414 }
1415
San Mehat207e5382010-02-04 20:46:54 -08001416 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001417 * Exposed API calls below here
1418 */
1419
1420 public void registerListener(IMountServiceListener listener) {
1421 synchronized (mListeners) {
1422 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1423 try {
1424 listener.asBinder().linkToDeath(bl, 0);
1425 mListeners.add(bl);
1426 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001427 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001428 }
1429 }
1430 }
1431
1432 public void unregisterListener(IMountServiceListener listener) {
1433 synchronized (mListeners) {
1434 for(MountServiceBinderListener bl : mListeners) {
Niklas Brunlidd64fe0f2013-07-05 08:54:03 +02001435 if (bl.mListener.asBinder() == listener.asBinder()) {
San Mehat4270e1e2010-01-29 05:32:19 -08001436 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001437 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001438 return;
1439 }
1440 }
1441 }
1442 }
1443
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001444 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001445 validatePermission(android.Manifest.permission.SHUTDOWN);
1446
San Mehata5078592010-03-25 09:36:54 -07001447 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001448 synchronized (mVolumesLock) {
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001449 // Get all volumes to be unmounted.
1450 MountShutdownLatch mountShutdownLatch = new MountShutdownLatch(observer,
1451 mVolumeStates.size());
1452
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001453 for (String path : mVolumeStates.keySet()) {
1454 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001455
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001456 if (state.equals(Environment.MEDIA_SHARED)) {
1457 /*
1458 * If the media is currently shared, unshare it.
1459 * XXX: This is still dangerous!. We should not
1460 * be rebooting at *all* if UMS is enabled, since
1461 * the UMS host could have dirty FAT cache entries
1462 * yet to flush.
1463 */
1464 setUsbMassStorageEnabled(false);
1465 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1466 /*
1467 * If the media is being checked, then we need to wait for
1468 * it to complete before being able to proceed.
1469 */
1470 // XXX: @hackbod - Should we disable the ANR timer here?
1471 int retries = 30;
1472 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1473 try {
1474 Thread.sleep(1000);
1475 } catch (InterruptedException iex) {
1476 Slog.e(TAG, "Interrupted while waiting for media", iex);
1477 break;
1478 }
1479 state = Environment.getExternalStorageState();
1480 }
1481 if (retries == 0) {
1482 Slog.e(TAG, "Timed out waiting for media to check");
1483 }
San Mehat91c77612010-01-07 10:39:41 -08001484 }
San Mehat91c77612010-01-07 10:39:41 -08001485
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001486 if (state.equals(Environment.MEDIA_MOUNTED)) {
1487 // Post a unmount message.
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001488 ShutdownCallBack ucb = new ShutdownCallBack(path, mountShutdownLatch);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001489 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1490 } else if (observer != null) {
1491 /*
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001492 * Count down, since nothing will be done. The observer will be
1493 * notified when we are done so shutdown sequence can continue.
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001494 */
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001495 mountShutdownLatch.countDown();
1496 Slog.i(TAG, "Unmount completed: " + path +
1497 ", result code: " + StorageResultCode.OperationSucceeded);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001498 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001499 }
San Mehat4270e1e2010-01-29 05:32:19 -08001500 }
1501 }
1502
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001503 private boolean getUmsEnabling() {
1504 synchronized (mListeners) {
1505 return mUmsEnabling;
1506 }
1507 }
1508
1509 private void setUmsEnabling(boolean enable) {
1510 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001511 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001512 }
1513 }
1514
San Mehatb1043402010-02-05 08:26:50 -08001515 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001516 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001517
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001518 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001519 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001520 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001521 synchronized (mListeners) {
1522 return mUmsAvailable;
1523 }
San Mehatb1043402010-02-05 08:26:50 -08001524 }
1525
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001526 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001527 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001528 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001529
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001530 final StorageVolume primary = getPrimaryPhysicalVolume();
1531 if (primary == null) return;
1532
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001533 // TODO: Add support for multiple share methods
1534
1535 /*
1536 * If the volume is mounted and we're enabling then unmount it
1537 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001538 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001539 String vs = getVolumeState(path);
1540 String method = "ums";
1541 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1542 // Override for isUsbMassStorageEnabled()
1543 setUmsEnabling(enable);
1544 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1545 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1546 // Clear override
1547 setUmsEnabling(false);
1548 }
1549 /*
1550 * If we disabled UMS then mount the volume
1551 */
1552 if (!enable) {
1553 doShareUnshareVolume(path, method, enable);
1554 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001555 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001556 " after disabling share method " + method);
1557 /*
1558 * Even though the mount failed, the unshare didn't so don't indicate an error.
1559 * The mountVolume() call will have set the storage state and sent the necessary
1560 * broadcasts.
1561 */
1562 }
1563 }
San Mehatb1043402010-02-05 08:26:50 -08001564 }
1565
1566 public boolean isUsbMassStorageEnabled() {
1567 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001568
1569 final StorageVolume primary = getPrimaryPhysicalVolume();
1570 if (primary != null) {
1571 return doGetVolumeShared(primary.getPath(), "ums");
1572 } else {
1573 return false;
1574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001576
San Mehat7fd0fee2009-12-17 07:12:23 -08001577 /**
1578 * @return state of the volume at the specified mount point
1579 */
San Mehat4270e1e2010-01-29 05:32:19 -08001580 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001581 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001582 String state = mVolumeStates.get(mountPoint);
1583 if (state == null) {
1584 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001585 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1586 state = Environment.MEDIA_REMOVED;
1587 } else {
1588 throw new IllegalArgumentException();
1589 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001590 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001591
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001592 return state;
1593 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001594 }
1595
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001596 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001597 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001598 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001599 }
1600
San Mehat4270e1e2010-01-29 05:32:19 -08001601 public int mountVolume(String path) {
1602 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001603
San Mehat207e5382010-02-04 20:46:54 -08001604 waitForReady();
1605 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607
Ben Komalo13c71972011-09-07 16:35:56 -07001608 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001609 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001610 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001612 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001613 if (DEBUG_UNMOUNT) {
1614 Slog.i(TAG, "Unmounting " + path
1615 + " force = " + force
1616 + " removeEncryption = " + removeEncryption);
1617 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001618 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1619 Environment.MEDIA_REMOVED.equals(volState) ||
1620 Environment.MEDIA_SHARED.equals(volState) ||
1621 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1622 // Media already unmounted or cannot be unmounted.
1623 // TODO return valid return code when adding observer call back.
1624 return;
1625 }
Ben Komalo13c71972011-09-07 16:35:56 -07001626 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001627 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629
San Mehat4270e1e2010-01-29 05:32:19 -08001630 public int formatVolume(String path) {
1631 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001632 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001633
San Mehat207e5382010-02-04 20:46:54 -08001634 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001637 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001638 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1639 waitForReady();
1640 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001641 final String[] r = NativeDaemonEvent.filterMessageList(
1642 mConnector.executeForList("storage", "users", path),
1643 VoldResponseCode.StorageUsersListResult);
1644
San Mehatc1b4ce92010-02-16 17:13:03 -08001645 // FMT: <pid> <process name>
1646 int[] data = new int[r.length];
1647 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001648 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001649 try {
1650 data[i] = Integer.parseInt(tok[0]);
1651 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001652 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001653 return new int[0];
1654 }
1655 }
1656 return data;
1657 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001658 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001659 return new int[0];
1660 }
1661 }
1662
San Mehatb1043402010-02-05 08:26:50 -08001663 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001664 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001665 if (primary != null) {
1666 boolean mounted = false;
1667 try {
1668 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001669 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001670 }
1671
1672 if (!mounted) {
1673 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1674 }
San Mehatb1043402010-02-05 08:26:50 -08001675 }
1676 }
1677
San Mehat4270e1e2010-01-29 05:32:19 -08001678 public String[] getSecureContainerList() {
1679 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001680 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001681 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001682
San Mehat4270e1e2010-01-29 05:32:19 -08001683 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001684 return NativeDaemonEvent.filterMessageList(
1685 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001686 } catch (NativeDaemonConnectorException e) {
1687 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 }
San Mehat36972292010-01-06 11:06:32 -08001690
Kenny Root6dceb882012-04-12 14:23:49 -07001691 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1692 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001693 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001694 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001695 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001696
San Mehatb1043402010-02-05 08:26:50 -08001697 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001698 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001699 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1700 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001701 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001702 rc = StorageResultCode.OperationFailedInternalError;
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 mAsecMountSet.add(id);
1708 }
1709 }
San Mehat4270e1e2010-01-29 05:32:19 -08001710 return rc;
San Mehat36972292010-01-06 11:06:32 -08001711 }
1712
San Mehat4270e1e2010-01-29 05:32:19 -08001713 public int finalizeSecureContainer(String id) {
1714 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001715 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001716
San Mehatb1043402010-02-05 08:26:50 -08001717 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001718 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001719 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001720 /*
1721 * Finalization does a remount, so no need
1722 * to update mAsecMountSet
1723 */
San Mehat4270e1e2010-01-29 05:32:19 -08001724 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001725 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001726 }
San Mehat4270e1e2010-01-29 05:32:19 -08001727 return rc;
San Mehat36972292010-01-06 11:06:32 -08001728 }
1729
Kenny Root6dceb882012-04-12 14:23:49 -07001730 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1731 validatePermission(android.Manifest.permission.ASEC_CREATE);
1732 warnOnNotMounted();
1733
1734 int rc = StorageResultCode.OperationSucceeded;
1735 try {
1736 mConnector.execute("asec", "fixperms", id, gid, filename);
1737 /*
1738 * Fix permissions does a remount, so no need to update
1739 * mAsecMountSet
1740 */
1741 } catch (NativeDaemonConnectorException e) {
1742 rc = StorageResultCode.OperationFailedInternalError;
1743 }
1744 return rc;
1745 }
1746
San Mehatd9709982010-02-18 11:43:03 -08001747 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001748 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001749 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001750 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001751
Kenny Rootaa485402010-09-14 14:49:41 -07001752 /*
1753 * Force a GC to make sure AssetManagers in other threads of the
1754 * system_server are cleaned up. We have to do this since AssetManager
1755 * instances are kept as a WeakReference and it's possible we have files
1756 * open on the external storage.
1757 */
1758 Runtime.getRuntime().gc();
1759
San Mehatb1043402010-02-05 08:26:50 -08001760 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001761 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001762 final Command cmd = new Command("asec", "destroy", id);
1763 if (force) {
1764 cmd.appendArg("force");
1765 }
1766 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001767 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001768 int code = e.getCode();
1769 if (code == VoldResponseCode.OpFailedStorageBusy) {
1770 rc = StorageResultCode.OperationFailedStorageBusy;
1771 } else {
1772 rc = StorageResultCode.OperationFailedInternalError;
1773 }
San Mehat02735bc2010-01-26 15:18:08 -08001774 }
San Mehata181b212010-02-11 06:50:20 -08001775
1776 if (rc == StorageResultCode.OperationSucceeded) {
1777 synchronized (mAsecMountSet) {
1778 if (mAsecMountSet.contains(id)) {
1779 mAsecMountSet.remove(id);
1780 }
1781 }
1782 }
1783
San Mehat4270e1e2010-01-29 05:32:19 -08001784 return rc;
San Mehat36972292010-01-06 11:06:32 -08001785 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001786
San Mehat4270e1e2010-01-29 05:32:19 -08001787 public int mountSecureContainer(String id, String key, int ownerUid) {
1788 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001789 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001790 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001791
San Mehata181b212010-02-11 06:50:20 -08001792 synchronized (mAsecMountSet) {
1793 if (mAsecMountSet.contains(id)) {
1794 return StorageResultCode.OperationFailedStorageMounted;
1795 }
1796 }
1797
San Mehatb1043402010-02-05 08:26:50 -08001798 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001799 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001800 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001801 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001802 int code = e.getCode();
1803 if (code != VoldResponseCode.OpFailedStorageBusy) {
1804 rc = StorageResultCode.OperationFailedInternalError;
1805 }
San Mehat02735bc2010-01-26 15:18:08 -08001806 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001807
1808 if (rc == StorageResultCode.OperationSucceeded) {
1809 synchronized (mAsecMountSet) {
1810 mAsecMountSet.add(id);
1811 }
1812 }
San Mehat4270e1e2010-01-29 05:32:19 -08001813 return rc;
San Mehat36972292010-01-06 11:06:32 -08001814 }
1815
San Mehatd9709982010-02-18 11:43:03 -08001816 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001817 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001818 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001819 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001820
San Mehat6cdd9c02010-02-09 14:45:20 -08001821 synchronized (mAsecMountSet) {
1822 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001823 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001824 }
1825 }
1826
Kenny Rootaa485402010-09-14 14:49:41 -07001827 /*
1828 * Force a GC to make sure AssetManagers in other threads of the
1829 * system_server are cleaned up. We have to do this since AssetManager
1830 * instances are kept as a WeakReference and it's possible we have files
1831 * open on the external storage.
1832 */
1833 Runtime.getRuntime().gc();
1834
San Mehatb1043402010-02-05 08:26:50 -08001835 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001836 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001837 final Command cmd = new Command("asec", "unmount", id);
1838 if (force) {
1839 cmd.appendArg("force");
1840 }
1841 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001842 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001843 int code = e.getCode();
1844 if (code == VoldResponseCode.OpFailedStorageBusy) {
1845 rc = StorageResultCode.OperationFailedStorageBusy;
1846 } else {
1847 rc = StorageResultCode.OperationFailedInternalError;
1848 }
San Mehat02735bc2010-01-26 15:18:08 -08001849 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001850
1851 if (rc == StorageResultCode.OperationSucceeded) {
1852 synchronized (mAsecMountSet) {
1853 mAsecMountSet.remove(id);
1854 }
1855 }
San Mehat4270e1e2010-01-29 05:32:19 -08001856 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001857 }
1858
San Mehat6cdd9c02010-02-09 14:45:20 -08001859 public boolean isSecureContainerMounted(String id) {
1860 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1861 waitForReady();
1862 warnOnNotMounted();
1863
1864 synchronized (mAsecMountSet) {
1865 return mAsecMountSet.contains(id);
1866 }
1867 }
1868
San Mehat4270e1e2010-01-29 05:32:19 -08001869 public int renameSecureContainer(String oldId, String newId) {
1870 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001871 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001872 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001873
San Mehata181b212010-02-11 06:50:20 -08001874 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001875 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001876 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001877 * changed while active, we must ensure both ids are not currently mounted.
1878 */
1879 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001880 return StorageResultCode.OperationFailedStorageMounted;
1881 }
1882 }
1883
San Mehatb1043402010-02-05 08:26:50 -08001884 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001885 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001886 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001887 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001888 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001889 }
San Mehata181b212010-02-11 06:50:20 -08001890
San Mehat4270e1e2010-01-29 05:32:19 -08001891 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001892 }
1893
San Mehat4270e1e2010-01-29 05:32:19 -08001894 public String getSecureContainerPath(String id) {
1895 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001896 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001897 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001898
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001899 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001900 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001901 event = mConnector.execute("asec", "path", id);
1902 event.checkCode(VoldResponseCode.AsecPathResult);
1903 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001904 } catch (NativeDaemonConnectorException e) {
1905 int code = e.getCode();
1906 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001907 Slog.i(TAG, String.format("Container '%s' not found", id));
1908 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001909 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001910 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001911 }
1912 }
San Mehat22dd86e2010-01-12 12:21:18 -08001913 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001914
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001915 public String getSecureContainerFilesystemPath(String id) {
1916 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1917 waitForReady();
1918 warnOnNotMounted();
1919
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001920 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001921 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001922 event = mConnector.execute("asec", "fspath", id);
1923 event.checkCode(VoldResponseCode.AsecPathResult);
1924 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001925 } catch (NativeDaemonConnectorException e) {
1926 int code = e.getCode();
1927 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1928 Slog.i(TAG, String.format("Container '%s' not found", id));
1929 return null;
1930 } else {
1931 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1932 }
1933 }
1934 }
1935
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001936 public void finishMediaUpdate() {
1937 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1938 }
Kenny Root02c87302010-07-01 08:10:18 -07001939
Kenny Roota02b8b02010-08-05 16:14:17 -07001940 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1941 if (callerUid == android.os.Process.SYSTEM_UID) {
1942 return true;
1943 }
1944
Kenny Root02c87302010-07-01 08:10:18 -07001945 if (packageName == null) {
1946 return false;
1947 }
1948
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001949 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001950
1951 if (DEBUG_OBB) {
1952 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1953 packageUid + ", callerUid = " + callerUid);
1954 }
1955
1956 return callerUid == packageUid;
1957 }
1958
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001959 public String getMountedObbPath(String rawPath) {
1960 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001961
Kenny Root02c87302010-07-01 08:10:18 -07001962 waitForReady();
1963 warnOnNotMounted();
1964
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001965 final ObbState state;
1966 synchronized (mObbPathToStateMap) {
1967 state = mObbPathToStateMap.get(rawPath);
1968 }
1969 if (state == null) {
1970 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1971 return null;
1972 }
1973
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001974 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001975 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001976 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001977 event.checkCode(VoldResponseCode.AsecPathResult);
1978 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001979 } catch (NativeDaemonConnectorException e) {
1980 int code = e.getCode();
1981 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001982 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001983 } else {
1984 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1985 }
1986 }
1987 }
1988
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001989 @Override
1990 public boolean isObbMounted(String rawPath) {
1991 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001992 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001993 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001994 }
Kenny Root02c87302010-07-01 08:10:18 -07001995 }
1996
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001997 @Override
1998 public void mountObb(
1999 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2000 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2001 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2002 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002003
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002004 final int callingUid = Binder.getCallingUid();
2005 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2006 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002007 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2008
2009 if (DEBUG_OBB)
2010 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002011 }
2012
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002013 @Override
2014 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2015 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2016
2017 final ObbState existingState;
2018 synchronized (mObbPathToStateMap) {
2019 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002020 }
2021
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002022 if (existingState != null) {
2023 // TODO: separate state object from request data
2024 final int callingUid = Binder.getCallingUid();
2025 final ObbState newState = new ObbState(
2026 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2027 final ObbAction action = new UnmountObbAction(newState, force);
2028 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002029
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002030 if (DEBUG_OBB)
2031 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2032 } else {
2033 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2034 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002035 }
2036
Ben Komalo444eca22011-09-01 15:17:44 -07002037 @Override
2038 public int getEncryptionState() {
2039 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2040 "no permission to access the crypt keeper");
2041
2042 waitForReady();
2043
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002044 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002045 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002046 event = mConnector.execute("cryptfs", "cryptocomplete");
2047 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002048 } catch (NumberFormatException e) {
2049 // Bad result - unexpected.
2050 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2051 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2052 } catch (NativeDaemonConnectorException e) {
2053 // Something bad happened.
2054 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2055 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2056 }
2057 }
2058
2059 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002060 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002061 if (TextUtils.isEmpty(password)) {
2062 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002063 }
2064
Jason parks8888c592011-01-20 22:46:41 -06002065 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2066 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002067
2068 waitForReady();
2069
2070 if (DEBUG_EVENTS) {
2071 Slog.i(TAG, "decrypting storage...");
2072 }
2073
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002074 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002075 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002076 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002077
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002078 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002079 if (code == 0) {
2080 // Decrypt was successful. Post a delayed message before restarting in order
2081 // to let the UI to clear itself
2082 mHandler.postDelayed(new Runnable() {
2083 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002084 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002085 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002086 } catch (NativeDaemonConnectorException e) {
2087 Slog.e(TAG, "problem executing in background", e);
2088 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002089 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002090 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002091 }
2092
2093 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002094 } catch (NativeDaemonConnectorException e) {
2095 // Decryption failed
2096 return e.getCode();
2097 }
Jason parks5af0b912010-11-29 09:05:25 -06002098 }
2099
Jason parks56aa5322011-01-07 09:01:15 -06002100 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002101 if (TextUtils.isEmpty(password)) {
2102 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002103 }
2104
Jason parks8888c592011-01-20 22:46:41 -06002105 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2106 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002107
2108 waitForReady();
2109
2110 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002111 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002112 }
2113
2114 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002115 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002116 } catch (NativeDaemonConnectorException e) {
2117 // Encryption failed
2118 return e.getCode();
2119 }
2120
2121 return 0;
2122 }
2123
Jason parksf7b3cd42011-01-27 09:28:25 -06002124 public int changeEncryptionPassword(String password) {
2125 if (TextUtils.isEmpty(password)) {
2126 throw new IllegalArgumentException("password cannot be empty");
2127 }
2128
2129 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2130 "no permission to access the crypt keeper");
2131
2132 waitForReady();
2133
2134 if (DEBUG_EVENTS) {
2135 Slog.i(TAG, "changing encryption password...");
2136 }
2137
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002138 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002139 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002140 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002141 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002142 } catch (NativeDaemonConnectorException e) {
2143 // Encryption failed
2144 return e.getCode();
2145 }
2146 }
2147
Christopher Tate32418be2011-10-10 13:51:12 -07002148 /**
2149 * Validate a user-supplied password string with cryptfs
2150 */
2151 @Override
2152 public int verifyEncryptionPassword(String password) throws RemoteException {
2153 // Only the system process is permitted to validate passwords
2154 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2155 throw new SecurityException("no permission to access the crypt keeper");
2156 }
2157
2158 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2159 "no permission to access the crypt keeper");
2160
2161 if (TextUtils.isEmpty(password)) {
2162 throw new IllegalArgumentException("password cannot be empty");
2163 }
2164
2165 waitForReady();
2166
2167 if (DEBUG_EVENTS) {
2168 Slog.i(TAG, "validating encryption password...");
2169 }
2170
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002171 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002172 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002173 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002174 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2175 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002176 } catch (NativeDaemonConnectorException e) {
2177 // Encryption failed
2178 return e.getCode();
2179 }
2180 }
2181
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002182 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002183 public int mkdirs(String callingPkg, String appPath) {
2184 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2185 final UserEnvironment userEnv = new UserEnvironment(userId);
2186
2187 // Validate that reported package name belongs to caller
2188 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2189 Context.APP_OPS_SERVICE);
2190 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2191
2192 try {
2193 appPath = new File(appPath).getCanonicalPath();
2194 } catch (IOException e) {
2195 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2196 return -1;
2197 }
2198
Jeff Sharkey5786a272013-10-02 12:50:34 -07002199 if (!appPath.endsWith("/")) {
2200 appPath = appPath + "/";
2201 }
2202
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002203 // Try translating the app path into a vold path, but require that it
2204 // belong to the calling package.
2205 String voldPath = maybeTranslatePathForVold(appPath,
2206 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2207 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2208 if (voldPath != null) {
2209 try {
2210 mConnector.execute("volume", "mkdirs", voldPath);
2211 return 0;
2212 } catch (NativeDaemonConnectorException e) {
2213 return e.getCode();
2214 }
2215 }
2216
2217 voldPath = maybeTranslatePathForVold(appPath,
2218 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2219 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2220 if (voldPath != null) {
2221 try {
2222 mConnector.execute("volume", "mkdirs", voldPath);
2223 return 0;
2224 } catch (NativeDaemonConnectorException e) {
2225 return e.getCode();
2226 }
2227 }
2228
2229 throw new SecurityException("Invalid mkdirs path: " + appPath);
2230 }
2231
2232 /**
2233 * Translate the given path from an app-visible path to a vold-visible path,
2234 * but only if it's under the given whitelisted paths.
2235 *
2236 * @param path a canonicalized app-visible path.
2237 * @param appPaths list of app-visible paths that are allowed.
2238 * @param voldPaths list of vold-visible paths directly corresponding to the
2239 * allowed app-visible paths argument.
2240 * @return a vold-visible path representing the original path, or
2241 * {@code null} if the given path didn't have an app-to-vold
2242 * mapping.
2243 */
2244 @VisibleForTesting
2245 public static String maybeTranslatePathForVold(
2246 String path, File[] appPaths, File[] voldPaths) {
2247 if (appPaths.length != voldPaths.length) {
2248 throw new IllegalStateException("Paths must be 1:1 mapping");
2249 }
2250
2251 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002252 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002253 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002254 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002255 .getAbsolutePath();
2256 if (!path.endsWith("/")) {
2257 path = path + "/";
2258 }
2259 return path;
2260 }
2261 }
2262 return null;
2263 }
2264
2265 @Override
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002266 public StorageVolume[] getVolumeList() {
2267 final int callingUserId = UserHandle.getCallingUserId();
2268 final boolean accessAll = (mContext.checkPermission(
2269 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2270 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2271
2272 synchronized (mVolumesLock) {
2273 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2274 for (StorageVolume volume : mVolumes) {
2275 final UserHandle owner = volume.getOwner();
2276 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2277 if (accessAll || ownerMatch) {
2278 filtered.add(volume);
2279 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002280 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002281 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002282 }
2283 }
2284
Kenny Rootaf9d6672010-10-08 09:21:39 -07002285 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2286 final IBinder binder = obbState.getBinder();
2287 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002288
Kenny Rootaf9d6672010-10-08 09:21:39 -07002289 if (obbStates == null) {
2290 obbStates = new ArrayList<ObbState>();
2291 mObbMounts.put(binder, obbStates);
2292 } else {
2293 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002294 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002295 throw new IllegalStateException("Attempt to add ObbState twice. "
2296 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002297 }
2298 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002299 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002300
2301 obbStates.add(obbState);
2302 try {
2303 obbState.link();
2304 } catch (RemoteException e) {
2305 /*
2306 * The binder died before we could link it, so clean up our state
2307 * and return failure.
2308 */
2309 obbStates.remove(obbState);
2310 if (obbStates.isEmpty()) {
2311 mObbMounts.remove(binder);
2312 }
2313
2314 // Rethrow the error so mountObb can get it
2315 throw e;
2316 }
2317
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002318 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002319 }
2320
Kenny Rootaf9d6672010-10-08 09:21:39 -07002321 private void removeObbStateLocked(ObbState obbState) {
2322 final IBinder binder = obbState.getBinder();
2323 final List<ObbState> obbStates = mObbMounts.get(binder);
2324 if (obbStates != null) {
2325 if (obbStates.remove(obbState)) {
2326 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002327 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002328 if (obbStates.isEmpty()) {
2329 mObbMounts.remove(binder);
2330 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002331 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002332
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002333 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002334 }
2335
Kenny Roota02b8b02010-08-05 16:14:17 -07002336 private class ObbActionHandler extends Handler {
2337 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002338 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002339
2340 ObbActionHandler(Looper l) {
2341 super(l);
2342 }
2343
2344 @Override
2345 public void handleMessage(Message msg) {
2346 switch (msg.what) {
2347 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002348 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002349
2350 if (DEBUG_OBB)
2351 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2352
2353 // If a bind was already initiated we don't really
2354 // need to do anything. The pending install
2355 // will be processed later on.
2356 if (!mBound) {
2357 // If this is the only one pending we might
2358 // have to bind to the service again.
2359 if (!connectToService()) {
2360 Slog.e(TAG, "Failed to bind to media container service");
2361 action.handleError();
2362 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002363 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002364 }
Kenny Root735de3b2010-09-30 14:11:39 -07002365
Kenny Root735de3b2010-09-30 14:11:39 -07002366 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002367 break;
2368 }
2369 case OBB_MCS_BOUND: {
2370 if (DEBUG_OBB)
2371 Slog.i(TAG, "OBB_MCS_BOUND");
2372 if (msg.obj != null) {
2373 mContainerService = (IMediaContainerService) msg.obj;
2374 }
2375 if (mContainerService == null) {
2376 // Something seriously wrong. Bail out
2377 Slog.e(TAG, "Cannot bind to media container service");
2378 for (ObbAction action : mActions) {
2379 // Indicate service bind error
2380 action.handleError();
2381 }
2382 mActions.clear();
2383 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002384 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002385 if (action != null) {
2386 action.execute(this);
2387 }
2388 } else {
2389 // Should never happen ideally.
2390 Slog.w(TAG, "Empty queue");
2391 }
2392 break;
2393 }
2394 case OBB_MCS_RECONNECT: {
2395 if (DEBUG_OBB)
2396 Slog.i(TAG, "OBB_MCS_RECONNECT");
2397 if (mActions.size() > 0) {
2398 if (mBound) {
2399 disconnectService();
2400 }
2401 if (!connectToService()) {
2402 Slog.e(TAG, "Failed to bind to media container service");
2403 for (ObbAction action : mActions) {
2404 // Indicate service bind error
2405 action.handleError();
2406 }
2407 mActions.clear();
2408 }
2409 }
2410 break;
2411 }
2412 case OBB_MCS_UNBIND: {
2413 if (DEBUG_OBB)
2414 Slog.i(TAG, "OBB_MCS_UNBIND");
2415
2416 // Delete pending install
2417 if (mActions.size() > 0) {
2418 mActions.remove(0);
2419 }
2420 if (mActions.size() == 0) {
2421 if (mBound) {
2422 disconnectService();
2423 }
2424 } else {
2425 // There are more pending requests in queue.
2426 // Just post MCS_BOUND message to trigger processing
2427 // of next pending install.
2428 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2429 }
2430 break;
2431 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002432 case OBB_FLUSH_MOUNT_STATE: {
2433 final String path = (String) msg.obj;
2434
2435 if (DEBUG_OBB)
2436 Slog.i(TAG, "Flushing all OBB state for path " + path);
2437
2438 synchronized (mObbMounts) {
2439 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2440
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002441 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002442 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002443 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444
2445 /*
2446 * If this entry's source file is in the volume path
2447 * that got unmounted, remove it because it's no
2448 * longer valid.
2449 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002450 if (state.canonicalPath.startsWith(path)) {
2451 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 }
2453 }
2454
2455 for (final ObbState obbState : obbStatesToRemove) {
2456 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002457 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002458
2459 removeObbStateLocked(obbState);
2460
2461 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002462 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463 OnObbStateChangeListener.UNMOUNTED);
2464 } catch (RemoteException e) {
2465 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002466 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002467 }
2468 }
2469 }
2470 break;
2471 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002472 }
2473 }
2474
2475 private boolean connectToService() {
2476 if (DEBUG_OBB)
2477 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2478
2479 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2480 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2481 mBound = true;
2482 return true;
2483 }
2484 return false;
2485 }
2486
2487 private void disconnectService() {
2488 mContainerService = null;
2489 mBound = false;
2490 mContext.unbindService(mDefContainerConn);
2491 }
2492 }
2493
2494 abstract class ObbAction {
2495 private static final int MAX_RETRIES = 3;
2496 private int mRetries;
2497
2498 ObbState mObbState;
2499
2500 ObbAction(ObbState obbState) {
2501 mObbState = obbState;
2502 }
2503
2504 public void execute(ObbActionHandler handler) {
2505 try {
2506 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002507 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002508 mRetries++;
2509 if (mRetries > MAX_RETRIES) {
2510 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002511 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002512 handleError();
2513 return;
2514 } else {
2515 handleExecute();
2516 if (DEBUG_OBB)
2517 Slog.i(TAG, "Posting install MCS_UNBIND");
2518 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2519 }
2520 } catch (RemoteException e) {
2521 if (DEBUG_OBB)
2522 Slog.i(TAG, "Posting install MCS_RECONNECT");
2523 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2524 } catch (Exception e) {
2525 if (DEBUG_OBB)
2526 Slog.d(TAG, "Error handling OBB action", e);
2527 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002528 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002529 }
2530 }
2531
Kenny Root05105f72010-09-22 17:29:43 -07002532 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002533 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002534
2535 protected ObbInfo getObbInfo() throws IOException {
2536 ObbInfo obbInfo;
2537 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002538 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002539 } catch (RemoteException e) {
2540 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002542 obbInfo = null;
2543 }
2544 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002545 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002546 }
2547 return obbInfo;
2548 }
2549
Kenny Rootaf9d6672010-10-08 09:21:39 -07002550 protected void sendNewStatusOrIgnore(int status) {
2551 if (mObbState == null || mObbState.token == null) {
2552 return;
2553 }
2554
Kenny Root38cf8862010-09-26 14:18:51 -07002555 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002556 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002557 } catch (RemoteException e) {
2558 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2559 }
2560 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002561 }
2562
2563 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002564 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002565 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002566
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002567 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002568 super(obbState);
2569 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002570 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002571 }
2572
Jason parks5af0b912010-11-29 09:05:25 -06002573 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002574 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002575 waitForReady();
2576 warnOnNotMounted();
2577
Kenny Root38cf8862010-09-26 14:18:51 -07002578 final ObbInfo obbInfo = getObbInfo();
2579
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002580 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002581 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2582 + " which is owned by " + obbInfo.packageName);
2583 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2584 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002585 }
2586
Kenny Rootaf9d6672010-10-08 09:21:39 -07002587 final boolean isMounted;
2588 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002589 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002590 }
2591 if (isMounted) {
2592 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2593 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2594 return;
2595 }
2596
Kenny Rootaf9d6672010-10-08 09:21:39 -07002597 final String hashedKey;
2598 if (mKey == null) {
2599 hashedKey = "none";
2600 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002601 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002602 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2603
2604 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2605 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2606 SecretKey key = factory.generateSecret(ks);
2607 BigInteger bi = new BigInteger(key.getEncoded());
2608 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002609 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002610 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2611 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2612 return;
2613 } catch (InvalidKeySpecException e) {
2614 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2615 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002616 return;
2617 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002618 }
Kenny Root38cf8862010-09-26 14:18:51 -07002619
Kenny Rootaf9d6672010-10-08 09:21:39 -07002620 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002621 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002622 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2623 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002624 } catch (NativeDaemonConnectorException e) {
2625 int code = e.getCode();
2626 if (code != VoldResponseCode.OpFailedStorageBusy) {
2627 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002628 }
2629 }
2630
Kenny Rootaf9d6672010-10-08 09:21:39 -07002631 if (rc == StorageResultCode.OperationSucceeded) {
2632 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002633 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002634
2635 synchronized (mObbMounts) {
2636 addObbStateLocked(mObbState);
2637 }
2638
2639 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002640 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002641 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002642
Kenny Rootaf9d6672010-10-08 09:21:39 -07002643 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002644 }
2645 }
2646
Jason parks5af0b912010-11-29 09:05:25 -06002647 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002648 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002649 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002650 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002651
2652 @Override
2653 public String toString() {
2654 StringBuilder sb = new StringBuilder();
2655 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002656 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002657 sb.append('}');
2658 return sb.toString();
2659 }
2660 }
2661
2662 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002663 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002664
2665 UnmountObbAction(ObbState obbState, boolean force) {
2666 super(obbState);
2667 mForceUnmount = force;
2668 }
2669
Jason parks5af0b912010-11-29 09:05:25 -06002670 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002671 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002672 waitForReady();
2673 warnOnNotMounted();
2674
Kenny Root38cf8862010-09-26 14:18:51 -07002675 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002676
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002677 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002678 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002679 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002680 }
Kenny Root38cf8862010-09-26 14:18:51 -07002681
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002682 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002683 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2684 return;
2685 }
2686
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002687 if (existingState.ownerGid != mObbState.ownerGid) {
2688 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2689 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002690 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2691 return;
2692 }
2693
Kenny Rootaf9d6672010-10-08 09:21:39 -07002694 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002695 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002696 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002697 if (mForceUnmount) {
2698 cmd.appendArg("force");
2699 }
2700 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002701 } catch (NativeDaemonConnectorException e) {
2702 int code = e.getCode();
2703 if (code == VoldResponseCode.OpFailedStorageBusy) {
2704 rc = StorageResultCode.OperationFailedStorageBusy;
2705 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2706 // If it's not mounted then we've already won.
2707 rc = StorageResultCode.OperationSucceeded;
2708 } else {
2709 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002710 }
2711 }
2712
Kenny Rootaf9d6672010-10-08 09:21:39 -07002713 if (rc == StorageResultCode.OperationSucceeded) {
2714 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002715 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002716 }
2717
Kenny Rootaf9d6672010-10-08 09:21:39 -07002718 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002719 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002720 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002721 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002722 }
2723 }
2724
Jason parks5af0b912010-11-29 09:05:25 -06002725 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002726 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002727 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002728 }
2729
2730 @Override
2731 public String toString() {
2732 StringBuilder sb = new StringBuilder();
2733 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002734 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002735 sb.append(",force=");
2736 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002737 sb.append('}');
2738 return sb.toString();
2739 }
Kenny Root02c87302010-07-01 08:10:18 -07002740 }
Kenny Root38cf8862010-09-26 14:18:51 -07002741
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002742 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002743 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2744 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002745 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002746
2747 // Only adjust paths when storage is emulated
2748 if (!Environment.isExternalStorageEmulated()) {
2749 return canonicalPath;
2750 }
2751
2752 String path = canonicalPath.toString();
2753
2754 // First trim off any external storage prefix
2755 final UserEnvironment userEnv = new UserEnvironment(userId);
2756
2757 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002758 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002759 // /storage/emulated_legacy
2760 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002761 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002762
2763 if (path.startsWith(externalPath)) {
2764 path = path.substring(externalPath.length() + 1);
2765 } else if (path.startsWith(legacyExternalPath)) {
2766 path = path.substring(legacyExternalPath.length() + 1);
2767 } else {
2768 return canonicalPath;
2769 }
2770
2771 // Handle special OBB paths on emulated storage
2772 final String obbPath = "Android/obb";
2773 if (path.startsWith(obbPath)) {
2774 path = path.substring(obbPath.length() + 1);
2775
2776 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002777 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002778 } else {
2779 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002780 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2781 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002782 }
2783 }
2784
2785 // Handle normal external storage paths
2786 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002787 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002788 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002789 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002790 }
2791 }
2792
Kenny Root38cf8862010-09-26 14:18:51 -07002793 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002794 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2795 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2796
2797 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07002798
Kenny Root38cf8862010-09-26 14:18:51 -07002799 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002800 pw.println("mObbMounts:");
2801 pw.increaseIndent();
2802 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
2803 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002804 while (binders.hasNext()) {
2805 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002806 pw.println(e.getKey() + ":");
2807 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002808 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002809 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002810 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002811 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002812 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002813 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002814 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002815
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002816 pw.println();
2817 pw.println("mObbPathToStateMap:");
2818 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002819 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2820 while (maps.hasNext()) {
2821 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002822 pw.print(e.getKey());
2823 pw.print(" -> ");
2824 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07002825 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002826 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002827 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002828
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002829 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002830 pw.println();
2831 pw.println("mVolumes:");
2832 pw.increaseIndent();
2833 for (StorageVolume volume : mVolumes) {
2834 pw.println(volume);
2835 pw.increaseIndent();
2836 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
2837 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002838 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002839 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002840 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002841
2842 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002843 pw.println("mConnection:");
2844 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08002845 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002846 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002849 /** {@inheritDoc} */
2850 public void monitor() {
2851 if (mConnector != null) {
2852 mConnector.monitor();
2853 }
2854 }
2855}