blob: 39410c26710934b37a4963f9dc21dbd6cbc49594 [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 Sharkeyb049e212012-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 Sharkeyb049e212012-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 Sharkeyb049e212012-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;
Paul Lawrence46791e72014-04-03 09:10:26 -070055import android.os.storage.StorageManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070056import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060058import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070060import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070061import android.util.Xml;
62
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080063import com.android.internal.annotations.GuardedBy;
64import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070065import com.android.internal.app.IMediaContainerService;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070066import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070067import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070068import com.android.internal.util.XmlUtils;
69import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070070import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070071import com.android.server.am.ActivityManagerService;
72import com.android.server.pm.PackageManagerService;
73import com.android.server.pm.UserManagerService;
74import com.google.android.collect.Lists;
75import com.google.android.collect.Maps;
76
Paul Lawrence8e397362014-01-27 15:22:30 -080077import org.apache.commons.codec.binary.Hex;
Paul Lawrence945490c2014-03-27 16:37:28 +000078import org.apache.commons.codec.DecoderException;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070079import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070080
Jeff Sharkeyb049e212012-09-07 23:16:01 -070081import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070082import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070083import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070084import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070085import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -080086import java.nio.charset.StandardCharsets;
Kenny Root735de3b2010-09-30 14:11:39 -070087import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070088import java.security.spec.InvalidKeySpecException;
89import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080090import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070091import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080092import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070093import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070094import java.util.LinkedList;
95import java.util.List;
96import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070097import java.util.Map.Entry;
Rickard Helldin5fb5df02014-02-07 09:35:04 +010098import java.util.concurrent.atomic.AtomicInteger;
Kenny Root51a573c2012-05-17 13:30:28 -070099import java.util.concurrent.CountDownLatch;
100import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Kenny Root3b1abba2010-10-13 15:00:07 -0700102import javax.crypto.SecretKey;
103import javax.crypto.SecretKeyFactory;
104import javax.crypto.spec.PBEKeySpec;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106/**
San Mehatb1043402010-02-05 08:26:50 -0800107 * MountService implements back-end services for platform storage
108 * management.
109 * @hide - Applications should use android.os.storage.StorageManager
110 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700112class MountService extends IMountService.Stub
113 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600114
Christopher Tated417d622013-08-19 16:14:25 -0700115 // Static direct instance pointer for the tightly-coupled idle service to use
116 static MountService sSelf = null;
117
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700118 // TODO: listen for user creation/deletion
119
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800120 private static final boolean LOCAL_LOGD = false;
121 private static final boolean DEBUG_UNMOUNT = false;
122 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800123 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700124
Kenny Root07714d42011-08-17 17:49:28 -0700125 // Disable this since it messes up long-running cryptfs operations.
126 private static final boolean WATCHDOG_ENABLE = false;
127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final String TAG = "MountService";
129
Kenny Root305bcbf2010-09-03 07:56:38 -0700130 private static final String VOLD_TAG = "VoldConnector";
131
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700132 /** Maximum number of ASEC containers allowed to be mounted. */
133 private static final int MAX_CONTAINERS = 250;
134
San Mehat4270e1e2010-01-29 05:32:19 -0800135 /*
136 * Internal vold volume state constants
137 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800138 class VolumeState {
139 public static final int Init = -1;
140 public static final int NoMedia = 0;
141 public static final int Idle = 1;
142 public static final int Pending = 2;
143 public static final int Checking = 3;
144 public static final int Mounted = 4;
145 public static final int Unmounting = 5;
146 public static final int Formatting = 6;
147 public static final int Shared = 7;
148 public static final int SharedMnt = 8;
149 }
150
San Mehat4270e1e2010-01-29 05:32:19 -0800151 /*
152 * Internal vold response code constants
153 */
San Mehat22dd86e2010-01-12 12:21:18 -0800154 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800155 /*
156 * 100 series - Requestion action was initiated; expect another reply
157 * before proceeding with a new command.
158 */
San Mehat22dd86e2010-01-12 12:21:18 -0800159 public static final int VolumeListResult = 110;
160 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800161 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700162 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800163
San Mehat4270e1e2010-01-29 05:32:19 -0800164 /*
165 * 200 series - Requestion action has been successfully completed.
166 */
167 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800168 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800169 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800170
San Mehat4270e1e2010-01-29 05:32:19 -0800171 /*
172 * 400 series - Command was accepted, but the requested action
173 * did not take place.
174 */
175 public static final int OpFailedNoMedia = 401;
176 public static final int OpFailedMediaBlank = 402;
177 public static final int OpFailedMediaCorrupt = 403;
178 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800179 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700180 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800181
182 /*
183 * 600 series - Unsolicited broadcasts.
184 */
San Mehat22dd86e2010-01-12 12:21:18 -0800185 public static final int VolumeStateChange = 605;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700186 public static final int VolumeUuidChange = 613;
187 public static final int VolumeUserLabelChange = 614;
San Mehat22dd86e2010-01-12 12:21:18 -0800188 public static final int VolumeDiskInserted = 630;
189 public static final int VolumeDiskRemoved = 631;
190 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700191
192 /*
193 * 700 series - fstrim
194 */
195 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800196 }
197
Paul Lawrence8e397362014-01-27 15:22:30 -0800198 /** List of crypto types.
199 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
200 * corresponding commands in CommandListener.cpp */
201 public static final String[] CRYPTO_TYPES
202 = { "password", "default", "pattern", "pin" };
203
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700204 private final Context mContext;
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700205 private final NativeDaemonConnector mConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700206
207 private final Object mVolumesLock = new Object();
208
209 /** When defined, base template for user-specific {@link StorageVolume}. */
210 private StorageVolume mEmulatedTemplate;
211
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700212 // TODO: separate storage volumes on per-user basis
213
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800214 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700215 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
216 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700218 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
219 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700221 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
222
223 private volatile boolean mSystemReady = false;
224
San Mehat4270e1e2010-01-29 05:32:19 -0800225 private PackageManagerService mPms;
226 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700227 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800228 // Used as a lock for methods that register/unregister listeners.
229 final private ArrayList<MountServiceBinderListener> mListeners =
230 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800231 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
232 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800233 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800234
San Mehat6cdd9c02010-02-09 14:45:20 -0800235 /**
236 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800237 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800238 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800239 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800240
Kenny Root02c87302010-07-01 08:10:18 -0700241 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700242 * The size of the crypto algorithm key in bits for OBB files. Currently
243 * Twofish is used which takes 128-bit keys.
244 */
245 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
246
247 /**
248 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
249 * 1024 is reasonably secure and not too slow.
250 */
251 private static final int PBKDF2_HASH_ROUNDS = 1024;
252
253 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700254 * Mounted OBB tracking information. Used to track the current state of all
255 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700256 */
Kenny Root735de3b2010-09-30 14:11:39 -0700257 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700258
259 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700260 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
261
262 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700263 public ObbState(String rawPath, String canonicalPath, int callingUid,
264 IObbActionListener token, int nonce) {
265 this.rawPath = rawPath;
266 this.canonicalPath = canonicalPath.toString();
267
268 final int userId = UserHandle.getUserId(callingUid);
269 this.ownerPath = buildObbPath(canonicalPath, userId, false);
270 this.voldPath = buildObbPath(canonicalPath, userId, true);
271
272 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700273 this.token = token;
274 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700275 }
276
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700277 final String rawPath;
278 final String canonicalPath;
279 final String ownerPath;
280 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700281
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700282 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700283
Kenny Rootaf9d6672010-10-08 09:21:39 -0700284 // Token of remote Binder caller
285 final IObbActionListener token;
286
287 // Identifier to pass back to the token
288 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700289
Kenny Root735de3b2010-09-30 14:11:39 -0700290 public IBinder getBinder() {
291 return token.asBinder();
292 }
293
Kenny Roota02b8b02010-08-05 16:14:17 -0700294 @Override
295 public void binderDied() {
296 ObbAction action = new UnmountObbAction(this, true);
297 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700298 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700299
Kenny Root5919ac62010-10-05 09:49:40 -0700300 public void link() throws RemoteException {
301 getBinder().linkToDeath(this, 0);
302 }
303
304 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700305 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700306 }
Kenny Root38cf8862010-09-26 14:18:51 -0700307
308 @Override
309 public String toString() {
310 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700311 sb.append("rawPath=").append(rawPath);
312 sb.append(",canonicalPath=").append(canonicalPath);
313 sb.append(",ownerPath=").append(ownerPath);
314 sb.append(",voldPath=").append(voldPath);
315 sb.append(",ownerGid=").append(ownerGid);
316 sb.append(",token=").append(token);
317 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700318 sb.append('}');
319 return sb.toString();
320 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700321 }
322
323 // OBB Action Handler
324 final private ObbActionHandler mObbActionHandler;
325
326 // OBB action handler messages
327 private static final int OBB_RUN_ACTION = 1;
328 private static final int OBB_MCS_BOUND = 2;
329 private static final int OBB_MCS_UNBIND = 3;
330 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700331 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700332
333 /*
334 * Default Container Service information
335 */
336 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
337 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
338
339 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
340
341 class DefaultContainerConnection implements ServiceConnection {
342 public void onServiceConnected(ComponentName name, IBinder service) {
343 if (DEBUG_OBB)
344 Slog.i(TAG, "onServiceConnected");
345 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
346 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
347 }
348
349 public void onServiceDisconnected(ComponentName name) {
350 if (DEBUG_OBB)
351 Slog.i(TAG, "onServiceDisconnected");
352 }
353 };
354
355 // Used in the ObbActionHandler
356 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700357
358 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359 private static final int H_UNMOUNT_PM_UPDATE = 1;
360 private static final int H_UNMOUNT_PM_DONE = 2;
361 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700362 private static final int H_SYSTEM_READY = 4;
Christopher Tated417d622013-08-19 16:14:25 -0700363 private static final int H_FSTRIM = 5;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700364
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
366 private static final int MAX_UNMOUNT_RETRIES = 4;
367
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800368 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700369 final String path;
370 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700371 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800372 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800373
Ben Komalo13c71972011-09-07 16:35:56 -0700374 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800375 retries = 0;
376 this.path = path;
377 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700378 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800379 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800380
381 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700382 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700383 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800384 }
385 }
386
387 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700388 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800389
390 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700391 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800392 this.method = method;
393 }
394
395 @Override
396 void handleFinished() {
397 super.handleFinished();
398 doShareUnshareVolume(path, method, true);
399 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800400 }
401
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800402 class ShutdownCallBack extends UnmountCallBack {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100403 MountShutdownLatch mMountShutdownLatch;
404 ShutdownCallBack(String path, final MountShutdownLatch mountShutdownLatch) {
Ben Komalo13c71972011-09-07 16:35:56 -0700405 super(path, true, false);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100406 mMountShutdownLatch = mountShutdownLatch;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800407 }
408
409 @Override
410 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700411 int ret = doUnmountVolume(path, true, removeEncryption);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100412 Slog.i(TAG, "Unmount completed: " + path + ", result code: " + ret);
413 mMountShutdownLatch.countDown();
414 }
415 }
416
417 static class MountShutdownLatch {
418 private IMountShutdownObserver mObserver;
419 private AtomicInteger mCount;
420
421 MountShutdownLatch(final IMountShutdownObserver observer, int count) {
422 mObserver = observer;
423 mCount = new AtomicInteger(count);
424 }
425
426 void countDown() {
427 boolean sendShutdown = false;
428 if (mCount.decrementAndGet() == 0) {
429 sendShutdown = true;
430 }
431 if (sendShutdown && mObserver != null) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800432 try {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100433 mObserver.onShutDownComplete(StorageResultCode.OperationSucceeded);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700435 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800436 }
437 }
438 }
439 }
440
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400441 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800442 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700443 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800444
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400445 MountServiceHandler(Looper l) {
446 super(l);
447 }
448
Jason parks5af0b912010-11-29 09:05:25 -0600449 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800450 public void handleMessage(Message msg) {
451 switch (msg.what) {
452 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700453 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800454 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
455 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700456 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800457 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700458 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700459 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700460 mUpdatingStatus = true;
461 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800462 }
463 break;
464 }
465 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700466 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700467 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700468 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800469 int size = mForceUnmounts.size();
470 int sizeArr[] = new int[size];
471 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700472 // Kill processes holding references first
473 ActivityManagerService ams = (ActivityManagerService)
474 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800475 for (int i = 0; i < size; i++) {
476 UnmountCallBack ucb = mForceUnmounts.get(i);
477 String path = ucb.path;
478 boolean done = false;
479 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800480 done = true;
481 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800482 int pids[] = getStorageUsers(path);
483 if (pids == null || pids.length == 0) {
484 done = true;
485 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800486 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800487 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700488 // Confirm if file references have been freed.
489 pids = getStorageUsers(path);
490 if (pids == null || pids.length == 0) {
491 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800492 }
493 }
494 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700495 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
496 // Retry again
497 Slog.i(TAG, "Retrying to kill storage users again");
498 mHandler.sendMessageDelayed(
499 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
500 ucb.retries++),
501 RETRY_UNMOUNT_DELAY);
502 } else {
503 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
504 Slog.i(TAG, "Failed to unmount media inspite of " +
505 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
506 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800507 sizeArr[sizeArrN++] = i;
508 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
509 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800510 }
511 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800512 // Remove already processed elements from list.
513 for (int i = (sizeArrN-1); i >= 0; i--) {
514 mForceUnmounts.remove(sizeArr[i]);
515 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800516 break;
517 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700518 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700519 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800520 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800521 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800522 break;
523 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700524 case H_SYSTEM_READY: {
525 try {
526 handleSystemReady();
527 } catch (Exception ex) {
528 Slog.e(TAG, "Boot-time mount exception", ex);
529 }
530 break;
531 }
Christopher Tated417d622013-08-19 16:14:25 -0700532 case H_FSTRIM: {
533 waitForReady();
534 Slog.i(TAG, "Running fstrim idle maintenance");
535 try {
536 // This method must be run on the main (handler) thread,
537 // so it is safe to directly call into vold.
538 mConnector.execute("fstrim", "dotrim");
539 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
540 } catch (NativeDaemonConnectorException ndce) {
541 Slog.e(TAG, "Failed to run fstrim!");
542 }
543 // invoke the completion callback, if any
544 Runnable callback = (Runnable) msg.obj;
545 if (callback != null) {
546 callback.run();
547 }
548 break;
549 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800550 }
551 }
552 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700553
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700554 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800555
Kenny Root51a573c2012-05-17 13:30:28 -0700556 void waitForAsecScan() {
557 waitForLatch(mAsecsScanned);
558 }
559
San Mehat207e5382010-02-04 20:46:54 -0800560 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700561 waitForLatch(mConnectedSignal);
562 }
563
564 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700565 for (;;) {
566 try {
567 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800568 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700569 } else {
570 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
571 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800572 }
Kenny Root51a573c2012-05-17 13:30:28 -0700573 } catch (InterruptedException e) {
574 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800575 }
San Mehat207e5382010-02-04 20:46:54 -0800576 }
San Mehat1f6301e2010-01-07 22:40:27 -0800577 }
Kenny Root02c87302010-07-01 08:10:18 -0700578
Paul Lawrence945490c2014-03-27 16:37:28 +0000579 private boolean isReady() {
580 try {
581 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
582 } catch (InterruptedException e) {
583 return false;
584 }
585 }
586
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700587 private void handleSystemReady() {
588 // Snapshot current volume states since it's not safe to call into vold
589 // while holding locks.
590 final HashMap<String, String> snapshot;
591 synchronized (mVolumesLock) {
592 snapshot = new HashMap<String, String>(mVolumeStates);
593 }
594
595 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
596 final String path = entry.getKey();
597 final String state = entry.getValue();
598
599 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
600 int rc = doMountVolume(path);
601 if (rc != StorageResultCode.OperationSucceeded) {
602 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
603 rc));
604 }
605 } else if (state.equals(Environment.MEDIA_SHARED)) {
606 /*
607 * Bootstrap UMS enabled state since vold indicates
608 * the volume is shared (runtime restart while ums enabled)
609 */
610 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
611 VolumeState.Shared);
612 }
613 }
614
615 // Push mounted state for all emulated storage
616 synchronized (mVolumesLock) {
617 for (StorageVolume volume : mVolumes) {
618 if (volume.isEmulated()) {
619 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
620 }
621 }
622 }
623
624 /*
625 * If UMS was connected on boot, send the connected event
626 * now that we're up.
627 */
628 if (mSendUmsConnectedOnBoot) {
629 sendUmsIntent(true);
630 mSendUmsConnectedOnBoot = false;
631 }
Christopher Tate115afda2014-06-06 19:06:26 -0700632
633 /*
634 * Start scheduling nominally-daily fstrim operations
635 */
636 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700637 }
638
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700639 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
640 @Override
641 public void onReceive(Context context, Intent intent) {
642 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
643 if (userId == -1) return;
644 final UserHandle user = new UserHandle(userId);
645
646 final String action = intent.getAction();
647 if (Intent.ACTION_USER_ADDED.equals(action)) {
648 synchronized (mVolumesLock) {
649 createEmulatedVolumeForUserLocked(user);
650 }
651
652 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
653 synchronized (mVolumesLock) {
654 final List<StorageVolume> toRemove = Lists.newArrayList();
655 for (StorageVolume volume : mVolumes) {
656 if (user.equals(volume.getOwner())) {
657 toRemove.add(volume);
658 }
659 }
660 for (StorageVolume volume : toRemove) {
661 removeVolumeLocked(volume);
662 }
663 }
664 }
665 }
666 };
667
668 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
669 @Override
670 public void onReceive(Context context, Intent intent) {
671 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
672 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
673 notifyShareAvailabilityChange(available);
674 }
675 };
676
San Mehat4270e1e2010-01-29 05:32:19 -0800677 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
678 final IMountServiceListener mListener;
679
680 MountServiceBinderListener(IMountServiceListener listener) {
681 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700682
San Mehat91c77612010-01-07 10:39:41 -0800683 }
684
San Mehat4270e1e2010-01-29 05:32:19 -0800685 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700686 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700687 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800688 mListeners.remove(this);
689 mListener.asBinder().unlinkToDeath(this, 0);
690 }
691 }
692 }
693
Christopher Tated417d622013-08-19 16:14:25 -0700694 void runIdleMaintenance(Runnable callback) {
695 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
696 }
697
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800698 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800699 // TODO: Add support for multiple share methods
700 if (!method.equals("ums")) {
701 throw new IllegalArgumentException(String.format("Method %s not supported", method));
702 }
703
San Mehat4270e1e2010-01-29 05:32:19 -0800704 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800705 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800706 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700707 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800708 }
San Mehat4270e1e2010-01-29 05:32:19 -0800709 }
710
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700711 private void updatePublicVolumeState(StorageVolume volume, String state) {
712 final String path = volume.getPath();
713 final String oldState;
714 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400715 oldState = mVolumeStates.put(path, state);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700716 volume.setState(state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400717 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700718
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400719 if (state.equals(oldState)) {
720 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
721 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800722 return;
723 }
San Mehatb1043402010-02-05 08:26:50 -0800724
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400725 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700726
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700727 // Tell PackageManager about changes to primary volume state, but only
728 // when not emulated.
729 if (volume.isPrimary() && !volume.isEmulated()) {
730 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
731 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400732
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700733 /*
734 * Some OBBs might have been unmounted when this volume was
735 * unmounted, so send a message to the handler to let it know to
736 * remove those from the list of mounted OBBS.
737 */
738 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
739 OBB_FLUSH_MOUNT_STATE, path));
740 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
741 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400742 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800743 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700744
San Mehat4270e1e2010-01-29 05:32:19 -0800745 synchronized (mListeners) {
746 for (int i = mListeners.size() -1; i >= 0; i--) {
747 MountServiceBinderListener bl = mListeners.get(i);
748 try {
San Mehatb1043402010-02-05 08:26:50 -0800749 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800750 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700751 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 mListeners.remove(i);
753 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700754 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800755 }
756 }
757 }
758 }
759
760 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800761 * Callback from NativeDaemonConnector
762 */
763 public void onDaemonConnected() {
764 /*
765 * Since we'll be calling back into the NativeDaemonConnector,
766 * we need to do our work in a new thread.
767 */
Kenny Root51a573c2012-05-17 13:30:28 -0700768 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600769 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800770 public void run() {
771 /**
772 * Determine media state and UMS detection status
773 */
San Mehat4270e1e2010-01-29 05:32:19 -0800774 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800775 final String[] vols = NativeDaemonEvent.filterMessageList(
776 mConnector.executeForList("volume", "list"),
777 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800778 for (String volstr : vols) {
779 String[] tok = volstr.split(" ");
780 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400781 String path = tok[1];
782 String state = Environment.MEDIA_REMOVED;
783
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700784 final StorageVolume volume;
785 synchronized (mVolumesLock) {
786 volume = mVolumesByPath.get(path);
787 }
788
San Mehat4270e1e2010-01-29 05:32:19 -0800789 int st = Integer.parseInt(tok[2]);
790 if (st == VolumeState.NoMedia) {
791 state = Environment.MEDIA_REMOVED;
792 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800793 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800794 } else if (st == VolumeState.Mounted) {
795 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700796 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800797 } else if (st == VolumeState.Shared) {
798 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700799 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800800 } else {
801 throw new Exception(String.format("Unexpected state %d", st));
802 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400803
804 if (state != null) {
805 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700806 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400807 }
San Mehat4270e1e2010-01-29 05:32:19 -0800808 }
809 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700810 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700811 final StorageVolume primary = getPrimaryPhysicalVolume();
812 if (primary != null) {
813 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
814 }
San Mehat4270e1e2010-01-29 05:32:19 -0800815 }
816
San Mehat207e5382010-02-04 20:46:54 -0800817 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600818 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800819 * the hounds!
820 */
Kenny Root51a573c2012-05-17 13:30:28 -0700821 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700822
823 // Let package manager load internal ASECs.
824 mPms.scanAvailableAsecs();
825
826 // Notify people waiting for ASECs to be scanned that it's done.
827 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800828 }
829 }.start();
830 }
831
832 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800833 * Callback from NativeDaemonConnector
834 */
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800835 public boolean onCheckHoldWakeLock(int code) {
836 return false;
837 }
838
839 /**
840 * Callback from NativeDaemonConnector
841 */
San Mehat4270e1e2010-01-29 05:32:19 -0800842 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800843 if (DEBUG_EVENTS) {
844 StringBuilder builder = new StringBuilder();
845 builder.append("onEvent::");
846 builder.append(" raw= " + raw);
847 if (cooked != null) {
848 builder.append(" cooked = " );
849 for (String str : cooked) {
850 builder.append(" " + str);
851 }
852 }
San Mehata5078592010-03-25 09:36:54 -0700853 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800854 }
San Mehat4270e1e2010-01-29 05:32:19 -0800855 if (code == VoldResponseCode.VolumeStateChange) {
856 /*
857 * One of the volumes we're managing has changed state.
858 * Format: "NNN Volume <label> <path> state changed
859 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
860 */
861 notifyVolumeStateChange(
862 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
863 Integer.parseInt(cooked[10]));
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700864 } else if (code == VoldResponseCode.VolumeUuidChange) {
865 // Format: nnn <label> <path> <uuid>
866 final String path = cooked[2];
867 final String uuid = (cooked.length > 3) ? cooked[3] : null;
868
869 final StorageVolume vol = mVolumesByPath.get(path);
870 if (vol != null) {
871 vol.setUuid(uuid);
872 }
873
874 } else if (code == VoldResponseCode.VolumeUserLabelChange) {
875 // Format: nnn <label> <path> <label>
876 final String path = cooked[2];
877 final String userLabel = (cooked.length > 3) ? cooked[3] : null;
878
879 final StorageVolume vol = mVolumesByPath.get(path);
880 if (vol != null) {
881 vol.setUserLabel(userLabel);
882 }
883
San Mehat4270e1e2010-01-29 05:32:19 -0800884 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
885 (code == VoldResponseCode.VolumeDiskRemoved) ||
886 (code == VoldResponseCode.VolumeBadRemoval)) {
887 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
888 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
889 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400890 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800891 final String label = cooked[2];
892 final String path = cooked[3];
893 int major = -1;
894 int minor = -1;
895
896 try {
897 String devComp = cooked[6].substring(1, cooked[6].length() -1);
898 String[] devTok = devComp.split(":");
899 major = Integer.parseInt(devTok[0]);
900 minor = Integer.parseInt(devTok[1]);
901 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700902 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800903 }
904
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700905 final StorageVolume volume;
906 final String state;
907 synchronized (mVolumesLock) {
908 volume = mVolumesByPath.get(path);
909 state = mVolumeStates.get(path);
910 }
911
San Mehat4270e1e2010-01-29 05:32:19 -0800912 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700913 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600914 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800915 public void run() {
916 try {
917 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800918 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700919 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800920 }
921 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700922 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800923 }
924 }
925 }.start();
926 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
927 /*
928 * This event gets trumped if we're already in BAD_REMOVAL state
929 */
930 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
931 return true;
932 }
933 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700934 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700935 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Johan Redestig0464c072014-01-18 22:46:56 +0100936 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800937
San Mehata5078592010-03-25 09:36:54 -0700938 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700939 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400940 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800941 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700942 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800943 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700944 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200945 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800946
San Mehata5078592010-03-25 09:36:54 -0700947 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700948 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400949 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700950 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700951 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800952 } else {
San Mehata5078592010-03-25 09:36:54 -0700953 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800954 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400955
956 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700957 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400958 }
San Mehat4270e1e2010-01-29 05:32:19 -0800959 } else {
960 return false;
961 }
962
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400963 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800964 }
965
San Mehat207e5382010-02-04 20:46:54 -0800966 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700967 final StorageVolume volume;
968 final String state;
969 synchronized (mVolumesLock) {
970 volume = mVolumesByPath.get(path);
971 state = getVolumeState(path);
972 }
973
974 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800975
Mike Lockwooda5250c92011-05-23 13:44:04 -0400976 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800977
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500978 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700979 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700980 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500981 }
982
San Mehat4270e1e2010-01-29 05:32:19 -0800983 if (newState == VolumeState.Init) {
984 } else if (newState == VolumeState.NoMedia) {
985 // NoMedia is handled via Disk Remove events
986 } else if (newState == VolumeState.Idle) {
987 /*
988 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
989 * if we're in the process of enabling UMS
990 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700991 if (!state.equals(
992 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
993 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800994 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700995 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700996 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400997 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800998 }
999 } else if (newState == VolumeState.Pending) {
1000 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -07001001 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001002 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001003 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -08001004 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -07001005 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001006 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001007 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -08001008 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001009 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -08001010 } else if (newState == VolumeState.Formatting) {
1011 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -07001012 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -08001013 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001014 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
1015 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001016
San Mehata5078592010-03-25 09:36:54 -07001017 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001018 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001019 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -07001020 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -08001021 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -07001022 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -08001023 return;
1024 } else {
San Mehata5078592010-03-25 09:36:54 -07001025 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001026 }
1027
Mike Lockwooda5250c92011-05-23 13:44:04 -04001028 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001029 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001030 }
1031 }
1032
San Mehat207e5382010-02-04 20:46:54 -08001033 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -08001034 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001035
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001036 final StorageVolume volume;
1037 synchronized (mVolumesLock) {
1038 volume = mVolumesByPath.get(path);
1039 }
1040
San Mehata5078592010-03-25 09:36:54 -07001041 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -08001042 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001043 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -08001044 } catch (NativeDaemonConnectorException e) {
1045 /*
1046 * Mount failed for some reason
1047 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001048 String action = null;
San Mehat207e5382010-02-04 20:46:54 -08001049 int code = e.getCode();
1050 if (code == VoldResponseCode.OpFailedNoMedia) {
1051 /*
1052 * Attempt to mount but no media inserted
1053 */
San Mehatb1043402010-02-05 08:26:50 -08001054 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001055 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -07001056 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -08001057 /*
1058 * Media is blank or does not contain a supported filesystem
1059 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001060 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001061 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -08001062 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -08001063 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -07001064 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -08001065 /*
1066 * Volume consistency check failed
1067 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001068 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001069 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -08001070 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001071 } else {
San Mehatb1043402010-02-05 08:26:50 -08001072 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001073 }
1074
1075 /*
1076 * Send broadcast intent (if required for the failure)
1077 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001078 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001079 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001080 }
1081 }
1082
1083 return rc;
1084 }
1085
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001086 /*
1087 * If force is not set, we do not unmount if there are
1088 * processes holding references to the volume about to be unmounted.
1089 * If force is set, all the processes holding references need to be
1090 * killed via the ActivityManager before actually unmounting the volume.
1091 * This might even take a while and might be retried after timed delays
1092 * to make sure we dont end up in an instable state and kill some core
1093 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001094 * If removeEncryption is set, force is implied, and the system will remove any encryption
1095 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001096 */
Ben Komalo13c71972011-09-07 16:35:56 -07001097 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001098 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001099 return VoldResponseCode.OpFailedVolNotMounted;
1100 }
Kenny Rootaa485402010-09-14 14:49:41 -07001101
1102 /*
1103 * Force a GC to make sure AssetManagers in other threads of the
1104 * system_server are cleaned up. We have to do this since AssetManager
1105 * instances are kept as a WeakReference and it's possible we have files
1106 * open on the external storage.
1107 */
1108 Runtime.getRuntime().gc();
1109
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001110 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001111 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001112 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001113 final Command cmd = new Command("volume", "unmount", path);
1114 if (removeEncryption) {
1115 cmd.appendArg("force_and_revert");
1116 } else if (force) {
1117 cmd.appendArg("force");
1118 }
1119 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001120 // We unmounted the volume. None of the asec containers are available now.
1121 synchronized (mAsecMountSet) {
1122 mAsecMountSet.clear();
1123 }
San Mehatb1043402010-02-05 08:26:50 -08001124 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001125 } catch (NativeDaemonConnectorException e) {
1126 // Don't worry about mismatch in PackageManager since the
1127 // call back will handle the status changes any way.
1128 int code = e.getCode();
1129 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001130 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001131 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1132 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001133 } else {
San Mehatb1043402010-02-05 08:26:50 -08001134 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001135 }
1136 }
1137 }
1138
1139 private int doFormatVolume(String path) {
1140 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001141 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001142 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001143 } catch (NativeDaemonConnectorException e) {
1144 int code = e.getCode();
1145 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001146 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001147 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001148 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001149 } else {
San Mehatb1043402010-02-05 08:26:50 -08001150 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001151 }
1152 }
1153 }
1154
San Mehatb1043402010-02-05 08:26:50 -08001155 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001156 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001157 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001158 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001159 } catch (NativeDaemonConnectorException ex) {
1160 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1161 return false;
1162 }
San Mehatb1043402010-02-05 08:26:50 -08001163
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001164 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1165 return event.getMessage().endsWith("enabled");
1166 } else {
1167 return false;
San Mehatb1043402010-02-05 08:26:50 -08001168 }
San Mehatb1043402010-02-05 08:26:50 -08001169 }
1170
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001171 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001172 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001173 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001174 for (int i = mListeners.size() -1; i >= 0; i--) {
1175 MountServiceBinderListener bl = mListeners.get(i);
1176 try {
San Mehatb1043402010-02-05 08:26:50 -08001177 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001178 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001179 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001180 mListeners.remove(i);
1181 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001182 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001183 }
1184 }
1185 }
1186
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001187 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001188 sendUmsIntent(avail);
1189 } else {
1190 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001191 }
San Mehat2fe718a2010-03-11 12:01:49 -08001192
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001193 final StorageVolume primary = getPrimaryPhysicalVolume();
1194 if (avail == false && primary != null
1195 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1196 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001197 /*
1198 * USB mass storage disconnected while enabled
1199 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001200 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001201 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001202 public void run() {
1203 try {
1204 int rc;
San Mehata5078592010-03-25 09:36:54 -07001205 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001206 doShareUnshareVolume(path, "ums", false);
1207 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001208 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001209 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1210 path, rc));
1211 }
1212 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001213 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001214 }
1215 }
1216 }.start();
1217 }
San Mehat4270e1e2010-01-29 05:32:19 -08001218 }
1219
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001220 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1221 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1222 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
Johan Redestig0464c072014-01-18 22:46:56 +01001223 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001224 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1225 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001226 }
1227
San Mehat6a965af22010-02-24 17:47:30 -08001228 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001229 mContext.sendBroadcastAsUser(
1230 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1231 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001232 }
1233
San Mehat207e5382010-02-04 20:46:54 -08001234 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001235 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1236 throw new SecurityException(String.format("Requires %s permission", perm));
1237 }
1238 }
1239
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001240 // Storage list XML tags
1241 private static final String TAG_STORAGE_LIST = "StorageList";
1242 private static final String TAG_STORAGE = "storage";
1243
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001244 private void readStorageListLocked() {
1245 mVolumes.clear();
1246 mVolumeStates.clear();
1247
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001248 Resources resources = mContext.getResources();
1249
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001250 int id = com.android.internal.R.xml.storage_list;
1251 XmlResourceParser parser = resources.getXml(id);
1252 AttributeSet attrs = Xml.asAttributeSet(parser);
1253
1254 try {
1255 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1256 while (true) {
1257 XmlUtils.nextElement(parser);
1258
1259 String element = parser.getName();
1260 if (element == null) break;
1261
1262 if (TAG_STORAGE.equals(element)) {
1263 TypedArray a = resources.obtainAttributes(attrs,
1264 com.android.internal.R.styleable.Storage);
1265
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001266 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001267 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001268 int descriptionId = a.getResourceId(
1269 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001270 CharSequence description = a.getText(
1271 com.android.internal.R.styleable.Storage_storageDescription);
1272 boolean primary = a.getBoolean(
1273 com.android.internal.R.styleable.Storage_primary, false);
1274 boolean removable = a.getBoolean(
1275 com.android.internal.R.styleable.Storage_removable, false);
1276 boolean emulated = a.getBoolean(
1277 com.android.internal.R.styleable.Storage_emulated, false);
1278 int mtpReserve = a.getInt(
1279 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001280 boolean allowMassStorage = a.getBoolean(
1281 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001282 // resource parser does not support longs, so XML value is in megabytes
1283 long maxFileSize = a.getInt(
1284 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001285
1286 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1287 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001288 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001289 " allowMassStorage: " + allowMassStorage +
1290 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001291
1292 if (emulated) {
1293 // For devices with emulated storage, we create separate
1294 // volumes for each known user.
1295 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1296 true, mtpReserve, false, maxFileSize, null);
1297
1298 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001299 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001300 createEmulatedVolumeForUserLocked(user.getUserHandle());
1301 }
1302
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001303 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001304 if (path == null || description == null) {
1305 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001306 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001307 final StorageVolume volume = new StorageVolume(new File(path),
1308 descriptionId, primary, removable, emulated, mtpReserve,
1309 allowMassStorage, maxFileSize, null);
1310 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001311
1312 // Until we hear otherwise, treat as unmounted
1313 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001314 volume.setState(Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001315 }
1316 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001317
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001318 a.recycle();
1319 }
1320 }
1321 } catch (XmlPullParserException e) {
1322 throw new RuntimeException(e);
1323 } catch (IOException e) {
1324 throw new RuntimeException(e);
1325 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001326 // Compute storage ID for each physical volume; emulated storage is
1327 // always 0 when defined.
1328 int index = isExternalStorageEmulated() ? 1 : 0;
1329 for (StorageVolume volume : mVolumes) {
1330 if (!volume.isEmulated()) {
1331 volume.setStorageId(index++);
1332 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001333 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001334 parser.close();
1335 }
1336 }
1337
San Mehat4270e1e2010-01-29 05:32:19 -08001338 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001339 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1340 * using {@link #mEmulatedTemplate} as template.
1341 */
1342 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1343 if (mEmulatedTemplate == null) {
1344 throw new IllegalStateException("Missing emulated volume multi-user template");
1345 }
1346
1347 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1348 final File path = userEnv.getExternalStorageDirectory();
1349 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1350 volume.setStorageId(0);
1351 addVolumeLocked(volume);
1352
1353 if (mSystemReady) {
1354 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1355 } else {
1356 // Place stub status for early callers to find
1357 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001358 volume.setState(Environment.MEDIA_MOUNTED);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001359 }
1360 }
1361
1362 private void addVolumeLocked(StorageVolume volume) {
1363 Slog.d(TAG, "addVolumeLocked() " + volume);
1364 mVolumes.add(volume);
1365 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1366 if (existing != null) {
1367 throw new IllegalStateException(
1368 "Volume at " + volume.getPath() + " already exists: " + existing);
1369 }
1370 }
1371
1372 private void removeVolumeLocked(StorageVolume volume) {
1373 Slog.d(TAG, "removeVolumeLocked() " + volume);
1374 mVolumes.remove(volume);
1375 mVolumesByPath.remove(volume.getPath());
1376 mVolumeStates.remove(volume.getPath());
1377 }
1378
1379 private StorageVolume getPrimaryPhysicalVolume() {
1380 synchronized (mVolumesLock) {
1381 for (StorageVolume volume : mVolumes) {
1382 if (volume.isPrimary() && !volume.isEmulated()) {
1383 return volume;
1384 }
1385 }
1386 }
1387 return null;
1388 }
1389
1390 /**
San Mehat207e5382010-02-04 20:46:54 -08001391 * Constructs a new MountService instance
1392 *
1393 * @param context Binder context for this service
1394 */
1395 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001396 sSelf = this;
1397
San Mehat207e5382010-02-04 20:46:54 -08001398 mContext = context;
1399
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001400 synchronized (mVolumesLock) {
1401 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001402 }
1403
San Mehat207e5382010-02-04 20:46:54 -08001404 // XXX: This will go away soon in favor of IMountServiceObserver
1405 mPms = (PackageManagerService) ServiceManager.getService("package");
1406
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001407 HandlerThread hthread = new HandlerThread(TAG);
1408 hthread.start();
1409 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001410
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001411 // Watch for user changes
1412 final IntentFilter userFilter = new IntentFilter();
1413 userFilter.addAction(Intent.ACTION_USER_ADDED);
1414 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1415 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1416
1417 // Watch for USB changes on primary volume
1418 final StorageVolume primary = getPrimaryPhysicalVolume();
1419 if (primary != null && primary.allowMassStorage()) {
1420 mContext.registerReceiver(
1421 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1422 }
1423
Kenny Roota02b8b02010-08-05 16:14:17 -07001424 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001425 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001426
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001427 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001428 * Create the connection to vold with a maximum queue of twice the
1429 * amount of containers we'd ever expect to have. This keeps an
1430 * "asec list" from blocking a thread repeatedly.
1431 */
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001432 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1433 null);
Kenny Root51a573c2012-05-17 13:30:28 -07001434
Kenny Root305bcbf2010-09-03 07:56:38 -07001435 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001436 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001437
Kenny Root07714d42011-08-17 17:49:28 -07001438 // Add ourself to the Watchdog monitors if enabled.
1439 if (WATCHDOG_ENABLE) {
1440 Watchdog.getInstance().addMonitor(this);
1441 }
San Mehat207e5382010-02-04 20:46:54 -08001442 }
1443
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001444 public void systemReady() {
1445 mSystemReady = true;
1446 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1447 }
1448
San Mehat207e5382010-02-04 20:46:54 -08001449 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001450 * Exposed API calls below here
1451 */
1452
1453 public void registerListener(IMountServiceListener listener) {
1454 synchronized (mListeners) {
1455 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1456 try {
1457 listener.asBinder().linkToDeath(bl, 0);
1458 mListeners.add(bl);
1459 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001460 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001461 }
1462 }
1463 }
1464
1465 public void unregisterListener(IMountServiceListener listener) {
1466 synchronized (mListeners) {
1467 for(MountServiceBinderListener bl : mListeners) {
Niklas Brunlidd64fe0f2013-07-05 08:54:03 +02001468 if (bl.mListener.asBinder() == listener.asBinder()) {
San Mehat4270e1e2010-01-29 05:32:19 -08001469 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001470 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001471 return;
1472 }
1473 }
1474 }
1475 }
1476
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001477 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001478 validatePermission(android.Manifest.permission.SHUTDOWN);
1479
San Mehata5078592010-03-25 09:36:54 -07001480 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001481 synchronized (mVolumesLock) {
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001482 // Get all volumes to be unmounted.
1483 MountShutdownLatch mountShutdownLatch = new MountShutdownLatch(observer,
1484 mVolumeStates.size());
1485
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001486 for (String path : mVolumeStates.keySet()) {
1487 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001488
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001489 if (state.equals(Environment.MEDIA_SHARED)) {
1490 /*
1491 * If the media is currently shared, unshare it.
1492 * XXX: This is still dangerous!. We should not
1493 * be rebooting at *all* if UMS is enabled, since
1494 * the UMS host could have dirty FAT cache entries
1495 * yet to flush.
1496 */
1497 setUsbMassStorageEnabled(false);
1498 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1499 /*
1500 * If the media is being checked, then we need to wait for
1501 * it to complete before being able to proceed.
1502 */
1503 // XXX: @hackbod - Should we disable the ANR timer here?
1504 int retries = 30;
1505 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1506 try {
1507 Thread.sleep(1000);
1508 } catch (InterruptedException iex) {
1509 Slog.e(TAG, "Interrupted while waiting for media", iex);
1510 break;
1511 }
1512 state = Environment.getExternalStorageState();
1513 }
1514 if (retries == 0) {
1515 Slog.e(TAG, "Timed out waiting for media to check");
1516 }
San Mehat91c77612010-01-07 10:39:41 -08001517 }
San Mehat91c77612010-01-07 10:39:41 -08001518
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001519 if (state.equals(Environment.MEDIA_MOUNTED)) {
1520 // Post a unmount message.
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001521 ShutdownCallBack ucb = new ShutdownCallBack(path, mountShutdownLatch);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001522 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1523 } else if (observer != null) {
1524 /*
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001525 * Count down, since nothing will be done. The observer will be
1526 * notified when we are done so shutdown sequence can continue.
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001527 */
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001528 mountShutdownLatch.countDown();
1529 Slog.i(TAG, "Unmount completed: " + path +
1530 ", result code: " + StorageResultCode.OperationSucceeded);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001531 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001532 }
San Mehat4270e1e2010-01-29 05:32:19 -08001533 }
1534 }
1535
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001536 private boolean getUmsEnabling() {
1537 synchronized (mListeners) {
1538 return mUmsEnabling;
1539 }
1540 }
1541
1542 private void setUmsEnabling(boolean enable) {
1543 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001544 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001545 }
1546 }
1547
San Mehatb1043402010-02-05 08:26:50 -08001548 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001549 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001550
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001551 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001552 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001553 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001554 synchronized (mListeners) {
1555 return mUmsAvailable;
1556 }
San Mehatb1043402010-02-05 08:26:50 -08001557 }
1558
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001559 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001560 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001561 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001562
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001563 final StorageVolume primary = getPrimaryPhysicalVolume();
1564 if (primary == null) return;
1565
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001566 // TODO: Add support for multiple share methods
1567
1568 /*
1569 * If the volume is mounted and we're enabling then unmount it
1570 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001571 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001572 String vs = getVolumeState(path);
1573 String method = "ums";
1574 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1575 // Override for isUsbMassStorageEnabled()
1576 setUmsEnabling(enable);
1577 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1578 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1579 // Clear override
1580 setUmsEnabling(false);
1581 }
1582 /*
1583 * If we disabled UMS then mount the volume
1584 */
1585 if (!enable) {
1586 doShareUnshareVolume(path, method, enable);
1587 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001588 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001589 " after disabling share method " + method);
1590 /*
1591 * Even though the mount failed, the unshare didn't so don't indicate an error.
1592 * The mountVolume() call will have set the storage state and sent the necessary
1593 * broadcasts.
1594 */
1595 }
1596 }
San Mehatb1043402010-02-05 08:26:50 -08001597 }
1598
1599 public boolean isUsbMassStorageEnabled() {
1600 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001601
1602 final StorageVolume primary = getPrimaryPhysicalVolume();
1603 if (primary != null) {
1604 return doGetVolumeShared(primary.getPath(), "ums");
1605 } else {
1606 return false;
1607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001609
San Mehat7fd0fee2009-12-17 07:12:23 -08001610 /**
1611 * @return state of the volume at the specified mount point
1612 */
San Mehat4270e1e2010-01-29 05:32:19 -08001613 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001614 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001615 String state = mVolumeStates.get(mountPoint);
1616 if (state == null) {
1617 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001618 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1619 state = Environment.MEDIA_REMOVED;
1620 } else {
1621 throw new IllegalArgumentException();
1622 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001623 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001624
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001625 return state;
1626 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001627 }
1628
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001629 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001630 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001631 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001632 }
1633
San Mehat4270e1e2010-01-29 05:32:19 -08001634 public int mountVolume(String path) {
1635 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001636
San Mehat207e5382010-02-04 20:46:54 -08001637 waitForReady();
1638 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
1640
Ben Komalo13c71972011-09-07 16:35:56 -07001641 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001642 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001643 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001645 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001646 if (DEBUG_UNMOUNT) {
1647 Slog.i(TAG, "Unmounting " + path
1648 + " force = " + force
1649 + " removeEncryption = " + removeEncryption);
1650 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001651 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1652 Environment.MEDIA_REMOVED.equals(volState) ||
1653 Environment.MEDIA_SHARED.equals(volState) ||
1654 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1655 // Media already unmounted or cannot be unmounted.
1656 // TODO return valid return code when adding observer call back.
1657 return;
1658 }
Ben Komalo13c71972011-09-07 16:35:56 -07001659 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001660 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662
San Mehat4270e1e2010-01-29 05:32:19 -08001663 public int formatVolume(String path) {
1664 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001665 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001666
San Mehat207e5382010-02-04 20:46:54 -08001667 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001670 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001671 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1672 waitForReady();
1673 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001674 final String[] r = NativeDaemonEvent.filterMessageList(
1675 mConnector.executeForList("storage", "users", path),
1676 VoldResponseCode.StorageUsersListResult);
1677
San Mehatc1b4ce92010-02-16 17:13:03 -08001678 // FMT: <pid> <process name>
1679 int[] data = new int[r.length];
1680 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001681 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001682 try {
1683 data[i] = Integer.parseInt(tok[0]);
1684 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001685 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001686 return new int[0];
1687 }
1688 }
1689 return data;
1690 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001691 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001692 return new int[0];
1693 }
1694 }
1695
San Mehatb1043402010-02-05 08:26:50 -08001696 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001697 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001698 if (primary != null) {
1699 boolean mounted = false;
1700 try {
1701 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001702 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001703 }
1704
1705 if (!mounted) {
1706 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1707 }
San Mehatb1043402010-02-05 08:26:50 -08001708 }
1709 }
1710
San Mehat4270e1e2010-01-29 05:32:19 -08001711 public String[] getSecureContainerList() {
1712 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001713 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001714 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001715
San Mehat4270e1e2010-01-29 05:32:19 -08001716 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001717 return NativeDaemonEvent.filterMessageList(
1718 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001719 } catch (NativeDaemonConnectorException e) {
1720 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722 }
San Mehat36972292010-01-06 11:06:32 -08001723
Kenny Root6dceb882012-04-12 14:23:49 -07001724 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1725 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001726 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001727 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001728 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001729
San Mehatb1043402010-02-05 08:26:50 -08001730 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001731 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001732 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1733 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001734 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001735 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001736 }
San Mehata181b212010-02-11 06:50:20 -08001737
1738 if (rc == StorageResultCode.OperationSucceeded) {
1739 synchronized (mAsecMountSet) {
1740 mAsecMountSet.add(id);
1741 }
1742 }
San Mehat4270e1e2010-01-29 05:32:19 -08001743 return rc;
San Mehat36972292010-01-06 11:06:32 -08001744 }
1745
San Mehat4270e1e2010-01-29 05:32:19 -08001746 public int finalizeSecureContainer(String id) {
1747 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001748 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001749
San Mehatb1043402010-02-05 08:26:50 -08001750 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001751 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001752 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001753 /*
1754 * Finalization does a remount, so no need
1755 * to update mAsecMountSet
1756 */
San Mehat4270e1e2010-01-29 05:32:19 -08001757 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001758 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001759 }
San Mehat4270e1e2010-01-29 05:32:19 -08001760 return rc;
San Mehat36972292010-01-06 11:06:32 -08001761 }
1762
Kenny Root6dceb882012-04-12 14:23:49 -07001763 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1764 validatePermission(android.Manifest.permission.ASEC_CREATE);
1765 warnOnNotMounted();
1766
1767 int rc = StorageResultCode.OperationSucceeded;
1768 try {
1769 mConnector.execute("asec", "fixperms", id, gid, filename);
1770 /*
1771 * Fix permissions does a remount, so no need to update
1772 * mAsecMountSet
1773 */
1774 } catch (NativeDaemonConnectorException e) {
1775 rc = StorageResultCode.OperationFailedInternalError;
1776 }
1777 return rc;
1778 }
1779
San Mehatd9709982010-02-18 11:43:03 -08001780 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001781 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001782 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001783 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001784
Kenny Rootaa485402010-09-14 14:49:41 -07001785 /*
1786 * Force a GC to make sure AssetManagers in other threads of the
1787 * system_server are cleaned up. We have to do this since AssetManager
1788 * instances are kept as a WeakReference and it's possible we have files
1789 * open on the external storage.
1790 */
1791 Runtime.getRuntime().gc();
1792
San Mehatb1043402010-02-05 08:26:50 -08001793 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001794 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001795 final Command cmd = new Command("asec", "destroy", id);
1796 if (force) {
1797 cmd.appendArg("force");
1798 }
1799 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001800 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001801 int code = e.getCode();
1802 if (code == VoldResponseCode.OpFailedStorageBusy) {
1803 rc = StorageResultCode.OperationFailedStorageBusy;
1804 } else {
1805 rc = StorageResultCode.OperationFailedInternalError;
1806 }
San Mehat02735bc2010-01-26 15:18:08 -08001807 }
San Mehata181b212010-02-11 06:50:20 -08001808
1809 if (rc == StorageResultCode.OperationSucceeded) {
1810 synchronized (mAsecMountSet) {
1811 if (mAsecMountSet.contains(id)) {
1812 mAsecMountSet.remove(id);
1813 }
1814 }
1815 }
1816
San Mehat4270e1e2010-01-29 05:32:19 -08001817 return rc;
San Mehat36972292010-01-06 11:06:32 -08001818 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001819
San Mehat4270e1e2010-01-29 05:32:19 -08001820 public int mountSecureContainer(String id, String key, int ownerUid) {
1821 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001822 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001823 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001824
San Mehata181b212010-02-11 06:50:20 -08001825 synchronized (mAsecMountSet) {
1826 if (mAsecMountSet.contains(id)) {
1827 return StorageResultCode.OperationFailedStorageMounted;
1828 }
1829 }
1830
San Mehatb1043402010-02-05 08:26:50 -08001831 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001832 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001833 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001834 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001835 int code = e.getCode();
1836 if (code != VoldResponseCode.OpFailedStorageBusy) {
1837 rc = StorageResultCode.OperationFailedInternalError;
1838 }
San Mehat02735bc2010-01-26 15:18:08 -08001839 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001840
1841 if (rc == StorageResultCode.OperationSucceeded) {
1842 synchronized (mAsecMountSet) {
1843 mAsecMountSet.add(id);
1844 }
1845 }
San Mehat4270e1e2010-01-29 05:32:19 -08001846 return rc;
San Mehat36972292010-01-06 11:06:32 -08001847 }
1848
San Mehatd9709982010-02-18 11:43:03 -08001849 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001850 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001851 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001852 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001853
San Mehat6cdd9c02010-02-09 14:45:20 -08001854 synchronized (mAsecMountSet) {
1855 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001856 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001857 }
1858 }
1859
Kenny Rootaa485402010-09-14 14:49:41 -07001860 /*
1861 * Force a GC to make sure AssetManagers in other threads of the
1862 * system_server are cleaned up. We have to do this since AssetManager
1863 * instances are kept as a WeakReference and it's possible we have files
1864 * open on the external storage.
1865 */
1866 Runtime.getRuntime().gc();
1867
San Mehatb1043402010-02-05 08:26:50 -08001868 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001869 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001870 final Command cmd = new Command("asec", "unmount", id);
1871 if (force) {
1872 cmd.appendArg("force");
1873 }
1874 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001875 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001876 int code = e.getCode();
1877 if (code == VoldResponseCode.OpFailedStorageBusy) {
1878 rc = StorageResultCode.OperationFailedStorageBusy;
1879 } else {
1880 rc = StorageResultCode.OperationFailedInternalError;
1881 }
San Mehat02735bc2010-01-26 15:18:08 -08001882 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001883
1884 if (rc == StorageResultCode.OperationSucceeded) {
1885 synchronized (mAsecMountSet) {
1886 mAsecMountSet.remove(id);
1887 }
1888 }
San Mehat4270e1e2010-01-29 05:32:19 -08001889 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001890 }
1891
San Mehat6cdd9c02010-02-09 14:45:20 -08001892 public boolean isSecureContainerMounted(String id) {
1893 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1894 waitForReady();
1895 warnOnNotMounted();
1896
1897 synchronized (mAsecMountSet) {
1898 return mAsecMountSet.contains(id);
1899 }
1900 }
1901
San Mehat4270e1e2010-01-29 05:32:19 -08001902 public int renameSecureContainer(String oldId, String newId) {
1903 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001904 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001905 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001906
San Mehata181b212010-02-11 06:50:20 -08001907 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001908 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001909 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001910 * changed while active, we must ensure both ids are not currently mounted.
1911 */
1912 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001913 return StorageResultCode.OperationFailedStorageMounted;
1914 }
1915 }
1916
San Mehatb1043402010-02-05 08:26:50 -08001917 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001918 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001919 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001920 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001921 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001922 }
San Mehata181b212010-02-11 06:50:20 -08001923
San Mehat4270e1e2010-01-29 05:32:19 -08001924 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001925 }
1926
San Mehat4270e1e2010-01-29 05:32:19 -08001927 public String getSecureContainerPath(String id) {
1928 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001929 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001930 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001931
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001932 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001933 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001934 event = mConnector.execute("asec", "path", id);
1935 event.checkCode(VoldResponseCode.AsecPathResult);
1936 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001937 } catch (NativeDaemonConnectorException e) {
1938 int code = e.getCode();
1939 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001940 Slog.i(TAG, String.format("Container '%s' not found", id));
1941 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001942 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001943 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001944 }
1945 }
San Mehat22dd86e2010-01-12 12:21:18 -08001946 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001947
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001948 public String getSecureContainerFilesystemPath(String id) {
1949 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1950 waitForReady();
1951 warnOnNotMounted();
1952
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001953 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001954 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001955 event = mConnector.execute("asec", "fspath", id);
1956 event.checkCode(VoldResponseCode.AsecPathResult);
1957 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001958 } catch (NativeDaemonConnectorException e) {
1959 int code = e.getCode();
1960 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1961 Slog.i(TAG, String.format("Container '%s' not found", id));
1962 return null;
1963 } else {
1964 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1965 }
1966 }
1967 }
1968
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001969 public void finishMediaUpdate() {
1970 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1971 }
Kenny Root02c87302010-07-01 08:10:18 -07001972
Kenny Roota02b8b02010-08-05 16:14:17 -07001973 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1974 if (callerUid == android.os.Process.SYSTEM_UID) {
1975 return true;
1976 }
1977
Kenny Root02c87302010-07-01 08:10:18 -07001978 if (packageName == null) {
1979 return false;
1980 }
1981
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001982 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001983
1984 if (DEBUG_OBB) {
1985 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1986 packageUid + ", callerUid = " + callerUid);
1987 }
1988
1989 return callerUid == packageUid;
1990 }
1991
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001992 public String getMountedObbPath(String rawPath) {
1993 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001994
Kenny Root02c87302010-07-01 08:10:18 -07001995 waitForReady();
1996 warnOnNotMounted();
1997
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001998 final ObbState state;
1999 synchronized (mObbPathToStateMap) {
2000 state = mObbPathToStateMap.get(rawPath);
2001 }
2002 if (state == null) {
2003 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2004 return null;
2005 }
2006
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002007 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002008 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002009 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002010 event.checkCode(VoldResponseCode.AsecPathResult);
2011 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002012 } catch (NativeDaemonConnectorException e) {
2013 int code = e.getCode();
2014 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002015 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002016 } else {
2017 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2018 }
2019 }
2020 }
2021
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002022 @Override
2023 public boolean isObbMounted(String rawPath) {
2024 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002025 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002026 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002027 }
Kenny Root02c87302010-07-01 08:10:18 -07002028 }
2029
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002030 @Override
2031 public void mountObb(
2032 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2033 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2034 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2035 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002036
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002037 final int callingUid = Binder.getCallingUid();
2038 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2039 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002040 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2041
2042 if (DEBUG_OBB)
2043 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002044 }
2045
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002046 @Override
2047 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2048 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2049
2050 final ObbState existingState;
2051 synchronized (mObbPathToStateMap) {
2052 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002053 }
2054
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002055 if (existingState != null) {
2056 // TODO: separate state object from request data
2057 final int callingUid = Binder.getCallingUid();
2058 final ObbState newState = new ObbState(
2059 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2060 final ObbAction action = new UnmountObbAction(newState, force);
2061 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002062
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002063 if (DEBUG_OBB)
2064 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2065 } else {
2066 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2067 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002068 }
2069
Ben Komalo444eca22011-09-01 15:17:44 -07002070 @Override
2071 public int getEncryptionState() {
2072 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2073 "no permission to access the crypt keeper");
2074
2075 waitForReady();
2076
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002077 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002078 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002079 event = mConnector.execute("cryptfs", "cryptocomplete");
2080 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002081 } catch (NumberFormatException e) {
2082 // Bad result - unexpected.
2083 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2084 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2085 } catch (NativeDaemonConnectorException e) {
2086 // Something bad happened.
2087 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2088 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2089 }
2090 }
2091
Paul Lawrence8e397362014-01-27 15:22:30 -08002092 private String toHex(String password) {
2093 if (password == null) {
Paul Lawrence945490c2014-03-27 16:37:28 +00002094 return new String();
Paul Lawrence8e397362014-01-27 15:22:30 -08002095 }
2096 byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
2097 return new String(Hex.encodeHex(bytes));
2098 }
2099
Paul Lawrence945490c2014-03-27 16:37:28 +00002100 private String fromHex(String hexPassword) {
2101 if (hexPassword == null) {
2102 return null;
2103 }
2104
2105 try {
2106 byte[] bytes = Hex.decodeHex(hexPassword.toCharArray());
2107 return new String(bytes, StandardCharsets.UTF_8);
2108 } catch (DecoderException e) {
2109 return null;
2110 }
2111 }
2112
Ben Komalo444eca22011-09-01 15:17:44 -07002113 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002114 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002115 if (TextUtils.isEmpty(password)) {
2116 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002117 }
2118
Jason parks8888c592011-01-20 22:46:41 -06002119 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2120 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002121
2122 waitForReady();
2123
2124 if (DEBUG_EVENTS) {
2125 Slog.i(TAG, "decrypting storage...");
2126 }
2127
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002128 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002129 try {
Paul Lawrence8e397362014-01-27 15:22:30 -08002130 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(toHex(password)));
Jason parks9ed98bc2011-01-17 09:58:35 -06002131
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002132 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002133 if (code == 0) {
2134 // Decrypt was successful. Post a delayed message before restarting in order
2135 // to let the UI to clear itself
2136 mHandler.postDelayed(new Runnable() {
2137 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002138 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002139 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002140 } catch (NativeDaemonConnectorException e) {
2141 Slog.e(TAG, "problem executing in background", e);
2142 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002143 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002144 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002145 }
2146
2147 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002148 } catch (NativeDaemonConnectorException e) {
2149 // Decryption failed
2150 return e.getCode();
2151 }
Jason parks5af0b912010-11-29 09:05:25 -06002152 }
2153
Paul Lawrence46791e72014-04-03 09:10:26 -07002154 public int encryptStorage(int type, String password) {
2155 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002156 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002157 }
2158
Jason parks8888c592011-01-20 22:46:41 -06002159 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2160 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002161
2162 waitForReady();
2163
2164 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002165 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002166 }
2167
2168 try {
Paul Lawrence46791e72014-04-03 09:10:26 -07002169 mConnector.execute("cryptfs", "enablecrypto", "inplace", CRYPTO_TYPES[type],
Paul Lawrence8e397362014-01-27 15:22:30 -08002170 new SensitiveArg(toHex(password)));
Jason parks56aa5322011-01-07 09:01:15 -06002171 } catch (NativeDaemonConnectorException e) {
2172 // Encryption failed
2173 return e.getCode();
2174 }
2175
2176 return 0;
2177 }
2178
Paul Lawrence8e397362014-01-27 15:22:30 -08002179 /** Set the password for encrypting the master key.
2180 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2181 * @param password The password to set.
2182 */
2183 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002184 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2185 "no permission to access the crypt keeper");
2186
2187 waitForReady();
2188
2189 if (DEBUG_EVENTS) {
2190 Slog.i(TAG, "changing encryption password...");
2191 }
2192
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002193 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002194 try {
Paul Lawrence8e397362014-01-27 15:22:30 -08002195 event = mConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
2196 new SensitiveArg(toHex(password)));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002197 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002198 } catch (NativeDaemonConnectorException e) {
2199 // Encryption failed
2200 return e.getCode();
2201 }
2202 }
2203
Christopher Tate32418be2011-10-10 13:51:12 -07002204 /**
2205 * Validate a user-supplied password string with cryptfs
2206 */
2207 @Override
2208 public int verifyEncryptionPassword(String password) throws RemoteException {
2209 // Only the system process is permitted to validate passwords
2210 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2211 throw new SecurityException("no permission to access the crypt keeper");
2212 }
2213
2214 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2215 "no permission to access the crypt keeper");
2216
2217 if (TextUtils.isEmpty(password)) {
2218 throw new IllegalArgumentException("password cannot be empty");
2219 }
2220
2221 waitForReady();
2222
2223 if (DEBUG_EVENTS) {
2224 Slog.i(TAG, "validating encryption password...");
2225 }
2226
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002227 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002228 try {
Paul Lawrence8e397362014-01-27 15:22:30 -08002229 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(toHex(password)));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002230 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2231 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002232 } catch (NativeDaemonConnectorException e) {
2233 // Encryption failed
2234 return e.getCode();
2235 }
2236 }
2237
Paul Lawrence8e397362014-01-27 15:22:30 -08002238 /**
2239 * Get the type of encryption used to encrypt the master key.
2240 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2241 */
2242 @Override
2243 public int getPasswordType() throws RemoteException {
2244
2245 waitForReady();
2246
2247 final NativeDaemonEvent event;
2248 try {
2249 event = mConnector.execute("cryptfs", "getpwtype");
2250 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2251 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2252 return i;
2253 }
2254
2255 throw new IllegalStateException("unexpected return from cryptfs");
2256 } catch (NativeDaemonConnectorException e) {
2257 throw e.rethrowAsParcelableException();
2258 }
2259 }
2260
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002261 /**
2262 * Set a field in the crypto header.
2263 * @param field field to set
2264 * @param contents contents to set in field
2265 */
2266 @Override
2267 public void setField(String field, String contents) throws RemoteException {
2268
2269 waitForReady();
2270
2271 final NativeDaemonEvent event;
2272 try {
2273 event = mConnector.execute("cryptfs", "setfield", field, contents);
2274 } catch (NativeDaemonConnectorException e) {
2275 throw e.rethrowAsParcelableException();
2276 }
2277 }
2278
2279 /**
2280 * Gets a field from the crypto header.
2281 * @param field field to get
2282 * @return contents of field
2283 */
2284 @Override
2285 public String getField(String field) throws RemoteException {
2286
2287 waitForReady();
2288
2289 final NativeDaemonEvent event;
2290 try {
2291 final String[] contents = NativeDaemonEvent.filterMessageList(
2292 mConnector.executeForList("cryptfs", "getfield", field),
2293 VoldResponseCode.CryptfsGetfieldResult);
2294 String result = new String();
2295 for (String content : contents) {
2296 result += content;
2297 }
2298 return result;
2299 } catch (NativeDaemonConnectorException e) {
2300 throw e.rethrowAsParcelableException();
2301 }
2302 }
2303
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002304 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002305 public String getPassword() throws RemoteException {
2306 if (!isReady()) {
2307 return new String();
2308 }
2309
2310 final NativeDaemonEvent event;
2311 try {
2312 event = mConnector.execute("cryptfs", "getpw");
2313 return fromHex(event.getMessage());
2314 } catch (NativeDaemonConnectorException e) {
2315 throw e.rethrowAsParcelableException();
2316 }
2317 }
2318
2319 @Override
2320 public void clearPassword() throws RemoteException {
2321 if (!isReady()) {
2322 return;
2323 }
2324
2325 final NativeDaemonEvent event;
2326 try {
2327 event = mConnector.execute("cryptfs", "clearpw");
2328 } catch (NativeDaemonConnectorException e) {
2329 throw e.rethrowAsParcelableException();
2330 }
2331 }
2332
2333 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002334 public int mkdirs(String callingPkg, String appPath) {
2335 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2336 final UserEnvironment userEnv = new UserEnvironment(userId);
2337
2338 // Validate that reported package name belongs to caller
2339 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2340 Context.APP_OPS_SERVICE);
2341 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2342
2343 try {
2344 appPath = new File(appPath).getCanonicalPath();
2345 } catch (IOException e) {
2346 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2347 return -1;
2348 }
2349
Jeff Sharkey5786a272013-10-02 12:50:34 -07002350 if (!appPath.endsWith("/")) {
2351 appPath = appPath + "/";
2352 }
2353
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002354 // Try translating the app path into a vold path, but require that it
2355 // belong to the calling package.
2356 String voldPath = maybeTranslatePathForVold(appPath,
2357 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2358 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2359 if (voldPath != null) {
2360 try {
2361 mConnector.execute("volume", "mkdirs", voldPath);
2362 return 0;
2363 } catch (NativeDaemonConnectorException e) {
2364 return e.getCode();
2365 }
2366 }
2367
2368 voldPath = maybeTranslatePathForVold(appPath,
2369 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2370 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2371 if (voldPath != null) {
2372 try {
2373 mConnector.execute("volume", "mkdirs", voldPath);
2374 return 0;
2375 } catch (NativeDaemonConnectorException e) {
2376 return e.getCode();
2377 }
2378 }
2379
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -07002380 voldPath = maybeTranslatePathForVold(appPath,
2381 userEnv.buildExternalStorageAppMediaDirs(callingPkg),
2382 userEnv.buildExternalStorageAppMediaDirsForVold(callingPkg));
2383 if (voldPath != null) {
2384 try {
2385 mConnector.execute("volume", "mkdirs", voldPath);
2386 return 0;
2387 } catch (NativeDaemonConnectorException e) {
2388 return e.getCode();
2389 }
2390 }
2391
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002392 throw new SecurityException("Invalid mkdirs path: " + appPath);
2393 }
2394
2395 /**
2396 * Translate the given path from an app-visible path to a vold-visible path,
2397 * but only if it's under the given whitelisted paths.
2398 *
2399 * @param path a canonicalized app-visible path.
2400 * @param appPaths list of app-visible paths that are allowed.
2401 * @param voldPaths list of vold-visible paths directly corresponding to the
2402 * allowed app-visible paths argument.
2403 * @return a vold-visible path representing the original path, or
2404 * {@code null} if the given path didn't have an app-to-vold
2405 * mapping.
2406 */
2407 @VisibleForTesting
2408 public static String maybeTranslatePathForVold(
2409 String path, File[] appPaths, File[] voldPaths) {
2410 if (appPaths.length != voldPaths.length) {
2411 throw new IllegalStateException("Paths must be 1:1 mapping");
2412 }
2413
2414 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002415 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002416 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002417 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002418 .getAbsolutePath();
2419 if (!path.endsWith("/")) {
2420 path = path + "/";
2421 }
2422 return path;
2423 }
2424 }
2425 return null;
2426 }
2427
2428 @Override
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002429 public StorageVolume[] getVolumeList() {
2430 final int callingUserId = UserHandle.getCallingUserId();
2431 final boolean accessAll = (mContext.checkPermission(
2432 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2433 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2434
2435 synchronized (mVolumesLock) {
2436 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2437 for (StorageVolume volume : mVolumes) {
2438 final UserHandle owner = volume.getOwner();
2439 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2440 if (accessAll || ownerMatch) {
2441 filtered.add(volume);
2442 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002443 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002444 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002445 }
2446 }
2447
Kenny Rootaf9d6672010-10-08 09:21:39 -07002448 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2449 final IBinder binder = obbState.getBinder();
2450 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002451
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 if (obbStates == null) {
2453 obbStates = new ArrayList<ObbState>();
2454 mObbMounts.put(binder, obbStates);
2455 } else {
2456 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002457 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002458 throw new IllegalStateException("Attempt to add ObbState twice. "
2459 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002460 }
2461 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002462 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463
2464 obbStates.add(obbState);
2465 try {
2466 obbState.link();
2467 } catch (RemoteException e) {
2468 /*
2469 * The binder died before we could link it, so clean up our state
2470 * and return failure.
2471 */
2472 obbStates.remove(obbState);
2473 if (obbStates.isEmpty()) {
2474 mObbMounts.remove(binder);
2475 }
2476
2477 // Rethrow the error so mountObb can get it
2478 throw e;
2479 }
2480
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002481 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002482 }
2483
Kenny Rootaf9d6672010-10-08 09:21:39 -07002484 private void removeObbStateLocked(ObbState obbState) {
2485 final IBinder binder = obbState.getBinder();
2486 final List<ObbState> obbStates = mObbMounts.get(binder);
2487 if (obbStates != null) {
2488 if (obbStates.remove(obbState)) {
2489 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002490 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002491 if (obbStates.isEmpty()) {
2492 mObbMounts.remove(binder);
2493 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002494 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002495
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002496 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002497 }
2498
Kenny Roota02b8b02010-08-05 16:14:17 -07002499 private class ObbActionHandler extends Handler {
2500 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002501 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002502
2503 ObbActionHandler(Looper l) {
2504 super(l);
2505 }
2506
2507 @Override
2508 public void handleMessage(Message msg) {
2509 switch (msg.what) {
2510 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002511 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002512
2513 if (DEBUG_OBB)
2514 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2515
2516 // If a bind was already initiated we don't really
2517 // need to do anything. The pending install
2518 // will be processed later on.
2519 if (!mBound) {
2520 // If this is the only one pending we might
2521 // have to bind to the service again.
2522 if (!connectToService()) {
2523 Slog.e(TAG, "Failed to bind to media container service");
2524 action.handleError();
2525 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002526 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002527 }
Kenny Root735de3b2010-09-30 14:11:39 -07002528
Kenny Root735de3b2010-09-30 14:11:39 -07002529 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002530 break;
2531 }
2532 case OBB_MCS_BOUND: {
2533 if (DEBUG_OBB)
2534 Slog.i(TAG, "OBB_MCS_BOUND");
2535 if (msg.obj != null) {
2536 mContainerService = (IMediaContainerService) msg.obj;
2537 }
2538 if (mContainerService == null) {
2539 // Something seriously wrong. Bail out
2540 Slog.e(TAG, "Cannot bind to media container service");
2541 for (ObbAction action : mActions) {
2542 // Indicate service bind error
2543 action.handleError();
2544 }
2545 mActions.clear();
2546 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002547 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002548 if (action != null) {
2549 action.execute(this);
2550 }
2551 } else {
2552 // Should never happen ideally.
2553 Slog.w(TAG, "Empty queue");
2554 }
2555 break;
2556 }
2557 case OBB_MCS_RECONNECT: {
2558 if (DEBUG_OBB)
2559 Slog.i(TAG, "OBB_MCS_RECONNECT");
2560 if (mActions.size() > 0) {
2561 if (mBound) {
2562 disconnectService();
2563 }
2564 if (!connectToService()) {
2565 Slog.e(TAG, "Failed to bind to media container service");
2566 for (ObbAction action : mActions) {
2567 // Indicate service bind error
2568 action.handleError();
2569 }
2570 mActions.clear();
2571 }
2572 }
2573 break;
2574 }
2575 case OBB_MCS_UNBIND: {
2576 if (DEBUG_OBB)
2577 Slog.i(TAG, "OBB_MCS_UNBIND");
2578
2579 // Delete pending install
2580 if (mActions.size() > 0) {
2581 mActions.remove(0);
2582 }
2583 if (mActions.size() == 0) {
2584 if (mBound) {
2585 disconnectService();
2586 }
2587 } else {
2588 // There are more pending requests in queue.
2589 // Just post MCS_BOUND message to trigger processing
2590 // of next pending install.
2591 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2592 }
2593 break;
2594 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002595 case OBB_FLUSH_MOUNT_STATE: {
2596 final String path = (String) msg.obj;
2597
2598 if (DEBUG_OBB)
2599 Slog.i(TAG, "Flushing all OBB state for path " + path);
2600
2601 synchronized (mObbMounts) {
2602 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2603
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002604 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002605 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002606 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002607
2608 /*
2609 * If this entry's source file is in the volume path
2610 * that got unmounted, remove it because it's no
2611 * longer valid.
2612 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002613 if (state.canonicalPath.startsWith(path)) {
2614 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002615 }
2616 }
2617
2618 for (final ObbState obbState : obbStatesToRemove) {
2619 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002620 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002621
2622 removeObbStateLocked(obbState);
2623
2624 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002625 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002626 OnObbStateChangeListener.UNMOUNTED);
2627 } catch (RemoteException e) {
2628 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002629 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002630 }
2631 }
2632 }
2633 break;
2634 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002635 }
2636 }
2637
2638 private boolean connectToService() {
2639 if (DEBUG_OBB)
2640 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2641
2642 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2643 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2644 mBound = true;
2645 return true;
2646 }
2647 return false;
2648 }
2649
2650 private void disconnectService() {
2651 mContainerService = null;
2652 mBound = false;
2653 mContext.unbindService(mDefContainerConn);
2654 }
2655 }
2656
2657 abstract class ObbAction {
2658 private static final int MAX_RETRIES = 3;
2659 private int mRetries;
2660
2661 ObbState mObbState;
2662
2663 ObbAction(ObbState obbState) {
2664 mObbState = obbState;
2665 }
2666
2667 public void execute(ObbActionHandler handler) {
2668 try {
2669 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002670 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002671 mRetries++;
2672 if (mRetries > MAX_RETRIES) {
2673 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002674 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002675 handleError();
2676 return;
2677 } else {
2678 handleExecute();
2679 if (DEBUG_OBB)
2680 Slog.i(TAG, "Posting install MCS_UNBIND");
2681 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2682 }
2683 } catch (RemoteException e) {
2684 if (DEBUG_OBB)
2685 Slog.i(TAG, "Posting install MCS_RECONNECT");
2686 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2687 } catch (Exception e) {
2688 if (DEBUG_OBB)
2689 Slog.d(TAG, "Error handling OBB action", e);
2690 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002691 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002692 }
2693 }
2694
Kenny Root05105f72010-09-22 17:29:43 -07002695 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002696 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002697
2698 protected ObbInfo getObbInfo() throws IOException {
2699 ObbInfo obbInfo;
2700 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002701 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002702 } catch (RemoteException e) {
2703 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002704 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002705 obbInfo = null;
2706 }
2707 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002708 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002709 }
2710 return obbInfo;
2711 }
2712
Kenny Rootaf9d6672010-10-08 09:21:39 -07002713 protected void sendNewStatusOrIgnore(int status) {
2714 if (mObbState == null || mObbState.token == null) {
2715 return;
2716 }
2717
Kenny Root38cf8862010-09-26 14:18:51 -07002718 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002719 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002720 } catch (RemoteException e) {
2721 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2722 }
2723 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002724 }
2725
2726 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002727 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002728 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002729
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002730 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002731 super(obbState);
2732 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002733 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002734 }
2735
Jason parks5af0b912010-11-29 09:05:25 -06002736 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002737 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002738 waitForReady();
2739 warnOnNotMounted();
2740
Kenny Root38cf8862010-09-26 14:18:51 -07002741 final ObbInfo obbInfo = getObbInfo();
2742
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002743 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002744 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2745 + " which is owned by " + obbInfo.packageName);
2746 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2747 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002748 }
2749
Kenny Rootaf9d6672010-10-08 09:21:39 -07002750 final boolean isMounted;
2751 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002752 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002753 }
2754 if (isMounted) {
2755 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2756 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2757 return;
2758 }
2759
Kenny Rootaf9d6672010-10-08 09:21:39 -07002760 final String hashedKey;
2761 if (mKey == null) {
2762 hashedKey = "none";
2763 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002764 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002765 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2766
2767 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2768 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2769 SecretKey key = factory.generateSecret(ks);
2770 BigInteger bi = new BigInteger(key.getEncoded());
2771 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002772 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002773 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2774 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2775 return;
2776 } catch (InvalidKeySpecException e) {
2777 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2778 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002779 return;
2780 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002781 }
Kenny Root38cf8862010-09-26 14:18:51 -07002782
Kenny Rootaf9d6672010-10-08 09:21:39 -07002783 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002784 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002785 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2786 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002787 } catch (NativeDaemonConnectorException e) {
2788 int code = e.getCode();
2789 if (code != VoldResponseCode.OpFailedStorageBusy) {
2790 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002791 }
2792 }
2793
Kenny Rootaf9d6672010-10-08 09:21:39 -07002794 if (rc == StorageResultCode.OperationSucceeded) {
2795 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002796 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002797
2798 synchronized (mObbMounts) {
2799 addObbStateLocked(mObbState);
2800 }
2801
2802 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002803 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002804 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002805
Kenny Rootaf9d6672010-10-08 09:21:39 -07002806 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002807 }
2808 }
2809
Jason parks5af0b912010-11-29 09:05:25 -06002810 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002811 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002812 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002813 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002814
2815 @Override
2816 public String toString() {
2817 StringBuilder sb = new StringBuilder();
2818 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002819 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002820 sb.append('}');
2821 return sb.toString();
2822 }
2823 }
2824
2825 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002826 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002827
2828 UnmountObbAction(ObbState obbState, boolean force) {
2829 super(obbState);
2830 mForceUnmount = force;
2831 }
2832
Jason parks5af0b912010-11-29 09:05:25 -06002833 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002834 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002835 waitForReady();
2836 warnOnNotMounted();
2837
Kenny Root38cf8862010-09-26 14:18:51 -07002838 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002839
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002840 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002841 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002842 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002843 }
Kenny Root38cf8862010-09-26 14:18:51 -07002844
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002845 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002846 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2847 return;
2848 }
2849
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002850 if (existingState.ownerGid != mObbState.ownerGid) {
2851 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2852 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002853 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2854 return;
2855 }
2856
Kenny Rootaf9d6672010-10-08 09:21:39 -07002857 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002858 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002859 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002860 if (mForceUnmount) {
2861 cmd.appendArg("force");
2862 }
2863 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002864 } catch (NativeDaemonConnectorException e) {
2865 int code = e.getCode();
2866 if (code == VoldResponseCode.OpFailedStorageBusy) {
2867 rc = StorageResultCode.OperationFailedStorageBusy;
2868 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2869 // If it's not mounted then we've already won.
2870 rc = StorageResultCode.OperationSucceeded;
2871 } else {
2872 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002873 }
2874 }
2875
Kenny Rootaf9d6672010-10-08 09:21:39 -07002876 if (rc == StorageResultCode.OperationSucceeded) {
2877 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002878 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002879 }
2880
Kenny Rootaf9d6672010-10-08 09:21:39 -07002881 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002882 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002883 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002884 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002885 }
2886 }
2887
Jason parks5af0b912010-11-29 09:05:25 -06002888 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002889 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002890 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002891 }
2892
2893 @Override
2894 public String toString() {
2895 StringBuilder sb = new StringBuilder();
2896 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002897 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002898 sb.append(",force=");
2899 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002900 sb.append('}');
2901 return sb.toString();
2902 }
Kenny Root02c87302010-07-01 08:10:18 -07002903 }
Kenny Root38cf8862010-09-26 14:18:51 -07002904
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002905 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002906 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2907 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002908 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002909
2910 // Only adjust paths when storage is emulated
2911 if (!Environment.isExternalStorageEmulated()) {
2912 return canonicalPath;
2913 }
2914
2915 String path = canonicalPath.toString();
2916
2917 // First trim off any external storage prefix
2918 final UserEnvironment userEnv = new UserEnvironment(userId);
2919
2920 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002921 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002922 // /storage/emulated_legacy
2923 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002924 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002925
2926 if (path.startsWith(externalPath)) {
2927 path = path.substring(externalPath.length() + 1);
2928 } else if (path.startsWith(legacyExternalPath)) {
2929 path = path.substring(legacyExternalPath.length() + 1);
2930 } else {
2931 return canonicalPath;
2932 }
2933
2934 // Handle special OBB paths on emulated storage
2935 final String obbPath = "Android/obb";
2936 if (path.startsWith(obbPath)) {
2937 path = path.substring(obbPath.length() + 1);
2938
2939 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002940 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002941 } else {
2942 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002943 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2944 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002945 }
2946 }
2947
2948 // Handle normal external storage paths
2949 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002950 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002951 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002952 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002953 }
2954 }
2955
Kenny Root38cf8862010-09-26 14:18:51 -07002956 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002957 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2958 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2959
2960 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07002961
Kenny Root38cf8862010-09-26 14:18:51 -07002962 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002963 pw.println("mObbMounts:");
2964 pw.increaseIndent();
2965 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
2966 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002967 while (binders.hasNext()) {
2968 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002969 pw.println(e.getKey() + ":");
2970 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002971 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002972 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002973 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002974 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002975 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002976 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002977 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002978
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002979 pw.println();
2980 pw.println("mObbPathToStateMap:");
2981 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002982 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2983 while (maps.hasNext()) {
2984 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002985 pw.print(e.getKey());
2986 pw.print(" -> ");
2987 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07002988 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002989 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002990 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002991
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002992 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002993 pw.println();
2994 pw.println("mVolumes:");
2995 pw.increaseIndent();
2996 for (StorageVolume volume : mVolumes) {
2997 pw.println(volume);
2998 pw.increaseIndent();
2999 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
3000 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07003001 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003002 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07003003 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08003004
3005 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003006 pw.println("mConnection:");
3007 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003008 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003009 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003012 /** {@inheritDoc} */
3013 public void monitor() {
3014 if (mConnector != null) {
3015 mConnector.monitor();
3016 }
3017 }
3018}