blob: c7ca1ea9cb3f5a93ab933a52d9e91800f8367fb3 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070064import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070065import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070066import com.android.internal.util.XmlUtils;
67import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070068import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070069import com.android.server.am.ActivityManagerService;
70import com.android.server.pm.PackageManagerService;
71import com.android.server.pm.UserManagerService;
72import com.google.android.collect.Lists;
73import com.google.android.collect.Maps;
74
Mike Lockwood2f6a3882011-05-09 19:08:06 -070075import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070076
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070077import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070078import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070079import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070080import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070081import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070082import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070083import java.security.spec.InvalidKeySpecException;
84import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080085import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070086import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080087import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070088import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070089import java.util.LinkedList;
90import java.util.List;
91import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070092import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070093import java.util.concurrent.CountDownLatch;
94import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Kenny Root3b1abba2010-10-13 15:00:07 -070096import javax.crypto.SecretKey;
97import javax.crypto.SecretKeyFactory;
98import javax.crypto.spec.PBEKeySpec;
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100/**
San Mehatb1043402010-02-05 08:26:50 -0800101 * MountService implements back-end services for platform storage
102 * management.
103 * @hide - Applications should use android.os.storage.StorageManager
104 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700106class MountService extends IMountService.Stub
107 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600108
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700109 // TODO: listen for user creation/deletion
110
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800111 private static final boolean LOCAL_LOGD = false;
112 private static final boolean DEBUG_UNMOUNT = false;
113 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800114 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700115
Kenny Root07714d42011-08-17 17:49:28 -0700116 // Disable this since it messes up long-running cryptfs operations.
117 private static final boolean WATCHDOG_ENABLE = false;
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final String TAG = "MountService";
120
Kenny Root305bcbf2010-09-03 07:56:38 -0700121 private static final String VOLD_TAG = "VoldConnector";
122
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700123 /** Maximum number of ASEC containers allowed to be mounted. */
124 private static final int MAX_CONTAINERS = 250;
125
San Mehat4270e1e2010-01-29 05:32:19 -0800126 /*
127 * Internal vold volume state constants
128 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800129 class VolumeState {
130 public static final int Init = -1;
131 public static final int NoMedia = 0;
132 public static final int Idle = 1;
133 public static final int Pending = 2;
134 public static final int Checking = 3;
135 public static final int Mounted = 4;
136 public static final int Unmounting = 5;
137 public static final int Formatting = 6;
138 public static final int Shared = 7;
139 public static final int SharedMnt = 8;
140 }
141
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * Internal vold response code constants
144 */
San Mehat22dd86e2010-01-12 12:21:18 -0800145 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800146 /*
147 * 100 series - Requestion action was initiated; expect another reply
148 * before proceeding with a new command.
149 */
San Mehat22dd86e2010-01-12 12:21:18 -0800150 public static final int VolumeListResult = 110;
151 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800152 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800153
San Mehat4270e1e2010-01-29 05:32:19 -0800154 /*
155 * 200 series - Requestion action has been successfully completed.
156 */
157 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800158 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800159 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800160
San Mehat4270e1e2010-01-29 05:32:19 -0800161 /*
162 * 400 series - Command was accepted, but the requested action
163 * did not take place.
164 */
165 public static final int OpFailedNoMedia = 401;
166 public static final int OpFailedMediaBlank = 402;
167 public static final int OpFailedMediaCorrupt = 403;
168 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800169 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700170 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800171
172 /*
173 * 600 series - Unsolicited broadcasts.
174 */
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800176 public static final int VolumeDiskInserted = 630;
177 public static final int VolumeDiskRemoved = 631;
178 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700179
180 /*
181 * 700 series - fstrim
182 */
183 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800184 }
185
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700186 private Context mContext;
187 private NativeDaemonConnector mConnector;
188
189 private final Object mVolumesLock = new Object();
190
191 /** When defined, base template for user-specific {@link StorageVolume}. */
192 private StorageVolume mEmulatedTemplate;
193
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700194 // TODO: separate storage volumes on per-user basis
195
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700197 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
198 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700200 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
201 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800202 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700203 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
204
205 private volatile boolean mSystemReady = false;
206
San Mehat4270e1e2010-01-29 05:32:19 -0800207 private PackageManagerService mPms;
208 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700209 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800210 // Used as a lock for methods that register/unregister listeners.
211 final private ArrayList<MountServiceBinderListener> mListeners =
212 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800213 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
214 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800215 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800216
San Mehat6cdd9c02010-02-09 14:45:20 -0800217 /**
218 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800219 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800220 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800221 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800222
Kenny Root02c87302010-07-01 08:10:18 -0700223 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700224 * The size of the crypto algorithm key in bits for OBB files. Currently
225 * Twofish is used which takes 128-bit keys.
226 */
227 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
228
229 /**
230 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
231 * 1024 is reasonably secure and not too slow.
232 */
233 private static final int PBKDF2_HASH_ROUNDS = 1024;
234
235 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700236 * Mounted OBB tracking information. Used to track the current state of all
237 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700238 */
Kenny Root735de3b2010-09-30 14:11:39 -0700239 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700240
241 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700242 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
243
244 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700245 public ObbState(String rawPath, String canonicalPath, int callingUid,
246 IObbActionListener token, int nonce) {
247 this.rawPath = rawPath;
248 this.canonicalPath = canonicalPath.toString();
249
250 final int userId = UserHandle.getUserId(callingUid);
251 this.ownerPath = buildObbPath(canonicalPath, userId, false);
252 this.voldPath = buildObbPath(canonicalPath, userId, true);
253
254 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700255 this.token = token;
256 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700257 }
258
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700259 final String rawPath;
260 final String canonicalPath;
261 final String ownerPath;
262 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700263
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700264 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700265
Kenny Rootaf9d6672010-10-08 09:21:39 -0700266 // Token of remote Binder caller
267 final IObbActionListener token;
268
269 // Identifier to pass back to the token
270 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700271
Kenny Root735de3b2010-09-30 14:11:39 -0700272 public IBinder getBinder() {
273 return token.asBinder();
274 }
275
Kenny Roota02b8b02010-08-05 16:14:17 -0700276 @Override
277 public void binderDied() {
278 ObbAction action = new UnmountObbAction(this, true);
279 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700280 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700281
Kenny Root5919ac62010-10-05 09:49:40 -0700282 public void link() throws RemoteException {
283 getBinder().linkToDeath(this, 0);
284 }
285
286 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700287 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700288 }
Kenny Root38cf8862010-09-26 14:18:51 -0700289
290 @Override
291 public String toString() {
292 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700293 sb.append("rawPath=").append(rawPath);
294 sb.append(",canonicalPath=").append(canonicalPath);
295 sb.append(",ownerPath=").append(ownerPath);
296 sb.append(",voldPath=").append(voldPath);
297 sb.append(",ownerGid=").append(ownerGid);
298 sb.append(",token=").append(token);
299 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700300 sb.append('}');
301 return sb.toString();
302 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700303 }
304
305 // OBB Action Handler
306 final private ObbActionHandler mObbActionHandler;
307
308 // OBB action handler messages
309 private static final int OBB_RUN_ACTION = 1;
310 private static final int OBB_MCS_BOUND = 2;
311 private static final int OBB_MCS_UNBIND = 3;
312 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700313 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700314
315 /*
316 * Default Container Service information
317 */
318 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
319 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
320
321 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
322
323 class DefaultContainerConnection implements ServiceConnection {
324 public void onServiceConnected(ComponentName name, IBinder service) {
325 if (DEBUG_OBB)
326 Slog.i(TAG, "onServiceConnected");
327 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
328 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
329 }
330
331 public void onServiceDisconnected(ComponentName name) {
332 if (DEBUG_OBB)
333 Slog.i(TAG, "onServiceDisconnected");
334 }
335 };
336
337 // Used in the ObbActionHandler
338 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700339
340 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800341 private static final int H_UNMOUNT_PM_UPDATE = 1;
342 private static final int H_UNMOUNT_PM_DONE = 2;
343 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700344 private static final int H_SYSTEM_READY = 4;
345
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
347 private static final int MAX_UNMOUNT_RETRIES = 4;
348
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700350 final String path;
351 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700352 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354
Ben Komalo13c71972011-09-07 16:35:56 -0700355 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800356 retries = 0;
357 this.path = path;
358 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700359 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800361
362 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700363 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700364 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800365 }
366 }
367
368 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700369 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370
371 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700372 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800373 this.method = method;
374 }
375
376 @Override
377 void handleFinished() {
378 super.handleFinished();
379 doShareUnshareVolume(path, method, true);
380 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800381 }
382
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 class ShutdownCallBack extends UnmountCallBack {
384 IMountShutdownObserver observer;
385 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700386 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 this.observer = observer;
388 }
389
390 @Override
391 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700392 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800393 if (observer != null) {
394 try {
395 observer.onShutDownComplete(ret);
396 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700397 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800398 }
399 }
400 }
401 }
402
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400403 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800404 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700405 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800406
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400407 MountServiceHandler(Looper l) {
408 super(l);
409 }
410
Jason parks5af0b912010-11-29 09:05:25 -0600411 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 public void handleMessage(Message msg) {
413 switch (msg.what) {
414 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800416 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
417 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700420 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700421 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700422 mUpdatingStatus = true;
423 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800424 }
425 break;
426 }
427 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700428 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700429 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700430 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800431 int size = mForceUnmounts.size();
432 int sizeArr[] = new int[size];
433 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700434 // Kill processes holding references first
435 ActivityManagerService ams = (ActivityManagerService)
436 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800437 for (int i = 0; i < size; i++) {
438 UnmountCallBack ucb = mForceUnmounts.get(i);
439 String path = ucb.path;
440 boolean done = false;
441 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800442 done = true;
443 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800444 int pids[] = getStorageUsers(path);
445 if (pids == null || pids.length == 0) {
446 done = true;
447 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800448 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800449 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700450 // Confirm if file references have been freed.
451 pids = getStorageUsers(path);
452 if (pids == null || pids.length == 0) {
453 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800454 }
455 }
456 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700457 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
458 // Retry again
459 Slog.i(TAG, "Retrying to kill storage users again");
460 mHandler.sendMessageDelayed(
461 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
462 ucb.retries++),
463 RETRY_UNMOUNT_DELAY);
464 } else {
465 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
466 Slog.i(TAG, "Failed to unmount media inspite of " +
467 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
468 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800469 sizeArr[sizeArrN++] = i;
470 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
471 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800472 }
473 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800474 // Remove already processed elements from list.
475 for (int i = (sizeArrN-1); i >= 0; i--) {
476 mForceUnmounts.remove(sizeArr[i]);
477 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800478 break;
479 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700480 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700481 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800482 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800483 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800484 break;
485 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700486 case H_SYSTEM_READY: {
487 try {
488 handleSystemReady();
489 } catch (Exception ex) {
490 Slog.e(TAG, "Boot-time mount exception", ex);
491 }
492 break;
493 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800494 }
495 }
496 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700497
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700498 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800499
Kenny Root51a573c2012-05-17 13:30:28 -0700500 void waitForAsecScan() {
501 waitForLatch(mAsecsScanned);
502 }
503
San Mehat207e5382010-02-04 20:46:54 -0800504 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700505 waitForLatch(mConnectedSignal);
506 }
507
508 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700509 for (;;) {
510 try {
511 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800512 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700513 } else {
514 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
515 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800516 }
Kenny Root51a573c2012-05-17 13:30:28 -0700517 } catch (InterruptedException e) {
518 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800519 }
San Mehat207e5382010-02-04 20:46:54 -0800520 }
San Mehat1f6301e2010-01-07 22:40:27 -0800521 }
Kenny Root02c87302010-07-01 08:10:18 -0700522
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700523 private void handleSystemReady() {
524 // Snapshot current volume states since it's not safe to call into vold
525 // while holding locks.
526 final HashMap<String, String> snapshot;
527 synchronized (mVolumesLock) {
528 snapshot = new HashMap<String, String>(mVolumeStates);
529 }
530
531 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
532 final String path = entry.getKey();
533 final String state = entry.getValue();
534
535 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
536 int rc = doMountVolume(path);
537 if (rc != StorageResultCode.OperationSucceeded) {
538 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
539 rc));
540 }
541 } else if (state.equals(Environment.MEDIA_SHARED)) {
542 /*
543 * Bootstrap UMS enabled state since vold indicates
544 * the volume is shared (runtime restart while ums enabled)
545 */
546 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
547 VolumeState.Shared);
548 }
549 }
550
551 // Push mounted state for all emulated storage
552 synchronized (mVolumesLock) {
553 for (StorageVolume volume : mVolumes) {
554 if (volume.isEmulated()) {
555 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
556 }
557 }
558 }
559
560 /*
561 * If UMS was connected on boot, send the connected event
562 * now that we're up.
563 */
564 if (mSendUmsConnectedOnBoot) {
565 sendUmsIntent(true);
566 mSendUmsConnectedOnBoot = false;
567 }
568 }
569
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700570 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
571 @Override
572 public void onReceive(Context context, Intent intent) {
573 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
574 if (userId == -1) return;
575 final UserHandle user = new UserHandle(userId);
576
577 final String action = intent.getAction();
578 if (Intent.ACTION_USER_ADDED.equals(action)) {
579 synchronized (mVolumesLock) {
580 createEmulatedVolumeForUserLocked(user);
581 }
582
583 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
584 synchronized (mVolumesLock) {
585 final List<StorageVolume> toRemove = Lists.newArrayList();
586 for (StorageVolume volume : mVolumes) {
587 if (user.equals(volume.getOwner())) {
588 toRemove.add(volume);
589 }
590 }
591 for (StorageVolume volume : toRemove) {
592 removeVolumeLocked(volume);
593 }
594 }
595 }
596 }
597 };
598
599 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
600 @Override
601 public void onReceive(Context context, Intent intent) {
602 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
603 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
604 notifyShareAvailabilityChange(available);
605 }
606 };
607
Svetoslava7452ee2013-03-20 12:06:59 -0700608 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
609 @Override
610 public void onReceive(Context context, Intent intent) {
611 waitForReady();
612 String action = intent.getAction();
613 // Since fstrim will be run on a daily basis we do not expect
614 // fstrim to be too long, so it is not interruptible. We will
615 // implement interruption only in case we see issues.
616 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
617 try {
618 // This method runs on the handler thread,
619 // so it is safe to directly call into vold.
620 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700621 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700622 } catch (NativeDaemonConnectorException ndce) {
623 Slog.e(TAG, "Failed to run fstrim!");
624 }
625 }
626 }
627 };
628
San Mehat4270e1e2010-01-29 05:32:19 -0800629 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
630 final IMountServiceListener mListener;
631
632 MountServiceBinderListener(IMountServiceListener listener) {
633 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700634
San Mehat91c77612010-01-07 10:39:41 -0800635 }
636
San Mehat4270e1e2010-01-29 05:32:19 -0800637 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700638 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700639 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800640 mListeners.remove(this);
641 mListener.asBinder().unlinkToDeath(this, 0);
642 }
643 }
644 }
645
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800646 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800647 // TODO: Add support for multiple share methods
648 if (!method.equals("ums")) {
649 throw new IllegalArgumentException(String.format("Method %s not supported", method));
650 }
651
San Mehat4270e1e2010-01-29 05:32:19 -0800652 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800653 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800654 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700655 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800656 }
San Mehat4270e1e2010-01-29 05:32:19 -0800657 }
658
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700659 private void updatePublicVolumeState(StorageVolume volume, String state) {
660 final String path = volume.getPath();
661 final String oldState;
662 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400663 oldState = mVolumeStates.put(path, state);
664 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700665
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400666 if (state.equals(oldState)) {
667 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
668 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800669 return;
670 }
San Mehatb1043402010-02-05 08:26:50 -0800671
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400672 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700673
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700674 // Tell PackageManager about changes to primary volume state, but only
675 // when not emulated.
676 if (volume.isPrimary() && !volume.isEmulated()) {
677 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
678 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400679
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700680 /*
681 * Some OBBs might have been unmounted when this volume was
682 * unmounted, so send a message to the handler to let it know to
683 * remove those from the list of mounted OBBS.
684 */
685 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
686 OBB_FLUSH_MOUNT_STATE, path));
687 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
688 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400689 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800690 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700691
San Mehat4270e1e2010-01-29 05:32:19 -0800692 synchronized (mListeners) {
693 for (int i = mListeners.size() -1; i >= 0; i--) {
694 MountServiceBinderListener bl = mListeners.get(i);
695 try {
San Mehatb1043402010-02-05 08:26:50 -0800696 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800697 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700698 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800699 mListeners.remove(i);
700 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700701 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800702 }
703 }
704 }
705 }
706
707 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800708 * Callback from NativeDaemonConnector
709 */
710 public void onDaemonConnected() {
711 /*
712 * Since we'll be calling back into the NativeDaemonConnector,
713 * we need to do our work in a new thread.
714 */
Kenny Root51a573c2012-05-17 13:30:28 -0700715 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600716 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800717 public void run() {
718 /**
719 * Determine media state and UMS detection status
720 */
San Mehat4270e1e2010-01-29 05:32:19 -0800721 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800722 final String[] vols = NativeDaemonEvent.filterMessageList(
723 mConnector.executeForList("volume", "list"),
724 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800725 for (String volstr : vols) {
726 String[] tok = volstr.split(" ");
727 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400728 String path = tok[1];
729 String state = Environment.MEDIA_REMOVED;
730
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700731 final StorageVolume volume;
732 synchronized (mVolumesLock) {
733 volume = mVolumesByPath.get(path);
734 }
735
San Mehat4270e1e2010-01-29 05:32:19 -0800736 int st = Integer.parseInt(tok[2]);
737 if (st == VolumeState.NoMedia) {
738 state = Environment.MEDIA_REMOVED;
739 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800740 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800741 } else if (st == VolumeState.Mounted) {
742 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700743 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800744 } else if (st == VolumeState.Shared) {
745 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700746 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800747 } else {
748 throw new Exception(String.format("Unexpected state %d", st));
749 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400750
751 if (state != null) {
752 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700753 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400754 }
San Mehat4270e1e2010-01-29 05:32:19 -0800755 }
756 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700757 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700758 final StorageVolume primary = getPrimaryPhysicalVolume();
759 if (primary != null) {
760 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
761 }
San Mehat4270e1e2010-01-29 05:32:19 -0800762 }
763
San Mehat207e5382010-02-04 20:46:54 -0800764 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600765 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800766 * the hounds!
767 */
Kenny Root51a573c2012-05-17 13:30:28 -0700768 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700769
770 // Let package manager load internal ASECs.
771 mPms.scanAvailableAsecs();
772
773 // Notify people waiting for ASECs to be scanned that it's done.
774 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800775 }
776 }.start();
777 }
778
779 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800780 * Callback from NativeDaemonConnector
781 */
782 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800783 if (DEBUG_EVENTS) {
784 StringBuilder builder = new StringBuilder();
785 builder.append("onEvent::");
786 builder.append(" raw= " + raw);
787 if (cooked != null) {
788 builder.append(" cooked = " );
789 for (String str : cooked) {
790 builder.append(" " + str);
791 }
792 }
San Mehata5078592010-03-25 09:36:54 -0700793 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800794 }
San Mehat4270e1e2010-01-29 05:32:19 -0800795 if (code == VoldResponseCode.VolumeStateChange) {
796 /*
797 * One of the volumes we're managing has changed state.
798 * Format: "NNN Volume <label> <path> state changed
799 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
800 */
801 notifyVolumeStateChange(
802 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
803 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800804 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
805 (code == VoldResponseCode.VolumeDiskRemoved) ||
806 (code == VoldResponseCode.VolumeBadRemoval)) {
807 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
808 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
809 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400810 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800811 final String label = cooked[2];
812 final String path = cooked[3];
813 int major = -1;
814 int minor = -1;
815
816 try {
817 String devComp = cooked[6].substring(1, cooked[6].length() -1);
818 String[] devTok = devComp.split(":");
819 major = Integer.parseInt(devTok[0]);
820 minor = Integer.parseInt(devTok[1]);
821 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700822 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800823 }
824
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700825 final StorageVolume volume;
826 final String state;
827 synchronized (mVolumesLock) {
828 volume = mVolumesByPath.get(path);
829 state = mVolumeStates.get(path);
830 }
831
San Mehat4270e1e2010-01-29 05:32:19 -0800832 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700833 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600834 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800835 public void run() {
836 try {
837 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800838 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700839 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800840 }
841 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700842 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800843 }
844 }
845 }.start();
846 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
847 /*
848 * This event gets trumped if we're already in BAD_REMOVAL state
849 */
850 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
851 return true;
852 }
853 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700854 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700855 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
856 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800857
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700859 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400860 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800861 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700862 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800863 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700864 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200865 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800866
San Mehata5078592010-03-25 09:36:54 -0700867 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700868 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400869 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700870 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700871 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800872 } else {
San Mehata5078592010-03-25 09:36:54 -0700873 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800874 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400875
876 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700877 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400878 }
San Mehat4270e1e2010-01-29 05:32:19 -0800879 } else {
880 return false;
881 }
882
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400883 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800884 }
885
San Mehat207e5382010-02-04 20:46:54 -0800886 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700887 final StorageVolume volume;
888 final String state;
889 synchronized (mVolumesLock) {
890 volume = mVolumesByPath.get(path);
891 state = getVolumeState(path);
892 }
893
894 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800895
Mike Lockwooda5250c92011-05-23 13:44:04 -0400896 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800897
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500898 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700899 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700900 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500901 }
902
San Mehat4270e1e2010-01-29 05:32:19 -0800903 if (newState == VolumeState.Init) {
904 } else if (newState == VolumeState.NoMedia) {
905 // NoMedia is handled via Disk Remove events
906 } else if (newState == VolumeState.Idle) {
907 /*
908 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
909 * if we're in the process of enabling UMS
910 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700911 if (!state.equals(
912 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
913 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800914 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700915 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700916 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400917 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800918 }
919 } else if (newState == VolumeState.Pending) {
920 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700921 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700922 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400923 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800924 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700925 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700926 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400927 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800928 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400929 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800930 } else if (newState == VolumeState.Formatting) {
931 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700932 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800933 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700934 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
935 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800936
San Mehata5078592010-03-25 09:36:54 -0700937 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700938 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400939 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700940 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800941 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700942 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800943 return;
944 } else {
San Mehata5078592010-03-25 09:36:54 -0700945 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800946 }
947
Mike Lockwooda5250c92011-05-23 13:44:04 -0400948 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700949 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800950 }
951 }
952
San Mehat207e5382010-02-04 20:46:54 -0800953 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800954 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800955
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700956 final StorageVolume volume;
957 synchronized (mVolumesLock) {
958 volume = mVolumesByPath.get(path);
959 }
960
San Mehata5078592010-03-25 09:36:54 -0700961 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800962 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800963 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800964 } catch (NativeDaemonConnectorException e) {
965 /*
966 * Mount failed for some reason
967 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400968 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800969 int code = e.getCode();
970 if (code == VoldResponseCode.OpFailedNoMedia) {
971 /*
972 * Attempt to mount but no media inserted
973 */
San Mehatb1043402010-02-05 08:26:50 -0800974 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800975 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700976 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800977 /*
978 * Media is blank or does not contain a supported filesystem
979 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700980 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400981 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800982 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800983 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700984 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800985 /*
986 * Volume consistency check failed
987 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700988 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400989 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800990 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800991 } else {
San Mehatb1043402010-02-05 08:26:50 -0800992 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800993 }
994
995 /*
996 * Send broadcast intent (if required for the failure)
997 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400998 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700999 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001000 }
1001 }
1002
1003 return rc;
1004 }
1005
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001006 /*
1007 * If force is not set, we do not unmount if there are
1008 * processes holding references to the volume about to be unmounted.
1009 * If force is set, all the processes holding references need to be
1010 * killed via the ActivityManager before actually unmounting the volume.
1011 * This might even take a while and might be retried after timed delays
1012 * to make sure we dont end up in an instable state and kill some core
1013 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001014 * If removeEncryption is set, force is implied, and the system will remove any encryption
1015 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001016 */
Ben Komalo13c71972011-09-07 16:35:56 -07001017 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001018 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001019 return VoldResponseCode.OpFailedVolNotMounted;
1020 }
Kenny Rootaa485402010-09-14 14:49:41 -07001021
1022 /*
1023 * Force a GC to make sure AssetManagers in other threads of the
1024 * system_server are cleaned up. We have to do this since AssetManager
1025 * instances are kept as a WeakReference and it's possible we have files
1026 * open on the external storage.
1027 */
1028 Runtime.getRuntime().gc();
1029
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001030 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001031 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001033 final Command cmd = new Command("volume", "unmount", path);
1034 if (removeEncryption) {
1035 cmd.appendArg("force_and_revert");
1036 } else if (force) {
1037 cmd.appendArg("force");
1038 }
1039 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001040 // We unmounted the volume. None of the asec containers are available now.
1041 synchronized (mAsecMountSet) {
1042 mAsecMountSet.clear();
1043 }
San Mehatb1043402010-02-05 08:26:50 -08001044 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001045 } catch (NativeDaemonConnectorException e) {
1046 // Don't worry about mismatch in PackageManager since the
1047 // call back will handle the status changes any way.
1048 int code = e.getCode();
1049 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001050 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001051 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1052 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001053 } else {
San Mehatb1043402010-02-05 08:26:50 -08001054 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001055 }
1056 }
1057 }
1058
1059 private int doFormatVolume(String path) {
1060 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001061 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001062 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001063 } catch (NativeDaemonConnectorException e) {
1064 int code = e.getCode();
1065 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001066 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001067 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001068 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001069 } else {
San Mehatb1043402010-02-05 08:26:50 -08001070 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001071 }
1072 }
1073 }
1074
San Mehatb1043402010-02-05 08:26:50 -08001075 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001076 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001077 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001078 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001079 } catch (NativeDaemonConnectorException ex) {
1080 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1081 return false;
1082 }
San Mehatb1043402010-02-05 08:26:50 -08001083
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001084 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1085 return event.getMessage().endsWith("enabled");
1086 } else {
1087 return false;
San Mehatb1043402010-02-05 08:26:50 -08001088 }
San Mehatb1043402010-02-05 08:26:50 -08001089 }
1090
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001091 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001092 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001093 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001094 for (int i = mListeners.size() -1; i >= 0; i--) {
1095 MountServiceBinderListener bl = mListeners.get(i);
1096 try {
San Mehatb1043402010-02-05 08:26:50 -08001097 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001098 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001099 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001100 mListeners.remove(i);
1101 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001102 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001103 }
1104 }
1105 }
1106
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001107 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001108 sendUmsIntent(avail);
1109 } else {
1110 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001111 }
San Mehat2fe718a2010-03-11 12:01:49 -08001112
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001113 final StorageVolume primary = getPrimaryPhysicalVolume();
1114 if (avail == false && primary != null
1115 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1116 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001117 /*
1118 * USB mass storage disconnected while enabled
1119 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001120 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001121 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001122 public void run() {
1123 try {
1124 int rc;
San Mehata5078592010-03-25 09:36:54 -07001125 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001126 doShareUnshareVolume(path, "ums", false);
1127 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001128 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001129 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1130 path, rc));
1131 }
1132 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001133 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001134 }
1135 }
1136 }.start();
1137 }
San Mehat4270e1e2010-01-29 05:32:19 -08001138 }
1139
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001140 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1141 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1142 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1143 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1144 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001145 }
1146
San Mehat6a965af22010-02-24 17:47:30 -08001147 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001148 mContext.sendBroadcastAsUser(
1149 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1150 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001151 }
1152
San Mehat207e5382010-02-04 20:46:54 -08001153 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001154 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1155 throw new SecurityException(String.format("Requires %s permission", perm));
1156 }
1157 }
1158
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001159 // Storage list XML tags
1160 private static final String TAG_STORAGE_LIST = "StorageList";
1161 private static final String TAG_STORAGE = "storage";
1162
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001163 private void readStorageListLocked() {
1164 mVolumes.clear();
1165 mVolumeStates.clear();
1166
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001167 Resources resources = mContext.getResources();
1168
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001169 int id = com.android.internal.R.xml.storage_list;
1170 XmlResourceParser parser = resources.getXml(id);
1171 AttributeSet attrs = Xml.asAttributeSet(parser);
1172
1173 try {
1174 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1175 while (true) {
1176 XmlUtils.nextElement(parser);
1177
1178 String element = parser.getName();
1179 if (element == null) break;
1180
1181 if (TAG_STORAGE.equals(element)) {
1182 TypedArray a = resources.obtainAttributes(attrs,
1183 com.android.internal.R.styleable.Storage);
1184
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001185 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001186 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001187 int descriptionId = a.getResourceId(
1188 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001189 CharSequence description = a.getText(
1190 com.android.internal.R.styleable.Storage_storageDescription);
1191 boolean primary = a.getBoolean(
1192 com.android.internal.R.styleable.Storage_primary, false);
1193 boolean removable = a.getBoolean(
1194 com.android.internal.R.styleable.Storage_removable, false);
1195 boolean emulated = a.getBoolean(
1196 com.android.internal.R.styleable.Storage_emulated, false);
1197 int mtpReserve = a.getInt(
1198 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001199 boolean allowMassStorage = a.getBoolean(
1200 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001201 // resource parser does not support longs, so XML value is in megabytes
1202 long maxFileSize = a.getInt(
1203 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001204
1205 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1206 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001207 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001208 " allowMassStorage: " + allowMassStorage +
1209 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001210
1211 if (emulated) {
1212 // For devices with emulated storage, we create separate
1213 // volumes for each known user.
1214 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1215 true, mtpReserve, false, maxFileSize, null);
1216
1217 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001218 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001219 createEmulatedVolumeForUserLocked(user.getUserHandle());
1220 }
1221
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001222 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001223 if (path == null || description == null) {
1224 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001225 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001226 final StorageVolume volume = new StorageVolume(new File(path),
1227 descriptionId, primary, removable, emulated, mtpReserve,
1228 allowMassStorage, maxFileSize, null);
1229 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001230
1231 // Until we hear otherwise, treat as unmounted
1232 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001233 }
1234 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001235
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001236 a.recycle();
1237 }
1238 }
1239 } catch (XmlPullParserException e) {
1240 throw new RuntimeException(e);
1241 } catch (IOException e) {
1242 throw new RuntimeException(e);
1243 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001244 // Compute storage ID for each physical volume; emulated storage is
1245 // always 0 when defined.
1246 int index = isExternalStorageEmulated() ? 1 : 0;
1247 for (StorageVolume volume : mVolumes) {
1248 if (!volume.isEmulated()) {
1249 volume.setStorageId(index++);
1250 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001251 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001252 parser.close();
1253 }
1254 }
1255
San Mehat4270e1e2010-01-29 05:32:19 -08001256 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001257 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1258 * using {@link #mEmulatedTemplate} as template.
1259 */
1260 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1261 if (mEmulatedTemplate == null) {
1262 throw new IllegalStateException("Missing emulated volume multi-user template");
1263 }
1264
1265 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1266 final File path = userEnv.getExternalStorageDirectory();
1267 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1268 volume.setStorageId(0);
1269 addVolumeLocked(volume);
1270
1271 if (mSystemReady) {
1272 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1273 } else {
1274 // Place stub status for early callers to find
1275 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1276 }
1277 }
1278
1279 private void addVolumeLocked(StorageVolume volume) {
1280 Slog.d(TAG, "addVolumeLocked() " + volume);
1281 mVolumes.add(volume);
1282 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1283 if (existing != null) {
1284 throw new IllegalStateException(
1285 "Volume at " + volume.getPath() + " already exists: " + existing);
1286 }
1287 }
1288
1289 private void removeVolumeLocked(StorageVolume volume) {
1290 Slog.d(TAG, "removeVolumeLocked() " + volume);
1291 mVolumes.remove(volume);
1292 mVolumesByPath.remove(volume.getPath());
1293 mVolumeStates.remove(volume.getPath());
1294 }
1295
1296 private StorageVolume getPrimaryPhysicalVolume() {
1297 synchronized (mVolumesLock) {
1298 for (StorageVolume volume : mVolumes) {
1299 if (volume.isPrimary() && !volume.isEmulated()) {
1300 return volume;
1301 }
1302 }
1303 }
1304 return null;
1305 }
1306
1307 /**
San Mehat207e5382010-02-04 20:46:54 -08001308 * Constructs a new MountService instance
1309 *
1310 * @param context Binder context for this service
1311 */
1312 public MountService(Context context) {
1313 mContext = context;
1314
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001315 synchronized (mVolumesLock) {
1316 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001317 }
1318
San Mehat207e5382010-02-04 20:46:54 -08001319 // XXX: This will go away soon in favor of IMountServiceObserver
1320 mPms = (PackageManagerService) ServiceManager.getService("package");
1321
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001322 HandlerThread hthread = new HandlerThread(TAG);
1323 hthread.start();
1324 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001325
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001326 // Watch for user changes
1327 final IntentFilter userFilter = new IntentFilter();
1328 userFilter.addAction(Intent.ACTION_USER_ADDED);
1329 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1330 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1331
1332 // Watch for USB changes on primary volume
1333 final StorageVolume primary = getPrimaryPhysicalVolume();
1334 if (primary != null && primary.allowMassStorage()) {
1335 mContext.registerReceiver(
1336 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1337 }
1338
Svetoslava7452ee2013-03-20 12:06:59 -07001339 // Watch for idle maintenance changes
1340 IntentFilter idleMaintenanceFilter = new IntentFilter();
1341 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1342 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1343 idleMaintenanceFilter, null, mHandler);
1344
Kenny Roota02b8b02010-08-05 16:14:17 -07001345 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001346 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001347
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001348 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001349 * Create the connection to vold with a maximum queue of twice the
1350 * amount of containers we'd ever expect to have. This keeps an
1351 * "asec list" from blocking a thread repeatedly.
1352 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001353 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001354
Kenny Root305bcbf2010-09-03 07:56:38 -07001355 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001356 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001357
Kenny Root07714d42011-08-17 17:49:28 -07001358 // Add ourself to the Watchdog monitors if enabled.
1359 if (WATCHDOG_ENABLE) {
1360 Watchdog.getInstance().addMonitor(this);
1361 }
San Mehat207e5382010-02-04 20:46:54 -08001362 }
1363
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001364 public void systemReady() {
1365 mSystemReady = true;
1366 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1367 }
1368
San Mehat207e5382010-02-04 20:46:54 -08001369 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001370 * Exposed API calls below here
1371 */
1372
1373 public void registerListener(IMountServiceListener listener) {
1374 synchronized (mListeners) {
1375 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1376 try {
1377 listener.asBinder().linkToDeath(bl, 0);
1378 mListeners.add(bl);
1379 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001380 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001381 }
1382 }
1383 }
1384
1385 public void unregisterListener(IMountServiceListener listener) {
1386 synchronized (mListeners) {
1387 for(MountServiceBinderListener bl : mListeners) {
1388 if (bl.mListener == listener) {
1389 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001390 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001391 return;
1392 }
1393 }
1394 }
1395 }
1396
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001397 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001398 validatePermission(android.Manifest.permission.SHUTDOWN);
1399
San Mehata5078592010-03-25 09:36:54 -07001400 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001401 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001402 for (String path : mVolumeStates.keySet()) {
1403 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001404
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001405 if (state.equals(Environment.MEDIA_SHARED)) {
1406 /*
1407 * If the media is currently shared, unshare it.
1408 * XXX: This is still dangerous!. We should not
1409 * be rebooting at *all* if UMS is enabled, since
1410 * the UMS host could have dirty FAT cache entries
1411 * yet to flush.
1412 */
1413 setUsbMassStorageEnabled(false);
1414 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1415 /*
1416 * If the media is being checked, then we need to wait for
1417 * it to complete before being able to proceed.
1418 */
1419 // XXX: @hackbod - Should we disable the ANR timer here?
1420 int retries = 30;
1421 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1422 try {
1423 Thread.sleep(1000);
1424 } catch (InterruptedException iex) {
1425 Slog.e(TAG, "Interrupted while waiting for media", iex);
1426 break;
1427 }
1428 state = Environment.getExternalStorageState();
1429 }
1430 if (retries == 0) {
1431 Slog.e(TAG, "Timed out waiting for media to check");
1432 }
San Mehat91c77612010-01-07 10:39:41 -08001433 }
San Mehat91c77612010-01-07 10:39:41 -08001434
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001435 if (state.equals(Environment.MEDIA_MOUNTED)) {
1436 // Post a unmount message.
1437 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1438 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1439 } else if (observer != null) {
1440 /*
1441 * Observer is waiting for onShutDownComplete when we are done.
1442 * Since nothing will be done send notification directly so shutdown
1443 * sequence can continue.
1444 */
1445 try {
1446 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1447 } catch (RemoteException e) {
1448 Slog.w(TAG, "RemoteException when shutting down");
1449 }
1450 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001451 }
San Mehat4270e1e2010-01-29 05:32:19 -08001452 }
1453 }
1454
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001455 private boolean getUmsEnabling() {
1456 synchronized (mListeners) {
1457 return mUmsEnabling;
1458 }
1459 }
1460
1461 private void setUmsEnabling(boolean enable) {
1462 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001463 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001464 }
1465 }
1466
San Mehatb1043402010-02-05 08:26:50 -08001467 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001468 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001469
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001470 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001471 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001472 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001473 synchronized (mListeners) {
1474 return mUmsAvailable;
1475 }
San Mehatb1043402010-02-05 08:26:50 -08001476 }
1477
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001478 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001479 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001480 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001481
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001482 final StorageVolume primary = getPrimaryPhysicalVolume();
1483 if (primary == null) return;
1484
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001485 // TODO: Add support for multiple share methods
1486
1487 /*
1488 * If the volume is mounted and we're enabling then unmount it
1489 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001490 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001491 String vs = getVolumeState(path);
1492 String method = "ums";
1493 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1494 // Override for isUsbMassStorageEnabled()
1495 setUmsEnabling(enable);
1496 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1497 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1498 // Clear override
1499 setUmsEnabling(false);
1500 }
1501 /*
1502 * If we disabled UMS then mount the volume
1503 */
1504 if (!enable) {
1505 doShareUnshareVolume(path, method, enable);
1506 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001507 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001508 " after disabling share method " + method);
1509 /*
1510 * Even though the mount failed, the unshare didn't so don't indicate an error.
1511 * The mountVolume() call will have set the storage state and sent the necessary
1512 * broadcasts.
1513 */
1514 }
1515 }
San Mehatb1043402010-02-05 08:26:50 -08001516 }
1517
1518 public boolean isUsbMassStorageEnabled() {
1519 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001520
1521 final StorageVolume primary = getPrimaryPhysicalVolume();
1522 if (primary != null) {
1523 return doGetVolumeShared(primary.getPath(), "ums");
1524 } else {
1525 return false;
1526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001528
San Mehat7fd0fee2009-12-17 07:12:23 -08001529 /**
1530 * @return state of the volume at the specified mount point
1531 */
San Mehat4270e1e2010-01-29 05:32:19 -08001532 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001533 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001534 String state = mVolumeStates.get(mountPoint);
1535 if (state == null) {
1536 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001537 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1538 state = Environment.MEDIA_REMOVED;
1539 } else {
1540 throw new IllegalArgumentException();
1541 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001542 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001543
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001544 return state;
1545 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001546 }
1547
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001548 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001549 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001550 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001551 }
1552
San Mehat4270e1e2010-01-29 05:32:19 -08001553 public int mountVolume(String path) {
1554 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001555
San Mehat207e5382010-02-04 20:46:54 -08001556 waitForReady();
1557 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559
Ben Komalo13c71972011-09-07 16:35:56 -07001560 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001561 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001562 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001564 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001565 if (DEBUG_UNMOUNT) {
1566 Slog.i(TAG, "Unmounting " + path
1567 + " force = " + force
1568 + " removeEncryption = " + removeEncryption);
1569 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001570 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1571 Environment.MEDIA_REMOVED.equals(volState) ||
1572 Environment.MEDIA_SHARED.equals(volState) ||
1573 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1574 // Media already unmounted or cannot be unmounted.
1575 // TODO return valid return code when adding observer call back.
1576 return;
1577 }
Ben Komalo13c71972011-09-07 16:35:56 -07001578 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001579 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
San Mehat4270e1e2010-01-29 05:32:19 -08001582 public int formatVolume(String path) {
1583 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001584 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001585
San Mehat207e5382010-02-04 20:46:54 -08001586 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001589 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001590 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1591 waitForReady();
1592 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001593 final String[] r = NativeDaemonEvent.filterMessageList(
1594 mConnector.executeForList("storage", "users", path),
1595 VoldResponseCode.StorageUsersListResult);
1596
San Mehatc1b4ce92010-02-16 17:13:03 -08001597 // FMT: <pid> <process name>
1598 int[] data = new int[r.length];
1599 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001600 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001601 try {
1602 data[i] = Integer.parseInt(tok[0]);
1603 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001604 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001605 return new int[0];
1606 }
1607 }
1608 return data;
1609 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001610 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001611 return new int[0];
1612 }
1613 }
1614
San Mehatb1043402010-02-05 08:26:50 -08001615 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001616 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001617 if (primary != null) {
1618 boolean mounted = false;
1619 try {
1620 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001621 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001622 }
1623
1624 if (!mounted) {
1625 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1626 }
San Mehatb1043402010-02-05 08:26:50 -08001627 }
1628 }
1629
San Mehat4270e1e2010-01-29 05:32:19 -08001630 public String[] getSecureContainerList() {
1631 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001632 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001633 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001634
San Mehat4270e1e2010-01-29 05:32:19 -08001635 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001636 return NativeDaemonEvent.filterMessageList(
1637 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001638 } catch (NativeDaemonConnectorException e) {
1639 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 }
San Mehat36972292010-01-06 11:06:32 -08001642
Kenny Root6dceb882012-04-12 14:23:49 -07001643 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1644 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001645 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001646 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001647 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001648
San Mehatb1043402010-02-05 08:26:50 -08001649 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001650 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001651 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1652 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001653 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001654 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001655 }
San Mehata181b212010-02-11 06:50:20 -08001656
1657 if (rc == StorageResultCode.OperationSucceeded) {
1658 synchronized (mAsecMountSet) {
1659 mAsecMountSet.add(id);
1660 }
1661 }
San Mehat4270e1e2010-01-29 05:32:19 -08001662 return rc;
San Mehat36972292010-01-06 11:06:32 -08001663 }
1664
San Mehat4270e1e2010-01-29 05:32:19 -08001665 public int finalizeSecureContainer(String id) {
1666 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001667 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001668
San Mehatb1043402010-02-05 08:26:50 -08001669 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001670 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001671 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001672 /*
1673 * Finalization does a remount, so no need
1674 * to update mAsecMountSet
1675 */
San Mehat4270e1e2010-01-29 05:32:19 -08001676 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001677 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001678 }
San Mehat4270e1e2010-01-29 05:32:19 -08001679 return rc;
San Mehat36972292010-01-06 11:06:32 -08001680 }
1681
Kenny Root6dceb882012-04-12 14:23:49 -07001682 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1683 validatePermission(android.Manifest.permission.ASEC_CREATE);
1684 warnOnNotMounted();
1685
1686 int rc = StorageResultCode.OperationSucceeded;
1687 try {
1688 mConnector.execute("asec", "fixperms", id, gid, filename);
1689 /*
1690 * Fix permissions does a remount, so no need to update
1691 * mAsecMountSet
1692 */
1693 } catch (NativeDaemonConnectorException e) {
1694 rc = StorageResultCode.OperationFailedInternalError;
1695 }
1696 return rc;
1697 }
1698
San Mehatd9709982010-02-18 11:43:03 -08001699 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001700 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001701 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001702 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001703
Kenny Rootaa485402010-09-14 14:49:41 -07001704 /*
1705 * Force a GC to make sure AssetManagers in other threads of the
1706 * system_server are cleaned up. We have to do this since AssetManager
1707 * instances are kept as a WeakReference and it's possible we have files
1708 * open on the external storage.
1709 */
1710 Runtime.getRuntime().gc();
1711
San Mehatb1043402010-02-05 08:26:50 -08001712 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001713 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001714 final Command cmd = new Command("asec", "destroy", id);
1715 if (force) {
1716 cmd.appendArg("force");
1717 }
1718 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001719 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001720 int code = e.getCode();
1721 if (code == VoldResponseCode.OpFailedStorageBusy) {
1722 rc = StorageResultCode.OperationFailedStorageBusy;
1723 } else {
1724 rc = StorageResultCode.OperationFailedInternalError;
1725 }
San Mehat02735bc2010-01-26 15:18:08 -08001726 }
San Mehata181b212010-02-11 06:50:20 -08001727
1728 if (rc == StorageResultCode.OperationSucceeded) {
1729 synchronized (mAsecMountSet) {
1730 if (mAsecMountSet.contains(id)) {
1731 mAsecMountSet.remove(id);
1732 }
1733 }
1734 }
1735
San Mehat4270e1e2010-01-29 05:32:19 -08001736 return rc;
San Mehat36972292010-01-06 11:06:32 -08001737 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001738
San Mehat4270e1e2010-01-29 05:32:19 -08001739 public int mountSecureContainer(String id, String key, int ownerUid) {
1740 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001741 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001742 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001743
San Mehata181b212010-02-11 06:50:20 -08001744 synchronized (mAsecMountSet) {
1745 if (mAsecMountSet.contains(id)) {
1746 return StorageResultCode.OperationFailedStorageMounted;
1747 }
1748 }
1749
San Mehatb1043402010-02-05 08:26:50 -08001750 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001751 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001752 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001753 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001754 int code = e.getCode();
1755 if (code != VoldResponseCode.OpFailedStorageBusy) {
1756 rc = StorageResultCode.OperationFailedInternalError;
1757 }
San Mehat02735bc2010-01-26 15:18:08 -08001758 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001759
1760 if (rc == StorageResultCode.OperationSucceeded) {
1761 synchronized (mAsecMountSet) {
1762 mAsecMountSet.add(id);
1763 }
1764 }
San Mehat4270e1e2010-01-29 05:32:19 -08001765 return rc;
San Mehat36972292010-01-06 11:06:32 -08001766 }
1767
San Mehatd9709982010-02-18 11:43:03 -08001768 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001769 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001770 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001771 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001772
San Mehat6cdd9c02010-02-09 14:45:20 -08001773 synchronized (mAsecMountSet) {
1774 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001775 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001776 }
1777 }
1778
Kenny Rootaa485402010-09-14 14:49:41 -07001779 /*
1780 * Force a GC to make sure AssetManagers in other threads of the
1781 * system_server are cleaned up. We have to do this since AssetManager
1782 * instances are kept as a WeakReference and it's possible we have files
1783 * open on the external storage.
1784 */
1785 Runtime.getRuntime().gc();
1786
San Mehatb1043402010-02-05 08:26:50 -08001787 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001788 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001789 final Command cmd = new Command("asec", "unmount", id);
1790 if (force) {
1791 cmd.appendArg("force");
1792 }
1793 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001794 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001795 int code = e.getCode();
1796 if (code == VoldResponseCode.OpFailedStorageBusy) {
1797 rc = StorageResultCode.OperationFailedStorageBusy;
1798 } else {
1799 rc = StorageResultCode.OperationFailedInternalError;
1800 }
San Mehat02735bc2010-01-26 15:18:08 -08001801 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001802
1803 if (rc == StorageResultCode.OperationSucceeded) {
1804 synchronized (mAsecMountSet) {
1805 mAsecMountSet.remove(id);
1806 }
1807 }
San Mehat4270e1e2010-01-29 05:32:19 -08001808 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001809 }
1810
San Mehat6cdd9c02010-02-09 14:45:20 -08001811 public boolean isSecureContainerMounted(String id) {
1812 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1813 waitForReady();
1814 warnOnNotMounted();
1815
1816 synchronized (mAsecMountSet) {
1817 return mAsecMountSet.contains(id);
1818 }
1819 }
1820
San Mehat4270e1e2010-01-29 05:32:19 -08001821 public int renameSecureContainer(String oldId, String newId) {
1822 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001823 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001824 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001825
San Mehata181b212010-02-11 06:50:20 -08001826 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001827 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001828 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001829 * changed while active, we must ensure both ids are not currently mounted.
1830 */
1831 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001832 return StorageResultCode.OperationFailedStorageMounted;
1833 }
1834 }
1835
San Mehatb1043402010-02-05 08:26:50 -08001836 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001837 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001838 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001839 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001840 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001841 }
San Mehata181b212010-02-11 06:50:20 -08001842
San Mehat4270e1e2010-01-29 05:32:19 -08001843 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001844 }
1845
San Mehat4270e1e2010-01-29 05:32:19 -08001846 public String getSecureContainerPath(String id) {
1847 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001848 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001849 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001850
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001851 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001852 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001853 event = mConnector.execute("asec", "path", id);
1854 event.checkCode(VoldResponseCode.AsecPathResult);
1855 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001856 } catch (NativeDaemonConnectorException e) {
1857 int code = e.getCode();
1858 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001859 Slog.i(TAG, String.format("Container '%s' not found", id));
1860 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001861 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001862 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001863 }
1864 }
San Mehat22dd86e2010-01-12 12:21:18 -08001865 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001866
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001867 public String getSecureContainerFilesystemPath(String id) {
1868 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1869 waitForReady();
1870 warnOnNotMounted();
1871
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001872 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001873 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001874 event = mConnector.execute("asec", "fspath", id);
1875 event.checkCode(VoldResponseCode.AsecPathResult);
1876 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001877 } catch (NativeDaemonConnectorException e) {
1878 int code = e.getCode();
1879 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1880 Slog.i(TAG, String.format("Container '%s' not found", id));
1881 return null;
1882 } else {
1883 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1884 }
1885 }
1886 }
1887
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001888 public void finishMediaUpdate() {
1889 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1890 }
Kenny Root02c87302010-07-01 08:10:18 -07001891
Kenny Roota02b8b02010-08-05 16:14:17 -07001892 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1893 if (callerUid == android.os.Process.SYSTEM_UID) {
1894 return true;
1895 }
1896
Kenny Root02c87302010-07-01 08:10:18 -07001897 if (packageName == null) {
1898 return false;
1899 }
1900
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001901 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001902
1903 if (DEBUG_OBB) {
1904 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1905 packageUid + ", callerUid = " + callerUid);
1906 }
1907
1908 return callerUid == packageUid;
1909 }
1910
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001911 public String getMountedObbPath(String rawPath) {
1912 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001913
Kenny Root02c87302010-07-01 08:10:18 -07001914 waitForReady();
1915 warnOnNotMounted();
1916
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001917 final ObbState state;
1918 synchronized (mObbPathToStateMap) {
1919 state = mObbPathToStateMap.get(rawPath);
1920 }
1921 if (state == null) {
1922 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1923 return null;
1924 }
1925
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001926 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001927 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001928 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001929 event.checkCode(VoldResponseCode.AsecPathResult);
1930 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001931 } catch (NativeDaemonConnectorException e) {
1932 int code = e.getCode();
1933 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001934 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001935 } else {
1936 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1937 }
1938 }
1939 }
1940
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001941 @Override
1942 public boolean isObbMounted(String rawPath) {
1943 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001944 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001945 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001946 }
Kenny Root02c87302010-07-01 08:10:18 -07001947 }
1948
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001949 @Override
1950 public void mountObb(
1951 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1952 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1953 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1954 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001955
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001956 final int callingUid = Binder.getCallingUid();
1957 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1958 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001959 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1960
1961 if (DEBUG_OBB)
1962 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001963 }
1964
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001965 @Override
1966 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1967 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1968
1969 final ObbState existingState;
1970 synchronized (mObbPathToStateMap) {
1971 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001972 }
1973
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001974 if (existingState != null) {
1975 // TODO: separate state object from request data
1976 final int callingUid = Binder.getCallingUid();
1977 final ObbState newState = new ObbState(
1978 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1979 final ObbAction action = new UnmountObbAction(newState, force);
1980 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001981
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001982 if (DEBUG_OBB)
1983 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1984 } else {
1985 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1986 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001987 }
1988
Ben Komalo444eca22011-09-01 15:17:44 -07001989 @Override
1990 public int getEncryptionState() {
1991 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1992 "no permission to access the crypt keeper");
1993
1994 waitForReady();
1995
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001996 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001997 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001998 event = mConnector.execute("cryptfs", "cryptocomplete");
1999 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002000 } catch (NumberFormatException e) {
2001 // Bad result - unexpected.
2002 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2003 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2004 } catch (NativeDaemonConnectorException e) {
2005 // Something bad happened.
2006 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2007 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2008 }
2009 }
2010
2011 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002012 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002013 if (TextUtils.isEmpty(password)) {
2014 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002015 }
2016
Jason parks8888c592011-01-20 22:46:41 -06002017 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2018 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002019
2020 waitForReady();
2021
2022 if (DEBUG_EVENTS) {
2023 Slog.i(TAG, "decrypting storage...");
2024 }
2025
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002026 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002027 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002028 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002029
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002030 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002031 if (code == 0) {
2032 // Decrypt was successful. Post a delayed message before restarting in order
2033 // to let the UI to clear itself
2034 mHandler.postDelayed(new Runnable() {
2035 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002036 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002037 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002038 } catch (NativeDaemonConnectorException e) {
2039 Slog.e(TAG, "problem executing in background", e);
2040 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002041 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002042 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002043 }
2044
2045 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002046 } catch (NativeDaemonConnectorException e) {
2047 // Decryption failed
2048 return e.getCode();
2049 }
Jason parks5af0b912010-11-29 09:05:25 -06002050 }
2051
Jason parks56aa5322011-01-07 09:01:15 -06002052 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002053 if (TextUtils.isEmpty(password)) {
2054 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002055 }
2056
Jason parks8888c592011-01-20 22:46:41 -06002057 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2058 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002059
2060 waitForReady();
2061
2062 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002063 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002064 }
2065
2066 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002067 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002068 } catch (NativeDaemonConnectorException e) {
2069 // Encryption failed
2070 return e.getCode();
2071 }
2072
2073 return 0;
2074 }
2075
Jason parksf7b3cd42011-01-27 09:28:25 -06002076 public int changeEncryptionPassword(String password) {
2077 if (TextUtils.isEmpty(password)) {
2078 throw new IllegalArgumentException("password cannot be empty");
2079 }
2080
2081 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2082 "no permission to access the crypt keeper");
2083
2084 waitForReady();
2085
2086 if (DEBUG_EVENTS) {
2087 Slog.i(TAG, "changing encryption password...");
2088 }
2089
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002090 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002091 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002092 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002093 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002094 } catch (NativeDaemonConnectorException e) {
2095 // Encryption failed
2096 return e.getCode();
2097 }
2098 }
2099
Christopher Tate32418be2011-10-10 13:51:12 -07002100 /**
2101 * Validate a user-supplied password string with cryptfs
2102 */
2103 @Override
2104 public int verifyEncryptionPassword(String password) throws RemoteException {
2105 // Only the system process is permitted to validate passwords
2106 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2107 throw new SecurityException("no permission to access the crypt keeper");
2108 }
2109
2110 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2111 "no permission to access the crypt keeper");
2112
2113 if (TextUtils.isEmpty(password)) {
2114 throw new IllegalArgumentException("password cannot be empty");
2115 }
2116
2117 waitForReady();
2118
2119 if (DEBUG_EVENTS) {
2120 Slog.i(TAG, "validating encryption password...");
2121 }
2122
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002123 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002124 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002125 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002126 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2127 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002128 } catch (NativeDaemonConnectorException e) {
2129 // Encryption failed
2130 return e.getCode();
2131 }
2132 }
2133
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002134 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002135 public int mkdirs(String callingPkg, String appPath) {
2136 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2137 final UserEnvironment userEnv = new UserEnvironment(userId);
2138
2139 // Validate that reported package name belongs to caller
2140 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2141 Context.APP_OPS_SERVICE);
2142 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2143
2144 try {
2145 appPath = new File(appPath).getCanonicalPath();
2146 } catch (IOException e) {
2147 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2148 return -1;
2149 }
2150
Jeff Sharkey5786a272013-10-02 12:50:34 -07002151 if (!appPath.endsWith("/")) {
2152 appPath = appPath + "/";
2153 }
2154
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002155 // Try translating the app path into a vold path, but require that it
2156 // belong to the calling package.
2157 String voldPath = maybeTranslatePathForVold(appPath,
2158 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2159 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2160 if (voldPath != null) {
2161 try {
2162 mConnector.execute("volume", "mkdirs", voldPath);
2163 return 0;
2164 } catch (NativeDaemonConnectorException e) {
2165 return e.getCode();
2166 }
2167 }
2168
2169 voldPath = maybeTranslatePathForVold(appPath,
2170 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2171 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2172 if (voldPath != null) {
2173 try {
2174 mConnector.execute("volume", "mkdirs", voldPath);
2175 return 0;
2176 } catch (NativeDaemonConnectorException e) {
2177 return e.getCode();
2178 }
2179 }
2180
2181 throw new SecurityException("Invalid mkdirs path: " + appPath);
2182 }
2183
2184 /**
2185 * Translate the given path from an app-visible path to a vold-visible path,
2186 * but only if it's under the given whitelisted paths.
2187 *
2188 * @param path a canonicalized app-visible path.
2189 * @param appPaths list of app-visible paths that are allowed.
2190 * @param voldPaths list of vold-visible paths directly corresponding to the
2191 * allowed app-visible paths argument.
2192 * @return a vold-visible path representing the original path, or
2193 * {@code null} if the given path didn't have an app-to-vold
2194 * mapping.
2195 */
2196 @VisibleForTesting
2197 public static String maybeTranslatePathForVold(
2198 String path, File[] appPaths, File[] voldPaths) {
2199 if (appPaths.length != voldPaths.length) {
2200 throw new IllegalStateException("Paths must be 1:1 mapping");
2201 }
2202
2203 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002204 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002205 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002206 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002207 .getAbsolutePath();
2208 if (!path.endsWith("/")) {
2209 path = path + "/";
2210 }
2211 return path;
2212 }
2213 }
2214 return null;
2215 }
2216
2217 @Override
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002218 public StorageVolume[] getVolumeList() {
2219 final int callingUserId = UserHandle.getCallingUserId();
2220 final boolean accessAll = (mContext.checkPermission(
2221 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2222 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2223
2224 synchronized (mVolumesLock) {
2225 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2226 for (StorageVolume volume : mVolumes) {
2227 final UserHandle owner = volume.getOwner();
2228 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2229 if (accessAll || ownerMatch) {
2230 filtered.add(volume);
2231 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002232 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002233 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002234 }
2235 }
2236
Kenny Rootaf9d6672010-10-08 09:21:39 -07002237 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2238 final IBinder binder = obbState.getBinder();
2239 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002240
Kenny Rootaf9d6672010-10-08 09:21:39 -07002241 if (obbStates == null) {
2242 obbStates = new ArrayList<ObbState>();
2243 mObbMounts.put(binder, obbStates);
2244 } else {
2245 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002246 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002247 throw new IllegalStateException("Attempt to add ObbState twice. "
2248 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002249 }
2250 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002251 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002252
2253 obbStates.add(obbState);
2254 try {
2255 obbState.link();
2256 } catch (RemoteException e) {
2257 /*
2258 * The binder died before we could link it, so clean up our state
2259 * and return failure.
2260 */
2261 obbStates.remove(obbState);
2262 if (obbStates.isEmpty()) {
2263 mObbMounts.remove(binder);
2264 }
2265
2266 // Rethrow the error so mountObb can get it
2267 throw e;
2268 }
2269
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002270 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002271 }
2272
Kenny Rootaf9d6672010-10-08 09:21:39 -07002273 private void removeObbStateLocked(ObbState obbState) {
2274 final IBinder binder = obbState.getBinder();
2275 final List<ObbState> obbStates = mObbMounts.get(binder);
2276 if (obbStates != null) {
2277 if (obbStates.remove(obbState)) {
2278 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002279 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002280 if (obbStates.isEmpty()) {
2281 mObbMounts.remove(binder);
2282 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002283 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002284
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002285 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002286 }
2287
Kenny Roota02b8b02010-08-05 16:14:17 -07002288 private class ObbActionHandler extends Handler {
2289 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002290 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002291
2292 ObbActionHandler(Looper l) {
2293 super(l);
2294 }
2295
2296 @Override
2297 public void handleMessage(Message msg) {
2298 switch (msg.what) {
2299 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002300 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002301
2302 if (DEBUG_OBB)
2303 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2304
2305 // If a bind was already initiated we don't really
2306 // need to do anything. The pending install
2307 // will be processed later on.
2308 if (!mBound) {
2309 // If this is the only one pending we might
2310 // have to bind to the service again.
2311 if (!connectToService()) {
2312 Slog.e(TAG, "Failed to bind to media container service");
2313 action.handleError();
2314 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002315 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002316 }
Kenny Root735de3b2010-09-30 14:11:39 -07002317
Kenny Root735de3b2010-09-30 14:11:39 -07002318 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002319 break;
2320 }
2321 case OBB_MCS_BOUND: {
2322 if (DEBUG_OBB)
2323 Slog.i(TAG, "OBB_MCS_BOUND");
2324 if (msg.obj != null) {
2325 mContainerService = (IMediaContainerService) msg.obj;
2326 }
2327 if (mContainerService == null) {
2328 // Something seriously wrong. Bail out
2329 Slog.e(TAG, "Cannot bind to media container service");
2330 for (ObbAction action : mActions) {
2331 // Indicate service bind error
2332 action.handleError();
2333 }
2334 mActions.clear();
2335 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002336 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002337 if (action != null) {
2338 action.execute(this);
2339 }
2340 } else {
2341 // Should never happen ideally.
2342 Slog.w(TAG, "Empty queue");
2343 }
2344 break;
2345 }
2346 case OBB_MCS_RECONNECT: {
2347 if (DEBUG_OBB)
2348 Slog.i(TAG, "OBB_MCS_RECONNECT");
2349 if (mActions.size() > 0) {
2350 if (mBound) {
2351 disconnectService();
2352 }
2353 if (!connectToService()) {
2354 Slog.e(TAG, "Failed to bind to media container service");
2355 for (ObbAction action : mActions) {
2356 // Indicate service bind error
2357 action.handleError();
2358 }
2359 mActions.clear();
2360 }
2361 }
2362 break;
2363 }
2364 case OBB_MCS_UNBIND: {
2365 if (DEBUG_OBB)
2366 Slog.i(TAG, "OBB_MCS_UNBIND");
2367
2368 // Delete pending install
2369 if (mActions.size() > 0) {
2370 mActions.remove(0);
2371 }
2372 if (mActions.size() == 0) {
2373 if (mBound) {
2374 disconnectService();
2375 }
2376 } else {
2377 // There are more pending requests in queue.
2378 // Just post MCS_BOUND message to trigger processing
2379 // of next pending install.
2380 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2381 }
2382 break;
2383 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002384 case OBB_FLUSH_MOUNT_STATE: {
2385 final String path = (String) msg.obj;
2386
2387 if (DEBUG_OBB)
2388 Slog.i(TAG, "Flushing all OBB state for path " + path);
2389
2390 synchronized (mObbMounts) {
2391 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2392
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002393 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002394 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002396
2397 /*
2398 * If this entry's source file is in the volume path
2399 * that got unmounted, remove it because it's no
2400 * longer valid.
2401 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002402 if (state.canonicalPath.startsWith(path)) {
2403 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002404 }
2405 }
2406
2407 for (final ObbState obbState : obbStatesToRemove) {
2408 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002409 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002410
2411 removeObbStateLocked(obbState);
2412
2413 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002414 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002415 OnObbStateChangeListener.UNMOUNTED);
2416 } catch (RemoteException e) {
2417 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002418 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002419 }
2420 }
2421 }
2422 break;
2423 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002424 }
2425 }
2426
2427 private boolean connectToService() {
2428 if (DEBUG_OBB)
2429 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2430
2431 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2432 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2433 mBound = true;
2434 return true;
2435 }
2436 return false;
2437 }
2438
2439 private void disconnectService() {
2440 mContainerService = null;
2441 mBound = false;
2442 mContext.unbindService(mDefContainerConn);
2443 }
2444 }
2445
2446 abstract class ObbAction {
2447 private static final int MAX_RETRIES = 3;
2448 private int mRetries;
2449
2450 ObbState mObbState;
2451
2452 ObbAction(ObbState obbState) {
2453 mObbState = obbState;
2454 }
2455
2456 public void execute(ObbActionHandler handler) {
2457 try {
2458 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002459 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002460 mRetries++;
2461 if (mRetries > MAX_RETRIES) {
2462 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002463 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002464 handleError();
2465 return;
2466 } else {
2467 handleExecute();
2468 if (DEBUG_OBB)
2469 Slog.i(TAG, "Posting install MCS_UNBIND");
2470 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2471 }
2472 } catch (RemoteException e) {
2473 if (DEBUG_OBB)
2474 Slog.i(TAG, "Posting install MCS_RECONNECT");
2475 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2476 } catch (Exception e) {
2477 if (DEBUG_OBB)
2478 Slog.d(TAG, "Error handling OBB action", e);
2479 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002480 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002481 }
2482 }
2483
Kenny Root05105f72010-09-22 17:29:43 -07002484 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002485 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002486
2487 protected ObbInfo getObbInfo() throws IOException {
2488 ObbInfo obbInfo;
2489 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002490 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002491 } catch (RemoteException e) {
2492 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002493 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002494 obbInfo = null;
2495 }
2496 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002497 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002498 }
2499 return obbInfo;
2500 }
2501
Kenny Rootaf9d6672010-10-08 09:21:39 -07002502 protected void sendNewStatusOrIgnore(int status) {
2503 if (mObbState == null || mObbState.token == null) {
2504 return;
2505 }
2506
Kenny Root38cf8862010-09-26 14:18:51 -07002507 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002508 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002509 } catch (RemoteException e) {
2510 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2511 }
2512 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002513 }
2514
2515 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002516 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002517 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002518
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002519 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002520 super(obbState);
2521 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002522 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002523 }
2524
Jason parks5af0b912010-11-29 09:05:25 -06002525 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002526 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002527 waitForReady();
2528 warnOnNotMounted();
2529
Kenny Root38cf8862010-09-26 14:18:51 -07002530 final ObbInfo obbInfo = getObbInfo();
2531
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002532 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002533 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2534 + " which is owned by " + obbInfo.packageName);
2535 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2536 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002537 }
2538
Kenny Rootaf9d6672010-10-08 09:21:39 -07002539 final boolean isMounted;
2540 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002542 }
2543 if (isMounted) {
2544 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2545 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2546 return;
2547 }
2548
Kenny Rootaf9d6672010-10-08 09:21:39 -07002549 final String hashedKey;
2550 if (mKey == null) {
2551 hashedKey = "none";
2552 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002553 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002554 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2555
2556 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2557 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2558 SecretKey key = factory.generateSecret(ks);
2559 BigInteger bi = new BigInteger(key.getEncoded());
2560 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002561 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002562 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2563 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2564 return;
2565 } catch (InvalidKeySpecException e) {
2566 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2567 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002568 return;
2569 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002570 }
Kenny Root38cf8862010-09-26 14:18:51 -07002571
Kenny Rootaf9d6672010-10-08 09:21:39 -07002572 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002573 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002574 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2575 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 } catch (NativeDaemonConnectorException e) {
2577 int code = e.getCode();
2578 if (code != VoldResponseCode.OpFailedStorageBusy) {
2579 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002580 }
2581 }
2582
Kenny Rootaf9d6672010-10-08 09:21:39 -07002583 if (rc == StorageResultCode.OperationSucceeded) {
2584 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002585 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002586
2587 synchronized (mObbMounts) {
2588 addObbStateLocked(mObbState);
2589 }
2590
2591 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002592 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002593 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002594
Kenny Rootaf9d6672010-10-08 09:21:39 -07002595 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002596 }
2597 }
2598
Jason parks5af0b912010-11-29 09:05:25 -06002599 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002600 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002601 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002602 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002603
2604 @Override
2605 public String toString() {
2606 StringBuilder sb = new StringBuilder();
2607 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002608 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002609 sb.append('}');
2610 return sb.toString();
2611 }
2612 }
2613
2614 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002615 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002616
2617 UnmountObbAction(ObbState obbState, boolean force) {
2618 super(obbState);
2619 mForceUnmount = force;
2620 }
2621
Jason parks5af0b912010-11-29 09:05:25 -06002622 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002623 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002624 waitForReady();
2625 warnOnNotMounted();
2626
Kenny Root38cf8862010-09-26 14:18:51 -07002627 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002628
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002629 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002630 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002631 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002632 }
Kenny Root38cf8862010-09-26 14:18:51 -07002633
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002634 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002635 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2636 return;
2637 }
2638
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002639 if (existingState.ownerGid != mObbState.ownerGid) {
2640 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2641 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002642 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2643 return;
2644 }
2645
Kenny Rootaf9d6672010-10-08 09:21:39 -07002646 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002647 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002648 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002649 if (mForceUnmount) {
2650 cmd.appendArg("force");
2651 }
2652 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002653 } catch (NativeDaemonConnectorException e) {
2654 int code = e.getCode();
2655 if (code == VoldResponseCode.OpFailedStorageBusy) {
2656 rc = StorageResultCode.OperationFailedStorageBusy;
2657 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2658 // If it's not mounted then we've already won.
2659 rc = StorageResultCode.OperationSucceeded;
2660 } else {
2661 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002662 }
2663 }
2664
Kenny Rootaf9d6672010-10-08 09:21:39 -07002665 if (rc == StorageResultCode.OperationSucceeded) {
2666 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002667 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002668 }
2669
Kenny Rootaf9d6672010-10-08 09:21:39 -07002670 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002671 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002672 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002673 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002674 }
2675 }
2676
Jason parks5af0b912010-11-29 09:05:25 -06002677 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002678 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002679 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002680 }
2681
2682 @Override
2683 public String toString() {
2684 StringBuilder sb = new StringBuilder();
2685 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002686 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002687 sb.append(",force=");
2688 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002689 sb.append('}');
2690 return sb.toString();
2691 }
Kenny Root02c87302010-07-01 08:10:18 -07002692 }
Kenny Root38cf8862010-09-26 14:18:51 -07002693
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002694 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002695 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2696 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002697 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002698
2699 // Only adjust paths when storage is emulated
2700 if (!Environment.isExternalStorageEmulated()) {
2701 return canonicalPath;
2702 }
2703
2704 String path = canonicalPath.toString();
2705
2706 // First trim off any external storage prefix
2707 final UserEnvironment userEnv = new UserEnvironment(userId);
2708
2709 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002710 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002711 // /storage/emulated_legacy
2712 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002713 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002714
2715 if (path.startsWith(externalPath)) {
2716 path = path.substring(externalPath.length() + 1);
2717 } else if (path.startsWith(legacyExternalPath)) {
2718 path = path.substring(legacyExternalPath.length() + 1);
2719 } else {
2720 return canonicalPath;
2721 }
2722
2723 // Handle special OBB paths on emulated storage
2724 final String obbPath = "Android/obb";
2725 if (path.startsWith(obbPath)) {
2726 path = path.substring(obbPath.length() + 1);
2727
2728 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002729 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002730 } else {
2731 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002732 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2733 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002734 }
2735 }
2736
2737 // Handle normal external storage paths
2738 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002739 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002740 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002741 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002742 }
2743 }
2744
Kenny Root38cf8862010-09-26 14:18:51 -07002745 @Override
2746 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2747 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2748 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2749 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2750 + " without permission " + android.Manifest.permission.DUMP);
2751 return;
2752 }
2753
Kenny Root38cf8862010-09-26 14:18:51 -07002754 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002755 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002756
Kenny Rootaf9d6672010-10-08 09:21:39 -07002757 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2758 while (binders.hasNext()) {
2759 Entry<IBinder, List<ObbState>> e = binders.next();
2760 pw.print(" Key="); pw.println(e.getKey().toString());
2761 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002762 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002763 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002764 }
2765 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002766
2767 pw.println("");
2768 pw.println(" mObbPathToStateMap:");
2769 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2770 while (maps.hasNext()) {
2771 final Entry<String, ObbState> e = maps.next();
2772 pw.print(" "); pw.print(e.getKey());
2773 pw.print(" -> "); pw.println(e.getValue().toString());
2774 }
Kenny Root38cf8862010-09-26 14:18:51 -07002775 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002776
2777 pw.println("");
2778
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002779 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002780 pw.println(" mVolumes:");
2781
2782 final int N = mVolumes.size();
2783 for (int i = 0; i < N; i++) {
2784 final StorageVolume v = mVolumes.get(i);
2785 pw.print(" ");
2786 pw.println(v.toString());
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07002787 pw.println(" state=" + mVolumeStates.get(v.getPath()));
Kenny Root4161f9b2011-07-13 09:48:33 -07002788 }
2789 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002790
2791 pw.println();
2792 pw.println(" mConnection:");
2793 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002796 /** {@inheritDoc} */
2797 public void monitor() {
2798 if (mConnector != null) {
2799 mConnector.monitor();
2800 }
2801 }
2802}