blob: 6c981c00504f9e0acf6f27f09be6fd29b85df274 [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;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070022import android.app.ActivityManagerNative;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070023import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070025import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070029import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.pm.PackageManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070031import android.content.pm.UserInfo;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070032import android.content.res.Configuration;
Kenny Root02c87302010-07-01 08:10:18 -070033import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070034import android.content.res.Resources;
35import android.content.res.TypedArray;
36import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070037import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070039import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070040import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070041import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080042import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070043import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070044import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040045import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080046import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080047import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080048import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070049import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070051import android.os.UserHandle;
Emily Bernier92aa5a22014-07-07 10:11:48 -040052import android.os.UserManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070053import android.os.storage.IMountService;
54import android.os.storage.IMountServiceListener;
55import android.os.storage.IMountShutdownObserver;
56import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070057import android.os.storage.OnObbStateChangeListener;
Paul Lawrence46791e72014-04-03 09:10:26 -070058import android.os.storage.StorageManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070059import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060061import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070062import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070063import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070064import android.util.Xml;
65
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080066import com.android.internal.annotations.GuardedBy;
67import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070068import com.android.internal.app.IMediaContainerService;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070069import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070070import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070071import com.android.internal.util.XmlUtils;
72import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070073import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070074import com.android.server.am.ActivityManagerService;
75import com.android.server.pm.PackageManagerService;
76import com.android.server.pm.UserManagerService;
77import com.google.android.collect.Lists;
78import com.google.android.collect.Maps;
79
Paul Lawrence8e397362014-01-27 15:22:30 -080080import org.apache.commons.codec.binary.Hex;
Paul Lawrence945490c2014-03-27 16:37:28 +000081import org.apache.commons.codec.DecoderException;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070082import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070083
Jeff Sharkeyb049e212012-09-07 23:16:01 -070084import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070085import java.io.FileDescriptor;
Christopher Tate7265abe2014-11-21 13:54:45 -080086import java.io.FileOutputStream;
Kenny Root05105f72010-09-22 17:29:43 -070087import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070088import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070089import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -080090import java.nio.charset.StandardCharsets;
Kenny Root735de3b2010-09-30 14:11:39 -070091import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070092import java.security.spec.InvalidKeySpecException;
93import java.security.spec.KeySpec;
Christopher Tate7265abe2014-11-21 13:54:45 -080094import java.text.SimpleDateFormat;
San Mehat22dd86e2010-01-12 12:21:18 -080095import java.util.ArrayList;
Christopher Tate7265abe2014-11-21 13:54:45 -080096import java.util.Date;
Kenny Roota02b8b02010-08-05 16:14:17 -070097import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080098import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070099import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -0700100import java.util.LinkedList;
101import java.util.List;
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700102import java.util.Locale;
Kenny Roota02b8b02010-08-05 16:14:17 -0700103import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -0700104import java.util.Map.Entry;
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100105import java.util.concurrent.atomic.AtomicInteger;
Kenny Root51a573c2012-05-17 13:30:28 -0700106import java.util.concurrent.CountDownLatch;
107import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Kenny Root3b1abba2010-10-13 15:00:07 -0700109import javax.crypto.SecretKey;
110import javax.crypto.SecretKeyFactory;
111import javax.crypto.spec.PBEKeySpec;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113/**
San Mehatb1043402010-02-05 08:26:50 -0800114 * MountService implements back-end services for platform storage
115 * management.
116 * @hide - Applications should use android.os.storage.StorageManager
117 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700119class MountService extends IMountService.Stub
120 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600121
Christopher Tated417d622013-08-19 16:14:25 -0700122 // Static direct instance pointer for the tightly-coupled idle service to use
123 static MountService sSelf = null;
124
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700125 // TODO: listen for user creation/deletion
126
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800127 private static final boolean LOCAL_LOGD = false;
128 private static final boolean DEBUG_UNMOUNT = false;
129 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800130 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700131
Kenny Root07714d42011-08-17 17:49:28 -0700132 // Disable this since it messes up long-running cryptfs operations.
133 private static final boolean WATCHDOG_ENABLE = false;
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private static final String TAG = "MountService";
136
Kenny Root305bcbf2010-09-03 07:56:38 -0700137 private static final String VOLD_TAG = "VoldConnector";
138
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700139 /** Maximum number of ASEC containers allowed to be mounted. */
140 private static final int MAX_CONTAINERS = 250;
141
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * Internal vold volume state constants
144 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800145 class VolumeState {
146 public static final int Init = -1;
147 public static final int NoMedia = 0;
148 public static final int Idle = 1;
149 public static final int Pending = 2;
150 public static final int Checking = 3;
151 public static final int Mounted = 4;
152 public static final int Unmounting = 5;
153 public static final int Formatting = 6;
154 public static final int Shared = 7;
155 public static final int SharedMnt = 8;
156 }
157
San Mehat4270e1e2010-01-29 05:32:19 -0800158 /*
159 * Internal vold response code constants
160 */
San Mehat22dd86e2010-01-12 12:21:18 -0800161 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800162 /*
163 * 100 series - Requestion action was initiated; expect another reply
164 * before proceeding with a new command.
165 */
San Mehat22dd86e2010-01-12 12:21:18 -0800166 public static final int VolumeListResult = 110;
167 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800168 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700169 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800170
San Mehat4270e1e2010-01-29 05:32:19 -0800171 /*
172 * 200 series - Requestion action has been successfully completed.
173 */
174 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800176 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800177
San Mehat4270e1e2010-01-29 05:32:19 -0800178 /*
179 * 400 series - Command was accepted, but the requested action
180 * did not take place.
181 */
182 public static final int OpFailedNoMedia = 401;
183 public static final int OpFailedMediaBlank = 402;
184 public static final int OpFailedMediaCorrupt = 403;
185 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800186 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700187 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800188
189 /*
190 * 600 series - Unsolicited broadcasts.
191 */
San Mehat22dd86e2010-01-12 12:21:18 -0800192 public static final int VolumeStateChange = 605;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700193 public static final int VolumeUuidChange = 613;
194 public static final int VolumeUserLabelChange = 614;
San Mehat22dd86e2010-01-12 12:21:18 -0800195 public static final int VolumeDiskInserted = 630;
196 public static final int VolumeDiskRemoved = 631;
197 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700198
199 /*
200 * 700 series - fstrim
201 */
202 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800203 }
204
Paul Lawrence8e397362014-01-27 15:22:30 -0800205 /** List of crypto types.
206 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
207 * corresponding commands in CommandListener.cpp */
208 public static final String[] CRYPTO_TYPES
209 = { "password", "default", "pattern", "pin" };
210
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700211 private final Context mContext;
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700212 private final NativeDaemonConnector mConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700213
214 private final Object mVolumesLock = new Object();
215
216 /** When defined, base template for user-specific {@link StorageVolume}. */
217 private StorageVolume mEmulatedTemplate;
218
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700219 // TODO: separate storage volumes on per-user basis
220
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800221 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700222 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
223 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800224 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700225 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
226 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800227 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700228 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
229
230 private volatile boolean mSystemReady = false;
231
San Mehat4270e1e2010-01-29 05:32:19 -0800232 private PackageManagerService mPms;
233 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700234 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800235 // Used as a lock for methods that register/unregister listeners.
236 final private ArrayList<MountServiceBinderListener> mListeners =
237 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800238 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
239 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800240 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800241
San Mehat6cdd9c02010-02-09 14:45:20 -0800242 /**
243 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800244 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800245 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800246 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800247
Kenny Root02c87302010-07-01 08:10:18 -0700248 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700249 * The size of the crypto algorithm key in bits for OBB files. Currently
250 * Twofish is used which takes 128-bit keys.
251 */
252 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
253
254 /**
255 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
256 * 1024 is reasonably secure and not too slow.
257 */
258 private static final int PBKDF2_HASH_ROUNDS = 1024;
259
260 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700261 * Mounted OBB tracking information. Used to track the current state of all
262 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700263 */
Kenny Root735de3b2010-09-30 14:11:39 -0700264 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700265
266 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700267 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
268
269 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700270 public ObbState(String rawPath, String canonicalPath, int callingUid,
271 IObbActionListener token, int nonce) {
272 this.rawPath = rawPath;
273 this.canonicalPath = canonicalPath.toString();
274
275 final int userId = UserHandle.getUserId(callingUid);
276 this.ownerPath = buildObbPath(canonicalPath, userId, false);
277 this.voldPath = buildObbPath(canonicalPath, userId, true);
278
279 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700280 this.token = token;
281 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700282 }
283
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700284 final String rawPath;
285 final String canonicalPath;
286 final String ownerPath;
287 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700288
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700289 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700290
Kenny Rootaf9d6672010-10-08 09:21:39 -0700291 // Token of remote Binder caller
292 final IObbActionListener token;
293
294 // Identifier to pass back to the token
295 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700296
Kenny Root735de3b2010-09-30 14:11:39 -0700297 public IBinder getBinder() {
298 return token.asBinder();
299 }
300
Kenny Roota02b8b02010-08-05 16:14:17 -0700301 @Override
302 public void binderDied() {
303 ObbAction action = new UnmountObbAction(this, true);
304 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700305 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700306
Kenny Root5919ac62010-10-05 09:49:40 -0700307 public void link() throws RemoteException {
308 getBinder().linkToDeath(this, 0);
309 }
310
311 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700312 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700313 }
Kenny Root38cf8862010-09-26 14:18:51 -0700314
315 @Override
316 public String toString() {
317 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700318 sb.append("rawPath=").append(rawPath);
319 sb.append(",canonicalPath=").append(canonicalPath);
320 sb.append(",ownerPath=").append(ownerPath);
321 sb.append(",voldPath=").append(voldPath);
322 sb.append(",ownerGid=").append(ownerGid);
323 sb.append(",token=").append(token);
324 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700325 sb.append('}');
326 return sb.toString();
327 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700328 }
329
330 // OBB Action Handler
331 final private ObbActionHandler mObbActionHandler;
332
333 // OBB action handler messages
334 private static final int OBB_RUN_ACTION = 1;
335 private static final int OBB_MCS_BOUND = 2;
336 private static final int OBB_MCS_UNBIND = 3;
337 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700338 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700339
340 /*
341 * Default Container Service information
342 */
343 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
344 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
345
346 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
347
348 class DefaultContainerConnection implements ServiceConnection {
349 public void onServiceConnected(ComponentName name, IBinder service) {
350 if (DEBUG_OBB)
351 Slog.i(TAG, "onServiceConnected");
352 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
353 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
354 }
355
356 public void onServiceDisconnected(ComponentName name) {
357 if (DEBUG_OBB)
358 Slog.i(TAG, "onServiceDisconnected");
359 }
360 };
361
362 // Used in the ObbActionHandler
363 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700364
Christopher Tate7265abe2014-11-21 13:54:45 -0800365 // Last fstrim operation tracking
366 private static final String LAST_FSTRIM_FILE = "last-fstrim";
367 private final File mLastMaintenanceFile;
368 private long mLastMaintenance;
369
Kenny Root02c87302010-07-01 08:10:18 -0700370 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800371 private static final int H_UNMOUNT_PM_UPDATE = 1;
372 private static final int H_UNMOUNT_PM_DONE = 2;
373 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700374 private static final int H_SYSTEM_READY = 4;
Christopher Tated417d622013-08-19 16:14:25 -0700375 private static final int H_FSTRIM = 5;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700376
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800377 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
378 private static final int MAX_UNMOUNT_RETRIES = 4;
379
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800380 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700381 final String path;
382 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700383 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800385
Ben Komalo13c71972011-09-07 16:35:56 -0700386 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800387 retries = 0;
388 this.path = path;
389 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700390 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800391 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800392
393 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700394 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700395 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800396 }
397 }
398
399 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700400 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800401
402 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700403 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800404 this.method = method;
405 }
406
407 @Override
408 void handleFinished() {
409 super.handleFinished();
410 doShareUnshareVolume(path, method, true);
411 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 }
413
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800414 class ShutdownCallBack extends UnmountCallBack {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100415 MountShutdownLatch mMountShutdownLatch;
416 ShutdownCallBack(String path, final MountShutdownLatch mountShutdownLatch) {
Ben Komalo13c71972011-09-07 16:35:56 -0700417 super(path, true, false);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100418 mMountShutdownLatch = mountShutdownLatch;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 }
420
421 @Override
422 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700423 int ret = doUnmountVolume(path, true, removeEncryption);
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100424 Slog.i(TAG, "Unmount completed: " + path + ", result code: " + ret);
425 mMountShutdownLatch.countDown();
426 }
427 }
428
429 static class MountShutdownLatch {
430 private IMountShutdownObserver mObserver;
431 private AtomicInteger mCount;
432
433 MountShutdownLatch(final IMountShutdownObserver observer, int count) {
434 mObserver = observer;
435 mCount = new AtomicInteger(count);
436 }
437
438 void countDown() {
439 boolean sendShutdown = false;
440 if (mCount.decrementAndGet() == 0) {
441 sendShutdown = true;
442 }
443 if (sendShutdown && mObserver != null) {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800444 try {
Rickard Helldin5fb5df02014-02-07 09:35:04 +0100445 mObserver.onShutDownComplete(StorageResultCode.OperationSucceeded);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800446 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700447 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800448 }
449 }
450 }
451 }
452
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400453 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800454 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700455 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800456
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400457 MountServiceHandler(Looper l) {
458 super(l);
459 }
460
Jason parks5af0b912010-11-29 09:05:25 -0600461 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800462 public void handleMessage(Message msg) {
463 switch (msg.what) {
464 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700465 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800466 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
467 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700468 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800469 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700470 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700471 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700472 mUpdatingStatus = true;
473 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800474 }
475 break;
476 }
477 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700478 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700479 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700480 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800481 int size = mForceUnmounts.size();
482 int sizeArr[] = new int[size];
483 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700484 // Kill processes holding references first
485 ActivityManagerService ams = (ActivityManagerService)
486 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800487 for (int i = 0; i < size; i++) {
488 UnmountCallBack ucb = mForceUnmounts.get(i);
489 String path = ucb.path;
490 boolean done = false;
491 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800492 done = true;
493 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800494 int pids[] = getStorageUsers(path);
495 if (pids == null || pids.length == 0) {
496 done = true;
497 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800498 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800499 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700500 // Confirm if file references have been freed.
501 pids = getStorageUsers(path);
502 if (pids == null || pids.length == 0) {
503 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800504 }
505 }
506 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700507 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
508 // Retry again
509 Slog.i(TAG, "Retrying to kill storage users again");
510 mHandler.sendMessageDelayed(
511 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
512 ucb.retries++),
513 RETRY_UNMOUNT_DELAY);
514 } else {
515 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
516 Slog.i(TAG, "Failed to unmount media inspite of " +
517 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
518 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800519 sizeArr[sizeArrN++] = i;
520 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
521 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800522 }
523 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800524 // Remove already processed elements from list.
525 for (int i = (sizeArrN-1); i >= 0; i--) {
526 mForceUnmounts.remove(sizeArr[i]);
527 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800528 break;
529 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700530 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700531 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800532 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800533 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800534 break;
535 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700536 case H_SYSTEM_READY: {
537 try {
538 handleSystemReady();
539 } catch (Exception ex) {
540 Slog.e(TAG, "Boot-time mount exception", ex);
541 }
542 break;
543 }
Christopher Tated417d622013-08-19 16:14:25 -0700544 case H_FSTRIM: {
545 waitForReady();
546 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800547
548 // Remember when we kicked it off
549 try {
550 mLastMaintenance = System.currentTimeMillis();
551 mLastMaintenanceFile.setLastModified(mLastMaintenance);
552 } catch (Exception e) {
553 Slog.e(TAG, "Unable to record last fstrim!");
554 }
555
Christopher Tated417d622013-08-19 16:14:25 -0700556 try {
557 // This method must be run on the main (handler) thread,
558 // so it is safe to directly call into vold.
559 mConnector.execute("fstrim", "dotrim");
560 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
561 } catch (NativeDaemonConnectorException ndce) {
562 Slog.e(TAG, "Failed to run fstrim!");
563 }
Christopher Tate7265abe2014-11-21 13:54:45 -0800564
Christopher Tated417d622013-08-19 16:14:25 -0700565 // invoke the completion callback, if any
566 Runnable callback = (Runnable) msg.obj;
567 if (callback != null) {
568 callback.run();
569 }
570 break;
571 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800572 }
573 }
574 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700575
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700576 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800577
Kenny Root51a573c2012-05-17 13:30:28 -0700578 void waitForAsecScan() {
579 waitForLatch(mAsecsScanned);
580 }
581
San Mehat207e5382010-02-04 20:46:54 -0800582 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700583 waitForLatch(mConnectedSignal);
584 }
585
586 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700587 for (;;) {
588 try {
589 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800590 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700591 } else {
592 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
593 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800594 }
Kenny Root51a573c2012-05-17 13:30:28 -0700595 } catch (InterruptedException e) {
596 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800597 }
San Mehat207e5382010-02-04 20:46:54 -0800598 }
San Mehat1f6301e2010-01-07 22:40:27 -0800599 }
Kenny Root02c87302010-07-01 08:10:18 -0700600
Paul Lawrence945490c2014-03-27 16:37:28 +0000601 private boolean isReady() {
602 try {
603 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
604 } catch (InterruptedException e) {
605 return false;
606 }
607 }
608
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700609 private void handleSystemReady() {
610 // Snapshot current volume states since it's not safe to call into vold
611 // while holding locks.
612 final HashMap<String, String> snapshot;
613 synchronized (mVolumesLock) {
614 snapshot = new HashMap<String, String>(mVolumeStates);
615 }
616
617 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
618 final String path = entry.getKey();
619 final String state = entry.getValue();
620
621 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
622 int rc = doMountVolume(path);
623 if (rc != StorageResultCode.OperationSucceeded) {
624 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
625 rc));
626 }
627 } else if (state.equals(Environment.MEDIA_SHARED)) {
628 /*
629 * Bootstrap UMS enabled state since vold indicates
630 * the volume is shared (runtime restart while ums enabled)
631 */
632 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
633 VolumeState.Shared);
634 }
635 }
636
637 // Push mounted state for all emulated storage
638 synchronized (mVolumesLock) {
639 for (StorageVolume volume : mVolumes) {
640 if (volume.isEmulated()) {
641 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
642 }
643 }
644 }
645
646 /*
647 * If UMS was connected on boot, send the connected event
648 * now that we're up.
649 */
650 if (mSendUmsConnectedOnBoot) {
651 sendUmsIntent(true);
652 mSendUmsConnectedOnBoot = false;
653 }
Christopher Tate115afda2014-06-06 19:06:26 -0700654
655 /*
656 * Start scheduling nominally-daily fstrim operations
657 */
658 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700659 }
660
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700661 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
662 @Override
663 public void onReceive(Context context, Intent intent) {
664 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
665 if (userId == -1) return;
666 final UserHandle user = new UserHandle(userId);
667
668 final String action = intent.getAction();
669 if (Intent.ACTION_USER_ADDED.equals(action)) {
670 synchronized (mVolumesLock) {
671 createEmulatedVolumeForUserLocked(user);
672 }
673
674 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
675 synchronized (mVolumesLock) {
676 final List<StorageVolume> toRemove = Lists.newArrayList();
677 for (StorageVolume volume : mVolumes) {
678 if (user.equals(volume.getOwner())) {
679 toRemove.add(volume);
680 }
681 }
682 for (StorageVolume volume : toRemove) {
683 removeVolumeLocked(volume);
684 }
685 }
686 }
687 }
688 };
689
690 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
691 @Override
692 public void onReceive(Context context, Intent intent) {
693 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
694 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
695 notifyShareAvailabilityChange(available);
696 }
697 };
698
San Mehat4270e1e2010-01-29 05:32:19 -0800699 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
700 final IMountServiceListener mListener;
701
702 MountServiceBinderListener(IMountServiceListener listener) {
703 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700704
San Mehat91c77612010-01-07 10:39:41 -0800705 }
706
San Mehat4270e1e2010-01-29 05:32:19 -0800707 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700708 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700709 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800710 mListeners.remove(this);
711 mListener.asBinder().unlinkToDeath(this, 0);
712 }
713 }
714 }
715
Christopher Tated417d622013-08-19 16:14:25 -0700716 void runIdleMaintenance(Runnable callback) {
717 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
718 }
719
Christopher Tate7265abe2014-11-21 13:54:45 -0800720 // Binder entry point for kicking off an immediate fstrim
721 @Override
722 public void runMaintenance() {
723 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
724 runIdleMaintenance(null);
725 }
726
727 @Override
728 public long lastMaintenance() {
729 return mLastMaintenance;
730 }
731
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800732 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800733 // TODO: Add support for multiple share methods
734 if (!method.equals("ums")) {
735 throw new IllegalArgumentException(String.format("Method %s not supported", method));
736 }
737
San Mehat4270e1e2010-01-29 05:32:19 -0800738 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800739 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800740 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700741 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800742 }
San Mehat4270e1e2010-01-29 05:32:19 -0800743 }
744
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700745 private void updatePublicVolumeState(StorageVolume volume, String state) {
746 final String path = volume.getPath();
747 final String oldState;
748 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400749 oldState = mVolumeStates.put(path, state);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700750 volume.setState(state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400751 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700752
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400753 if (state.equals(oldState)) {
754 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
755 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800756 return;
757 }
San Mehatb1043402010-02-05 08:26:50 -0800758
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400759 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700760
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700761 // Tell PackageManager about changes to primary volume state, but only
762 // when not emulated.
763 if (volume.isPrimary() && !volume.isEmulated()) {
764 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
765 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400766
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700767 /*
768 * Some OBBs might have been unmounted when this volume was
769 * unmounted, so send a message to the handler to let it know to
770 * remove those from the list of mounted OBBS.
771 */
772 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
773 OBB_FLUSH_MOUNT_STATE, path));
774 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
775 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400776 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800777 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700778
San Mehat4270e1e2010-01-29 05:32:19 -0800779 synchronized (mListeners) {
780 for (int i = mListeners.size() -1; i >= 0; i--) {
781 MountServiceBinderListener bl = mListeners.get(i);
782 try {
San Mehatb1043402010-02-05 08:26:50 -0800783 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800784 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700785 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800786 mListeners.remove(i);
787 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700788 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800789 }
790 }
791 }
792 }
793
794 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800795 * Callback from NativeDaemonConnector
796 */
797 public void onDaemonConnected() {
798 /*
799 * Since we'll be calling back into the NativeDaemonConnector,
800 * we need to do our work in a new thread.
801 */
Kenny Root51a573c2012-05-17 13:30:28 -0700802 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600803 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800804 public void run() {
805 /**
806 * Determine media state and UMS detection status
807 */
San Mehat4270e1e2010-01-29 05:32:19 -0800808 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800809 final String[] vols = NativeDaemonEvent.filterMessageList(
JP Abgrall5f054ce2014-07-24 18:19:12 -0700810 mConnector.executeForList("volume", "list", "broadcast"),
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800811 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800812 for (String volstr : vols) {
813 String[] tok = volstr.split(" ");
814 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400815 String path = tok[1];
816 String state = Environment.MEDIA_REMOVED;
817
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700818 final StorageVolume volume;
819 synchronized (mVolumesLock) {
820 volume = mVolumesByPath.get(path);
821 }
822
San Mehat4270e1e2010-01-29 05:32:19 -0800823 int st = Integer.parseInt(tok[2]);
824 if (st == VolumeState.NoMedia) {
825 state = Environment.MEDIA_REMOVED;
826 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800827 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800828 } else if (st == VolumeState.Mounted) {
829 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800831 } else if (st == VolumeState.Shared) {
832 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700833 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800834 } else {
835 throw new Exception(String.format("Unexpected state %d", st));
836 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400837
838 if (state != null) {
839 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700840 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400841 }
San Mehat4270e1e2010-01-29 05:32:19 -0800842 }
843 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700844 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700845 final StorageVolume primary = getPrimaryPhysicalVolume();
846 if (primary != null) {
847 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
848 }
San Mehat4270e1e2010-01-29 05:32:19 -0800849 }
850
San Mehat207e5382010-02-04 20:46:54 -0800851 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600852 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800853 * the hounds!
854 */
Kenny Root51a573c2012-05-17 13:30:28 -0700855 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700856
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700857 // On an encrypted device we can't see system properties yet, so pull
858 // the system locale out of the mount service.
Paul Lawrencec220d8e2014-10-24 10:37:40 -0700859 if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
860 copyLocaleFromMountService();
861 }
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700862
Kenny Root51a573c2012-05-17 13:30:28 -0700863 // Let package manager load internal ASECs.
864 mPms.scanAvailableAsecs();
865
866 // Notify people waiting for ASECs to be scanned that it's done.
867 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800868 }
869 }.start();
870 }
871
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700872 private void copyLocaleFromMountService() {
873 String systemLocale;
874 try {
875 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
876 } catch (RemoteException e) {
877 return;
878 }
879 if (TextUtils.isEmpty(systemLocale)) {
880 return;
881 }
882
883 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
884 Locale locale = Locale.forLanguageTag(systemLocale);
885 Configuration config = new Configuration();
886 config.setLocale(locale);
887 try {
888 ActivityManagerNative.getDefault().updateConfiguration(config);
889 } catch (RemoteException e) {
890 Slog.e(TAG, "Error setting system locale from mount service", e);
891 }
Elliott Hughes9c33f282014-10-13 12:39:56 -0700892
893 // Temporary workaround for http://b/17945169.
894 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
895 SystemProperties.set("persist.sys.language", locale.getLanguage());
896 SystemProperties.set("persist.sys.country", locale.getCountry());
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700897 }
898
San Mehat4270e1e2010-01-29 05:32:19 -0800899 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800900 * Callback from NativeDaemonConnector
901 */
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800902 public boolean onCheckHoldWakeLock(int code) {
903 return false;
904 }
905
906 /**
907 * Callback from NativeDaemonConnector
908 */
San Mehat4270e1e2010-01-29 05:32:19 -0800909 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800910 if (DEBUG_EVENTS) {
911 StringBuilder builder = new StringBuilder();
912 builder.append("onEvent::");
913 builder.append(" raw= " + raw);
914 if (cooked != null) {
915 builder.append(" cooked = " );
916 for (String str : cooked) {
917 builder.append(" " + str);
918 }
919 }
San Mehata5078592010-03-25 09:36:54 -0700920 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800921 }
San Mehat4270e1e2010-01-29 05:32:19 -0800922 if (code == VoldResponseCode.VolumeStateChange) {
923 /*
924 * One of the volumes we're managing has changed state.
925 * Format: "NNN Volume <label> <path> state changed
926 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
927 */
928 notifyVolumeStateChange(
929 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
930 Integer.parseInt(cooked[10]));
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700931 } else if (code == VoldResponseCode.VolumeUuidChange) {
932 // Format: nnn <label> <path> <uuid>
933 final String path = cooked[2];
934 final String uuid = (cooked.length > 3) ? cooked[3] : null;
935
936 final StorageVolume vol = mVolumesByPath.get(path);
937 if (vol != null) {
938 vol.setUuid(uuid);
939 }
940
941 } else if (code == VoldResponseCode.VolumeUserLabelChange) {
942 // Format: nnn <label> <path> <label>
943 final String path = cooked[2];
944 final String userLabel = (cooked.length > 3) ? cooked[3] : null;
945
946 final StorageVolume vol = mVolumesByPath.get(path);
947 if (vol != null) {
948 vol.setUserLabel(userLabel);
949 }
950
San Mehat4270e1e2010-01-29 05:32:19 -0800951 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
952 (code == VoldResponseCode.VolumeDiskRemoved) ||
953 (code == VoldResponseCode.VolumeBadRemoval)) {
954 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
955 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
956 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400957 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800958 final String label = cooked[2];
959 final String path = cooked[3];
960 int major = -1;
961 int minor = -1;
962
963 try {
964 String devComp = cooked[6].substring(1, cooked[6].length() -1);
965 String[] devTok = devComp.split(":");
966 major = Integer.parseInt(devTok[0]);
967 minor = Integer.parseInt(devTok[1]);
968 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800970 }
971
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700972 final StorageVolume volume;
973 final String state;
974 synchronized (mVolumesLock) {
975 volume = mVolumesByPath.get(path);
976 state = mVolumeStates.get(path);
977 }
978
San Mehat4270e1e2010-01-29 05:32:19 -0800979 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700980 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600981 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800982 public void run() {
983 try {
984 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800985 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700986 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800987 }
988 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700989 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800990 }
991 }
992 }.start();
993 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
994 /*
995 * This event gets trumped if we're already in BAD_REMOVAL state
996 */
997 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
998 return true;
999 }
1000 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -07001001 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001002 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Johan Redestig0464c072014-01-18 22:46:56 +01001003 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001004
San Mehata5078592010-03-25 09:36:54 -07001005 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001006 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001007 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -08001008 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -07001009 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -08001010 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001011 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +02001012 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001013
San Mehata5078592010-03-25 09:36:54 -07001014 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001015 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001016 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -07001017 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -07001018 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -08001019 } else {
San Mehata5078592010-03-25 09:36:54 -07001020 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -08001021 }
Mike Lockwooda5250c92011-05-23 13:44:04 -04001022
1023 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001024 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001025 }
San Mehat4270e1e2010-01-29 05:32:19 -08001026 } else {
1027 return false;
1028 }
1029
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001030 return true;
San Mehat4270e1e2010-01-29 05:32:19 -08001031 }
1032
San Mehat207e5382010-02-04 20:46:54 -08001033 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001034 final StorageVolume volume;
1035 final String state;
1036 synchronized (mVolumesLock) {
1037 volume = mVolumesByPath.get(path);
1038 state = getVolumeState(path);
1039 }
1040
1041 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -08001042
Mike Lockwooda5250c92011-05-23 13:44:04 -04001043 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -08001044
Mike Lockwoodbf2dd442010-03-03 06:16:52 -05001045 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -07001046 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001047 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -05001048 }
1049
San Mehat4270e1e2010-01-29 05:32:19 -08001050 if (newState == VolumeState.Init) {
1051 } else if (newState == VolumeState.NoMedia) {
1052 // NoMedia is handled via Disk Remove events
1053 } else if (newState == VolumeState.Idle) {
1054 /*
1055 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
1056 * if we're in the process of enabling UMS
1057 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001058 if (!state.equals(
1059 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
1060 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001061 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -07001062 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001063 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001064 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -08001065 }
1066 } else if (newState == VolumeState.Pending) {
1067 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -07001068 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001069 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001070 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -08001071 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -07001072 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001073 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001074 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -08001075 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -04001076 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -08001077 } else if (newState == VolumeState.Formatting) {
1078 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -07001079 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -08001080 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001081 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
1082 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001083
San Mehata5078592010-03-25 09:36:54 -07001084 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001085 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001086 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -07001087 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -08001088 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -07001089 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -08001090 return;
1091 } else {
San Mehata5078592010-03-25 09:36:54 -07001092 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -08001093 }
1094
Mike Lockwooda5250c92011-05-23 13:44:04 -04001095 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001096 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -08001097 }
1098 }
1099
San Mehat207e5382010-02-04 20:46:54 -08001100 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -08001101 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001102
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001103 final StorageVolume volume;
1104 synchronized (mVolumesLock) {
1105 volume = mVolumesByPath.get(path);
1106 }
1107
Emily Bernier92aa5a22014-07-07 10:11:48 -04001108 if (!volume.isEmulated() && hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA)) {
1109 Slog.w(TAG, "User has restriction DISALLOW_MOUNT_PHYSICAL_MEDIA; cannot mount volume.");
1110 return StorageResultCode.OperationFailedInternalError;
1111 }
1112
San Mehata5078592010-03-25 09:36:54 -07001113 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -08001114 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001115 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -08001116 } catch (NativeDaemonConnectorException e) {
1117 /*
1118 * Mount failed for some reason
1119 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001120 String action = null;
San Mehat207e5382010-02-04 20:46:54 -08001121 int code = e.getCode();
1122 if (code == VoldResponseCode.OpFailedNoMedia) {
1123 /*
1124 * Attempt to mount but no media inserted
1125 */
San Mehatb1043402010-02-05 08:26:50 -08001126 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001127 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -07001128 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -08001129 /*
1130 * Media is blank or does not contain a supported filesystem
1131 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001132 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001133 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -08001134 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -08001135 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -07001136 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -08001137 /*
1138 * Volume consistency check failed
1139 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001140 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001141 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -08001142 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001143 } else {
San Mehatb1043402010-02-05 08:26:50 -08001144 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001145 }
1146
1147 /*
1148 * Send broadcast intent (if required for the failure)
1149 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001150 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001151 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001152 }
1153 }
1154
1155 return rc;
1156 }
1157
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001158 /*
1159 * If force is not set, we do not unmount if there are
1160 * processes holding references to the volume about to be unmounted.
1161 * If force is set, all the processes holding references need to be
1162 * killed via the ActivityManager before actually unmounting the volume.
1163 * This might even take a while and might be retried after timed delays
1164 * to make sure we dont end up in an instable state and kill some core
1165 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001166 * If removeEncryption is set, force is implied, and the system will remove any encryption
1167 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001168 */
Ben Komalo13c71972011-09-07 16:35:56 -07001169 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001170 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001171 return VoldResponseCode.OpFailedVolNotMounted;
1172 }
Kenny Rootaa485402010-09-14 14:49:41 -07001173
1174 /*
1175 * Force a GC to make sure AssetManagers in other threads of the
1176 * system_server are cleaned up. We have to do this since AssetManager
1177 * instances are kept as a WeakReference and it's possible we have files
1178 * open on the external storage.
1179 */
1180 Runtime.getRuntime().gc();
1181
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001182 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001183 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001184 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001185 final Command cmd = new Command("volume", "unmount", path);
1186 if (removeEncryption) {
1187 cmd.appendArg("force_and_revert");
1188 } else if (force) {
1189 cmd.appendArg("force");
1190 }
1191 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001192 // We unmounted the volume. None of the asec containers are available now.
1193 synchronized (mAsecMountSet) {
1194 mAsecMountSet.clear();
1195 }
San Mehatb1043402010-02-05 08:26:50 -08001196 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001197 } catch (NativeDaemonConnectorException e) {
1198 // Don't worry about mismatch in PackageManager since the
1199 // call back will handle the status changes any way.
1200 int code = e.getCode();
1201 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001202 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001203 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1204 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001205 } else {
San Mehatb1043402010-02-05 08:26:50 -08001206 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001207 }
1208 }
1209 }
1210
1211 private int doFormatVolume(String path) {
1212 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001213 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001214 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001215 } catch (NativeDaemonConnectorException e) {
1216 int code = e.getCode();
1217 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001218 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001219 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001220 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001221 } else {
San Mehatb1043402010-02-05 08:26:50 -08001222 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001223 }
1224 }
1225 }
1226
San Mehatb1043402010-02-05 08:26:50 -08001227 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001228 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001229 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001230 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001231 } catch (NativeDaemonConnectorException ex) {
1232 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1233 return false;
1234 }
San Mehatb1043402010-02-05 08:26:50 -08001235
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001236 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1237 return event.getMessage().endsWith("enabled");
1238 } else {
1239 return false;
San Mehatb1043402010-02-05 08:26:50 -08001240 }
San Mehatb1043402010-02-05 08:26:50 -08001241 }
1242
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001243 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001244 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001245 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001246 for (int i = mListeners.size() -1; i >= 0; i--) {
1247 MountServiceBinderListener bl = mListeners.get(i);
1248 try {
San Mehatb1043402010-02-05 08:26:50 -08001249 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001250 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001251 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001252 mListeners.remove(i);
1253 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001254 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001255 }
1256 }
1257 }
1258
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001259 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001260 sendUmsIntent(avail);
1261 } else {
1262 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001263 }
San Mehat2fe718a2010-03-11 12:01:49 -08001264
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001265 final StorageVolume primary = getPrimaryPhysicalVolume();
1266 if (avail == false && primary != null
1267 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1268 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001269 /*
1270 * USB mass storage disconnected while enabled
1271 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001272 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001273 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001274 public void run() {
1275 try {
1276 int rc;
San Mehata5078592010-03-25 09:36:54 -07001277 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001278 doShareUnshareVolume(path, "ums", false);
1279 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001280 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001281 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1282 path, rc));
1283 }
1284 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001285 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001286 }
1287 }
1288 }.start();
1289 }
San Mehat4270e1e2010-01-29 05:32:19 -08001290 }
1291
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001292 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1293 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1294 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
Johan Redestig0464c072014-01-18 22:46:56 +01001295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001296 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1297 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001298 }
1299
San Mehat6a965af22010-02-24 17:47:30 -08001300 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001301 mContext.sendBroadcastAsUser(
1302 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1303 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001304 }
1305
San Mehat207e5382010-02-04 20:46:54 -08001306 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001307 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1308 throw new SecurityException(String.format("Requires %s permission", perm));
1309 }
1310 }
1311
Emily Bernier92aa5a22014-07-07 10:11:48 -04001312 private boolean hasUserRestriction(String restriction) {
1313 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1314 return um.hasUserRestriction(restriction, Binder.getCallingUserHandle());
1315 }
1316
1317 private void validateUserRestriction(String restriction) {
1318 if (hasUserRestriction(restriction)) {
1319 throw new SecurityException("User has restriction " + restriction);
1320 }
1321 }
1322
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001323 // Storage list XML tags
1324 private static final String TAG_STORAGE_LIST = "StorageList";
1325 private static final String TAG_STORAGE = "storage";
1326
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001327 private void readStorageListLocked() {
1328 mVolumes.clear();
1329 mVolumeStates.clear();
1330
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001331 Resources resources = mContext.getResources();
1332
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001333 int id = com.android.internal.R.xml.storage_list;
1334 XmlResourceParser parser = resources.getXml(id);
1335 AttributeSet attrs = Xml.asAttributeSet(parser);
1336
1337 try {
1338 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1339 while (true) {
1340 XmlUtils.nextElement(parser);
1341
1342 String element = parser.getName();
1343 if (element == null) break;
1344
1345 if (TAG_STORAGE.equals(element)) {
1346 TypedArray a = resources.obtainAttributes(attrs,
1347 com.android.internal.R.styleable.Storage);
1348
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001349 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001350 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001351 int descriptionId = a.getResourceId(
1352 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001353 CharSequence description = a.getText(
1354 com.android.internal.R.styleable.Storage_storageDescription);
1355 boolean primary = a.getBoolean(
1356 com.android.internal.R.styleable.Storage_primary, false);
1357 boolean removable = a.getBoolean(
1358 com.android.internal.R.styleable.Storage_removable, false);
1359 boolean emulated = a.getBoolean(
1360 com.android.internal.R.styleable.Storage_emulated, false);
1361 int mtpReserve = a.getInt(
1362 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001363 boolean allowMassStorage = a.getBoolean(
1364 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001365 // resource parser does not support longs, so XML value is in megabytes
1366 long maxFileSize = a.getInt(
1367 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001368
1369 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1370 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001371 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001372 " allowMassStorage: " + allowMassStorage +
1373 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001374
1375 if (emulated) {
1376 // For devices with emulated storage, we create separate
1377 // volumes for each known user.
1378 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1379 true, mtpReserve, false, maxFileSize, null);
1380
1381 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001382 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001383 createEmulatedVolumeForUserLocked(user.getUserHandle());
1384 }
1385
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001386 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001387 if (path == null || description == null) {
1388 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001389 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001390 final StorageVolume volume = new StorageVolume(new File(path),
1391 descriptionId, primary, removable, emulated, mtpReserve,
1392 allowMassStorage, maxFileSize, null);
1393 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001394
1395 // Until we hear otherwise, treat as unmounted
1396 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001397 volume.setState(Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001398 }
1399 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001400
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001401 a.recycle();
1402 }
1403 }
1404 } catch (XmlPullParserException e) {
1405 throw new RuntimeException(e);
1406 } catch (IOException e) {
1407 throw new RuntimeException(e);
1408 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001409 // Compute storage ID for each physical volume; emulated storage is
1410 // always 0 when defined.
1411 int index = isExternalStorageEmulated() ? 1 : 0;
1412 for (StorageVolume volume : mVolumes) {
1413 if (!volume.isEmulated()) {
1414 volume.setStorageId(index++);
1415 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001416 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001417 parser.close();
1418 }
1419 }
1420
San Mehat4270e1e2010-01-29 05:32:19 -08001421 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001422 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1423 * using {@link #mEmulatedTemplate} as template.
1424 */
1425 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1426 if (mEmulatedTemplate == null) {
1427 throw new IllegalStateException("Missing emulated volume multi-user template");
1428 }
1429
1430 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1431 final File path = userEnv.getExternalStorageDirectory();
1432 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1433 volume.setStorageId(0);
1434 addVolumeLocked(volume);
1435
1436 if (mSystemReady) {
1437 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1438 } else {
1439 // Place stub status for early callers to find
1440 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001441 volume.setState(Environment.MEDIA_MOUNTED);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001442 }
1443 }
1444
1445 private void addVolumeLocked(StorageVolume volume) {
1446 Slog.d(TAG, "addVolumeLocked() " + volume);
1447 mVolumes.add(volume);
1448 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1449 if (existing != null) {
1450 throw new IllegalStateException(
1451 "Volume at " + volume.getPath() + " already exists: " + existing);
1452 }
1453 }
1454
1455 private void removeVolumeLocked(StorageVolume volume) {
1456 Slog.d(TAG, "removeVolumeLocked() " + volume);
1457 mVolumes.remove(volume);
1458 mVolumesByPath.remove(volume.getPath());
1459 mVolumeStates.remove(volume.getPath());
1460 }
1461
1462 private StorageVolume getPrimaryPhysicalVolume() {
1463 synchronized (mVolumesLock) {
1464 for (StorageVolume volume : mVolumes) {
1465 if (volume.isPrimary() && !volume.isEmulated()) {
1466 return volume;
1467 }
1468 }
1469 }
1470 return null;
1471 }
1472
1473 /**
San Mehat207e5382010-02-04 20:46:54 -08001474 * Constructs a new MountService instance
1475 *
1476 * @param context Binder context for this service
1477 */
1478 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001479 sSelf = this;
1480
San Mehat207e5382010-02-04 20:46:54 -08001481 mContext = context;
1482
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001483 synchronized (mVolumesLock) {
1484 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001485 }
1486
San Mehat207e5382010-02-04 20:46:54 -08001487 // XXX: This will go away soon in favor of IMountServiceObserver
1488 mPms = (PackageManagerService) ServiceManager.getService("package");
1489
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001490 HandlerThread hthread = new HandlerThread(TAG);
1491 hthread.start();
1492 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001493
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001494 // Watch for user changes
1495 final IntentFilter userFilter = new IntentFilter();
1496 userFilter.addAction(Intent.ACTION_USER_ADDED);
1497 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1498 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1499
1500 // Watch for USB changes on primary volume
1501 final StorageVolume primary = getPrimaryPhysicalVolume();
1502 if (primary != null && primary.allowMassStorage()) {
1503 mContext.registerReceiver(
1504 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1505 }
1506
Kenny Roota02b8b02010-08-05 16:14:17 -07001507 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001508 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001509
Christopher Tate7265abe2014-11-21 13:54:45 -08001510 // Initialize the last-fstrim tracking if necessary
1511 File dataDir = Environment.getDataDirectory();
1512 File systemDir = new File(dataDir, "system");
1513 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1514 if (!mLastMaintenanceFile.exists()) {
1515 // Not setting mLastMaintenance here means that we will force an
1516 // fstrim during reboot following the OTA that installs this code.
1517 try {
1518 (new FileOutputStream(mLastMaintenanceFile)).close();
1519 } catch (IOException e) {
1520 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1521 }
1522 } else {
1523 mLastMaintenance = mLastMaintenanceFile.lastModified();
1524 }
1525
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001526 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001527 * Create the connection to vold with a maximum queue of twice the
1528 * amount of containers we'd ever expect to have. This keeps an
1529 * "asec list" from blocking a thread repeatedly.
1530 */
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001531 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1532 null);
Kenny Root51a573c2012-05-17 13:30:28 -07001533
Kenny Root305bcbf2010-09-03 07:56:38 -07001534 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001535 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001536
Kenny Root07714d42011-08-17 17:49:28 -07001537 // Add ourself to the Watchdog monitors if enabled.
1538 if (WATCHDOG_ENABLE) {
1539 Watchdog.getInstance().addMonitor(this);
1540 }
San Mehat207e5382010-02-04 20:46:54 -08001541 }
1542
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001543 public void systemReady() {
1544 mSystemReady = true;
1545 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1546 }
1547
San Mehat207e5382010-02-04 20:46:54 -08001548 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001549 * Exposed API calls below here
1550 */
1551
1552 public void registerListener(IMountServiceListener listener) {
1553 synchronized (mListeners) {
1554 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1555 try {
1556 listener.asBinder().linkToDeath(bl, 0);
1557 mListeners.add(bl);
1558 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001559 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001560 }
1561 }
1562 }
1563
1564 public void unregisterListener(IMountServiceListener listener) {
1565 synchronized (mListeners) {
1566 for(MountServiceBinderListener bl : mListeners) {
Niklas Brunlidd64fe0f2013-07-05 08:54:03 +02001567 if (bl.mListener.asBinder() == listener.asBinder()) {
San Mehat4270e1e2010-01-29 05:32:19 -08001568 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001569 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001570 return;
1571 }
1572 }
1573 }
1574 }
1575
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001576 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001577 validatePermission(android.Manifest.permission.SHUTDOWN);
1578
San Mehata5078592010-03-25 09:36:54 -07001579 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001580 synchronized (mVolumesLock) {
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001581 // Get all volumes to be unmounted.
1582 MountShutdownLatch mountShutdownLatch = new MountShutdownLatch(observer,
1583 mVolumeStates.size());
1584
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001585 for (String path : mVolumeStates.keySet()) {
1586 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001587
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001588 if (state.equals(Environment.MEDIA_SHARED)) {
1589 /*
1590 * If the media is currently shared, unshare it.
1591 * XXX: This is still dangerous!. We should not
1592 * be rebooting at *all* if UMS is enabled, since
1593 * the UMS host could have dirty FAT cache entries
1594 * yet to flush.
1595 */
1596 setUsbMassStorageEnabled(false);
1597 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1598 /*
1599 * If the media is being checked, then we need to wait for
1600 * it to complete before being able to proceed.
1601 */
1602 // XXX: @hackbod - Should we disable the ANR timer here?
1603 int retries = 30;
1604 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1605 try {
1606 Thread.sleep(1000);
1607 } catch (InterruptedException iex) {
1608 Slog.e(TAG, "Interrupted while waiting for media", iex);
1609 break;
1610 }
1611 state = Environment.getExternalStorageState();
1612 }
1613 if (retries == 0) {
1614 Slog.e(TAG, "Timed out waiting for media to check");
1615 }
San Mehat91c77612010-01-07 10:39:41 -08001616 }
San Mehat91c77612010-01-07 10:39:41 -08001617
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001618 if (state.equals(Environment.MEDIA_MOUNTED)) {
1619 // Post a unmount message.
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001620 ShutdownCallBack ucb = new ShutdownCallBack(path, mountShutdownLatch);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001621 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1622 } else if (observer != null) {
1623 /*
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001624 * Count down, since nothing will be done. The observer will be
1625 * notified when we are done so shutdown sequence can continue.
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001626 */
Rickard Helldin5fb5df02014-02-07 09:35:04 +01001627 mountShutdownLatch.countDown();
1628 Slog.i(TAG, "Unmount completed: " + path +
1629 ", result code: " + StorageResultCode.OperationSucceeded);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001630 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001631 }
San Mehat4270e1e2010-01-29 05:32:19 -08001632 }
1633 }
1634
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001635 private boolean getUmsEnabling() {
1636 synchronized (mListeners) {
1637 return mUmsEnabling;
1638 }
1639 }
1640
1641 private void setUmsEnabling(boolean enable) {
1642 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001643 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001644 }
1645 }
1646
San Mehatb1043402010-02-05 08:26:50 -08001647 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001648 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001649
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001650 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001651 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001652 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001653 synchronized (mListeners) {
1654 return mUmsAvailable;
1655 }
San Mehatb1043402010-02-05 08:26:50 -08001656 }
1657
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001658 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001659 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001660 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001661 validateUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER);
San Mehatb1043402010-02-05 08:26:50 -08001662
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001663 final StorageVolume primary = getPrimaryPhysicalVolume();
1664 if (primary == null) return;
1665
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001666 // TODO: Add support for multiple share methods
1667
1668 /*
1669 * If the volume is mounted and we're enabling then unmount it
1670 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001671 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001672 String vs = getVolumeState(path);
1673 String method = "ums";
1674 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1675 // Override for isUsbMassStorageEnabled()
1676 setUmsEnabling(enable);
1677 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1678 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1679 // Clear override
1680 setUmsEnabling(false);
1681 }
1682 /*
1683 * If we disabled UMS then mount the volume
1684 */
1685 if (!enable) {
1686 doShareUnshareVolume(path, method, enable);
1687 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001688 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001689 " after disabling share method " + method);
1690 /*
1691 * Even though the mount failed, the unshare didn't so don't indicate an error.
1692 * The mountVolume() call will have set the storage state and sent the necessary
1693 * broadcasts.
1694 */
1695 }
1696 }
San Mehatb1043402010-02-05 08:26:50 -08001697 }
1698
1699 public boolean isUsbMassStorageEnabled() {
1700 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001701
1702 final StorageVolume primary = getPrimaryPhysicalVolume();
1703 if (primary != null) {
1704 return doGetVolumeShared(primary.getPath(), "ums");
1705 } else {
1706 return false;
1707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001709
San Mehat7fd0fee2009-12-17 07:12:23 -08001710 /**
1711 * @return state of the volume at the specified mount point
1712 */
San Mehat4270e1e2010-01-29 05:32:19 -08001713 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001714 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001715 String state = mVolumeStates.get(mountPoint);
1716 if (state == null) {
1717 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001718 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1719 state = Environment.MEDIA_REMOVED;
1720 } else {
1721 throw new IllegalArgumentException();
1722 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001723 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001724
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001725 return state;
1726 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001727 }
1728
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001729 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001730 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001731 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001732 }
1733
San Mehat4270e1e2010-01-29 05:32:19 -08001734 public int mountVolume(String path) {
1735 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001736 waitForReady();
1737 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
1739
Ben Komalo13c71972011-09-07 16:35:56 -07001740 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001741 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001742 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001744 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001745 if (DEBUG_UNMOUNT) {
1746 Slog.i(TAG, "Unmounting " + path
1747 + " force = " + force
1748 + " removeEncryption = " + removeEncryption);
1749 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001750 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1751 Environment.MEDIA_REMOVED.equals(volState) ||
1752 Environment.MEDIA_SHARED.equals(volState) ||
1753 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1754 // Media already unmounted or cannot be unmounted.
1755 // TODO return valid return code when adding observer call back.
1756 return;
1757 }
Ben Komalo13c71972011-09-07 16:35:56 -07001758 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001759 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761
San Mehat4270e1e2010-01-29 05:32:19 -08001762 public int formatVolume(String path) {
1763 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001764 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001765
San Mehat207e5382010-02-04 20:46:54 -08001766 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001769 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001770 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1771 waitForReady();
1772 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001773 final String[] r = NativeDaemonEvent.filterMessageList(
1774 mConnector.executeForList("storage", "users", path),
1775 VoldResponseCode.StorageUsersListResult);
1776
San Mehatc1b4ce92010-02-16 17:13:03 -08001777 // FMT: <pid> <process name>
1778 int[] data = new int[r.length];
1779 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001780 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001781 try {
1782 data[i] = Integer.parseInt(tok[0]);
1783 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001784 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001785 return new int[0];
1786 }
1787 }
1788 return data;
1789 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001790 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001791 return new int[0];
1792 }
1793 }
1794
San Mehatb1043402010-02-05 08:26:50 -08001795 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001796 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001797 if (primary != null) {
1798 boolean mounted = false;
1799 try {
1800 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001801 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001802 }
1803
1804 if (!mounted) {
1805 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1806 }
San Mehatb1043402010-02-05 08:26:50 -08001807 }
1808 }
1809
San Mehat4270e1e2010-01-29 05:32:19 -08001810 public String[] getSecureContainerList() {
1811 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001812 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001813 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001814
San Mehat4270e1e2010-01-29 05:32:19 -08001815 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001816 return NativeDaemonEvent.filterMessageList(
1817 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001818 } catch (NativeDaemonConnectorException e) {
1819 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821 }
San Mehat36972292010-01-06 11:06:32 -08001822
Kenny Root6dceb882012-04-12 14:23:49 -07001823 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1824 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001825 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001826 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001827 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001828
San Mehatb1043402010-02-05 08:26:50 -08001829 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001830 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001831 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1832 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001833 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001834 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001835 }
San Mehata181b212010-02-11 06:50:20 -08001836
1837 if (rc == StorageResultCode.OperationSucceeded) {
1838 synchronized (mAsecMountSet) {
1839 mAsecMountSet.add(id);
1840 }
1841 }
San Mehat4270e1e2010-01-29 05:32:19 -08001842 return rc;
San Mehat36972292010-01-06 11:06:32 -08001843 }
1844
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07001845 @Override
1846 public int resizeSecureContainer(String id, int sizeMb, String key) {
1847 validatePermission(android.Manifest.permission.ASEC_CREATE);
1848 waitForReady();
1849 warnOnNotMounted();
1850
1851 int rc = StorageResultCode.OperationSucceeded;
1852 try {
1853 mConnector.execute("asec", "resize", id, sizeMb, new SensitiveArg(key));
1854 } catch (NativeDaemonConnectorException e) {
1855 rc = StorageResultCode.OperationFailedInternalError;
1856 }
1857 return rc;
1858 }
1859
San Mehat4270e1e2010-01-29 05:32:19 -08001860 public int finalizeSecureContainer(String id) {
1861 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001862 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001863
San Mehatb1043402010-02-05 08:26:50 -08001864 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001865 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001866 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001867 /*
1868 * Finalization does a remount, so no need
1869 * to update mAsecMountSet
1870 */
San Mehat4270e1e2010-01-29 05:32:19 -08001871 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001872 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001873 }
San Mehat4270e1e2010-01-29 05:32:19 -08001874 return rc;
San Mehat36972292010-01-06 11:06:32 -08001875 }
1876
Kenny Root6dceb882012-04-12 14:23:49 -07001877 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1878 validatePermission(android.Manifest.permission.ASEC_CREATE);
1879 warnOnNotMounted();
1880
1881 int rc = StorageResultCode.OperationSucceeded;
1882 try {
1883 mConnector.execute("asec", "fixperms", id, gid, filename);
1884 /*
1885 * Fix permissions does a remount, so no need to update
1886 * mAsecMountSet
1887 */
1888 } catch (NativeDaemonConnectorException e) {
1889 rc = StorageResultCode.OperationFailedInternalError;
1890 }
1891 return rc;
1892 }
1893
San Mehatd9709982010-02-18 11:43:03 -08001894 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001895 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001896 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001897 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001898
Kenny Rootaa485402010-09-14 14:49:41 -07001899 /*
1900 * Force a GC to make sure AssetManagers in other threads of the
1901 * system_server are cleaned up. We have to do this since AssetManager
1902 * instances are kept as a WeakReference and it's possible we have files
1903 * open on the external storage.
1904 */
1905 Runtime.getRuntime().gc();
1906
San Mehatb1043402010-02-05 08:26:50 -08001907 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001908 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001909 final Command cmd = new Command("asec", "destroy", id);
1910 if (force) {
1911 cmd.appendArg("force");
1912 }
1913 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001914 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001915 int code = e.getCode();
1916 if (code == VoldResponseCode.OpFailedStorageBusy) {
1917 rc = StorageResultCode.OperationFailedStorageBusy;
1918 } else {
1919 rc = StorageResultCode.OperationFailedInternalError;
1920 }
San Mehat02735bc2010-01-26 15:18:08 -08001921 }
San Mehata181b212010-02-11 06:50:20 -08001922
1923 if (rc == StorageResultCode.OperationSucceeded) {
1924 synchronized (mAsecMountSet) {
1925 if (mAsecMountSet.contains(id)) {
1926 mAsecMountSet.remove(id);
1927 }
1928 }
1929 }
1930
San Mehat4270e1e2010-01-29 05:32:19 -08001931 return rc;
San Mehat36972292010-01-06 11:06:32 -08001932 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001933
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07001934 public int mountSecureContainer(String id, String key, int ownerUid, boolean readOnly) {
San Mehat4270e1e2010-01-29 05:32:19 -08001935 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001936 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001937 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001938
San Mehata181b212010-02-11 06:50:20 -08001939 synchronized (mAsecMountSet) {
1940 if (mAsecMountSet.contains(id)) {
1941 return StorageResultCode.OperationFailedStorageMounted;
1942 }
1943 }
1944
San Mehatb1043402010-02-05 08:26:50 -08001945 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001946 try {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07001947 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid,
1948 readOnly ? "ro" : "rw");
San Mehat4270e1e2010-01-29 05:32:19 -08001949 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001950 int code = e.getCode();
1951 if (code != VoldResponseCode.OpFailedStorageBusy) {
1952 rc = StorageResultCode.OperationFailedInternalError;
1953 }
San Mehat02735bc2010-01-26 15:18:08 -08001954 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001955
1956 if (rc == StorageResultCode.OperationSucceeded) {
1957 synchronized (mAsecMountSet) {
1958 mAsecMountSet.add(id);
1959 }
1960 }
San Mehat4270e1e2010-01-29 05:32:19 -08001961 return rc;
San Mehat36972292010-01-06 11:06:32 -08001962 }
1963
San Mehatd9709982010-02-18 11:43:03 -08001964 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001965 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001966 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001967 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001968
San Mehat6cdd9c02010-02-09 14:45:20 -08001969 synchronized (mAsecMountSet) {
1970 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001971 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001972 }
1973 }
1974
Kenny Rootaa485402010-09-14 14:49:41 -07001975 /*
1976 * Force a GC to make sure AssetManagers in other threads of the
1977 * system_server are cleaned up. We have to do this since AssetManager
1978 * instances are kept as a WeakReference and it's possible we have files
1979 * open on the external storage.
1980 */
1981 Runtime.getRuntime().gc();
1982
San Mehatb1043402010-02-05 08:26:50 -08001983 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001984 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001985 final Command cmd = new Command("asec", "unmount", id);
1986 if (force) {
1987 cmd.appendArg("force");
1988 }
1989 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001990 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001991 int code = e.getCode();
1992 if (code == VoldResponseCode.OpFailedStorageBusy) {
1993 rc = StorageResultCode.OperationFailedStorageBusy;
1994 } else {
1995 rc = StorageResultCode.OperationFailedInternalError;
1996 }
San Mehat02735bc2010-01-26 15:18:08 -08001997 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001998
1999 if (rc == StorageResultCode.OperationSucceeded) {
2000 synchronized (mAsecMountSet) {
2001 mAsecMountSet.remove(id);
2002 }
2003 }
San Mehat4270e1e2010-01-29 05:32:19 -08002004 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08002005 }
2006
San Mehat6cdd9c02010-02-09 14:45:20 -08002007 public boolean isSecureContainerMounted(String id) {
2008 validatePermission(android.Manifest.permission.ASEC_ACCESS);
2009 waitForReady();
2010 warnOnNotMounted();
2011
2012 synchronized (mAsecMountSet) {
2013 return mAsecMountSet.contains(id);
2014 }
2015 }
2016
San Mehat4270e1e2010-01-29 05:32:19 -08002017 public int renameSecureContainer(String oldId, String newId) {
2018 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08002019 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002020 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002021
San Mehata181b212010-02-11 06:50:20 -08002022 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08002023 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06002024 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08002025 * changed while active, we must ensure both ids are not currently mounted.
2026 */
2027 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08002028 return StorageResultCode.OperationFailedStorageMounted;
2029 }
2030 }
2031
San Mehatb1043402010-02-05 08:26:50 -08002032 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002033 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002034 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08002035 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002036 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002037 }
San Mehata181b212010-02-11 06:50:20 -08002038
San Mehat4270e1e2010-01-29 05:32:19 -08002039 return rc;
San Mehat45f61042010-01-23 08:12:43 -08002040 }
2041
San Mehat4270e1e2010-01-29 05:32:19 -08002042 public String getSecureContainerPath(String id) {
2043 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002044 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002045 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002046
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002047 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07002048 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002049 event = mConnector.execute("asec", "path", id);
2050 event.checkCode(VoldResponseCode.AsecPathResult);
2051 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07002052 } catch (NativeDaemonConnectorException e) {
2053 int code = e.getCode();
2054 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01002055 Slog.i(TAG, String.format("Container '%s' not found", id));
2056 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08002057 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07002058 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08002059 }
2060 }
San Mehat22dd86e2010-01-12 12:21:18 -08002061 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002062
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002063 public String getSecureContainerFilesystemPath(String id) {
2064 validatePermission(android.Manifest.permission.ASEC_ACCESS);
2065 waitForReady();
2066 warnOnNotMounted();
2067
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002068 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002069 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002070 event = mConnector.execute("asec", "fspath", id);
2071 event.checkCode(VoldResponseCode.AsecPathResult);
2072 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002073 } catch (NativeDaemonConnectorException e) {
2074 int code = e.getCode();
2075 if (code == VoldResponseCode.OpFailedStorageNotFound) {
2076 Slog.i(TAG, String.format("Container '%s' not found", id));
2077 return null;
2078 } else {
2079 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2080 }
2081 }
2082 }
2083
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002084 public void finishMediaUpdate() {
2085 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
2086 }
Kenny Root02c87302010-07-01 08:10:18 -07002087
Kenny Roota02b8b02010-08-05 16:14:17 -07002088 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2089 if (callerUid == android.os.Process.SYSTEM_UID) {
2090 return true;
2091 }
2092
Kenny Root02c87302010-07-01 08:10:18 -07002093 if (packageName == null) {
2094 return false;
2095 }
2096
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002097 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002098
2099 if (DEBUG_OBB) {
2100 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2101 packageUid + ", callerUid = " + callerUid);
2102 }
2103
2104 return callerUid == packageUid;
2105 }
2106
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002107 public String getMountedObbPath(String rawPath) {
2108 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002109
Kenny Root02c87302010-07-01 08:10:18 -07002110 waitForReady();
2111 warnOnNotMounted();
2112
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002113 final ObbState state;
2114 synchronized (mObbPathToStateMap) {
2115 state = mObbPathToStateMap.get(rawPath);
2116 }
2117 if (state == null) {
2118 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2119 return null;
2120 }
2121
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002122 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002123 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002124 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002125 event.checkCode(VoldResponseCode.AsecPathResult);
2126 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002127 } catch (NativeDaemonConnectorException e) {
2128 int code = e.getCode();
2129 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002130 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002131 } else {
2132 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2133 }
2134 }
2135 }
2136
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002137 @Override
2138 public boolean isObbMounted(String rawPath) {
2139 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002140 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002141 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002142 }
Kenny Root02c87302010-07-01 08:10:18 -07002143 }
2144
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002145 @Override
2146 public void mountObb(
2147 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2148 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2149 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2150 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002151
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002152 final int callingUid = Binder.getCallingUid();
2153 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2154 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002155 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2156
2157 if (DEBUG_OBB)
2158 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002159 }
2160
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002161 @Override
2162 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2163 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2164
2165 final ObbState existingState;
2166 synchronized (mObbPathToStateMap) {
2167 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002168 }
2169
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002170 if (existingState != null) {
2171 // TODO: separate state object from request data
2172 final int callingUid = Binder.getCallingUid();
2173 final ObbState newState = new ObbState(
2174 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2175 final ObbAction action = new UnmountObbAction(newState, force);
2176 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002177
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002178 if (DEBUG_OBB)
2179 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2180 } else {
2181 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2182 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002183 }
2184
Ben Komalo444eca22011-09-01 15:17:44 -07002185 @Override
2186 public int getEncryptionState() {
2187 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2188 "no permission to access the crypt keeper");
2189
2190 waitForReady();
2191
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002192 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002193 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002194 event = mConnector.execute("cryptfs", "cryptocomplete");
2195 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002196 } catch (NumberFormatException e) {
2197 // Bad result - unexpected.
2198 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2199 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2200 } catch (NativeDaemonConnectorException e) {
2201 // Something bad happened.
2202 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2203 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2204 }
2205 }
2206
Paul Lawrence8e397362014-01-27 15:22:30 -08002207 private String toHex(String password) {
2208 if (password == null) {
Paul Lawrence945490c2014-03-27 16:37:28 +00002209 return new String();
Paul Lawrence8e397362014-01-27 15:22:30 -08002210 }
2211 byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
2212 return new String(Hex.encodeHex(bytes));
2213 }
2214
Paul Lawrence945490c2014-03-27 16:37:28 +00002215 private String fromHex(String hexPassword) {
2216 if (hexPassword == null) {
2217 return null;
2218 }
2219
2220 try {
2221 byte[] bytes = Hex.decodeHex(hexPassword.toCharArray());
2222 return new String(bytes, StandardCharsets.UTF_8);
2223 } catch (DecoderException e) {
2224 return null;
2225 }
2226 }
2227
Ben Komalo444eca22011-09-01 15:17:44 -07002228 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002229 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002230 if (TextUtils.isEmpty(password)) {
2231 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002232 }
2233
Jason parks8888c592011-01-20 22:46:41 -06002234 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2235 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002236
2237 waitForReady();
2238
2239 if (DEBUG_EVENTS) {
2240 Slog.i(TAG, "decrypting storage...");
2241 }
2242
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002243 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002244 try {
Paul Lawrence8e397362014-01-27 15:22:30 -08002245 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(toHex(password)));
Jason parks9ed98bc2011-01-17 09:58:35 -06002246
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002247 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002248 if (code == 0) {
2249 // Decrypt was successful. Post a delayed message before restarting in order
2250 // to let the UI to clear itself
2251 mHandler.postDelayed(new Runnable() {
2252 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002253 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002254 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002255 } catch (NativeDaemonConnectorException e) {
2256 Slog.e(TAG, "problem executing in background", e);
2257 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002258 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002259 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002260 }
2261
2262 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002263 } catch (NativeDaemonConnectorException e) {
2264 // Decryption failed
2265 return e.getCode();
2266 }
Jason parks5af0b912010-11-29 09:05:25 -06002267 }
2268
Paul Lawrence46791e72014-04-03 09:10:26 -07002269 public int encryptStorage(int type, String password) {
2270 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002271 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002272 }
2273
Jason parks8888c592011-01-20 22:46:41 -06002274 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2275 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002276
2277 waitForReady();
2278
2279 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002280 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002281 }
2282
2283 try {
Paul Lawrence46791e72014-04-03 09:10:26 -07002284 mConnector.execute("cryptfs", "enablecrypto", "inplace", CRYPTO_TYPES[type],
Paul Lawrence8e397362014-01-27 15:22:30 -08002285 new SensitiveArg(toHex(password)));
Jason parks56aa5322011-01-07 09:01:15 -06002286 } catch (NativeDaemonConnectorException e) {
2287 // Encryption failed
2288 return e.getCode();
2289 }
2290
2291 return 0;
2292 }
2293
Paul Lawrence8e397362014-01-27 15:22:30 -08002294 /** Set the password for encrypting the master key.
2295 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2296 * @param password The password to set.
2297 */
2298 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002299 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2300 "no permission to access the crypt keeper");
2301
2302 waitForReady();
2303
2304 if (DEBUG_EVENTS) {
2305 Slog.i(TAG, "changing encryption password...");
2306 }
2307
2308 try {
Svetoslava6711ff2014-10-17 11:38:06 -07002309 NativeDaemonEvent event = mConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
Svetoslav16e4a1a2014-09-29 18:16:20 -07002310 new SensitiveArg(toHex(password)));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002311 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002312 } catch (NativeDaemonConnectorException e) {
2313 // Encryption failed
2314 return e.getCode();
2315 }
2316 }
2317
Christopher Tate32418be2011-10-10 13:51:12 -07002318 /**
2319 * Validate a user-supplied password string with cryptfs
2320 */
2321 @Override
2322 public int verifyEncryptionPassword(String password) throws RemoteException {
2323 // Only the system process is permitted to validate passwords
2324 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2325 throw new SecurityException("no permission to access the crypt keeper");
2326 }
2327
2328 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2329 "no permission to access the crypt keeper");
2330
2331 if (TextUtils.isEmpty(password)) {
2332 throw new IllegalArgumentException("password cannot be empty");
2333 }
2334
2335 waitForReady();
2336
2337 if (DEBUG_EVENTS) {
2338 Slog.i(TAG, "validating encryption password...");
2339 }
2340
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002341 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002342 try {
Paul Lawrence8e397362014-01-27 15:22:30 -08002343 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(toHex(password)));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002344 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2345 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002346 } catch (NativeDaemonConnectorException e) {
2347 // Encryption failed
2348 return e.getCode();
2349 }
2350 }
2351
Paul Lawrence8e397362014-01-27 15:22:30 -08002352 /**
2353 * Get the type of encryption used to encrypt the master key.
2354 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2355 */
2356 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002357 public int getPasswordType() {
Paul Lawrence8e397362014-01-27 15:22:30 -08002358
2359 waitForReady();
2360
2361 final NativeDaemonEvent event;
2362 try {
2363 event = mConnector.execute("cryptfs", "getpwtype");
2364 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2365 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2366 return i;
2367 }
2368
2369 throw new IllegalStateException("unexpected return from cryptfs");
2370 } catch (NativeDaemonConnectorException e) {
2371 throw e.rethrowAsParcelableException();
2372 }
2373 }
2374
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002375 /**
2376 * Set a field in the crypto header.
2377 * @param field field to set
2378 * @param contents contents to set in field
2379 */
2380 @Override
2381 public void setField(String field, String contents) throws RemoteException {
2382
2383 waitForReady();
2384
2385 final NativeDaemonEvent event;
2386 try {
2387 event = mConnector.execute("cryptfs", "setfield", field, contents);
2388 } catch (NativeDaemonConnectorException e) {
2389 throw e.rethrowAsParcelableException();
2390 }
2391 }
2392
2393 /**
2394 * Gets a field from the crypto header.
2395 * @param field field to get
2396 * @return contents of field
2397 */
2398 @Override
2399 public String getField(String field) throws RemoteException {
2400
2401 waitForReady();
2402
2403 final NativeDaemonEvent event;
2404 try {
2405 final String[] contents = NativeDaemonEvent.filterMessageList(
2406 mConnector.executeForList("cryptfs", "getfield", field),
2407 VoldResponseCode.CryptfsGetfieldResult);
2408 String result = new String();
2409 for (String content : contents) {
2410 result += content;
2411 }
2412 return result;
2413 } catch (NativeDaemonConnectorException e) {
2414 throw e.rethrowAsParcelableException();
2415 }
2416 }
2417
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002418 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002419 public String getPassword() throws RemoteException {
2420 if (!isReady()) {
2421 return new String();
2422 }
2423
2424 final NativeDaemonEvent event;
2425 try {
2426 event = mConnector.execute("cryptfs", "getpw");
2427 return fromHex(event.getMessage());
2428 } catch (NativeDaemonConnectorException e) {
2429 throw e.rethrowAsParcelableException();
2430 }
2431 }
2432
2433 @Override
2434 public void clearPassword() throws RemoteException {
2435 if (!isReady()) {
2436 return;
2437 }
2438
2439 final NativeDaemonEvent event;
2440 try {
2441 event = mConnector.execute("cryptfs", "clearpw");
2442 } catch (NativeDaemonConnectorException e) {
2443 throw e.rethrowAsParcelableException();
2444 }
2445 }
2446
2447 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002448 public int mkdirs(String callingPkg, String appPath) {
2449 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2450 final UserEnvironment userEnv = new UserEnvironment(userId);
2451
2452 // Validate that reported package name belongs to caller
2453 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2454 Context.APP_OPS_SERVICE);
2455 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2456
2457 try {
2458 appPath = new File(appPath).getCanonicalPath();
2459 } catch (IOException e) {
2460 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2461 return -1;
2462 }
2463
Jeff Sharkey5786a272013-10-02 12:50:34 -07002464 if (!appPath.endsWith("/")) {
2465 appPath = appPath + "/";
2466 }
2467
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002468 // Try translating the app path into a vold path, but require that it
2469 // belong to the calling package.
2470 String voldPath = maybeTranslatePathForVold(appPath,
2471 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2472 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2473 if (voldPath != null) {
2474 try {
2475 mConnector.execute("volume", "mkdirs", voldPath);
2476 return 0;
2477 } catch (NativeDaemonConnectorException e) {
2478 return e.getCode();
2479 }
2480 }
2481
2482 voldPath = maybeTranslatePathForVold(appPath,
2483 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2484 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2485 if (voldPath != null) {
2486 try {
2487 mConnector.execute("volume", "mkdirs", voldPath);
2488 return 0;
2489 } catch (NativeDaemonConnectorException e) {
2490 return e.getCode();
2491 }
2492 }
2493
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -07002494 voldPath = maybeTranslatePathForVold(appPath,
2495 userEnv.buildExternalStorageAppMediaDirs(callingPkg),
2496 userEnv.buildExternalStorageAppMediaDirsForVold(callingPkg));
2497 if (voldPath != null) {
2498 try {
2499 mConnector.execute("volume", "mkdirs", voldPath);
2500 return 0;
2501 } catch (NativeDaemonConnectorException e) {
2502 return e.getCode();
2503 }
2504 }
2505
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002506 throw new SecurityException("Invalid mkdirs path: " + appPath);
2507 }
2508
2509 /**
2510 * Translate the given path from an app-visible path to a vold-visible path,
2511 * but only if it's under the given whitelisted paths.
2512 *
2513 * @param path a canonicalized app-visible path.
2514 * @param appPaths list of app-visible paths that are allowed.
2515 * @param voldPaths list of vold-visible paths directly corresponding to the
2516 * allowed app-visible paths argument.
2517 * @return a vold-visible path representing the original path, or
2518 * {@code null} if the given path didn't have an app-to-vold
2519 * mapping.
2520 */
2521 @VisibleForTesting
2522 public static String maybeTranslatePathForVold(
2523 String path, File[] appPaths, File[] voldPaths) {
2524 if (appPaths.length != voldPaths.length) {
2525 throw new IllegalStateException("Paths must be 1:1 mapping");
2526 }
2527
2528 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002529 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002530 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002531 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002532 .getAbsolutePath();
2533 if (!path.endsWith("/")) {
2534 path = path + "/";
2535 }
2536 return path;
2537 }
2538 }
2539 return null;
2540 }
2541
2542 @Override
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002543 public StorageVolume[] getVolumeList() {
2544 final int callingUserId = UserHandle.getCallingUserId();
2545 final boolean accessAll = (mContext.checkPermission(
2546 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2547 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2548
2549 synchronized (mVolumesLock) {
2550 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2551 for (StorageVolume volume : mVolumes) {
2552 final UserHandle owner = volume.getOwner();
2553 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2554 if (accessAll || ownerMatch) {
2555 filtered.add(volume);
2556 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002557 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002558 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002559 }
2560 }
2561
Kenny Rootaf9d6672010-10-08 09:21:39 -07002562 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2563 final IBinder binder = obbState.getBinder();
2564 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002565
Kenny Rootaf9d6672010-10-08 09:21:39 -07002566 if (obbStates == null) {
2567 obbStates = new ArrayList<ObbState>();
2568 mObbMounts.put(binder, obbStates);
2569 } else {
2570 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002571 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002572 throw new IllegalStateException("Attempt to add ObbState twice. "
2573 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002574 }
2575 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002576 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002577
2578 obbStates.add(obbState);
2579 try {
2580 obbState.link();
2581 } catch (RemoteException e) {
2582 /*
2583 * The binder died before we could link it, so clean up our state
2584 * and return failure.
2585 */
2586 obbStates.remove(obbState);
2587 if (obbStates.isEmpty()) {
2588 mObbMounts.remove(binder);
2589 }
2590
2591 // Rethrow the error so mountObb can get it
2592 throw e;
2593 }
2594
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002595 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002596 }
2597
Kenny Rootaf9d6672010-10-08 09:21:39 -07002598 private void removeObbStateLocked(ObbState obbState) {
2599 final IBinder binder = obbState.getBinder();
2600 final List<ObbState> obbStates = mObbMounts.get(binder);
2601 if (obbStates != null) {
2602 if (obbStates.remove(obbState)) {
2603 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002604 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002605 if (obbStates.isEmpty()) {
2606 mObbMounts.remove(binder);
2607 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002608 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002609
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002610 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002611 }
2612
Kenny Roota02b8b02010-08-05 16:14:17 -07002613 private class ObbActionHandler extends Handler {
2614 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002615 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002616
2617 ObbActionHandler(Looper l) {
2618 super(l);
2619 }
2620
2621 @Override
2622 public void handleMessage(Message msg) {
2623 switch (msg.what) {
2624 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002625 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002626
2627 if (DEBUG_OBB)
2628 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2629
2630 // If a bind was already initiated we don't really
2631 // need to do anything. The pending install
2632 // will be processed later on.
2633 if (!mBound) {
2634 // If this is the only one pending we might
2635 // have to bind to the service again.
2636 if (!connectToService()) {
2637 Slog.e(TAG, "Failed to bind to media container service");
2638 action.handleError();
2639 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002640 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002641 }
Kenny Root735de3b2010-09-30 14:11:39 -07002642
Kenny Root735de3b2010-09-30 14:11:39 -07002643 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002644 break;
2645 }
2646 case OBB_MCS_BOUND: {
2647 if (DEBUG_OBB)
2648 Slog.i(TAG, "OBB_MCS_BOUND");
2649 if (msg.obj != null) {
2650 mContainerService = (IMediaContainerService) msg.obj;
2651 }
2652 if (mContainerService == null) {
2653 // Something seriously wrong. Bail out
2654 Slog.e(TAG, "Cannot bind to media container service");
2655 for (ObbAction action : mActions) {
2656 // Indicate service bind error
2657 action.handleError();
2658 }
2659 mActions.clear();
2660 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002661 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002662 if (action != null) {
2663 action.execute(this);
2664 }
2665 } else {
2666 // Should never happen ideally.
2667 Slog.w(TAG, "Empty queue");
2668 }
2669 break;
2670 }
2671 case OBB_MCS_RECONNECT: {
2672 if (DEBUG_OBB)
2673 Slog.i(TAG, "OBB_MCS_RECONNECT");
2674 if (mActions.size() > 0) {
2675 if (mBound) {
2676 disconnectService();
2677 }
2678 if (!connectToService()) {
2679 Slog.e(TAG, "Failed to bind to media container service");
2680 for (ObbAction action : mActions) {
2681 // Indicate service bind error
2682 action.handleError();
2683 }
2684 mActions.clear();
2685 }
2686 }
2687 break;
2688 }
2689 case OBB_MCS_UNBIND: {
2690 if (DEBUG_OBB)
2691 Slog.i(TAG, "OBB_MCS_UNBIND");
2692
2693 // Delete pending install
2694 if (mActions.size() > 0) {
2695 mActions.remove(0);
2696 }
2697 if (mActions.size() == 0) {
2698 if (mBound) {
2699 disconnectService();
2700 }
2701 } else {
2702 // There are more pending requests in queue.
2703 // Just post MCS_BOUND message to trigger processing
2704 // of next pending install.
2705 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2706 }
2707 break;
2708 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002709 case OBB_FLUSH_MOUNT_STATE: {
2710 final String path = (String) msg.obj;
2711
2712 if (DEBUG_OBB)
2713 Slog.i(TAG, "Flushing all OBB state for path " + path);
2714
2715 synchronized (mObbMounts) {
2716 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2717
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002718 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002719 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002720 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002721
2722 /*
2723 * If this entry's source file is in the volume path
2724 * that got unmounted, remove it because it's no
2725 * longer valid.
2726 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002727 if (state.canonicalPath.startsWith(path)) {
2728 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002729 }
2730 }
2731
2732 for (final ObbState obbState : obbStatesToRemove) {
2733 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002734 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002735
2736 removeObbStateLocked(obbState);
2737
2738 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002739 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002740 OnObbStateChangeListener.UNMOUNTED);
2741 } catch (RemoteException e) {
2742 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002743 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002744 }
2745 }
2746 }
2747 break;
2748 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002749 }
2750 }
2751
2752 private boolean connectToService() {
2753 if (DEBUG_OBB)
2754 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2755
2756 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2757 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2758 mBound = true;
2759 return true;
2760 }
2761 return false;
2762 }
2763
2764 private void disconnectService() {
2765 mContainerService = null;
2766 mBound = false;
2767 mContext.unbindService(mDefContainerConn);
2768 }
2769 }
2770
2771 abstract class ObbAction {
2772 private static final int MAX_RETRIES = 3;
2773 private int mRetries;
2774
2775 ObbState mObbState;
2776
2777 ObbAction(ObbState obbState) {
2778 mObbState = obbState;
2779 }
2780
2781 public void execute(ObbActionHandler handler) {
2782 try {
2783 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002784 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002785 mRetries++;
2786 if (mRetries > MAX_RETRIES) {
2787 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002788 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002789 handleError();
2790 return;
2791 } else {
2792 handleExecute();
2793 if (DEBUG_OBB)
2794 Slog.i(TAG, "Posting install MCS_UNBIND");
2795 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2796 }
2797 } catch (RemoteException e) {
2798 if (DEBUG_OBB)
2799 Slog.i(TAG, "Posting install MCS_RECONNECT");
2800 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2801 } catch (Exception e) {
2802 if (DEBUG_OBB)
2803 Slog.d(TAG, "Error handling OBB action", e);
2804 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002805 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002806 }
2807 }
2808
Kenny Root05105f72010-09-22 17:29:43 -07002809 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002810 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002811
2812 protected ObbInfo getObbInfo() throws IOException {
2813 ObbInfo obbInfo;
2814 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002815 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002816 } catch (RemoteException e) {
2817 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002818 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002819 obbInfo = null;
2820 }
2821 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002822 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002823 }
2824 return obbInfo;
2825 }
2826
Kenny Rootaf9d6672010-10-08 09:21:39 -07002827 protected void sendNewStatusOrIgnore(int status) {
2828 if (mObbState == null || mObbState.token == null) {
2829 return;
2830 }
2831
Kenny Root38cf8862010-09-26 14:18:51 -07002832 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002833 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002834 } catch (RemoteException e) {
2835 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2836 }
2837 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002838 }
2839
2840 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002841 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002842 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002843
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002844 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002845 super(obbState);
2846 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002847 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002848 }
2849
Jason parks5af0b912010-11-29 09:05:25 -06002850 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002851 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002852 waitForReady();
2853 warnOnNotMounted();
2854
Kenny Root38cf8862010-09-26 14:18:51 -07002855 final ObbInfo obbInfo = getObbInfo();
2856
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002857 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002858 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2859 + " which is owned by " + obbInfo.packageName);
2860 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2861 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002862 }
2863
Kenny Rootaf9d6672010-10-08 09:21:39 -07002864 final boolean isMounted;
2865 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002866 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002867 }
2868 if (isMounted) {
2869 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2870 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2871 return;
2872 }
2873
Kenny Rootaf9d6672010-10-08 09:21:39 -07002874 final String hashedKey;
2875 if (mKey == null) {
2876 hashedKey = "none";
2877 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002878 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002879 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2880
2881 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2882 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2883 SecretKey key = factory.generateSecret(ks);
2884 BigInteger bi = new BigInteger(key.getEncoded());
2885 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002886 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002887 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2888 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2889 return;
2890 } catch (InvalidKeySpecException e) {
2891 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2892 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002893 return;
2894 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002895 }
Kenny Root38cf8862010-09-26 14:18:51 -07002896
Kenny Rootaf9d6672010-10-08 09:21:39 -07002897 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002898 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002899 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2900 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002901 } catch (NativeDaemonConnectorException e) {
2902 int code = e.getCode();
2903 if (code != VoldResponseCode.OpFailedStorageBusy) {
2904 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002905 }
2906 }
2907
Kenny Rootaf9d6672010-10-08 09:21:39 -07002908 if (rc == StorageResultCode.OperationSucceeded) {
2909 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002910 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002911
2912 synchronized (mObbMounts) {
2913 addObbStateLocked(mObbState);
2914 }
2915
2916 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002917 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002918 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002919
Kenny Rootaf9d6672010-10-08 09:21:39 -07002920 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002921 }
2922 }
2923
Jason parks5af0b912010-11-29 09:05:25 -06002924 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002925 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002926 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002927 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002928
2929 @Override
2930 public String toString() {
2931 StringBuilder sb = new StringBuilder();
2932 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002933 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002934 sb.append('}');
2935 return sb.toString();
2936 }
2937 }
2938
2939 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002940 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002941
2942 UnmountObbAction(ObbState obbState, boolean force) {
2943 super(obbState);
2944 mForceUnmount = force;
2945 }
2946
Jason parks5af0b912010-11-29 09:05:25 -06002947 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002948 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002949 waitForReady();
2950 warnOnNotMounted();
2951
Kenny Root38cf8862010-09-26 14:18:51 -07002952 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002953
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002954 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002955 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002956 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002957 }
Kenny Root38cf8862010-09-26 14:18:51 -07002958
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002959 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002960 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2961 return;
2962 }
2963
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002964 if (existingState.ownerGid != mObbState.ownerGid) {
2965 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2966 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002967 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2968 return;
2969 }
2970
Kenny Rootaf9d6672010-10-08 09:21:39 -07002971 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002972 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002973 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002974 if (mForceUnmount) {
2975 cmd.appendArg("force");
2976 }
2977 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002978 } catch (NativeDaemonConnectorException e) {
2979 int code = e.getCode();
2980 if (code == VoldResponseCode.OpFailedStorageBusy) {
2981 rc = StorageResultCode.OperationFailedStorageBusy;
2982 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2983 // If it's not mounted then we've already won.
2984 rc = StorageResultCode.OperationSucceeded;
2985 } else {
2986 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002987 }
2988 }
2989
Kenny Rootaf9d6672010-10-08 09:21:39 -07002990 if (rc == StorageResultCode.OperationSucceeded) {
2991 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002992 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002993 }
2994
Kenny Rootaf9d6672010-10-08 09:21:39 -07002995 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002996 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002997 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002998 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002999 }
3000 }
3001
Jason parks5af0b912010-11-29 09:05:25 -06003002 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003003 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003004 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07003005 }
3006
3007 @Override
3008 public String toString() {
3009 StringBuilder sb = new StringBuilder();
3010 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003011 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003012 sb.append(",force=");
3013 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003014 sb.append('}');
3015 return sb.toString();
3016 }
Kenny Root02c87302010-07-01 08:10:18 -07003017 }
Kenny Root38cf8862010-09-26 14:18:51 -07003018
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003019 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003020 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
3021 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003022 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003023
3024 // Only adjust paths when storage is emulated
3025 if (!Environment.isExternalStorageEmulated()) {
3026 return canonicalPath;
3027 }
3028
3029 String path = canonicalPath.toString();
3030
3031 // First trim off any external storage prefix
3032 final UserEnvironment userEnv = new UserEnvironment(userId);
3033
3034 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003035 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003036 // /storage/emulated_legacy
3037 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003038 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003039
3040 if (path.startsWith(externalPath)) {
3041 path = path.substring(externalPath.length() + 1);
3042 } else if (path.startsWith(legacyExternalPath)) {
3043 path = path.substring(legacyExternalPath.length() + 1);
3044 } else {
3045 return canonicalPath;
3046 }
3047
3048 // Handle special OBB paths on emulated storage
3049 final String obbPath = "Android/obb";
3050 if (path.startsWith(obbPath)) {
3051 path = path.substring(obbPath.length() + 1);
3052
3053 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003054 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003055 } else {
3056 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003057 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
3058 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003059 }
3060 }
3061
3062 // Handle normal external storage paths
3063 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07003064 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003065 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003066 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003067 }
3068 }
3069
Kenny Root38cf8862010-09-26 14:18:51 -07003070 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003071 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
3073
3074 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07003075
Kenny Root38cf8862010-09-26 14:18:51 -07003076 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003077 pw.println("mObbMounts:");
3078 pw.increaseIndent();
3079 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3080 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003081 while (binders.hasNext()) {
3082 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003083 pw.println(e.getKey() + ":");
3084 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003085 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003086 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003087 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003088 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003089 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003090 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003091 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003092
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003093 pw.println();
3094 pw.println("mObbPathToStateMap:");
3095 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003096 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3097 while (maps.hasNext()) {
3098 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003099 pw.print(e.getKey());
3100 pw.print(" -> ");
3101 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003102 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003103 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003104 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003105
Jeff Sharkeyb049e212012-09-07 23:16:01 -07003106 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003107 pw.println();
3108 pw.println("mVolumes:");
3109 pw.increaseIndent();
3110 for (StorageVolume volume : mVolumes) {
3111 pw.println(volume);
3112 pw.increaseIndent();
3113 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
3114 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07003115 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003116 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07003117 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08003118
3119 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003120 pw.println("mConnection:");
3121 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003122 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003123 pw.decreaseIndent();
Christopher Tate7265abe2014-11-21 13:54:45 -08003124
3125 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3126
3127 pw.println();
3128 pw.print("Last maintenance: ");
3129 pw.println(sdf.format(new Date(mLastMaintenance)));
Kenny Root38cf8862010-09-26 14:18:51 -07003130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003132 /** {@inheritDoc} */
3133 public void monitor() {
3134 if (mConnector != null) {
3135 mConnector.monitor();
3136 }
3137 }
3138}