blob: 83739f55e000361f4a6acea7d4c33acb0a7864ef [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e212012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070040import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070041import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080043import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080044import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080045import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070046import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070049import android.os.storage.IMountService;
50import android.os.storage.IMountServiceListener;
51import android.os.storage.IMountShutdownObserver;
52import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070053import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070054import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070055import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060056import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070058import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.Xml;
60
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080061import com.android.internal.annotations.GuardedBy;
62import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070063import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070064import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070065import com.android.internal.util.XmlUtils;
66import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070067import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070068import com.android.server.am.ActivityManagerService;
69import com.android.server.pm.PackageManagerService;
70import com.android.server.pm.UserManagerService;
71import com.google.android.collect.Lists;
72import com.google.android.collect.Maps;
73
Mike Lockwood2f6a3882011-05-09 19:08:06 -070074import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070075
Jeff Sharkeyb049e212012-09-07 23:16:01 -070076import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070078import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070080import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070081import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070082import java.security.spec.InvalidKeySpecException;
83import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080084import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070085import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080086import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070087import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070088import java.util.LinkedList;
89import java.util.List;
90import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070091import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070092import java.util.concurrent.CountDownLatch;
93import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Kenny Root3b1abba2010-10-13 15:00:07 -070095import javax.crypto.SecretKey;
96import javax.crypto.SecretKeyFactory;
97import javax.crypto.spec.PBEKeySpec;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099/**
San Mehatb1043402010-02-05 08:26:50 -0800100 * MountService implements back-end services for platform storage
101 * management.
102 * @hide - Applications should use android.os.storage.StorageManager
103 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700105class MountService extends IMountService.Stub
106 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600107
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700108 // TODO: listen for user creation/deletion
109
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800110 private static final boolean LOCAL_LOGD = false;
111 private static final boolean DEBUG_UNMOUNT = false;
112 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800113 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700114
Kenny Root07714d42011-08-17 17:49:28 -0700115 // Disable this since it messes up long-running cryptfs operations.
116 private static final boolean WATCHDOG_ENABLE = false;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "MountService";
119
Kenny Root305bcbf2010-09-03 07:56:38 -0700120 private static final String VOLD_TAG = "VoldConnector";
121
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700122 /** Maximum number of ASEC containers allowed to be mounted. */
123 private static final int MAX_CONTAINERS = 250;
124
San Mehat4270e1e2010-01-29 05:32:19 -0800125 /*
126 * Internal vold volume state constants
127 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800128 class VolumeState {
129 public static final int Init = -1;
130 public static final int NoMedia = 0;
131 public static final int Idle = 1;
132 public static final int Pending = 2;
133 public static final int Checking = 3;
134 public static final int Mounted = 4;
135 public static final int Unmounting = 5;
136 public static final int Formatting = 6;
137 public static final int Shared = 7;
138 public static final int SharedMnt = 8;
139 }
140
San Mehat4270e1e2010-01-29 05:32:19 -0800141 /*
142 * Internal vold response code constants
143 */
San Mehat22dd86e2010-01-12 12:21:18 -0800144 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800145 /*
146 * 100 series - Requestion action was initiated; expect another reply
147 * before proceeding with a new command.
148 */
San Mehat22dd86e2010-01-12 12:21:18 -0800149 public static final int VolumeListResult = 110;
150 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800151 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800152
San Mehat4270e1e2010-01-29 05:32:19 -0800153 /*
154 * 200 series - Requestion action has been successfully completed.
155 */
156 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800157 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800158 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800159
San Mehat4270e1e2010-01-29 05:32:19 -0800160 /*
161 * 400 series - Command was accepted, but the requested action
162 * did not take place.
163 */
164 public static final int OpFailedNoMedia = 401;
165 public static final int OpFailedMediaBlank = 402;
166 public static final int OpFailedMediaCorrupt = 403;
167 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800168 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700169 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800170
171 /*
172 * 600 series - Unsolicited broadcasts.
173 */
San Mehat22dd86e2010-01-12 12:21:18 -0800174 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int VolumeDiskInserted = 630;
176 public static final int VolumeDiskRemoved = 631;
177 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700178
179 /*
180 * 700 series - fstrim
181 */
182 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800183 }
184
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700185 private Context mContext;
186 private NativeDaemonConnector mConnector;
187
188 private final Object mVolumesLock = new Object();
189
190 /** When defined, base template for user-specific {@link StorageVolume}. */
191 private StorageVolume mEmulatedTemplate;
192
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800193 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700194 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
195 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700197 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
198 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700200 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
201
202 private volatile boolean mSystemReady = false;
203
San Mehat4270e1e2010-01-29 05:32:19 -0800204 private PackageManagerService mPms;
205 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700206 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800207 // Used as a lock for methods that register/unregister listeners.
208 final private ArrayList<MountServiceBinderListener> mListeners =
209 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800210 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
211 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800212 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800213
San Mehat6cdd9c02010-02-09 14:45:20 -0800214 /**
215 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800216 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800217 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800218 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800219
Kenny Root02c87302010-07-01 08:10:18 -0700220 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700221 * The size of the crypto algorithm key in bits for OBB files. Currently
222 * Twofish is used which takes 128-bit keys.
223 */
224 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
225
226 /**
227 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
228 * 1024 is reasonably secure and not too slow.
229 */
230 private static final int PBKDF2_HASH_ROUNDS = 1024;
231
232 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700233 * Mounted OBB tracking information. Used to track the current state of all
234 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700235 */
Kenny Root735de3b2010-09-30 14:11:39 -0700236 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700237
238 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700239 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
240
241 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700242 public ObbState(String rawPath, String canonicalPath, int callingUid,
243 IObbActionListener token, int nonce) {
244 this.rawPath = rawPath;
245 this.canonicalPath = canonicalPath.toString();
246
247 final int userId = UserHandle.getUserId(callingUid);
248 this.ownerPath = buildObbPath(canonicalPath, userId, false);
249 this.voldPath = buildObbPath(canonicalPath, userId, true);
250
251 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700252 this.token = token;
253 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700254 }
255
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700256 final String rawPath;
257 final String canonicalPath;
258 final String ownerPath;
259 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700260
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700261 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262
Kenny Rootaf9d6672010-10-08 09:21:39 -0700263 // Token of remote Binder caller
264 final IObbActionListener token;
265
266 // Identifier to pass back to the token
267 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
Kenny Root735de3b2010-09-30 14:11:39 -0700269 public IBinder getBinder() {
270 return token.asBinder();
271 }
272
Kenny Roota02b8b02010-08-05 16:14:17 -0700273 @Override
274 public void binderDied() {
275 ObbAction action = new UnmountObbAction(this, true);
276 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700277 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700278
Kenny Root5919ac62010-10-05 09:49:40 -0700279 public void link() throws RemoteException {
280 getBinder().linkToDeath(this, 0);
281 }
282
283 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700284 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700285 }
Kenny Root38cf8862010-09-26 14:18:51 -0700286
287 @Override
288 public String toString() {
289 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700290 sb.append("rawPath=").append(rawPath);
291 sb.append(",canonicalPath=").append(canonicalPath);
292 sb.append(",ownerPath=").append(ownerPath);
293 sb.append(",voldPath=").append(voldPath);
294 sb.append(",ownerGid=").append(ownerGid);
295 sb.append(",token=").append(token);
296 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700297 sb.append('}');
298 return sb.toString();
299 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700300 }
301
302 // OBB Action Handler
303 final private ObbActionHandler mObbActionHandler;
304
305 // OBB action handler messages
306 private static final int OBB_RUN_ACTION = 1;
307 private static final int OBB_MCS_BOUND = 2;
308 private static final int OBB_MCS_UNBIND = 3;
309 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700310 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700311
312 /*
313 * Default Container Service information
314 */
315 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
316 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
317
318 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
319
320 class DefaultContainerConnection implements ServiceConnection {
321 public void onServiceConnected(ComponentName name, IBinder service) {
322 if (DEBUG_OBB)
323 Slog.i(TAG, "onServiceConnected");
324 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
325 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
326 }
327
328 public void onServiceDisconnected(ComponentName name) {
329 if (DEBUG_OBB)
330 Slog.i(TAG, "onServiceDisconnected");
331 }
332 };
333
334 // Used in the ObbActionHandler
335 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700336
337 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 private static final int H_UNMOUNT_PM_UPDATE = 1;
339 private static final int H_UNMOUNT_PM_DONE = 2;
340 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700341 private static final int H_SYSTEM_READY = 4;
342
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
344 private static final int MAX_UNMOUNT_RETRIES = 4;
345
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700347 final String path;
348 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700349 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800351
Ben Komalo13c71972011-09-07 16:35:56 -0700352 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 retries = 0;
354 this.path = path;
355 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700356 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800357 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800358
359 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700360 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700361 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800362 }
363 }
364
365 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700366 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800367
368 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700369 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370 this.method = method;
371 }
372
373 @Override
374 void handleFinished() {
375 super.handleFinished();
376 doShareUnshareVolume(path, method, true);
377 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800378 }
379
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 class ShutdownCallBack extends UnmountCallBack {
381 IMountShutdownObserver observer;
382 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700383 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800384 this.observer = observer;
385 }
386
387 @Override
388 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700389 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800390 if (observer != null) {
391 try {
392 observer.onShutDownComplete(ret);
393 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700394 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800395 }
396 }
397 }
398 }
399
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400400 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700402 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400404 MountServiceHandler(Looper l) {
405 super(l);
406 }
407
Jason parks5af0b912010-11-29 09:05:25 -0600408 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 public void handleMessage(Message msg) {
410 switch (msg.what) {
411 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700412 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800413 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
414 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800416 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700417 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700419 mUpdatingStatus = true;
420 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 }
422 break;
423 }
424 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700425 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700426 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700427 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800428 int size = mForceUnmounts.size();
429 int sizeArr[] = new int[size];
430 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700431 // Kill processes holding references first
432 ActivityManagerService ams = (ActivityManagerService)
433 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 for (int i = 0; i < size; i++) {
435 UnmountCallBack ucb = mForceUnmounts.get(i);
436 String path = ucb.path;
437 boolean done = false;
438 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 done = true;
440 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800441 int pids[] = getStorageUsers(path);
442 if (pids == null || pids.length == 0) {
443 done = true;
444 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800445 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800446 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700447 // Confirm if file references have been freed.
448 pids = getStorageUsers(path);
449 if (pids == null || pids.length == 0) {
450 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800451 }
452 }
453 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700454 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
455 // Retry again
456 Slog.i(TAG, "Retrying to kill storage users again");
457 mHandler.sendMessageDelayed(
458 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
459 ucb.retries++),
460 RETRY_UNMOUNT_DELAY);
461 } else {
462 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
463 Slog.i(TAG, "Failed to unmount media inspite of " +
464 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
465 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800466 sizeArr[sizeArrN++] = i;
467 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
468 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800469 }
470 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800471 // Remove already processed elements from list.
472 for (int i = (sizeArrN-1); i >= 0; i--) {
473 mForceUnmounts.remove(sizeArr[i]);
474 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800475 break;
476 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700477 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700478 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800479 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800480 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800481 break;
482 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700483 case H_SYSTEM_READY: {
484 try {
485 handleSystemReady();
486 } catch (Exception ex) {
487 Slog.e(TAG, "Boot-time mount exception", ex);
488 }
489 break;
490 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800491 }
492 }
493 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700494
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700495 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800496
Kenny Root51a573c2012-05-17 13:30:28 -0700497 void waitForAsecScan() {
498 waitForLatch(mAsecsScanned);
499 }
500
San Mehat207e5382010-02-04 20:46:54 -0800501 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700502 waitForLatch(mConnectedSignal);
503 }
504
505 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700506 for (;;) {
507 try {
508 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800509 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700510 } else {
511 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
512 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800513 }
Kenny Root51a573c2012-05-17 13:30:28 -0700514 } catch (InterruptedException e) {
515 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800516 }
San Mehat207e5382010-02-04 20:46:54 -0800517 }
San Mehat1f6301e2010-01-07 22:40:27 -0800518 }
Kenny Root02c87302010-07-01 08:10:18 -0700519
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700520 private void handleSystemReady() {
521 // Snapshot current volume states since it's not safe to call into vold
522 // while holding locks.
523 final HashMap<String, String> snapshot;
524 synchronized (mVolumesLock) {
525 snapshot = new HashMap<String, String>(mVolumeStates);
526 }
527
528 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
529 final String path = entry.getKey();
530 final String state = entry.getValue();
531
532 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
533 int rc = doMountVolume(path);
534 if (rc != StorageResultCode.OperationSucceeded) {
535 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
536 rc));
537 }
538 } else if (state.equals(Environment.MEDIA_SHARED)) {
539 /*
540 * Bootstrap UMS enabled state since vold indicates
541 * the volume is shared (runtime restart while ums enabled)
542 */
543 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
544 VolumeState.Shared);
545 }
546 }
547
548 // Push mounted state for all emulated storage
549 synchronized (mVolumesLock) {
550 for (StorageVolume volume : mVolumes) {
551 if (volume.isEmulated()) {
552 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
553 }
554 }
555 }
556
557 /*
558 * If UMS was connected on boot, send the connected event
559 * now that we're up.
560 */
561 if (mSendUmsConnectedOnBoot) {
562 sendUmsIntent(true);
563 mSendUmsConnectedOnBoot = false;
564 }
565 }
566
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700567 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
568 @Override
569 public void onReceive(Context context, Intent intent) {
570 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
571 if (userId == -1) return;
572 final UserHandle user = new UserHandle(userId);
573
574 final String action = intent.getAction();
575 if (Intent.ACTION_USER_ADDED.equals(action)) {
576 synchronized (mVolumesLock) {
577 createEmulatedVolumeForUserLocked(user);
578 }
579
580 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
581 synchronized (mVolumesLock) {
582 final List<StorageVolume> toRemove = Lists.newArrayList();
583 for (StorageVolume volume : mVolumes) {
584 if (user.equals(volume.getOwner())) {
585 toRemove.add(volume);
586 }
587 }
588 for (StorageVolume volume : toRemove) {
589 removeVolumeLocked(volume);
590 }
591 }
592 }
593 }
594 };
595
596 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
597 @Override
598 public void onReceive(Context context, Intent intent) {
599 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
600 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
601 notifyShareAvailabilityChange(available);
602 }
603 };
604
Svetoslava7452ee2013-03-20 12:06:59 -0700605 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
606 @Override
607 public void onReceive(Context context, Intent intent) {
608 waitForReady();
609 String action = intent.getAction();
610 // Since fstrim will be run on a daily basis we do not expect
611 // fstrim to be too long, so it is not interruptible. We will
612 // implement interruption only in case we see issues.
613 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
614 try {
615 // This method runs on the handler thread,
616 // so it is safe to directly call into vold.
617 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700618 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700619 } catch (NativeDaemonConnectorException ndce) {
620 Slog.e(TAG, "Failed to run fstrim!");
621 }
622 }
623 }
624 };
625
San Mehat4270e1e2010-01-29 05:32:19 -0800626 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
627 final IMountServiceListener mListener;
628
629 MountServiceBinderListener(IMountServiceListener listener) {
630 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700631
San Mehat91c77612010-01-07 10:39:41 -0800632 }
633
San Mehat4270e1e2010-01-29 05:32:19 -0800634 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700635 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700636 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800637 mListeners.remove(this);
638 mListener.asBinder().unlinkToDeath(this, 0);
639 }
640 }
641 }
642
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800643 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800644 // TODO: Add support for multiple share methods
645 if (!method.equals("ums")) {
646 throw new IllegalArgumentException(String.format("Method %s not supported", method));
647 }
648
San Mehat4270e1e2010-01-29 05:32:19 -0800649 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800650 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800651 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700652 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800653 }
San Mehat4270e1e2010-01-29 05:32:19 -0800654 }
655
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700656 private void updatePublicVolumeState(StorageVolume volume, String state) {
657 final String path = volume.getPath();
658 final String oldState;
659 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400660 oldState = mVolumeStates.put(path, state);
661 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700662
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400663 if (state.equals(oldState)) {
664 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
665 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800666 return;
667 }
San Mehatb1043402010-02-05 08:26:50 -0800668
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400669 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700670
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700671 // Tell PackageManager about changes to primary volume state, but only
672 // when not emulated.
673 if (volume.isPrimary() && !volume.isEmulated()) {
674 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
675 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400676
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700677 /*
678 * Some OBBs might have been unmounted when this volume was
679 * unmounted, so send a message to the handler to let it know to
680 * remove those from the list of mounted OBBS.
681 */
682 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
683 OBB_FLUSH_MOUNT_STATE, path));
684 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
685 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400686 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800687 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700688
San Mehat4270e1e2010-01-29 05:32:19 -0800689 synchronized (mListeners) {
690 for (int i = mListeners.size() -1; i >= 0; i--) {
691 MountServiceBinderListener bl = mListeners.get(i);
692 try {
San Mehatb1043402010-02-05 08:26:50 -0800693 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800694 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700695 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800696 mListeners.remove(i);
697 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700698 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800699 }
700 }
701 }
702 }
703
704 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800705 * Callback from NativeDaemonConnector
706 */
707 public void onDaemonConnected() {
708 /*
709 * Since we'll be calling back into the NativeDaemonConnector,
710 * we need to do our work in a new thread.
711 */
Kenny Root51a573c2012-05-17 13:30:28 -0700712 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600713 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800714 public void run() {
715 /**
716 * Determine media state and UMS detection status
717 */
San Mehat4270e1e2010-01-29 05:32:19 -0800718 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800719 final String[] vols = NativeDaemonEvent.filterMessageList(
720 mConnector.executeForList("volume", "list"),
721 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800722 for (String volstr : vols) {
723 String[] tok = volstr.split(" ");
724 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400725 String path = tok[1];
726 String state = Environment.MEDIA_REMOVED;
727
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700728 final StorageVolume volume;
729 synchronized (mVolumesLock) {
730 volume = mVolumesByPath.get(path);
731 }
732
San Mehat4270e1e2010-01-29 05:32:19 -0800733 int st = Integer.parseInt(tok[2]);
734 if (st == VolumeState.NoMedia) {
735 state = Environment.MEDIA_REMOVED;
736 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800737 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800738 } else if (st == VolumeState.Mounted) {
739 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700740 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800741 } else if (st == VolumeState.Shared) {
742 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700743 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800744 } else {
745 throw new Exception(String.format("Unexpected state %d", st));
746 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400747
748 if (state != null) {
749 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700750 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400751 }
San Mehat4270e1e2010-01-29 05:32:19 -0800752 }
753 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700754 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700755 final StorageVolume primary = getPrimaryPhysicalVolume();
756 if (primary != null) {
757 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
758 }
San Mehat4270e1e2010-01-29 05:32:19 -0800759 }
760
San Mehat207e5382010-02-04 20:46:54 -0800761 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600762 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800763 * the hounds!
764 */
Kenny Root51a573c2012-05-17 13:30:28 -0700765 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700766
767 // Let package manager load internal ASECs.
768 mPms.scanAvailableAsecs();
769
770 // Notify people waiting for ASECs to be scanned that it's done.
771 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800772 }
773 }.start();
774 }
775
776 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800777 * Callback from NativeDaemonConnector
778 */
779 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800780 if (DEBUG_EVENTS) {
781 StringBuilder builder = new StringBuilder();
782 builder.append("onEvent::");
783 builder.append(" raw= " + raw);
784 if (cooked != null) {
785 builder.append(" cooked = " );
786 for (String str : cooked) {
787 builder.append(" " + str);
788 }
789 }
San Mehata5078592010-03-25 09:36:54 -0700790 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800791 }
San Mehat4270e1e2010-01-29 05:32:19 -0800792 if (code == VoldResponseCode.VolumeStateChange) {
793 /*
794 * One of the volumes we're managing has changed state.
795 * Format: "NNN Volume <label> <path> state changed
796 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
797 */
798 notifyVolumeStateChange(
799 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
800 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800801 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
802 (code == VoldResponseCode.VolumeDiskRemoved) ||
803 (code == VoldResponseCode.VolumeBadRemoval)) {
804 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
805 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
806 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400807 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800808 final String label = cooked[2];
809 final String path = cooked[3];
810 int major = -1;
811 int minor = -1;
812
813 try {
814 String devComp = cooked[6].substring(1, cooked[6].length() -1);
815 String[] devTok = devComp.split(":");
816 major = Integer.parseInt(devTok[0]);
817 minor = Integer.parseInt(devTok[1]);
818 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700819 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800820 }
821
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700822 final StorageVolume volume;
823 final String state;
824 synchronized (mVolumesLock) {
825 volume = mVolumesByPath.get(path);
826 state = mVolumeStates.get(path);
827 }
828
San Mehat4270e1e2010-01-29 05:32:19 -0800829 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700830 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600831 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800832 public void run() {
833 try {
834 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800835 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700836 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800837 }
838 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700839 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800840 }
841 }
842 }.start();
843 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
844 /*
845 * This event gets trumped if we're already in BAD_REMOVAL state
846 */
847 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
848 return true;
849 }
850 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700851 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700852 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
853 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800854
San Mehata5078592010-03-25 09:36:54 -0700855 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700856 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400857 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800858 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700859 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800860 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700861 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200862 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800863
San Mehata5078592010-03-25 09:36:54 -0700864 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700865 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400866 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700867 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700868 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800869 } else {
San Mehata5078592010-03-25 09:36:54 -0700870 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800871 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400872
873 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700874 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400875 }
San Mehat4270e1e2010-01-29 05:32:19 -0800876 } else {
877 return false;
878 }
879
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400880 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800881 }
882
San Mehat207e5382010-02-04 20:46:54 -0800883 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700884 final StorageVolume volume;
885 final String state;
886 synchronized (mVolumesLock) {
887 volume = mVolumesByPath.get(path);
888 state = getVolumeState(path);
889 }
890
891 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800892
Mike Lockwooda5250c92011-05-23 13:44:04 -0400893 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800894
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500895 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700896 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700897 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500898 }
899
San Mehat4270e1e2010-01-29 05:32:19 -0800900 if (newState == VolumeState.Init) {
901 } else if (newState == VolumeState.NoMedia) {
902 // NoMedia is handled via Disk Remove events
903 } else if (newState == VolumeState.Idle) {
904 /*
905 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
906 * if we're in the process of enabling UMS
907 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700908 if (!state.equals(
909 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
910 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800911 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700912 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700913 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400914 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800915 }
916 } else if (newState == VolumeState.Pending) {
917 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700918 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700919 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400920 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800921 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700922 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700923 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400924 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800925 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400926 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800927 } else if (newState == VolumeState.Formatting) {
928 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700929 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800930 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700931 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
932 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800933
San Mehata5078592010-03-25 09:36:54 -0700934 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700935 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400936 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700937 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800938 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700939 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800940 return;
941 } else {
San Mehata5078592010-03-25 09:36:54 -0700942 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800943 }
944
Mike Lockwooda5250c92011-05-23 13:44:04 -0400945 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700946 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800947 }
948 }
949
San Mehat207e5382010-02-04 20:46:54 -0800950 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800951 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800952
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700953 final StorageVolume volume;
954 synchronized (mVolumesLock) {
955 volume = mVolumesByPath.get(path);
956 }
957
San Mehata5078592010-03-25 09:36:54 -0700958 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800959 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800960 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800961 } catch (NativeDaemonConnectorException e) {
962 /*
963 * Mount failed for some reason
964 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400965 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800966 int code = e.getCode();
967 if (code == VoldResponseCode.OpFailedNoMedia) {
968 /*
969 * Attempt to mount but no media inserted
970 */
San Mehatb1043402010-02-05 08:26:50 -0800971 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800972 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700973 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800974 /*
975 * Media is blank or does not contain a supported filesystem
976 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700977 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400978 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800979 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800980 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700981 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800982 /*
983 * Volume consistency check failed
984 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700985 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400986 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800987 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800988 } else {
San Mehatb1043402010-02-05 08:26:50 -0800989 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800990 }
991
992 /*
993 * Send broadcast intent (if required for the failure)
994 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400995 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700996 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800997 }
998 }
999
1000 return rc;
1001 }
1002
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001003 /*
1004 * If force is not set, we do not unmount if there are
1005 * processes holding references to the volume about to be unmounted.
1006 * If force is set, all the processes holding references need to be
1007 * killed via the ActivityManager before actually unmounting the volume.
1008 * This might even take a while and might be retried after timed delays
1009 * to make sure we dont end up in an instable state and kill some core
1010 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001011 * If removeEncryption is set, force is implied, and the system will remove any encryption
1012 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001013 */
Ben Komalo13c71972011-09-07 16:35:56 -07001014 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001015 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001016 return VoldResponseCode.OpFailedVolNotMounted;
1017 }
Kenny Rootaa485402010-09-14 14:49:41 -07001018
1019 /*
1020 * Force a GC to make sure AssetManagers in other threads of the
1021 * system_server are cleaned up. We have to do this since AssetManager
1022 * instances are kept as a WeakReference and it's possible we have files
1023 * open on the external storage.
1024 */
1025 Runtime.getRuntime().gc();
1026
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001027 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001028 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001029 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001030 final Command cmd = new Command("volume", "unmount", path);
1031 if (removeEncryption) {
1032 cmd.appendArg("force_and_revert");
1033 } else if (force) {
1034 cmd.appendArg("force");
1035 }
1036 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001037 // We unmounted the volume. None of the asec containers are available now.
1038 synchronized (mAsecMountSet) {
1039 mAsecMountSet.clear();
1040 }
San Mehatb1043402010-02-05 08:26:50 -08001041 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001042 } catch (NativeDaemonConnectorException e) {
1043 // Don't worry about mismatch in PackageManager since the
1044 // call back will handle the status changes any way.
1045 int code = e.getCode();
1046 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001047 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001048 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1049 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001050 } else {
San Mehatb1043402010-02-05 08:26:50 -08001051 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001052 }
1053 }
1054 }
1055
1056 private int doFormatVolume(String path) {
1057 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001058 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001059 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001060 } catch (NativeDaemonConnectorException e) {
1061 int code = e.getCode();
1062 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001063 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001064 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001065 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001066 } else {
San Mehatb1043402010-02-05 08:26:50 -08001067 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001068 }
1069 }
1070 }
1071
San Mehatb1043402010-02-05 08:26:50 -08001072 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001073 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001074 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001075 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001076 } catch (NativeDaemonConnectorException ex) {
1077 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1078 return false;
1079 }
San Mehatb1043402010-02-05 08:26:50 -08001080
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001081 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1082 return event.getMessage().endsWith("enabled");
1083 } else {
1084 return false;
San Mehatb1043402010-02-05 08:26:50 -08001085 }
San Mehatb1043402010-02-05 08:26:50 -08001086 }
1087
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001088 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001089 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001090 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001091 for (int i = mListeners.size() -1; i >= 0; i--) {
1092 MountServiceBinderListener bl = mListeners.get(i);
1093 try {
San Mehatb1043402010-02-05 08:26:50 -08001094 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001095 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001096 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001097 mListeners.remove(i);
1098 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001099 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001100 }
1101 }
1102 }
1103
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001104 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001105 sendUmsIntent(avail);
1106 } else {
1107 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001108 }
San Mehat2fe718a2010-03-11 12:01:49 -08001109
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001110 final StorageVolume primary = getPrimaryPhysicalVolume();
1111 if (avail == false && primary != null
1112 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1113 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001114 /*
1115 * USB mass storage disconnected while enabled
1116 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001117 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001118 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001119 public void run() {
1120 try {
1121 int rc;
San Mehata5078592010-03-25 09:36:54 -07001122 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001123 doShareUnshareVolume(path, "ums", false);
1124 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001125 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001126 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1127 path, rc));
1128 }
1129 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001130 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001131 }
1132 }
1133 }.start();
1134 }
San Mehat4270e1e2010-01-29 05:32:19 -08001135 }
1136
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001137 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1138 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1139 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1140 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1141 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001142 }
1143
San Mehat6a965af22010-02-24 17:47:30 -08001144 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001145 mContext.sendBroadcastAsUser(
1146 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1147 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001148 }
1149
San Mehat207e5382010-02-04 20:46:54 -08001150 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001151 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1152 throw new SecurityException(String.format("Requires %s permission", perm));
1153 }
1154 }
1155
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001156 // Storage list XML tags
1157 private static final String TAG_STORAGE_LIST = "StorageList";
1158 private static final String TAG_STORAGE = "storage";
1159
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001160 private void readStorageListLocked() {
1161 mVolumes.clear();
1162 mVolumeStates.clear();
1163
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001164 Resources resources = mContext.getResources();
1165
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001166 int id = com.android.internal.R.xml.storage_list;
1167 XmlResourceParser parser = resources.getXml(id);
1168 AttributeSet attrs = Xml.asAttributeSet(parser);
1169
1170 try {
1171 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1172 while (true) {
1173 XmlUtils.nextElement(parser);
1174
1175 String element = parser.getName();
1176 if (element == null) break;
1177
1178 if (TAG_STORAGE.equals(element)) {
1179 TypedArray a = resources.obtainAttributes(attrs,
1180 com.android.internal.R.styleable.Storage);
1181
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001182 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001183 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001184 int descriptionId = a.getResourceId(
1185 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001186 CharSequence description = a.getText(
1187 com.android.internal.R.styleable.Storage_storageDescription);
1188 boolean primary = a.getBoolean(
1189 com.android.internal.R.styleable.Storage_primary, false);
1190 boolean removable = a.getBoolean(
1191 com.android.internal.R.styleable.Storage_removable, false);
1192 boolean emulated = a.getBoolean(
1193 com.android.internal.R.styleable.Storage_emulated, false);
1194 int mtpReserve = a.getInt(
1195 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001196 boolean allowMassStorage = a.getBoolean(
1197 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001198 // resource parser does not support longs, so XML value is in megabytes
1199 long maxFileSize = a.getInt(
1200 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001201
1202 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1203 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001204 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001205 " allowMassStorage: " + allowMassStorage +
1206 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001207
1208 if (emulated) {
1209 // For devices with emulated storage, we create separate
1210 // volumes for each known user.
1211 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1212 true, mtpReserve, false, maxFileSize, null);
1213
1214 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001215 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001216 createEmulatedVolumeForUserLocked(user.getUserHandle());
1217 }
1218
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001219 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001220 if (path == null || description == null) {
1221 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001222 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001223 final StorageVolume volume = new StorageVolume(new File(path),
1224 descriptionId, primary, removable, emulated, mtpReserve,
1225 allowMassStorage, maxFileSize, null);
1226 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001227 }
1228 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001229
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001230 a.recycle();
1231 }
1232 }
1233 } catch (XmlPullParserException e) {
1234 throw new RuntimeException(e);
1235 } catch (IOException e) {
1236 throw new RuntimeException(e);
1237 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001238 // Compute storage ID for each physical volume; emulated storage is
1239 // always 0 when defined.
1240 int index = isExternalStorageEmulated() ? 1 : 0;
1241 for (StorageVolume volume : mVolumes) {
1242 if (!volume.isEmulated()) {
1243 volume.setStorageId(index++);
1244 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001245 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001246 parser.close();
1247 }
1248 }
1249
San Mehat4270e1e2010-01-29 05:32:19 -08001250 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001251 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1252 * using {@link #mEmulatedTemplate} as template.
1253 */
1254 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1255 if (mEmulatedTemplate == null) {
1256 throw new IllegalStateException("Missing emulated volume multi-user template");
1257 }
1258
1259 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1260 final File path = userEnv.getExternalStorageDirectory();
1261 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1262 volume.setStorageId(0);
1263 addVolumeLocked(volume);
1264
1265 if (mSystemReady) {
1266 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1267 } else {
1268 // Place stub status for early callers to find
1269 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1270 }
1271 }
1272
1273 private void addVolumeLocked(StorageVolume volume) {
1274 Slog.d(TAG, "addVolumeLocked() " + volume);
1275 mVolumes.add(volume);
1276 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1277 if (existing != null) {
1278 throw new IllegalStateException(
1279 "Volume at " + volume.getPath() + " already exists: " + existing);
1280 }
1281 }
1282
1283 private void removeVolumeLocked(StorageVolume volume) {
1284 Slog.d(TAG, "removeVolumeLocked() " + volume);
1285 mVolumes.remove(volume);
1286 mVolumesByPath.remove(volume.getPath());
1287 mVolumeStates.remove(volume.getPath());
1288 }
1289
1290 private StorageVolume getPrimaryPhysicalVolume() {
1291 synchronized (mVolumesLock) {
1292 for (StorageVolume volume : mVolumes) {
1293 if (volume.isPrimary() && !volume.isEmulated()) {
1294 return volume;
1295 }
1296 }
1297 }
1298 return null;
1299 }
1300
1301 /**
San Mehat207e5382010-02-04 20:46:54 -08001302 * Constructs a new MountService instance
1303 *
1304 * @param context Binder context for this service
1305 */
1306 public MountService(Context context) {
1307 mContext = context;
1308
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001309 synchronized (mVolumesLock) {
1310 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001311 }
1312
San Mehat207e5382010-02-04 20:46:54 -08001313 // XXX: This will go away soon in favor of IMountServiceObserver
1314 mPms = (PackageManagerService) ServiceManager.getService("package");
1315
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001316 HandlerThread hthread = new HandlerThread(TAG);
1317 hthread.start();
1318 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001319
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001320 // Watch for user changes
1321 final IntentFilter userFilter = new IntentFilter();
1322 userFilter.addAction(Intent.ACTION_USER_ADDED);
1323 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1324 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1325
1326 // Watch for USB changes on primary volume
1327 final StorageVolume primary = getPrimaryPhysicalVolume();
1328 if (primary != null && primary.allowMassStorage()) {
1329 mContext.registerReceiver(
1330 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1331 }
1332
Svetoslava7452ee2013-03-20 12:06:59 -07001333 // Watch for idle maintenance changes
1334 IntentFilter idleMaintenanceFilter = new IntentFilter();
1335 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1336 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1337 idleMaintenanceFilter, null, mHandler);
1338
Kenny Roota02b8b02010-08-05 16:14:17 -07001339 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001340 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001341
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001342 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001343 * Create the connection to vold with a maximum queue of twice the
1344 * amount of containers we'd ever expect to have. This keeps an
1345 * "asec list" from blocking a thread repeatedly.
1346 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001347 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001348
Kenny Root305bcbf2010-09-03 07:56:38 -07001349 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001350 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001351
Kenny Root07714d42011-08-17 17:49:28 -07001352 // Add ourself to the Watchdog monitors if enabled.
1353 if (WATCHDOG_ENABLE) {
1354 Watchdog.getInstance().addMonitor(this);
1355 }
San Mehat207e5382010-02-04 20:46:54 -08001356 }
1357
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001358 public void systemReady() {
1359 mSystemReady = true;
1360 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1361 }
1362
San Mehat207e5382010-02-04 20:46:54 -08001363 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001364 * Exposed API calls below here
1365 */
1366
1367 public void registerListener(IMountServiceListener listener) {
1368 synchronized (mListeners) {
1369 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1370 try {
1371 listener.asBinder().linkToDeath(bl, 0);
1372 mListeners.add(bl);
1373 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001374 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001375 }
1376 }
1377 }
1378
1379 public void unregisterListener(IMountServiceListener listener) {
1380 synchronized (mListeners) {
1381 for(MountServiceBinderListener bl : mListeners) {
1382 if (bl.mListener == listener) {
1383 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001384 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001385 return;
1386 }
1387 }
1388 }
1389 }
1390
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001391 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001392 validatePermission(android.Manifest.permission.SHUTDOWN);
1393
San Mehata5078592010-03-25 09:36:54 -07001394 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001395 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001396 for (String path : mVolumeStates.keySet()) {
1397 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001398
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001399 if (state.equals(Environment.MEDIA_SHARED)) {
1400 /*
1401 * If the media is currently shared, unshare it.
1402 * XXX: This is still dangerous!. We should not
1403 * be rebooting at *all* if UMS is enabled, since
1404 * the UMS host could have dirty FAT cache entries
1405 * yet to flush.
1406 */
1407 setUsbMassStorageEnabled(false);
1408 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1409 /*
1410 * If the media is being checked, then we need to wait for
1411 * it to complete before being able to proceed.
1412 */
1413 // XXX: @hackbod - Should we disable the ANR timer here?
1414 int retries = 30;
1415 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1416 try {
1417 Thread.sleep(1000);
1418 } catch (InterruptedException iex) {
1419 Slog.e(TAG, "Interrupted while waiting for media", iex);
1420 break;
1421 }
1422 state = Environment.getExternalStorageState();
1423 }
1424 if (retries == 0) {
1425 Slog.e(TAG, "Timed out waiting for media to check");
1426 }
San Mehat91c77612010-01-07 10:39:41 -08001427 }
San Mehat91c77612010-01-07 10:39:41 -08001428
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001429 if (state.equals(Environment.MEDIA_MOUNTED)) {
1430 // Post a unmount message.
1431 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1432 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1433 } else if (observer != null) {
1434 /*
1435 * Observer is waiting for onShutDownComplete when we are done.
1436 * Since nothing will be done send notification directly so shutdown
1437 * sequence can continue.
1438 */
1439 try {
1440 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1441 } catch (RemoteException e) {
1442 Slog.w(TAG, "RemoteException when shutting down");
1443 }
1444 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001445 }
San Mehat4270e1e2010-01-29 05:32:19 -08001446 }
1447 }
1448
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001449 private boolean getUmsEnabling() {
1450 synchronized (mListeners) {
1451 return mUmsEnabling;
1452 }
1453 }
1454
1455 private void setUmsEnabling(boolean enable) {
1456 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001457 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001458 }
1459 }
1460
San Mehatb1043402010-02-05 08:26:50 -08001461 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001462 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001463
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001464 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001465 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001466 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001467 synchronized (mListeners) {
1468 return mUmsAvailable;
1469 }
San Mehatb1043402010-02-05 08:26:50 -08001470 }
1471
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001472 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001473 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001474 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001475
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001476 final StorageVolume primary = getPrimaryPhysicalVolume();
1477 if (primary == null) return;
1478
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001479 // TODO: Add support for multiple share methods
1480
1481 /*
1482 * If the volume is mounted and we're enabling then unmount it
1483 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001484 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001485 String vs = getVolumeState(path);
1486 String method = "ums";
1487 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1488 // Override for isUsbMassStorageEnabled()
1489 setUmsEnabling(enable);
1490 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1491 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1492 // Clear override
1493 setUmsEnabling(false);
1494 }
1495 /*
1496 * If we disabled UMS then mount the volume
1497 */
1498 if (!enable) {
1499 doShareUnshareVolume(path, method, enable);
1500 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001501 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001502 " after disabling share method " + method);
1503 /*
1504 * Even though the mount failed, the unshare didn't so don't indicate an error.
1505 * The mountVolume() call will have set the storage state and sent the necessary
1506 * broadcasts.
1507 */
1508 }
1509 }
San Mehatb1043402010-02-05 08:26:50 -08001510 }
1511
1512 public boolean isUsbMassStorageEnabled() {
1513 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001514
1515 final StorageVolume primary = getPrimaryPhysicalVolume();
1516 if (primary != null) {
1517 return doGetVolumeShared(primary.getPath(), "ums");
1518 } else {
1519 return false;
1520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001522
San Mehat7fd0fee2009-12-17 07:12:23 -08001523 /**
1524 * @return state of the volume at the specified mount point
1525 */
San Mehat4270e1e2010-01-29 05:32:19 -08001526 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001527 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001528 String state = mVolumeStates.get(mountPoint);
1529 if (state == null) {
1530 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001531 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1532 state = Environment.MEDIA_REMOVED;
1533 } else {
1534 throw new IllegalArgumentException();
1535 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001536 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001537
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001538 return state;
1539 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001540 }
1541
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001542 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001543 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001544 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001545 }
1546
San Mehat4270e1e2010-01-29 05:32:19 -08001547 public int mountVolume(String path) {
1548 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001549
San Mehat207e5382010-02-04 20:46:54 -08001550 waitForReady();
1551 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
1553
Ben Komalo13c71972011-09-07 16:35:56 -07001554 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001555 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001556 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001558 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001559 if (DEBUG_UNMOUNT) {
1560 Slog.i(TAG, "Unmounting " + path
1561 + " force = " + force
1562 + " removeEncryption = " + removeEncryption);
1563 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001564 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1565 Environment.MEDIA_REMOVED.equals(volState) ||
1566 Environment.MEDIA_SHARED.equals(volState) ||
1567 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1568 // Media already unmounted or cannot be unmounted.
1569 // TODO return valid return code when adding observer call back.
1570 return;
1571 }
Ben Komalo13c71972011-09-07 16:35:56 -07001572 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001573 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575
San Mehat4270e1e2010-01-29 05:32:19 -08001576 public int formatVolume(String path) {
1577 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001578 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001579
San Mehat207e5382010-02-04 20:46:54 -08001580 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
1582
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001583 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001584 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1585 waitForReady();
1586 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001587 final String[] r = NativeDaemonEvent.filterMessageList(
1588 mConnector.executeForList("storage", "users", path),
1589 VoldResponseCode.StorageUsersListResult);
1590
San Mehatc1b4ce92010-02-16 17:13:03 -08001591 // FMT: <pid> <process name>
1592 int[] data = new int[r.length];
1593 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001594 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001595 try {
1596 data[i] = Integer.parseInt(tok[0]);
1597 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001598 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001599 return new int[0];
1600 }
1601 }
1602 return data;
1603 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001604 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001605 return new int[0];
1606 }
1607 }
1608
San Mehatb1043402010-02-05 08:26:50 -08001609 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001610 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001611 if (primary != null) {
1612 boolean mounted = false;
1613 try {
1614 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001615 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001616 }
1617
1618 if (!mounted) {
1619 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1620 }
San Mehatb1043402010-02-05 08:26:50 -08001621 }
1622 }
1623
San Mehat4270e1e2010-01-29 05:32:19 -08001624 public String[] getSecureContainerList() {
1625 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001626 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001627 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001628
San Mehat4270e1e2010-01-29 05:32:19 -08001629 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001630 return NativeDaemonEvent.filterMessageList(
1631 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001632 } catch (NativeDaemonConnectorException e) {
1633 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 }
San Mehat36972292010-01-06 11:06:32 -08001636
Kenny Root6dceb882012-04-12 14:23:49 -07001637 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1638 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001639 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001640 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001641 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001642
San Mehatb1043402010-02-05 08:26:50 -08001643 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001644 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001645 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1646 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001647 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001648 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001649 }
San Mehata181b212010-02-11 06:50:20 -08001650
1651 if (rc == StorageResultCode.OperationSucceeded) {
1652 synchronized (mAsecMountSet) {
1653 mAsecMountSet.add(id);
1654 }
1655 }
San Mehat4270e1e2010-01-29 05:32:19 -08001656 return rc;
San Mehat36972292010-01-06 11:06:32 -08001657 }
1658
San Mehat4270e1e2010-01-29 05:32:19 -08001659 public int finalizeSecureContainer(String id) {
1660 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001661 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001662
San Mehatb1043402010-02-05 08:26:50 -08001663 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001664 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001665 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001666 /*
1667 * Finalization does a remount, so no need
1668 * to update mAsecMountSet
1669 */
San Mehat4270e1e2010-01-29 05:32:19 -08001670 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001671 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001672 }
San Mehat4270e1e2010-01-29 05:32:19 -08001673 return rc;
San Mehat36972292010-01-06 11:06:32 -08001674 }
1675
Kenny Root6dceb882012-04-12 14:23:49 -07001676 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1677 validatePermission(android.Manifest.permission.ASEC_CREATE);
1678 warnOnNotMounted();
1679
1680 int rc = StorageResultCode.OperationSucceeded;
1681 try {
1682 mConnector.execute("asec", "fixperms", id, gid, filename);
1683 /*
1684 * Fix permissions does a remount, so no need to update
1685 * mAsecMountSet
1686 */
1687 } catch (NativeDaemonConnectorException e) {
1688 rc = StorageResultCode.OperationFailedInternalError;
1689 }
1690 return rc;
1691 }
1692
San Mehatd9709982010-02-18 11:43:03 -08001693 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001694 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001695 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001696 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001697
Kenny Rootaa485402010-09-14 14:49:41 -07001698 /*
1699 * Force a GC to make sure AssetManagers in other threads of the
1700 * system_server are cleaned up. We have to do this since AssetManager
1701 * instances are kept as a WeakReference and it's possible we have files
1702 * open on the external storage.
1703 */
1704 Runtime.getRuntime().gc();
1705
San Mehatb1043402010-02-05 08:26:50 -08001706 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001707 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001708 final Command cmd = new Command("asec", "destroy", id);
1709 if (force) {
1710 cmd.appendArg("force");
1711 }
1712 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001713 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001714 int code = e.getCode();
1715 if (code == VoldResponseCode.OpFailedStorageBusy) {
1716 rc = StorageResultCode.OperationFailedStorageBusy;
1717 } else {
1718 rc = StorageResultCode.OperationFailedInternalError;
1719 }
San Mehat02735bc2010-01-26 15:18:08 -08001720 }
San Mehata181b212010-02-11 06:50:20 -08001721
1722 if (rc == StorageResultCode.OperationSucceeded) {
1723 synchronized (mAsecMountSet) {
1724 if (mAsecMountSet.contains(id)) {
1725 mAsecMountSet.remove(id);
1726 }
1727 }
1728 }
1729
San Mehat4270e1e2010-01-29 05:32:19 -08001730 return rc;
San Mehat36972292010-01-06 11:06:32 -08001731 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001732
San Mehat4270e1e2010-01-29 05:32:19 -08001733 public int mountSecureContainer(String id, String key, int ownerUid) {
1734 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001735 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001736 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001737
San Mehata181b212010-02-11 06:50:20 -08001738 synchronized (mAsecMountSet) {
1739 if (mAsecMountSet.contains(id)) {
1740 return StorageResultCode.OperationFailedStorageMounted;
1741 }
1742 }
1743
San Mehatb1043402010-02-05 08:26:50 -08001744 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001745 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001746 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001747 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001748 int code = e.getCode();
1749 if (code != VoldResponseCode.OpFailedStorageBusy) {
1750 rc = StorageResultCode.OperationFailedInternalError;
1751 }
San Mehat02735bc2010-01-26 15:18:08 -08001752 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001753
1754 if (rc == StorageResultCode.OperationSucceeded) {
1755 synchronized (mAsecMountSet) {
1756 mAsecMountSet.add(id);
1757 }
1758 }
San Mehat4270e1e2010-01-29 05:32:19 -08001759 return rc;
San Mehat36972292010-01-06 11:06:32 -08001760 }
1761
San Mehatd9709982010-02-18 11:43:03 -08001762 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001763 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001764 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001765 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001766
San Mehat6cdd9c02010-02-09 14:45:20 -08001767 synchronized (mAsecMountSet) {
1768 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001769 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001770 }
1771 }
1772
Kenny Rootaa485402010-09-14 14:49:41 -07001773 /*
1774 * Force a GC to make sure AssetManagers in other threads of the
1775 * system_server are cleaned up. We have to do this since AssetManager
1776 * instances are kept as a WeakReference and it's possible we have files
1777 * open on the external storage.
1778 */
1779 Runtime.getRuntime().gc();
1780
San Mehatb1043402010-02-05 08:26:50 -08001781 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001782 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001783 final Command cmd = new Command("asec", "unmount", id);
1784 if (force) {
1785 cmd.appendArg("force");
1786 }
1787 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001788 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001789 int code = e.getCode();
1790 if (code == VoldResponseCode.OpFailedStorageBusy) {
1791 rc = StorageResultCode.OperationFailedStorageBusy;
1792 } else {
1793 rc = StorageResultCode.OperationFailedInternalError;
1794 }
San Mehat02735bc2010-01-26 15:18:08 -08001795 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001796
1797 if (rc == StorageResultCode.OperationSucceeded) {
1798 synchronized (mAsecMountSet) {
1799 mAsecMountSet.remove(id);
1800 }
1801 }
San Mehat4270e1e2010-01-29 05:32:19 -08001802 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001803 }
1804
San Mehat6cdd9c02010-02-09 14:45:20 -08001805 public boolean isSecureContainerMounted(String id) {
1806 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1807 waitForReady();
1808 warnOnNotMounted();
1809
1810 synchronized (mAsecMountSet) {
1811 return mAsecMountSet.contains(id);
1812 }
1813 }
1814
San Mehat4270e1e2010-01-29 05:32:19 -08001815 public int renameSecureContainer(String oldId, String newId) {
1816 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001817 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001818 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001819
San Mehata181b212010-02-11 06:50:20 -08001820 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001821 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001822 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001823 * changed while active, we must ensure both ids are not currently mounted.
1824 */
1825 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001826 return StorageResultCode.OperationFailedStorageMounted;
1827 }
1828 }
1829
San Mehatb1043402010-02-05 08:26:50 -08001830 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001831 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001832 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001833 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001834 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001835 }
San Mehata181b212010-02-11 06:50:20 -08001836
San Mehat4270e1e2010-01-29 05:32:19 -08001837 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001838 }
1839
San Mehat4270e1e2010-01-29 05:32:19 -08001840 public String getSecureContainerPath(String id) {
1841 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001842 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001843 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001844
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001845 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001846 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001847 event = mConnector.execute("asec", "path", id);
1848 event.checkCode(VoldResponseCode.AsecPathResult);
1849 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001850 } catch (NativeDaemonConnectorException e) {
1851 int code = e.getCode();
1852 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001853 Slog.i(TAG, String.format("Container '%s' not found", id));
1854 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001855 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001856 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001857 }
1858 }
San Mehat22dd86e2010-01-12 12:21:18 -08001859 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001860
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001861 public String getSecureContainerFilesystemPath(String id) {
1862 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1863 waitForReady();
1864 warnOnNotMounted();
1865
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001866 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001867 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001868 event = mConnector.execute("asec", "fspath", id);
1869 event.checkCode(VoldResponseCode.AsecPathResult);
1870 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001871 } catch (NativeDaemonConnectorException e) {
1872 int code = e.getCode();
1873 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1874 Slog.i(TAG, String.format("Container '%s' not found", id));
1875 return null;
1876 } else {
1877 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1878 }
1879 }
1880 }
1881
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001882 public void finishMediaUpdate() {
1883 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1884 }
Kenny Root02c87302010-07-01 08:10:18 -07001885
Kenny Roota02b8b02010-08-05 16:14:17 -07001886 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1887 if (callerUid == android.os.Process.SYSTEM_UID) {
1888 return true;
1889 }
1890
Kenny Root02c87302010-07-01 08:10:18 -07001891 if (packageName == null) {
1892 return false;
1893 }
1894
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001895 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001896
1897 if (DEBUG_OBB) {
1898 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1899 packageUid + ", callerUid = " + callerUid);
1900 }
1901
1902 return callerUid == packageUid;
1903 }
1904
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001905 public String getMountedObbPath(String rawPath) {
1906 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001907
Kenny Root02c87302010-07-01 08:10:18 -07001908 waitForReady();
1909 warnOnNotMounted();
1910
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001911 final ObbState state;
1912 synchronized (mObbPathToStateMap) {
1913 state = mObbPathToStateMap.get(rawPath);
1914 }
1915 if (state == null) {
1916 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1917 return null;
1918 }
1919
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001920 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001921 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001922 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001923 event.checkCode(VoldResponseCode.AsecPathResult);
1924 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001925 } catch (NativeDaemonConnectorException e) {
1926 int code = e.getCode();
1927 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001928 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001929 } else {
1930 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1931 }
1932 }
1933 }
1934
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001935 @Override
1936 public boolean isObbMounted(String rawPath) {
1937 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001938 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001939 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940 }
Kenny Root02c87302010-07-01 08:10:18 -07001941 }
1942
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001943 @Override
1944 public void mountObb(
1945 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1946 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1947 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1948 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001949
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001950 final int callingUid = Binder.getCallingUid();
1951 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1952 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001953 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1954
1955 if (DEBUG_OBB)
1956 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001957 }
1958
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001959 @Override
1960 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1961 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1962
1963 final ObbState existingState;
1964 synchronized (mObbPathToStateMap) {
1965 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001966 }
1967
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001968 if (existingState != null) {
1969 // TODO: separate state object from request data
1970 final int callingUid = Binder.getCallingUid();
1971 final ObbState newState = new ObbState(
1972 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1973 final ObbAction action = new UnmountObbAction(newState, force);
1974 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001975
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001976 if (DEBUG_OBB)
1977 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1978 } else {
1979 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1980 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001981 }
1982
Ben Komalo444eca22011-09-01 15:17:44 -07001983 @Override
1984 public int getEncryptionState() {
1985 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1986 "no permission to access the crypt keeper");
1987
1988 waitForReady();
1989
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001990 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001991 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001992 event = mConnector.execute("cryptfs", "cryptocomplete");
1993 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001994 } catch (NumberFormatException e) {
1995 // Bad result - unexpected.
1996 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1997 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1998 } catch (NativeDaemonConnectorException e) {
1999 // Something bad happened.
2000 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2001 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2002 }
2003 }
2004
2005 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002006 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002007 if (TextUtils.isEmpty(password)) {
2008 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002009 }
2010
Jason parks8888c592011-01-20 22:46:41 -06002011 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2012 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002013
2014 waitForReady();
2015
2016 if (DEBUG_EVENTS) {
2017 Slog.i(TAG, "decrypting storage...");
2018 }
2019
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002020 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002021 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002022 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002023
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002024 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002025 if (code == 0) {
2026 // Decrypt was successful. Post a delayed message before restarting in order
2027 // to let the UI to clear itself
2028 mHandler.postDelayed(new Runnable() {
2029 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002030 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002031 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002032 } catch (NativeDaemonConnectorException e) {
2033 Slog.e(TAG, "problem executing in background", e);
2034 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002035 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002036 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002037 }
2038
2039 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002040 } catch (NativeDaemonConnectorException e) {
2041 // Decryption failed
2042 return e.getCode();
2043 }
Jason parks5af0b912010-11-29 09:05:25 -06002044 }
2045
Jason parks56aa5322011-01-07 09:01:15 -06002046 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002047 if (TextUtils.isEmpty(password)) {
2048 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002049 }
2050
Jason parks8888c592011-01-20 22:46:41 -06002051 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2052 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002053
2054 waitForReady();
2055
2056 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002057 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002058 }
2059
2060 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002061 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002062 } catch (NativeDaemonConnectorException e) {
2063 // Encryption failed
2064 return e.getCode();
2065 }
2066
2067 return 0;
2068 }
2069
Jason parksf7b3cd42011-01-27 09:28:25 -06002070 public int changeEncryptionPassword(String password) {
2071 if (TextUtils.isEmpty(password)) {
2072 throw new IllegalArgumentException("password cannot be empty");
2073 }
2074
2075 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2076 "no permission to access the crypt keeper");
2077
2078 waitForReady();
2079
2080 if (DEBUG_EVENTS) {
2081 Slog.i(TAG, "changing encryption password...");
2082 }
2083
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002084 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002085 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002086 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002087 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002088 } catch (NativeDaemonConnectorException e) {
2089 // Encryption failed
2090 return e.getCode();
2091 }
2092 }
2093
Christopher Tate32418be2011-10-10 13:51:12 -07002094 /**
2095 * Validate a user-supplied password string with cryptfs
2096 */
2097 @Override
2098 public int verifyEncryptionPassword(String password) throws RemoteException {
2099 // Only the system process is permitted to validate passwords
2100 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2101 throw new SecurityException("no permission to access the crypt keeper");
2102 }
2103
2104 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2105 "no permission to access the crypt keeper");
2106
2107 if (TextUtils.isEmpty(password)) {
2108 throw new IllegalArgumentException("password cannot be empty");
2109 }
2110
2111 waitForReady();
2112
2113 if (DEBUG_EVENTS) {
2114 Slog.i(TAG, "validating encryption password...");
2115 }
2116
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002117 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002118 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002119 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002120 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2121 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002122 } catch (NativeDaemonConnectorException e) {
2123 // Encryption failed
2124 return e.getCode();
2125 }
2126 }
2127
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002128 @Override
2129 public StorageVolume[] getVolumeList() {
2130 final int callingUserId = UserHandle.getCallingUserId();
2131 final boolean accessAll = (mContext.checkPermission(
2132 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2133 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2134
2135 synchronized (mVolumesLock) {
2136 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2137 for (StorageVolume volume : mVolumes) {
2138 final UserHandle owner = volume.getOwner();
2139 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2140 if (accessAll || ownerMatch) {
2141 filtered.add(volume);
2142 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002143 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002144 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002145 }
2146 }
2147
Kenny Rootaf9d6672010-10-08 09:21:39 -07002148 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2149 final IBinder binder = obbState.getBinder();
2150 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002151
Kenny Rootaf9d6672010-10-08 09:21:39 -07002152 if (obbStates == null) {
2153 obbStates = new ArrayList<ObbState>();
2154 mObbMounts.put(binder, obbStates);
2155 } else {
2156 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002157 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002158 throw new IllegalStateException("Attempt to add ObbState twice. "
2159 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002160 }
2161 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002162 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002163
2164 obbStates.add(obbState);
2165 try {
2166 obbState.link();
2167 } catch (RemoteException e) {
2168 /*
2169 * The binder died before we could link it, so clean up our state
2170 * and return failure.
2171 */
2172 obbStates.remove(obbState);
2173 if (obbStates.isEmpty()) {
2174 mObbMounts.remove(binder);
2175 }
2176
2177 // Rethrow the error so mountObb can get it
2178 throw e;
2179 }
2180
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002181 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002182 }
2183
Kenny Rootaf9d6672010-10-08 09:21:39 -07002184 private void removeObbStateLocked(ObbState obbState) {
2185 final IBinder binder = obbState.getBinder();
2186 final List<ObbState> obbStates = mObbMounts.get(binder);
2187 if (obbStates != null) {
2188 if (obbStates.remove(obbState)) {
2189 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002190 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002191 if (obbStates.isEmpty()) {
2192 mObbMounts.remove(binder);
2193 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002194 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002195
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002196 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002197 }
2198
Kenny Roota02b8b02010-08-05 16:14:17 -07002199 private class ObbActionHandler extends Handler {
2200 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002201 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002202
2203 ObbActionHandler(Looper l) {
2204 super(l);
2205 }
2206
2207 @Override
2208 public void handleMessage(Message msg) {
2209 switch (msg.what) {
2210 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002211 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002212
2213 if (DEBUG_OBB)
2214 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2215
2216 // If a bind was already initiated we don't really
2217 // need to do anything. The pending install
2218 // will be processed later on.
2219 if (!mBound) {
2220 // If this is the only one pending we might
2221 // have to bind to the service again.
2222 if (!connectToService()) {
2223 Slog.e(TAG, "Failed to bind to media container service");
2224 action.handleError();
2225 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002226 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002227 }
Kenny Root735de3b2010-09-30 14:11:39 -07002228
Kenny Root735de3b2010-09-30 14:11:39 -07002229 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002230 break;
2231 }
2232 case OBB_MCS_BOUND: {
2233 if (DEBUG_OBB)
2234 Slog.i(TAG, "OBB_MCS_BOUND");
2235 if (msg.obj != null) {
2236 mContainerService = (IMediaContainerService) msg.obj;
2237 }
2238 if (mContainerService == null) {
2239 // Something seriously wrong. Bail out
2240 Slog.e(TAG, "Cannot bind to media container service");
2241 for (ObbAction action : mActions) {
2242 // Indicate service bind error
2243 action.handleError();
2244 }
2245 mActions.clear();
2246 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002247 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002248 if (action != null) {
2249 action.execute(this);
2250 }
2251 } else {
2252 // Should never happen ideally.
2253 Slog.w(TAG, "Empty queue");
2254 }
2255 break;
2256 }
2257 case OBB_MCS_RECONNECT: {
2258 if (DEBUG_OBB)
2259 Slog.i(TAG, "OBB_MCS_RECONNECT");
2260 if (mActions.size() > 0) {
2261 if (mBound) {
2262 disconnectService();
2263 }
2264 if (!connectToService()) {
2265 Slog.e(TAG, "Failed to bind to media container service");
2266 for (ObbAction action : mActions) {
2267 // Indicate service bind error
2268 action.handleError();
2269 }
2270 mActions.clear();
2271 }
2272 }
2273 break;
2274 }
2275 case OBB_MCS_UNBIND: {
2276 if (DEBUG_OBB)
2277 Slog.i(TAG, "OBB_MCS_UNBIND");
2278
2279 // Delete pending install
2280 if (mActions.size() > 0) {
2281 mActions.remove(0);
2282 }
2283 if (mActions.size() == 0) {
2284 if (mBound) {
2285 disconnectService();
2286 }
2287 } else {
2288 // There are more pending requests in queue.
2289 // Just post MCS_BOUND message to trigger processing
2290 // of next pending install.
2291 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2292 }
2293 break;
2294 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002295 case OBB_FLUSH_MOUNT_STATE: {
2296 final String path = (String) msg.obj;
2297
2298 if (DEBUG_OBB)
2299 Slog.i(TAG, "Flushing all OBB state for path " + path);
2300
2301 synchronized (mObbMounts) {
2302 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2303
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002304 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002305 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002306 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002307
2308 /*
2309 * If this entry's source file is in the volume path
2310 * that got unmounted, remove it because it's no
2311 * longer valid.
2312 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002313 if (state.canonicalPath.startsWith(path)) {
2314 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002315 }
2316 }
2317
2318 for (final ObbState obbState : obbStatesToRemove) {
2319 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002320 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002321
2322 removeObbStateLocked(obbState);
2323
2324 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002325 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002326 OnObbStateChangeListener.UNMOUNTED);
2327 } catch (RemoteException e) {
2328 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002329 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002330 }
2331 }
2332 }
2333 break;
2334 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002335 }
2336 }
2337
2338 private boolean connectToService() {
2339 if (DEBUG_OBB)
2340 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2341
2342 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2343 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2344 mBound = true;
2345 return true;
2346 }
2347 return false;
2348 }
2349
2350 private void disconnectService() {
2351 mContainerService = null;
2352 mBound = false;
2353 mContext.unbindService(mDefContainerConn);
2354 }
2355 }
2356
2357 abstract class ObbAction {
2358 private static final int MAX_RETRIES = 3;
2359 private int mRetries;
2360
2361 ObbState mObbState;
2362
2363 ObbAction(ObbState obbState) {
2364 mObbState = obbState;
2365 }
2366
2367 public void execute(ObbActionHandler handler) {
2368 try {
2369 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002370 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002371 mRetries++;
2372 if (mRetries > MAX_RETRIES) {
2373 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002374 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002375 handleError();
2376 return;
2377 } else {
2378 handleExecute();
2379 if (DEBUG_OBB)
2380 Slog.i(TAG, "Posting install MCS_UNBIND");
2381 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2382 }
2383 } catch (RemoteException e) {
2384 if (DEBUG_OBB)
2385 Slog.i(TAG, "Posting install MCS_RECONNECT");
2386 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2387 } catch (Exception e) {
2388 if (DEBUG_OBB)
2389 Slog.d(TAG, "Error handling OBB action", e);
2390 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002391 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002392 }
2393 }
2394
Kenny Root05105f72010-09-22 17:29:43 -07002395 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002396 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002397
2398 protected ObbInfo getObbInfo() throws IOException {
2399 ObbInfo obbInfo;
2400 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002401 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002402 } catch (RemoteException e) {
2403 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002404 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002405 obbInfo = null;
2406 }
2407 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002408 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002409 }
2410 return obbInfo;
2411 }
2412
Kenny Rootaf9d6672010-10-08 09:21:39 -07002413 protected void sendNewStatusOrIgnore(int status) {
2414 if (mObbState == null || mObbState.token == null) {
2415 return;
2416 }
2417
Kenny Root38cf8862010-09-26 14:18:51 -07002418 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002419 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002420 } catch (RemoteException e) {
2421 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2422 }
2423 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002424 }
2425
2426 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002427 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002428 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002429
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002430 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002431 super(obbState);
2432 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002433 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002434 }
2435
Jason parks5af0b912010-11-29 09:05:25 -06002436 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002437 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002438 waitForReady();
2439 warnOnNotMounted();
2440
Kenny Root38cf8862010-09-26 14:18:51 -07002441 final ObbInfo obbInfo = getObbInfo();
2442
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002443 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2445 + " which is owned by " + obbInfo.packageName);
2446 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2447 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002448 }
2449
Kenny Rootaf9d6672010-10-08 09:21:39 -07002450 final boolean isMounted;
2451 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002452 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002453 }
2454 if (isMounted) {
2455 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2456 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2457 return;
2458 }
2459
Kenny Rootaf9d6672010-10-08 09:21:39 -07002460 final String hashedKey;
2461 if (mKey == null) {
2462 hashedKey = "none";
2463 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002464 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002465 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2466
2467 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2468 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2469 SecretKey key = factory.generateSecret(ks);
2470 BigInteger bi = new BigInteger(key.getEncoded());
2471 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002472 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002473 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2474 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2475 return;
2476 } catch (InvalidKeySpecException e) {
2477 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2478 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002479 return;
2480 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002481 }
Kenny Root38cf8862010-09-26 14:18:51 -07002482
Kenny Rootaf9d6672010-10-08 09:21:39 -07002483 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002484 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002485 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2486 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002487 } catch (NativeDaemonConnectorException e) {
2488 int code = e.getCode();
2489 if (code != VoldResponseCode.OpFailedStorageBusy) {
2490 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002491 }
2492 }
2493
Kenny Rootaf9d6672010-10-08 09:21:39 -07002494 if (rc == StorageResultCode.OperationSucceeded) {
2495 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002496 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002497
2498 synchronized (mObbMounts) {
2499 addObbStateLocked(mObbState);
2500 }
2501
2502 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002503 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002504 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002505
Kenny Rootaf9d6672010-10-08 09:21:39 -07002506 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002507 }
2508 }
2509
Jason parks5af0b912010-11-29 09:05:25 -06002510 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002511 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002512 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002513 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002514
2515 @Override
2516 public String toString() {
2517 StringBuilder sb = new StringBuilder();
2518 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002519 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002520 sb.append('}');
2521 return sb.toString();
2522 }
2523 }
2524
2525 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002526 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002527
2528 UnmountObbAction(ObbState obbState, boolean force) {
2529 super(obbState);
2530 mForceUnmount = force;
2531 }
2532
Jason parks5af0b912010-11-29 09:05:25 -06002533 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002534 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002535 waitForReady();
2536 warnOnNotMounted();
2537
Kenny Root38cf8862010-09-26 14:18:51 -07002538 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002539
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002540 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002541 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002542 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002543 }
Kenny Root38cf8862010-09-26 14:18:51 -07002544
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002545 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002546 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2547 return;
2548 }
2549
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002550 if (existingState.ownerGid != mObbState.ownerGid) {
2551 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2552 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002553 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2554 return;
2555 }
2556
Kenny Rootaf9d6672010-10-08 09:21:39 -07002557 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002558 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002559 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002560 if (mForceUnmount) {
2561 cmd.appendArg("force");
2562 }
2563 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002564 } catch (NativeDaemonConnectorException e) {
2565 int code = e.getCode();
2566 if (code == VoldResponseCode.OpFailedStorageBusy) {
2567 rc = StorageResultCode.OperationFailedStorageBusy;
2568 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2569 // If it's not mounted then we've already won.
2570 rc = StorageResultCode.OperationSucceeded;
2571 } else {
2572 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002573 }
2574 }
2575
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 if (rc == StorageResultCode.OperationSucceeded) {
2577 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002578 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002579 }
2580
Kenny Rootaf9d6672010-10-08 09:21:39 -07002581 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002582 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002583 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002584 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002585 }
2586 }
2587
Jason parks5af0b912010-11-29 09:05:25 -06002588 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002589 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002590 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002591 }
2592
2593 @Override
2594 public String toString() {
2595 StringBuilder sb = new StringBuilder();
2596 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002597 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002598 sb.append(",force=");
2599 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002600 sb.append('}');
2601 return sb.toString();
2602 }
Kenny Root02c87302010-07-01 08:10:18 -07002603 }
Kenny Root38cf8862010-09-26 14:18:51 -07002604
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002605 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002606 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2607 // TODO: allow caller to provide Environment for full testing
2608
2609 // Only adjust paths when storage is emulated
2610 if (!Environment.isExternalStorageEmulated()) {
2611 return canonicalPath;
2612 }
2613
2614 String path = canonicalPath.toString();
2615
2616 // First trim off any external storage prefix
2617 final UserEnvironment userEnv = new UserEnvironment(userId);
2618
2619 // /storage/emulated/0
2620 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2621 // /storage/emulated_legacy
2622 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2623 .toString();
2624
2625 if (path.startsWith(externalPath)) {
2626 path = path.substring(externalPath.length() + 1);
2627 } else if (path.startsWith(legacyExternalPath)) {
2628 path = path.substring(legacyExternalPath.length() + 1);
2629 } else {
2630 return canonicalPath;
2631 }
2632
2633 // Handle special OBB paths on emulated storage
2634 final String obbPath = "Android/obb";
2635 if (path.startsWith(obbPath)) {
2636 path = path.substring(obbPath.length() + 1);
2637
2638 if (forVold) {
2639 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2640 } else {
2641 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2642 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2643 }
2644 }
2645
2646 // Handle normal external storage paths
2647 if (forVold) {
2648 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2649 } else {
2650 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2651 }
2652 }
2653
Kenny Root38cf8862010-09-26 14:18:51 -07002654 @Override
2655 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2656 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2657 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2658 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2659 + " without permission " + android.Manifest.permission.DUMP);
2660 return;
2661 }
2662
Kenny Root38cf8862010-09-26 14:18:51 -07002663 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002664 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002665
Kenny Rootaf9d6672010-10-08 09:21:39 -07002666 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2667 while (binders.hasNext()) {
2668 Entry<IBinder, List<ObbState>> e = binders.next();
2669 pw.print(" Key="); pw.println(e.getKey().toString());
2670 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002671 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002672 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002673 }
2674 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002675
2676 pw.println("");
2677 pw.println(" mObbPathToStateMap:");
2678 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2679 while (maps.hasNext()) {
2680 final Entry<String, ObbState> e = maps.next();
2681 pw.print(" "); pw.print(e.getKey());
2682 pw.print(" -> "); pw.println(e.getValue().toString());
2683 }
Kenny Root38cf8862010-09-26 14:18:51 -07002684 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002685
2686 pw.println("");
2687
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002688 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002689 pw.println(" mVolumes:");
2690
2691 final int N = mVolumes.size();
2692 for (int i = 0; i < N; i++) {
2693 final StorageVolume v = mVolumes.get(i);
2694 pw.print(" ");
2695 pw.println(v.toString());
2696 }
2697 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002698
2699 pw.println();
2700 pw.println(" mConnection:");
2701 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002704 /** {@inheritDoc} */
2705 public void monitor() {
2706 if (mConnector != null) {
2707 mConnector.monitor();
2708 }
2709 }
2710}