blob: e8d7882017655e91689fd3aac611affe8c150884 [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;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040040import 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.IMountService;
49import android.os.storage.IMountServiceListener;
50import android.os.storage.IMountShutdownObserver;
51import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070052import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070053import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070054import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060055import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070057import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.Xml;
59
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080060import com.android.internal.annotations.GuardedBy;
61import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070062import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070063import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070064import com.android.internal.util.XmlUtils;
65import com.android.server.NativeDaemonConnector.Command;
66import com.android.server.am.ActivityManagerService;
67import com.android.server.pm.PackageManagerService;
68import com.android.server.pm.UserManagerService;
69import com.google.android.collect.Lists;
70import com.google.android.collect.Maps;
71
Mike Lockwood2f6a3882011-05-09 19:08:06 -070072import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070073
Jeff Sharkeyb049e212012-09-07 23:16:01 -070074import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070076import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070078import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070079import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070080import java.security.spec.InvalidKeySpecException;
81import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080082import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070083import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080084import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070085import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070086import java.util.LinkedList;
87import java.util.List;
88import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070089import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070090import java.util.concurrent.CountDownLatch;
91import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Kenny Root3b1abba2010-10-13 15:00:07 -070093import javax.crypto.SecretKey;
94import javax.crypto.SecretKeyFactory;
95import javax.crypto.spec.PBEKeySpec;
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097/**
San Mehatb1043402010-02-05 08:26:50 -080098 * MountService implements back-end services for platform storage
99 * management.
100 * @hide - Applications should use android.os.storage.StorageManager
101 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700103class MountService extends IMountService.Stub
104 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600105
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700106 // TODO: listen for user creation/deletion
107
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800108 private static final boolean LOCAL_LOGD = false;
109 private static final boolean DEBUG_UNMOUNT = false;
110 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800111 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700112
Kenny Root07714d42011-08-17 17:49:28 -0700113 // Disable this since it messes up long-running cryptfs operations.
114 private static final boolean WATCHDOG_ENABLE = false;
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private static final String TAG = "MountService";
117
Kenny Root305bcbf2010-09-03 07:56:38 -0700118 private static final String VOLD_TAG = "VoldConnector";
119
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700120 /** Maximum number of ASEC containers allowed to be mounted. */
121 private static final int MAX_CONTAINERS = 250;
122
San Mehat4270e1e2010-01-29 05:32:19 -0800123 /*
124 * Internal vold volume state constants
125 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800126 class VolumeState {
127 public static final int Init = -1;
128 public static final int NoMedia = 0;
129 public static final int Idle = 1;
130 public static final int Pending = 2;
131 public static final int Checking = 3;
132 public static final int Mounted = 4;
133 public static final int Unmounting = 5;
134 public static final int Formatting = 6;
135 public static final int Shared = 7;
136 public static final int SharedMnt = 8;
137 }
138
San Mehat4270e1e2010-01-29 05:32:19 -0800139 /*
140 * Internal vold response code constants
141 */
San Mehat22dd86e2010-01-12 12:21:18 -0800142 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800143 /*
144 * 100 series - Requestion action was initiated; expect another reply
145 * before proceeding with a new command.
146 */
San Mehat22dd86e2010-01-12 12:21:18 -0800147 public static final int VolumeListResult = 110;
148 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800149 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800150
San Mehat4270e1e2010-01-29 05:32:19 -0800151 /*
152 * 200 series - Requestion action has been successfully completed.
153 */
154 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800155 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800156 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800157
San Mehat4270e1e2010-01-29 05:32:19 -0800158 /*
159 * 400 series - Command was accepted, but the requested action
160 * did not take place.
161 */
162 public static final int OpFailedNoMedia = 401;
163 public static final int OpFailedMediaBlank = 402;
164 public static final int OpFailedMediaCorrupt = 403;
165 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800166 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700167 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800168
169 /*
170 * 600 series - Unsolicited broadcasts.
171 */
San Mehat22dd86e2010-01-12 12:21:18 -0800172 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800173 public static final int VolumeDiskInserted = 630;
174 public static final int VolumeDiskRemoved = 631;
175 public static final int VolumeBadRemoval = 632;
176 }
177
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700178 private Context mContext;
179 private NativeDaemonConnector mConnector;
180
181 private final Object mVolumesLock = new Object();
182
183 /** When defined, base template for user-specific {@link StorageVolume}. */
184 private StorageVolume mEmulatedTemplate;
185
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800186 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700187 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
188 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800189 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700190 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
191 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700193 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
194
195 private volatile boolean mSystemReady = false;
196
San Mehat4270e1e2010-01-29 05:32:19 -0800197 private PackageManagerService mPms;
198 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700199 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800200 // Used as a lock for methods that register/unregister listeners.
201 final private ArrayList<MountServiceBinderListener> mListeners =
202 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800203 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
204 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800205 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800206
San Mehat6cdd9c02010-02-09 14:45:20 -0800207 /**
208 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800209 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800210 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800211 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800212
Kenny Root02c87302010-07-01 08:10:18 -0700213 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700214 * The size of the crypto algorithm key in bits for OBB files. Currently
215 * Twofish is used which takes 128-bit keys.
216 */
217 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
218
219 /**
220 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
221 * 1024 is reasonably secure and not too slow.
222 */
223 private static final int PBKDF2_HASH_ROUNDS = 1024;
224
225 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700226 * Mounted OBB tracking information. Used to track the current state of all
227 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700228 */
Kenny Root735de3b2010-09-30 14:11:39 -0700229 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700230
231 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700232 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
233
234 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700235 public ObbState(String rawPath, String canonicalPath, int callingUid,
236 IObbActionListener token, int nonce) {
237 this.rawPath = rawPath;
238 this.canonicalPath = canonicalPath.toString();
239
240 final int userId = UserHandle.getUserId(callingUid);
241 this.ownerPath = buildObbPath(canonicalPath, userId, false);
242 this.voldPath = buildObbPath(canonicalPath, userId, true);
243
244 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700245 this.token = token;
246 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700247 }
248
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700249 final String rawPath;
250 final String canonicalPath;
251 final String ownerPath;
252 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700253
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700254 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700255
Kenny Rootaf9d6672010-10-08 09:21:39 -0700256 // Token of remote Binder caller
257 final IObbActionListener token;
258
259 // Identifier to pass back to the token
260 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700261
Kenny Root735de3b2010-09-30 14:11:39 -0700262 public IBinder getBinder() {
263 return token.asBinder();
264 }
265
Kenny Roota02b8b02010-08-05 16:14:17 -0700266 @Override
267 public void binderDied() {
268 ObbAction action = new UnmountObbAction(this, true);
269 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700270 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700271
Kenny Root5919ac62010-10-05 09:49:40 -0700272 public void link() throws RemoteException {
273 getBinder().linkToDeath(this, 0);
274 }
275
276 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700277 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700278 }
Kenny Root38cf8862010-09-26 14:18:51 -0700279
280 @Override
281 public String toString() {
282 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700283 sb.append("rawPath=").append(rawPath);
284 sb.append(",canonicalPath=").append(canonicalPath);
285 sb.append(",ownerPath=").append(ownerPath);
286 sb.append(",voldPath=").append(voldPath);
287 sb.append(",ownerGid=").append(ownerGid);
288 sb.append(",token=").append(token);
289 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700290 sb.append('}');
291 return sb.toString();
292 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700293 }
294
295 // OBB Action Handler
296 final private ObbActionHandler mObbActionHandler;
297
298 // OBB action handler messages
299 private static final int OBB_RUN_ACTION = 1;
300 private static final int OBB_MCS_BOUND = 2;
301 private static final int OBB_MCS_UNBIND = 3;
302 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700303 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700304
305 /*
306 * Default Container Service information
307 */
308 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
309 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
310
311 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
312
313 class DefaultContainerConnection implements ServiceConnection {
314 public void onServiceConnected(ComponentName name, IBinder service) {
315 if (DEBUG_OBB)
316 Slog.i(TAG, "onServiceConnected");
317 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
318 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
319 }
320
321 public void onServiceDisconnected(ComponentName name) {
322 if (DEBUG_OBB)
323 Slog.i(TAG, "onServiceDisconnected");
324 }
325 };
326
327 // Used in the ObbActionHandler
328 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700329
330 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800331 private static final int H_UNMOUNT_PM_UPDATE = 1;
332 private static final int H_UNMOUNT_PM_DONE = 2;
333 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700334 private static final int H_SYSTEM_READY = 4;
335
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800336 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
337 private static final int MAX_UNMOUNT_RETRIES = 4;
338
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800339 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700340 final String path;
341 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700342 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800344
Ben Komalo13c71972011-09-07 16:35:56 -0700345 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 retries = 0;
347 this.path = path;
348 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700349 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800351
352 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700353 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700354 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800355 }
356 }
357
358 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700359 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800360
361 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700362 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800363 this.method = method;
364 }
365
366 @Override
367 void handleFinished() {
368 super.handleFinished();
369 doShareUnshareVolume(path, method, true);
370 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800371 }
372
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800373 class ShutdownCallBack extends UnmountCallBack {
374 IMountShutdownObserver observer;
375 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700376 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800377 this.observer = observer;
378 }
379
380 @Override
381 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700382 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 if (observer != null) {
384 try {
385 observer.onShutDownComplete(ret);
386 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700387 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800388 }
389 }
390 }
391 }
392
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400393 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800394 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700395 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800396
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400397 MountServiceHandler(Looper l) {
398 super(l);
399 }
400
Jason parks5af0b912010-11-29 09:05:25 -0600401 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402 public void handleMessage(Message msg) {
403 switch (msg.what) {
404 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700405 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800406 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
407 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700408 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800409 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700410 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700411 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700412 mUpdatingStatus = true;
413 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800414 }
415 break;
416 }
417 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700419 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700420 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800421 int size = mForceUnmounts.size();
422 int sizeArr[] = new int[size];
423 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700424 // Kill processes holding references first
425 ActivityManagerService ams = (ActivityManagerService)
426 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800427 for (int i = 0; i < size; i++) {
428 UnmountCallBack ucb = mForceUnmounts.get(i);
429 String path = ucb.path;
430 boolean done = false;
431 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800432 done = true;
433 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 int pids[] = getStorageUsers(path);
435 if (pids == null || pids.length == 0) {
436 done = true;
437 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800438 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800439 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700440 // Confirm if file references have been freed.
441 pids = getStorageUsers(path);
442 if (pids == null || pids.length == 0) {
443 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800444 }
445 }
446 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700447 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
448 // Retry again
449 Slog.i(TAG, "Retrying to kill storage users again");
450 mHandler.sendMessageDelayed(
451 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
452 ucb.retries++),
453 RETRY_UNMOUNT_DELAY);
454 } else {
455 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
456 Slog.i(TAG, "Failed to unmount media inspite of " +
457 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
458 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800459 sizeArr[sizeArrN++] = i;
460 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
461 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800462 }
463 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800464 // Remove already processed elements from list.
465 for (int i = (sizeArrN-1); i >= 0; i--) {
466 mForceUnmounts.remove(sizeArr[i]);
467 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800468 break;
469 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700470 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700471 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800472 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800473 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800474 break;
475 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700476 case H_SYSTEM_READY: {
477 try {
478 handleSystemReady();
479 } catch (Exception ex) {
480 Slog.e(TAG, "Boot-time mount exception", ex);
481 }
482 break;
483 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800484 }
485 }
486 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700487
488 private final HandlerThread mHandlerThread;
489 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800490
Kenny Root51a573c2012-05-17 13:30:28 -0700491 void waitForAsecScan() {
492 waitForLatch(mAsecsScanned);
493 }
494
San Mehat207e5382010-02-04 20:46:54 -0800495 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700496 waitForLatch(mConnectedSignal);
497 }
498
499 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700500 for (;;) {
501 try {
502 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800503 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700504 } else {
505 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
506 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800507 }
Kenny Root51a573c2012-05-17 13:30:28 -0700508 } catch (InterruptedException e) {
509 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800510 }
San Mehat207e5382010-02-04 20:46:54 -0800511 }
San Mehat1f6301e2010-01-07 22:40:27 -0800512 }
Kenny Root02c87302010-07-01 08:10:18 -0700513
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700514 private void handleSystemReady() {
515 // Snapshot current volume states since it's not safe to call into vold
516 // while holding locks.
517 final HashMap<String, String> snapshot;
518 synchronized (mVolumesLock) {
519 snapshot = new HashMap<String, String>(mVolumeStates);
520 }
521
522 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
523 final String path = entry.getKey();
524 final String state = entry.getValue();
525
526 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
527 int rc = doMountVolume(path);
528 if (rc != StorageResultCode.OperationSucceeded) {
529 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
530 rc));
531 }
532 } else if (state.equals(Environment.MEDIA_SHARED)) {
533 /*
534 * Bootstrap UMS enabled state since vold indicates
535 * the volume is shared (runtime restart while ums enabled)
536 */
537 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
538 VolumeState.Shared);
539 }
540 }
541
542 // Push mounted state for all emulated storage
543 synchronized (mVolumesLock) {
544 for (StorageVolume volume : mVolumes) {
545 if (volume.isEmulated()) {
546 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
547 }
548 }
549 }
550
551 /*
552 * If UMS was connected on boot, send the connected event
553 * now that we're up.
554 */
555 if (mSendUmsConnectedOnBoot) {
556 sendUmsIntent(true);
557 mSendUmsConnectedOnBoot = false;
558 }
559 }
560
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700561 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
562 @Override
563 public void onReceive(Context context, Intent intent) {
564 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
565 if (userId == -1) return;
566 final UserHandle user = new UserHandle(userId);
567
568 final String action = intent.getAction();
569 if (Intent.ACTION_USER_ADDED.equals(action)) {
570 synchronized (mVolumesLock) {
571 createEmulatedVolumeForUserLocked(user);
572 }
573
574 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
575 synchronized (mVolumesLock) {
576 final List<StorageVolume> toRemove = Lists.newArrayList();
577 for (StorageVolume volume : mVolumes) {
578 if (user.equals(volume.getOwner())) {
579 toRemove.add(volume);
580 }
581 }
582 for (StorageVolume volume : toRemove) {
583 removeVolumeLocked(volume);
584 }
585 }
586 }
587 }
588 };
589
590 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
591 @Override
592 public void onReceive(Context context, Intent intent) {
593 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
594 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
595 notifyShareAvailabilityChange(available);
596 }
597 };
598
Svetoslava7452ee2013-03-20 12:06:59 -0700599 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
600 @Override
601 public void onReceive(Context context, Intent intent) {
602 waitForReady();
603 String action = intent.getAction();
604 // Since fstrim will be run on a daily basis we do not expect
605 // fstrim to be too long, so it is not interruptible. We will
606 // implement interruption only in case we see issues.
607 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
608 try {
609 // This method runs on the handler thread,
610 // so it is safe to directly call into vold.
611 mConnector.execute("fstrim", "dotrim");
612 } catch (NativeDaemonConnectorException ndce) {
613 Slog.e(TAG, "Failed to run fstrim!");
614 }
615 }
616 }
617 };
618
San Mehat4270e1e2010-01-29 05:32:19 -0800619 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
620 final IMountServiceListener mListener;
621
622 MountServiceBinderListener(IMountServiceListener listener) {
623 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700624
San Mehat91c77612010-01-07 10:39:41 -0800625 }
626
San Mehat4270e1e2010-01-29 05:32:19 -0800627 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700628 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700629 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800630 mListeners.remove(this);
631 mListener.asBinder().unlinkToDeath(this, 0);
632 }
633 }
634 }
635
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800636 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800637 // TODO: Add support for multiple share methods
638 if (!method.equals("ums")) {
639 throw new IllegalArgumentException(String.format("Method %s not supported", method));
640 }
641
San Mehat4270e1e2010-01-29 05:32:19 -0800642 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800643 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800644 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700645 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800646 }
San Mehat4270e1e2010-01-29 05:32:19 -0800647 }
648
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700649 private void updatePublicVolumeState(StorageVolume volume, String state) {
650 final String path = volume.getPath();
651 final String oldState;
652 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400653 oldState = mVolumeStates.put(path, state);
654 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700655
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400656 if (state.equals(oldState)) {
657 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
658 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800659 return;
660 }
San Mehatb1043402010-02-05 08:26:50 -0800661
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400662 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700663
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700664 // Tell PackageManager about changes to primary volume state, but only
665 // when not emulated.
666 if (volume.isPrimary() && !volume.isEmulated()) {
667 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
668 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400669
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700670 /*
671 * Some OBBs might have been unmounted when this volume was
672 * unmounted, so send a message to the handler to let it know to
673 * remove those from the list of mounted OBBS.
674 */
675 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
676 OBB_FLUSH_MOUNT_STATE, path));
677 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
678 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400679 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800680 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700681
San Mehat4270e1e2010-01-29 05:32:19 -0800682 synchronized (mListeners) {
683 for (int i = mListeners.size() -1; i >= 0; i--) {
684 MountServiceBinderListener bl = mListeners.get(i);
685 try {
San Mehatb1043402010-02-05 08:26:50 -0800686 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800687 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700688 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800689 mListeners.remove(i);
690 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700691 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800692 }
693 }
694 }
695 }
696
697 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800698 * Callback from NativeDaemonConnector
699 */
700 public void onDaemonConnected() {
701 /*
702 * Since we'll be calling back into the NativeDaemonConnector,
703 * we need to do our work in a new thread.
704 */
Kenny Root51a573c2012-05-17 13:30:28 -0700705 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600706 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800707 public void run() {
708 /**
709 * Determine media state and UMS detection status
710 */
San Mehat4270e1e2010-01-29 05:32:19 -0800711 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800712 final String[] vols = NativeDaemonEvent.filterMessageList(
713 mConnector.executeForList("volume", "list"),
714 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800715 for (String volstr : vols) {
716 String[] tok = volstr.split(" ");
717 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400718 String path = tok[1];
719 String state = Environment.MEDIA_REMOVED;
720
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700721 final StorageVolume volume;
722 synchronized (mVolumesLock) {
723 volume = mVolumesByPath.get(path);
724 }
725
San Mehat4270e1e2010-01-29 05:32:19 -0800726 int st = Integer.parseInt(tok[2]);
727 if (st == VolumeState.NoMedia) {
728 state = Environment.MEDIA_REMOVED;
729 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800730 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800731 } else if (st == VolumeState.Mounted) {
732 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700733 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800734 } else if (st == VolumeState.Shared) {
735 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700736 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800737 } else {
738 throw new Exception(String.format("Unexpected state %d", st));
739 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400740
741 if (state != null) {
742 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700743 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400744 }
San Mehat4270e1e2010-01-29 05:32:19 -0800745 }
746 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700747 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700748 final StorageVolume primary = getPrimaryPhysicalVolume();
749 if (primary != null) {
750 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
751 }
San Mehat4270e1e2010-01-29 05:32:19 -0800752 }
753
San Mehat207e5382010-02-04 20:46:54 -0800754 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600755 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800756 * the hounds!
757 */
Kenny Root51a573c2012-05-17 13:30:28 -0700758 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700759
760 // Let package manager load internal ASECs.
761 mPms.scanAvailableAsecs();
762
763 // Notify people waiting for ASECs to be scanned that it's done.
764 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800765 }
766 }.start();
767 }
768
769 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800770 * Callback from NativeDaemonConnector
771 */
772 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800773 if (DEBUG_EVENTS) {
774 StringBuilder builder = new StringBuilder();
775 builder.append("onEvent::");
776 builder.append(" raw= " + raw);
777 if (cooked != null) {
778 builder.append(" cooked = " );
779 for (String str : cooked) {
780 builder.append(" " + str);
781 }
782 }
San Mehata5078592010-03-25 09:36:54 -0700783 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800784 }
San Mehat4270e1e2010-01-29 05:32:19 -0800785 if (code == VoldResponseCode.VolumeStateChange) {
786 /*
787 * One of the volumes we're managing has changed state.
788 * Format: "NNN Volume <label> <path> state changed
789 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
790 */
791 notifyVolumeStateChange(
792 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
793 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800794 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
795 (code == VoldResponseCode.VolumeDiskRemoved) ||
796 (code == VoldResponseCode.VolumeBadRemoval)) {
797 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
798 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
799 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400800 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800801 final String label = cooked[2];
802 final String path = cooked[3];
803 int major = -1;
804 int minor = -1;
805
806 try {
807 String devComp = cooked[6].substring(1, cooked[6].length() -1);
808 String[] devTok = devComp.split(":");
809 major = Integer.parseInt(devTok[0]);
810 minor = Integer.parseInt(devTok[1]);
811 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700812 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800813 }
814
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700815 final StorageVolume volume;
816 final String state;
817 synchronized (mVolumesLock) {
818 volume = mVolumesByPath.get(path);
819 state = mVolumeStates.get(path);
820 }
821
San Mehat4270e1e2010-01-29 05:32:19 -0800822 if (code == VoldResponseCode.VolumeDiskInserted) {
823 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600824 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800825 public void run() {
826 try {
827 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800828 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700829 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800830 }
831 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700832 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800833 }
834 }
835 }.start();
836 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
837 /*
838 * This event gets trumped if we're already in BAD_REMOVAL state
839 */
840 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
841 return true;
842 }
843 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700844 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700845 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
846 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800847
San Mehata5078592010-03-25 09:36:54 -0700848 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700849 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400850 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800851 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700852 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800853 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700854 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400855 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800856
San Mehata5078592010-03-25 09:36:54 -0700857 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700858 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400859 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800860 } else {
San Mehata5078592010-03-25 09:36:54 -0700861 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800862 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400863
864 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700865 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400866 }
San Mehat4270e1e2010-01-29 05:32:19 -0800867 } else {
868 return false;
869 }
870
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400871 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800872 }
873
San Mehat207e5382010-02-04 20:46:54 -0800874 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700875 final StorageVolume volume;
876 final String state;
877 synchronized (mVolumesLock) {
878 volume = mVolumesByPath.get(path);
879 state = getVolumeState(path);
880 }
881
882 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800883
Mike Lockwooda5250c92011-05-23 13:44:04 -0400884 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800885
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500886 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700887 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700888 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500889 }
890
San Mehat4270e1e2010-01-29 05:32:19 -0800891 if (newState == VolumeState.Init) {
892 } else if (newState == VolumeState.NoMedia) {
893 // NoMedia is handled via Disk Remove events
894 } else if (newState == VolumeState.Idle) {
895 /*
896 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
897 * if we're in the process of enabling UMS
898 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700899 if (!state.equals(
900 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
901 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800902 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700903 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700904 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400905 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800906 }
907 } else if (newState == VolumeState.Pending) {
908 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700909 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700910 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400911 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800912 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700913 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700914 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400915 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800916 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400917 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800918 } else if (newState == VolumeState.Formatting) {
919 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700920 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800921 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700922 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
923 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800924
San Mehata5078592010-03-25 09:36:54 -0700925 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700926 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400927 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700928 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800929 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700930 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800931 return;
932 } else {
San Mehata5078592010-03-25 09:36:54 -0700933 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800934 }
935
Mike Lockwooda5250c92011-05-23 13:44:04 -0400936 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700937 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800938 }
939 }
940
San Mehat207e5382010-02-04 20:46:54 -0800941 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800942 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800943
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700944 final StorageVolume volume;
945 synchronized (mVolumesLock) {
946 volume = mVolumesByPath.get(path);
947 }
948
San Mehata5078592010-03-25 09:36:54 -0700949 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800950 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800951 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800952 } catch (NativeDaemonConnectorException e) {
953 /*
954 * Mount failed for some reason
955 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400956 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800957 int code = e.getCode();
958 if (code == VoldResponseCode.OpFailedNoMedia) {
959 /*
960 * Attempt to mount but no media inserted
961 */
San Mehatb1043402010-02-05 08:26:50 -0800962 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800963 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700964 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800965 /*
966 * Media is blank or does not contain a supported filesystem
967 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700968 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400969 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800970 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800971 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700972 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800973 /*
974 * Volume consistency check failed
975 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700976 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400977 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800978 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800979 } else {
San Mehatb1043402010-02-05 08:26:50 -0800980 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800981 }
982
983 /*
984 * Send broadcast intent (if required for the failure)
985 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400986 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700987 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800988 }
989 }
990
991 return rc;
992 }
993
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800994 /*
995 * If force is not set, we do not unmount if there are
996 * processes holding references to the volume about to be unmounted.
997 * If force is set, all the processes holding references need to be
998 * killed via the ActivityManager before actually unmounting the volume.
999 * This might even take a while and might be retried after timed delays
1000 * to make sure we dont end up in an instable state and kill some core
1001 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001002 * If removeEncryption is set, force is implied, and the system will remove any encryption
1003 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001004 */
Ben Komalo13c71972011-09-07 16:35:56 -07001005 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001006 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001007 return VoldResponseCode.OpFailedVolNotMounted;
1008 }
Kenny Rootaa485402010-09-14 14:49:41 -07001009
1010 /*
1011 * Force a GC to make sure AssetManagers in other threads of the
1012 * system_server are cleaned up. We have to do this since AssetManager
1013 * instances are kept as a WeakReference and it's possible we have files
1014 * open on the external storage.
1015 */
1016 Runtime.getRuntime().gc();
1017
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001018 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001019 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001020 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001021 final Command cmd = new Command("volume", "unmount", path);
1022 if (removeEncryption) {
1023 cmd.appendArg("force_and_revert");
1024 } else if (force) {
1025 cmd.appendArg("force");
1026 }
1027 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001028 // We unmounted the volume. None of the asec containers are available now.
1029 synchronized (mAsecMountSet) {
1030 mAsecMountSet.clear();
1031 }
San Mehatb1043402010-02-05 08:26:50 -08001032 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001033 } catch (NativeDaemonConnectorException e) {
1034 // Don't worry about mismatch in PackageManager since the
1035 // call back will handle the status changes any way.
1036 int code = e.getCode();
1037 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001038 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001039 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1040 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001041 } else {
San Mehatb1043402010-02-05 08:26:50 -08001042 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001043 }
1044 }
1045 }
1046
1047 private int doFormatVolume(String path) {
1048 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001049 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001050 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001051 } catch (NativeDaemonConnectorException e) {
1052 int code = e.getCode();
1053 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001054 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001055 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001056 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001057 } else {
San Mehatb1043402010-02-05 08:26:50 -08001058 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001059 }
1060 }
1061 }
1062
San Mehatb1043402010-02-05 08:26:50 -08001063 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001064 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001065 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001066 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001067 } catch (NativeDaemonConnectorException ex) {
1068 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1069 return false;
1070 }
San Mehatb1043402010-02-05 08:26:50 -08001071
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001072 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1073 return event.getMessage().endsWith("enabled");
1074 } else {
1075 return false;
San Mehatb1043402010-02-05 08:26:50 -08001076 }
San Mehatb1043402010-02-05 08:26:50 -08001077 }
1078
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001079 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001080 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001081 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001082 for (int i = mListeners.size() -1; i >= 0; i--) {
1083 MountServiceBinderListener bl = mListeners.get(i);
1084 try {
San Mehatb1043402010-02-05 08:26:50 -08001085 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001086 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001087 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001088 mListeners.remove(i);
1089 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001090 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001091 }
1092 }
1093 }
1094
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001095 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001096 sendUmsIntent(avail);
1097 } else {
1098 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001099 }
San Mehat2fe718a2010-03-11 12:01:49 -08001100
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001101 final StorageVolume primary = getPrimaryPhysicalVolume();
1102 if (avail == false && primary != null
1103 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1104 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001105 /*
1106 * USB mass storage disconnected while enabled
1107 */
1108 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001109 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001110 public void run() {
1111 try {
1112 int rc;
San Mehata5078592010-03-25 09:36:54 -07001113 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001114 doShareUnshareVolume(path, "ums", false);
1115 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001116 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001117 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1118 path, rc));
1119 }
1120 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001121 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001122 }
1123 }
1124 }.start();
1125 }
San Mehat4270e1e2010-01-29 05:32:19 -08001126 }
1127
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001128 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1129 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1130 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1131 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1132 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001133 }
1134
San Mehat6a965af22010-02-24 17:47:30 -08001135 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001136 mContext.sendBroadcastAsUser(
1137 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1138 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001139 }
1140
San Mehat207e5382010-02-04 20:46:54 -08001141 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001142 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1143 throw new SecurityException(String.format("Requires %s permission", perm));
1144 }
1145 }
1146
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001147 // Storage list XML tags
1148 private static final String TAG_STORAGE_LIST = "StorageList";
1149 private static final String TAG_STORAGE = "storage";
1150
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001151 private void readStorageListLocked() {
1152 mVolumes.clear();
1153 mVolumeStates.clear();
1154
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001155 Resources resources = mContext.getResources();
1156
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001157 int id = com.android.internal.R.xml.storage_list;
1158 XmlResourceParser parser = resources.getXml(id);
1159 AttributeSet attrs = Xml.asAttributeSet(parser);
1160
1161 try {
1162 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1163 while (true) {
1164 XmlUtils.nextElement(parser);
1165
1166 String element = parser.getName();
1167 if (element == null) break;
1168
1169 if (TAG_STORAGE.equals(element)) {
1170 TypedArray a = resources.obtainAttributes(attrs,
1171 com.android.internal.R.styleable.Storage);
1172
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001173 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001174 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001175 int descriptionId = a.getResourceId(
1176 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001177 CharSequence description = a.getText(
1178 com.android.internal.R.styleable.Storage_storageDescription);
1179 boolean primary = a.getBoolean(
1180 com.android.internal.R.styleable.Storage_primary, false);
1181 boolean removable = a.getBoolean(
1182 com.android.internal.R.styleable.Storage_removable, false);
1183 boolean emulated = a.getBoolean(
1184 com.android.internal.R.styleable.Storage_emulated, false);
1185 int mtpReserve = a.getInt(
1186 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001187 boolean allowMassStorage = a.getBoolean(
1188 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001189 // resource parser does not support longs, so XML value is in megabytes
1190 long maxFileSize = a.getInt(
1191 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001192
1193 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1194 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001195 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001196 " allowMassStorage: " + allowMassStorage +
1197 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001198
1199 if (emulated) {
1200 // For devices with emulated storage, we create separate
1201 // volumes for each known user.
1202 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1203 true, mtpReserve, false, maxFileSize, null);
1204
1205 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001206 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001207 createEmulatedVolumeForUserLocked(user.getUserHandle());
1208 }
1209
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001210 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001211 if (path == null || description == null) {
1212 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001213 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001214 final StorageVolume volume = new StorageVolume(new File(path),
1215 descriptionId, primary, removable, emulated, mtpReserve,
1216 allowMassStorage, maxFileSize, null);
1217 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001218 }
1219 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001220
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001221 a.recycle();
1222 }
1223 }
1224 } catch (XmlPullParserException e) {
1225 throw new RuntimeException(e);
1226 } catch (IOException e) {
1227 throw new RuntimeException(e);
1228 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001229 // Compute storage ID for each physical volume; emulated storage is
1230 // always 0 when defined.
1231 int index = isExternalStorageEmulated() ? 1 : 0;
1232 for (StorageVolume volume : mVolumes) {
1233 if (!volume.isEmulated()) {
1234 volume.setStorageId(index++);
1235 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001236 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001237 parser.close();
1238 }
1239 }
1240
San Mehat4270e1e2010-01-29 05:32:19 -08001241 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001242 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1243 * using {@link #mEmulatedTemplate} as template.
1244 */
1245 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1246 if (mEmulatedTemplate == null) {
1247 throw new IllegalStateException("Missing emulated volume multi-user template");
1248 }
1249
1250 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1251 final File path = userEnv.getExternalStorageDirectory();
1252 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1253 volume.setStorageId(0);
1254 addVolumeLocked(volume);
1255
1256 if (mSystemReady) {
1257 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1258 } else {
1259 // Place stub status for early callers to find
1260 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1261 }
1262 }
1263
1264 private void addVolumeLocked(StorageVolume volume) {
1265 Slog.d(TAG, "addVolumeLocked() " + volume);
1266 mVolumes.add(volume);
1267 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1268 if (existing != null) {
1269 throw new IllegalStateException(
1270 "Volume at " + volume.getPath() + " already exists: " + existing);
1271 }
1272 }
1273
1274 private void removeVolumeLocked(StorageVolume volume) {
1275 Slog.d(TAG, "removeVolumeLocked() " + volume);
1276 mVolumes.remove(volume);
1277 mVolumesByPath.remove(volume.getPath());
1278 mVolumeStates.remove(volume.getPath());
1279 }
1280
1281 private StorageVolume getPrimaryPhysicalVolume() {
1282 synchronized (mVolumesLock) {
1283 for (StorageVolume volume : mVolumes) {
1284 if (volume.isPrimary() && !volume.isEmulated()) {
1285 return volume;
1286 }
1287 }
1288 }
1289 return null;
1290 }
1291
1292 /**
San Mehat207e5382010-02-04 20:46:54 -08001293 * Constructs a new MountService instance
1294 *
1295 * @param context Binder context for this service
1296 */
1297 public MountService(Context context) {
1298 mContext = context;
1299
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001300 synchronized (mVolumesLock) {
1301 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001302 }
1303
San Mehat207e5382010-02-04 20:46:54 -08001304 // XXX: This will go away soon in favor of IMountServiceObserver
1305 mPms = (PackageManagerService) ServiceManager.getService("package");
1306
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001307 mHandlerThread = new HandlerThread("MountService");
1308 mHandlerThread.start();
1309 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1310
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001311 // Watch for user changes
1312 final IntentFilter userFilter = new IntentFilter();
1313 userFilter.addAction(Intent.ACTION_USER_ADDED);
1314 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1315 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1316
1317 // Watch for USB changes on primary volume
1318 final StorageVolume primary = getPrimaryPhysicalVolume();
1319 if (primary != null && primary.allowMassStorage()) {
1320 mContext.registerReceiver(
1321 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1322 }
1323
Svetoslava7452ee2013-03-20 12:06:59 -07001324 // Watch for idle maintenance changes
1325 IntentFilter idleMaintenanceFilter = new IntentFilter();
1326 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1327 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1328 idleMaintenanceFilter, null, mHandler);
1329
Kenny Roota02b8b02010-08-05 16:14:17 -07001330 // Add OBB Action Handler to MountService thread.
1331 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1332
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001333 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001334 * Create the connection to vold with a maximum queue of twice the
1335 * amount of containers we'd ever expect to have. This keeps an
1336 * "asec list" from blocking a thread repeatedly.
1337 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001338 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001339
Kenny Root305bcbf2010-09-03 07:56:38 -07001340 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001341 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001342
Kenny Root07714d42011-08-17 17:49:28 -07001343 // Add ourself to the Watchdog monitors if enabled.
1344 if (WATCHDOG_ENABLE) {
1345 Watchdog.getInstance().addMonitor(this);
1346 }
San Mehat207e5382010-02-04 20:46:54 -08001347 }
1348
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001349 public void systemReady() {
1350 mSystemReady = true;
1351 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1352 }
1353
San Mehat207e5382010-02-04 20:46:54 -08001354 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001355 * Exposed API calls below here
1356 */
1357
1358 public void registerListener(IMountServiceListener listener) {
1359 synchronized (mListeners) {
1360 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1361 try {
1362 listener.asBinder().linkToDeath(bl, 0);
1363 mListeners.add(bl);
1364 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001365 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001366 }
1367 }
1368 }
1369
1370 public void unregisterListener(IMountServiceListener listener) {
1371 synchronized (mListeners) {
1372 for(MountServiceBinderListener bl : mListeners) {
1373 if (bl.mListener == listener) {
1374 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001375 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001376 return;
1377 }
1378 }
1379 }
1380 }
1381
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001382 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001383 validatePermission(android.Manifest.permission.SHUTDOWN);
1384
San Mehata5078592010-03-25 09:36:54 -07001385 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001386 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001387 for (String path : mVolumeStates.keySet()) {
1388 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001389
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001390 if (state.equals(Environment.MEDIA_SHARED)) {
1391 /*
1392 * If the media is currently shared, unshare it.
1393 * XXX: This is still dangerous!. We should not
1394 * be rebooting at *all* if UMS is enabled, since
1395 * the UMS host could have dirty FAT cache entries
1396 * yet to flush.
1397 */
1398 setUsbMassStorageEnabled(false);
1399 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1400 /*
1401 * If the media is being checked, then we need to wait for
1402 * it to complete before being able to proceed.
1403 */
1404 // XXX: @hackbod - Should we disable the ANR timer here?
1405 int retries = 30;
1406 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1407 try {
1408 Thread.sleep(1000);
1409 } catch (InterruptedException iex) {
1410 Slog.e(TAG, "Interrupted while waiting for media", iex);
1411 break;
1412 }
1413 state = Environment.getExternalStorageState();
1414 }
1415 if (retries == 0) {
1416 Slog.e(TAG, "Timed out waiting for media to check");
1417 }
San Mehat91c77612010-01-07 10:39:41 -08001418 }
San Mehat91c77612010-01-07 10:39:41 -08001419
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001420 if (state.equals(Environment.MEDIA_MOUNTED)) {
1421 // Post a unmount message.
1422 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1423 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1424 } else if (observer != null) {
1425 /*
1426 * Observer is waiting for onShutDownComplete when we are done.
1427 * Since nothing will be done send notification directly so shutdown
1428 * sequence can continue.
1429 */
1430 try {
1431 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1432 } catch (RemoteException e) {
1433 Slog.w(TAG, "RemoteException when shutting down");
1434 }
1435 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001436 }
San Mehat4270e1e2010-01-29 05:32:19 -08001437 }
1438 }
1439
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001440 private boolean getUmsEnabling() {
1441 synchronized (mListeners) {
1442 return mUmsEnabling;
1443 }
1444 }
1445
1446 private void setUmsEnabling(boolean enable) {
1447 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001448 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001449 }
1450 }
1451
San Mehatb1043402010-02-05 08:26:50 -08001452 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001453 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001454
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001455 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001456 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001457 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001458 synchronized (mListeners) {
1459 return mUmsAvailable;
1460 }
San Mehatb1043402010-02-05 08:26:50 -08001461 }
1462
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001463 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001464 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001465 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001466
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001467 final StorageVolume primary = getPrimaryPhysicalVolume();
1468 if (primary == null) return;
1469
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001470 // TODO: Add support for multiple share methods
1471
1472 /*
1473 * If the volume is mounted and we're enabling then unmount it
1474 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001475 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001476 String vs = getVolumeState(path);
1477 String method = "ums";
1478 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1479 // Override for isUsbMassStorageEnabled()
1480 setUmsEnabling(enable);
1481 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1482 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1483 // Clear override
1484 setUmsEnabling(false);
1485 }
1486 /*
1487 * If we disabled UMS then mount the volume
1488 */
1489 if (!enable) {
1490 doShareUnshareVolume(path, method, enable);
1491 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001492 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001493 " after disabling share method " + method);
1494 /*
1495 * Even though the mount failed, the unshare didn't so don't indicate an error.
1496 * The mountVolume() call will have set the storage state and sent the necessary
1497 * broadcasts.
1498 */
1499 }
1500 }
San Mehatb1043402010-02-05 08:26:50 -08001501 }
1502
1503 public boolean isUsbMassStorageEnabled() {
1504 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001505
1506 final StorageVolume primary = getPrimaryPhysicalVolume();
1507 if (primary != null) {
1508 return doGetVolumeShared(primary.getPath(), "ums");
1509 } else {
1510 return false;
1511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001513
San Mehat7fd0fee2009-12-17 07:12:23 -08001514 /**
1515 * @return state of the volume at the specified mount point
1516 */
San Mehat4270e1e2010-01-29 05:32:19 -08001517 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001518 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001519 String state = mVolumeStates.get(mountPoint);
1520 if (state == null) {
1521 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001522 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1523 state = Environment.MEDIA_REMOVED;
1524 } else {
1525 throw new IllegalArgumentException();
1526 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001527 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001528
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001529 return state;
1530 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001531 }
1532
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001533 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001534 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001535 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001536 }
1537
San Mehat4270e1e2010-01-29 05:32:19 -08001538 public int mountVolume(String path) {
1539 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001540
San Mehat207e5382010-02-04 20:46:54 -08001541 waitForReady();
1542 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544
Ben Komalo13c71972011-09-07 16:35:56 -07001545 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001546 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001547 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001549 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001550 if (DEBUG_UNMOUNT) {
1551 Slog.i(TAG, "Unmounting " + path
1552 + " force = " + force
1553 + " removeEncryption = " + removeEncryption);
1554 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001555 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1556 Environment.MEDIA_REMOVED.equals(volState) ||
1557 Environment.MEDIA_SHARED.equals(volState) ||
1558 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1559 // Media already unmounted or cannot be unmounted.
1560 // TODO return valid return code when adding observer call back.
1561 return;
1562 }
Ben Komalo13c71972011-09-07 16:35:56 -07001563 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001564 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566
San Mehat4270e1e2010-01-29 05:32:19 -08001567 public int formatVolume(String path) {
1568 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001569 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001570
San Mehat207e5382010-02-04 20:46:54 -08001571 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001574 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001575 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1576 waitForReady();
1577 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001578 final String[] r = NativeDaemonEvent.filterMessageList(
1579 mConnector.executeForList("storage", "users", path),
1580 VoldResponseCode.StorageUsersListResult);
1581
San Mehatc1b4ce92010-02-16 17:13:03 -08001582 // FMT: <pid> <process name>
1583 int[] data = new int[r.length];
1584 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001585 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001586 try {
1587 data[i] = Integer.parseInt(tok[0]);
1588 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001589 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001590 return new int[0];
1591 }
1592 }
1593 return data;
1594 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001595 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001596 return new int[0];
1597 }
1598 }
1599
San Mehatb1043402010-02-05 08:26:50 -08001600 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001601 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001602 if (primary != null) {
1603 boolean mounted = false;
1604 try {
1605 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001606 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001607 }
1608
1609 if (!mounted) {
1610 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1611 }
San Mehatb1043402010-02-05 08:26:50 -08001612 }
1613 }
1614
San Mehat4270e1e2010-01-29 05:32:19 -08001615 public String[] getSecureContainerList() {
1616 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001617 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001618 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001619
San Mehat4270e1e2010-01-29 05:32:19 -08001620 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001621 return NativeDaemonEvent.filterMessageList(
1622 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001623 } catch (NativeDaemonConnectorException e) {
1624 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
1626 }
San Mehat36972292010-01-06 11:06:32 -08001627
Kenny Root6dceb882012-04-12 14:23:49 -07001628 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1629 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001630 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001631 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001632 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001633
San Mehatb1043402010-02-05 08:26:50 -08001634 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001635 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001636 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1637 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001638 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001639 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001640 }
San Mehata181b212010-02-11 06:50:20 -08001641
1642 if (rc == StorageResultCode.OperationSucceeded) {
1643 synchronized (mAsecMountSet) {
1644 mAsecMountSet.add(id);
1645 }
1646 }
San Mehat4270e1e2010-01-29 05:32:19 -08001647 return rc;
San Mehat36972292010-01-06 11:06:32 -08001648 }
1649
San Mehat4270e1e2010-01-29 05:32:19 -08001650 public int finalizeSecureContainer(String id) {
1651 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001652 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001653
San Mehatb1043402010-02-05 08:26:50 -08001654 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001655 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001656 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001657 /*
1658 * Finalization does a remount, so no need
1659 * to update mAsecMountSet
1660 */
San Mehat4270e1e2010-01-29 05:32:19 -08001661 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001662 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001663 }
San Mehat4270e1e2010-01-29 05:32:19 -08001664 return rc;
San Mehat36972292010-01-06 11:06:32 -08001665 }
1666
Kenny Root6dceb882012-04-12 14:23:49 -07001667 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1668 validatePermission(android.Manifest.permission.ASEC_CREATE);
1669 warnOnNotMounted();
1670
1671 int rc = StorageResultCode.OperationSucceeded;
1672 try {
1673 mConnector.execute("asec", "fixperms", id, gid, filename);
1674 /*
1675 * Fix permissions does a remount, so no need to update
1676 * mAsecMountSet
1677 */
1678 } catch (NativeDaemonConnectorException e) {
1679 rc = StorageResultCode.OperationFailedInternalError;
1680 }
1681 return rc;
1682 }
1683
San Mehatd9709982010-02-18 11:43:03 -08001684 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001685 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001686 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001687 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001688
Kenny Rootaa485402010-09-14 14:49:41 -07001689 /*
1690 * Force a GC to make sure AssetManagers in other threads of the
1691 * system_server are cleaned up. We have to do this since AssetManager
1692 * instances are kept as a WeakReference and it's possible we have files
1693 * open on the external storage.
1694 */
1695 Runtime.getRuntime().gc();
1696
San Mehatb1043402010-02-05 08:26:50 -08001697 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001698 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001699 final Command cmd = new Command("asec", "destroy", id);
1700 if (force) {
1701 cmd.appendArg("force");
1702 }
1703 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001704 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001705 int code = e.getCode();
1706 if (code == VoldResponseCode.OpFailedStorageBusy) {
1707 rc = StorageResultCode.OperationFailedStorageBusy;
1708 } else {
1709 rc = StorageResultCode.OperationFailedInternalError;
1710 }
San Mehat02735bc2010-01-26 15:18:08 -08001711 }
San Mehata181b212010-02-11 06:50:20 -08001712
1713 if (rc == StorageResultCode.OperationSucceeded) {
1714 synchronized (mAsecMountSet) {
1715 if (mAsecMountSet.contains(id)) {
1716 mAsecMountSet.remove(id);
1717 }
1718 }
1719 }
1720
San Mehat4270e1e2010-01-29 05:32:19 -08001721 return rc;
San Mehat36972292010-01-06 11:06:32 -08001722 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001723
San Mehat4270e1e2010-01-29 05:32:19 -08001724 public int mountSecureContainer(String id, String key, int ownerUid) {
1725 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001726 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001727 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001728
San Mehata181b212010-02-11 06:50:20 -08001729 synchronized (mAsecMountSet) {
1730 if (mAsecMountSet.contains(id)) {
1731 return StorageResultCode.OperationFailedStorageMounted;
1732 }
1733 }
1734
San Mehatb1043402010-02-05 08:26:50 -08001735 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001736 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001737 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001738 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001739 int code = e.getCode();
1740 if (code != VoldResponseCode.OpFailedStorageBusy) {
1741 rc = StorageResultCode.OperationFailedInternalError;
1742 }
San Mehat02735bc2010-01-26 15:18:08 -08001743 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001744
1745 if (rc == StorageResultCode.OperationSucceeded) {
1746 synchronized (mAsecMountSet) {
1747 mAsecMountSet.add(id);
1748 }
1749 }
San Mehat4270e1e2010-01-29 05:32:19 -08001750 return rc;
San Mehat36972292010-01-06 11:06:32 -08001751 }
1752
San Mehatd9709982010-02-18 11:43:03 -08001753 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001754 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001755 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001756 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001757
San Mehat6cdd9c02010-02-09 14:45:20 -08001758 synchronized (mAsecMountSet) {
1759 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001760 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001761 }
1762 }
1763
Kenny Rootaa485402010-09-14 14:49:41 -07001764 /*
1765 * Force a GC to make sure AssetManagers in other threads of the
1766 * system_server are cleaned up. We have to do this since AssetManager
1767 * instances are kept as a WeakReference and it's possible we have files
1768 * open on the external storage.
1769 */
1770 Runtime.getRuntime().gc();
1771
San Mehatb1043402010-02-05 08:26:50 -08001772 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001773 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001774 final Command cmd = new Command("asec", "unmount", id);
1775 if (force) {
1776 cmd.appendArg("force");
1777 }
1778 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001779 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001780 int code = e.getCode();
1781 if (code == VoldResponseCode.OpFailedStorageBusy) {
1782 rc = StorageResultCode.OperationFailedStorageBusy;
1783 } else {
1784 rc = StorageResultCode.OperationFailedInternalError;
1785 }
San Mehat02735bc2010-01-26 15:18:08 -08001786 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001787
1788 if (rc == StorageResultCode.OperationSucceeded) {
1789 synchronized (mAsecMountSet) {
1790 mAsecMountSet.remove(id);
1791 }
1792 }
San Mehat4270e1e2010-01-29 05:32:19 -08001793 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001794 }
1795
San Mehat6cdd9c02010-02-09 14:45:20 -08001796 public boolean isSecureContainerMounted(String id) {
1797 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1798 waitForReady();
1799 warnOnNotMounted();
1800
1801 synchronized (mAsecMountSet) {
1802 return mAsecMountSet.contains(id);
1803 }
1804 }
1805
San Mehat4270e1e2010-01-29 05:32:19 -08001806 public int renameSecureContainer(String oldId, String newId) {
1807 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001808 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001809 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001810
San Mehata181b212010-02-11 06:50:20 -08001811 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001812 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001813 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001814 * changed while active, we must ensure both ids are not currently mounted.
1815 */
1816 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001817 return StorageResultCode.OperationFailedStorageMounted;
1818 }
1819 }
1820
San Mehatb1043402010-02-05 08:26:50 -08001821 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001822 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001823 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001824 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001825 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001826 }
San Mehata181b212010-02-11 06:50:20 -08001827
San Mehat4270e1e2010-01-29 05:32:19 -08001828 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001829 }
1830
San Mehat4270e1e2010-01-29 05:32:19 -08001831 public String getSecureContainerPath(String id) {
1832 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001833 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001834 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001835
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001836 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001837 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001838 event = mConnector.execute("asec", "path", id);
1839 event.checkCode(VoldResponseCode.AsecPathResult);
1840 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001841 } catch (NativeDaemonConnectorException e) {
1842 int code = e.getCode();
1843 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001844 Slog.i(TAG, String.format("Container '%s' not found", id));
1845 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001846 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001847 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001848 }
1849 }
San Mehat22dd86e2010-01-12 12:21:18 -08001850 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001851
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001852 public String getSecureContainerFilesystemPath(String id) {
1853 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1854 waitForReady();
1855 warnOnNotMounted();
1856
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001857 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001858 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001859 event = mConnector.execute("asec", "fspath", id);
1860 event.checkCode(VoldResponseCode.AsecPathResult);
1861 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001862 } catch (NativeDaemonConnectorException e) {
1863 int code = e.getCode();
1864 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1865 Slog.i(TAG, String.format("Container '%s' not found", id));
1866 return null;
1867 } else {
1868 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1869 }
1870 }
1871 }
1872
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001873 public void finishMediaUpdate() {
1874 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1875 }
Kenny Root02c87302010-07-01 08:10:18 -07001876
Kenny Roota02b8b02010-08-05 16:14:17 -07001877 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1878 if (callerUid == android.os.Process.SYSTEM_UID) {
1879 return true;
1880 }
1881
Kenny Root02c87302010-07-01 08:10:18 -07001882 if (packageName == null) {
1883 return false;
1884 }
1885
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001886 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001887
1888 if (DEBUG_OBB) {
1889 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1890 packageUid + ", callerUid = " + callerUid);
1891 }
1892
1893 return callerUid == packageUid;
1894 }
1895
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001896 public String getMountedObbPath(String rawPath) {
1897 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001898
Kenny Root02c87302010-07-01 08:10:18 -07001899 waitForReady();
1900 warnOnNotMounted();
1901
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001902 final ObbState state;
1903 synchronized (mObbPathToStateMap) {
1904 state = mObbPathToStateMap.get(rawPath);
1905 }
1906 if (state == null) {
1907 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1908 return null;
1909 }
1910
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001911 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001912 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001913 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001914 event.checkCode(VoldResponseCode.AsecPathResult);
1915 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001916 } catch (NativeDaemonConnectorException e) {
1917 int code = e.getCode();
1918 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001919 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001920 } else {
1921 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1922 }
1923 }
1924 }
1925
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001926 @Override
1927 public boolean isObbMounted(String rawPath) {
1928 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001929 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001930 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001931 }
Kenny Root02c87302010-07-01 08:10:18 -07001932 }
1933
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001934 @Override
1935 public void mountObb(
1936 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1937 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1938 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1939 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001941 final int callingUid = Binder.getCallingUid();
1942 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1943 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1945
1946 if (DEBUG_OBB)
1947 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001948 }
1949
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001950 @Override
1951 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1952 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1953
1954 final ObbState existingState;
1955 synchronized (mObbPathToStateMap) {
1956 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001957 }
1958
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001959 if (existingState != null) {
1960 // TODO: separate state object from request data
1961 final int callingUid = Binder.getCallingUid();
1962 final ObbState newState = new ObbState(
1963 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1964 final ObbAction action = new UnmountObbAction(newState, force);
1965 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001966
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001967 if (DEBUG_OBB)
1968 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1969 } else {
1970 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1971 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001972 }
1973
Ben Komalo444eca22011-09-01 15:17:44 -07001974 @Override
1975 public int getEncryptionState() {
1976 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1977 "no permission to access the crypt keeper");
1978
1979 waitForReady();
1980
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001981 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001982 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001983 event = mConnector.execute("cryptfs", "cryptocomplete");
1984 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001985 } catch (NumberFormatException e) {
1986 // Bad result - unexpected.
1987 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1988 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1989 } catch (NativeDaemonConnectorException e) {
1990 // Something bad happened.
1991 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1992 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1993 }
1994 }
1995
1996 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001997 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001998 if (TextUtils.isEmpty(password)) {
1999 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002000 }
2001
Jason parks8888c592011-01-20 22:46:41 -06002002 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2003 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002004
2005 waitForReady();
2006
2007 if (DEBUG_EVENTS) {
2008 Slog.i(TAG, "decrypting storage...");
2009 }
2010
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002011 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002012 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002013 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06002014
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002015 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002016 if (code == 0) {
2017 // Decrypt was successful. Post a delayed message before restarting in order
2018 // to let the UI to clear itself
2019 mHandler.postDelayed(new Runnable() {
2020 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002021 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002022 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002023 } catch (NativeDaemonConnectorException e) {
2024 Slog.e(TAG, "problem executing in background", e);
2025 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002026 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002027 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002028 }
2029
2030 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002031 } catch (NativeDaemonConnectorException e) {
2032 // Decryption failed
2033 return e.getCode();
2034 }
Jason parks5af0b912010-11-29 09:05:25 -06002035 }
2036
Jason parks56aa5322011-01-07 09:01:15 -06002037 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002038 if (TextUtils.isEmpty(password)) {
2039 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002040 }
2041
Jason parks8888c592011-01-20 22:46:41 -06002042 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2043 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002044
2045 waitForReady();
2046
2047 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002048 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002049 }
2050
2051 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002052 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002053 } catch (NativeDaemonConnectorException e) {
2054 // Encryption failed
2055 return e.getCode();
2056 }
2057
2058 return 0;
2059 }
2060
Jason parksf7b3cd42011-01-27 09:28:25 -06002061 public int changeEncryptionPassword(String password) {
2062 if (TextUtils.isEmpty(password)) {
2063 throw new IllegalArgumentException("password cannot be empty");
2064 }
2065
2066 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2067 "no permission to access the crypt keeper");
2068
2069 waitForReady();
2070
2071 if (DEBUG_EVENTS) {
2072 Slog.i(TAG, "changing encryption password...");
2073 }
2074
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002075 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002076 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002077 event = mConnector.execute("cryptfs", "changepw", password);
2078 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002079 } catch (NativeDaemonConnectorException e) {
2080 // Encryption failed
2081 return e.getCode();
2082 }
2083 }
2084
Christopher Tate32418be2011-10-10 13:51:12 -07002085 /**
2086 * Validate a user-supplied password string with cryptfs
2087 */
2088 @Override
2089 public int verifyEncryptionPassword(String password) throws RemoteException {
2090 // Only the system process is permitted to validate passwords
2091 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2092 throw new SecurityException("no permission to access the crypt keeper");
2093 }
2094
2095 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2096 "no permission to access the crypt keeper");
2097
2098 if (TextUtils.isEmpty(password)) {
2099 throw new IllegalArgumentException("password cannot be empty");
2100 }
2101
2102 waitForReady();
2103
2104 if (DEBUG_EVENTS) {
2105 Slog.i(TAG, "validating encryption password...");
2106 }
2107
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002108 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002109 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002110 event = mConnector.execute("cryptfs", "verifypw", password);
2111 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2112 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002113 } catch (NativeDaemonConnectorException e) {
2114 // Encryption failed
2115 return e.getCode();
2116 }
2117 }
2118
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002119 @Override
2120 public StorageVolume[] getVolumeList() {
2121 final int callingUserId = UserHandle.getCallingUserId();
2122 final boolean accessAll = (mContext.checkPermission(
2123 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2124 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2125
2126 synchronized (mVolumesLock) {
2127 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2128 for (StorageVolume volume : mVolumes) {
2129 final UserHandle owner = volume.getOwner();
2130 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2131 if (accessAll || ownerMatch) {
2132 filtered.add(volume);
2133 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002134 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002135 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002136 }
2137 }
2138
Kenny Rootaf9d6672010-10-08 09:21:39 -07002139 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2140 final IBinder binder = obbState.getBinder();
2141 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002142
Kenny Rootaf9d6672010-10-08 09:21:39 -07002143 if (obbStates == null) {
2144 obbStates = new ArrayList<ObbState>();
2145 mObbMounts.put(binder, obbStates);
2146 } else {
2147 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002148 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002149 throw new IllegalStateException("Attempt to add ObbState twice. "
2150 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002151 }
2152 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002153 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154
2155 obbStates.add(obbState);
2156 try {
2157 obbState.link();
2158 } catch (RemoteException e) {
2159 /*
2160 * The binder died before we could link it, so clean up our state
2161 * and return failure.
2162 */
2163 obbStates.remove(obbState);
2164 if (obbStates.isEmpty()) {
2165 mObbMounts.remove(binder);
2166 }
2167
2168 // Rethrow the error so mountObb can get it
2169 throw e;
2170 }
2171
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002172 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002173 }
2174
Kenny Rootaf9d6672010-10-08 09:21:39 -07002175 private void removeObbStateLocked(ObbState obbState) {
2176 final IBinder binder = obbState.getBinder();
2177 final List<ObbState> obbStates = mObbMounts.get(binder);
2178 if (obbStates != null) {
2179 if (obbStates.remove(obbState)) {
2180 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002181 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002182 if (obbStates.isEmpty()) {
2183 mObbMounts.remove(binder);
2184 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002185 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002186
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002187 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002188 }
2189
Kenny Roota02b8b02010-08-05 16:14:17 -07002190 private class ObbActionHandler extends Handler {
2191 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002192 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002193
2194 ObbActionHandler(Looper l) {
2195 super(l);
2196 }
2197
2198 @Override
2199 public void handleMessage(Message msg) {
2200 switch (msg.what) {
2201 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002202 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002203
2204 if (DEBUG_OBB)
2205 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2206
2207 // If a bind was already initiated we don't really
2208 // need to do anything. The pending install
2209 // will be processed later on.
2210 if (!mBound) {
2211 // If this is the only one pending we might
2212 // have to bind to the service again.
2213 if (!connectToService()) {
2214 Slog.e(TAG, "Failed to bind to media container service");
2215 action.handleError();
2216 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002217 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002218 }
Kenny Root735de3b2010-09-30 14:11:39 -07002219
Kenny Root735de3b2010-09-30 14:11:39 -07002220 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002221 break;
2222 }
2223 case OBB_MCS_BOUND: {
2224 if (DEBUG_OBB)
2225 Slog.i(TAG, "OBB_MCS_BOUND");
2226 if (msg.obj != null) {
2227 mContainerService = (IMediaContainerService) msg.obj;
2228 }
2229 if (mContainerService == null) {
2230 // Something seriously wrong. Bail out
2231 Slog.e(TAG, "Cannot bind to media container service");
2232 for (ObbAction action : mActions) {
2233 // Indicate service bind error
2234 action.handleError();
2235 }
2236 mActions.clear();
2237 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002238 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002239 if (action != null) {
2240 action.execute(this);
2241 }
2242 } else {
2243 // Should never happen ideally.
2244 Slog.w(TAG, "Empty queue");
2245 }
2246 break;
2247 }
2248 case OBB_MCS_RECONNECT: {
2249 if (DEBUG_OBB)
2250 Slog.i(TAG, "OBB_MCS_RECONNECT");
2251 if (mActions.size() > 0) {
2252 if (mBound) {
2253 disconnectService();
2254 }
2255 if (!connectToService()) {
2256 Slog.e(TAG, "Failed to bind to media container service");
2257 for (ObbAction action : mActions) {
2258 // Indicate service bind error
2259 action.handleError();
2260 }
2261 mActions.clear();
2262 }
2263 }
2264 break;
2265 }
2266 case OBB_MCS_UNBIND: {
2267 if (DEBUG_OBB)
2268 Slog.i(TAG, "OBB_MCS_UNBIND");
2269
2270 // Delete pending install
2271 if (mActions.size() > 0) {
2272 mActions.remove(0);
2273 }
2274 if (mActions.size() == 0) {
2275 if (mBound) {
2276 disconnectService();
2277 }
2278 } else {
2279 // There are more pending requests in queue.
2280 // Just post MCS_BOUND message to trigger processing
2281 // of next pending install.
2282 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2283 }
2284 break;
2285 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002286 case OBB_FLUSH_MOUNT_STATE: {
2287 final String path = (String) msg.obj;
2288
2289 if (DEBUG_OBB)
2290 Slog.i(TAG, "Flushing all OBB state for path " + path);
2291
2292 synchronized (mObbMounts) {
2293 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2294
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002295 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002296 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002297 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002298
2299 /*
2300 * If this entry's source file is in the volume path
2301 * that got unmounted, remove it because it's no
2302 * longer valid.
2303 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002304 if (state.canonicalPath.startsWith(path)) {
2305 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 }
2307 }
2308
2309 for (final ObbState obbState : obbStatesToRemove) {
2310 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002311 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002312
2313 removeObbStateLocked(obbState);
2314
2315 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002316 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 OnObbStateChangeListener.UNMOUNTED);
2318 } catch (RemoteException e) {
2319 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002320 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002321 }
2322 }
2323 }
2324 break;
2325 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002326 }
2327 }
2328
2329 private boolean connectToService() {
2330 if (DEBUG_OBB)
2331 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2332
2333 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2334 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2335 mBound = true;
2336 return true;
2337 }
2338 return false;
2339 }
2340
2341 private void disconnectService() {
2342 mContainerService = null;
2343 mBound = false;
2344 mContext.unbindService(mDefContainerConn);
2345 }
2346 }
2347
2348 abstract class ObbAction {
2349 private static final int MAX_RETRIES = 3;
2350 private int mRetries;
2351
2352 ObbState mObbState;
2353
2354 ObbAction(ObbState obbState) {
2355 mObbState = obbState;
2356 }
2357
2358 public void execute(ObbActionHandler handler) {
2359 try {
2360 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002361 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002362 mRetries++;
2363 if (mRetries > MAX_RETRIES) {
2364 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002365 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002366 handleError();
2367 return;
2368 } else {
2369 handleExecute();
2370 if (DEBUG_OBB)
2371 Slog.i(TAG, "Posting install MCS_UNBIND");
2372 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2373 }
2374 } catch (RemoteException e) {
2375 if (DEBUG_OBB)
2376 Slog.i(TAG, "Posting install MCS_RECONNECT");
2377 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2378 } catch (Exception e) {
2379 if (DEBUG_OBB)
2380 Slog.d(TAG, "Error handling OBB action", e);
2381 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002382 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002383 }
2384 }
2385
Kenny Root05105f72010-09-22 17:29:43 -07002386 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002387 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002388
2389 protected ObbInfo getObbInfo() throws IOException {
2390 ObbInfo obbInfo;
2391 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002392 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002393 } catch (RemoteException e) {
2394 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002396 obbInfo = null;
2397 }
2398 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002399 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002400 }
2401 return obbInfo;
2402 }
2403
Kenny Rootaf9d6672010-10-08 09:21:39 -07002404 protected void sendNewStatusOrIgnore(int status) {
2405 if (mObbState == null || mObbState.token == null) {
2406 return;
2407 }
2408
Kenny Root38cf8862010-09-26 14:18:51 -07002409 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002410 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002411 } catch (RemoteException e) {
2412 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2413 }
2414 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002415 }
2416
2417 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002418 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002419 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002420
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002422 super(obbState);
2423 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002424 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002425 }
2426
Jason parks5af0b912010-11-29 09:05:25 -06002427 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002428 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002429 waitForReady();
2430 warnOnNotMounted();
2431
Kenny Root38cf8862010-09-26 14:18:51 -07002432 final ObbInfo obbInfo = getObbInfo();
2433
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002434 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002435 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2436 + " which is owned by " + obbInfo.packageName);
2437 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2438 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002439 }
2440
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 final boolean isMounted;
2442 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002443 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444 }
2445 if (isMounted) {
2446 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2447 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2448 return;
2449 }
2450
Kenny Rootaf9d6672010-10-08 09:21:39 -07002451 final String hashedKey;
2452 if (mKey == null) {
2453 hashedKey = "none";
2454 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002455 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002456 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2457
2458 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2459 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2460 SecretKey key = factory.generateSecret(ks);
2461 BigInteger bi = new BigInteger(key.getEncoded());
2462 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002464 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2465 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2466 return;
2467 } catch (InvalidKeySpecException e) {
2468 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2469 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002470 return;
2471 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002472 }
Kenny Root38cf8862010-09-26 14:18:51 -07002473
Kenny Rootaf9d6672010-10-08 09:21:39 -07002474 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002475 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002476 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002477 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002478 } catch (NativeDaemonConnectorException e) {
2479 int code = e.getCode();
2480 if (code != VoldResponseCode.OpFailedStorageBusy) {
2481 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002482 }
2483 }
2484
Kenny Rootaf9d6672010-10-08 09:21:39 -07002485 if (rc == StorageResultCode.OperationSucceeded) {
2486 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002487 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002488
2489 synchronized (mObbMounts) {
2490 addObbStateLocked(mObbState);
2491 }
2492
2493 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002494 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002495 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002496
Kenny Rootaf9d6672010-10-08 09:21:39 -07002497 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002498 }
2499 }
2500
Jason parks5af0b912010-11-29 09:05:25 -06002501 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002502 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002503 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002504 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002505
2506 @Override
2507 public String toString() {
2508 StringBuilder sb = new StringBuilder();
2509 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002510 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002511 sb.append('}');
2512 return sb.toString();
2513 }
2514 }
2515
2516 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002517 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002518
2519 UnmountObbAction(ObbState obbState, boolean force) {
2520 super(obbState);
2521 mForceUnmount = force;
2522 }
2523
Jason parks5af0b912010-11-29 09:05:25 -06002524 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002525 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002526 waitForReady();
2527 warnOnNotMounted();
2528
Kenny Root38cf8862010-09-26 14:18:51 -07002529 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002530
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002531 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002532 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002533 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002534 }
Kenny Root38cf8862010-09-26 14:18:51 -07002535
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002536 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002537 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2538 return;
2539 }
2540
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 if (existingState.ownerGid != mObbState.ownerGid) {
2542 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2543 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2545 return;
2546 }
2547
Kenny Rootaf9d6672010-10-08 09:21:39 -07002548 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002549 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002550 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002551 if (mForceUnmount) {
2552 cmd.appendArg("force");
2553 }
2554 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002555 } catch (NativeDaemonConnectorException e) {
2556 int code = e.getCode();
2557 if (code == VoldResponseCode.OpFailedStorageBusy) {
2558 rc = StorageResultCode.OperationFailedStorageBusy;
2559 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2560 // If it's not mounted then we've already won.
2561 rc = StorageResultCode.OperationSucceeded;
2562 } else {
2563 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002564 }
2565 }
2566
Kenny Rootaf9d6672010-10-08 09:21:39 -07002567 if (rc == StorageResultCode.OperationSucceeded) {
2568 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002569 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002570 }
2571
Kenny Rootaf9d6672010-10-08 09:21:39 -07002572 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002573 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002574 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002575 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002576 }
2577 }
2578
Jason parks5af0b912010-11-29 09:05:25 -06002579 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002580 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002581 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002582 }
2583
2584 @Override
2585 public String toString() {
2586 StringBuilder sb = new StringBuilder();
2587 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002588 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002589 sb.append(",force=");
2590 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002591 sb.append('}');
2592 return sb.toString();
2593 }
Kenny Root02c87302010-07-01 08:10:18 -07002594 }
Kenny Root38cf8862010-09-26 14:18:51 -07002595
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002596 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002597 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2598 // TODO: allow caller to provide Environment for full testing
2599
2600 // Only adjust paths when storage is emulated
2601 if (!Environment.isExternalStorageEmulated()) {
2602 return canonicalPath;
2603 }
2604
2605 String path = canonicalPath.toString();
2606
2607 // First trim off any external storage prefix
2608 final UserEnvironment userEnv = new UserEnvironment(userId);
2609
2610 // /storage/emulated/0
2611 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2612 // /storage/emulated_legacy
2613 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2614 .toString();
2615
2616 if (path.startsWith(externalPath)) {
2617 path = path.substring(externalPath.length() + 1);
2618 } else if (path.startsWith(legacyExternalPath)) {
2619 path = path.substring(legacyExternalPath.length() + 1);
2620 } else {
2621 return canonicalPath;
2622 }
2623
2624 // Handle special OBB paths on emulated storage
2625 final String obbPath = "Android/obb";
2626 if (path.startsWith(obbPath)) {
2627 path = path.substring(obbPath.length() + 1);
2628
2629 if (forVold) {
2630 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2631 } else {
2632 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2633 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2634 }
2635 }
2636
2637 // Handle normal external storage paths
2638 if (forVold) {
2639 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2640 } else {
2641 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2642 }
2643 }
2644
Kenny Root38cf8862010-09-26 14:18:51 -07002645 @Override
2646 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2647 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2648 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2649 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2650 + " without permission " + android.Manifest.permission.DUMP);
2651 return;
2652 }
2653
Kenny Root38cf8862010-09-26 14:18:51 -07002654 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002655 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002656
Kenny Rootaf9d6672010-10-08 09:21:39 -07002657 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2658 while (binders.hasNext()) {
2659 Entry<IBinder, List<ObbState>> e = binders.next();
2660 pw.print(" Key="); pw.println(e.getKey().toString());
2661 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002662 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002663 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002664 }
2665 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002666
2667 pw.println("");
2668 pw.println(" mObbPathToStateMap:");
2669 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2670 while (maps.hasNext()) {
2671 final Entry<String, ObbState> e = maps.next();
2672 pw.print(" "); pw.print(e.getKey());
2673 pw.print(" -> "); pw.println(e.getValue().toString());
2674 }
Kenny Root38cf8862010-09-26 14:18:51 -07002675 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002676
2677 pw.println("");
2678
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002679 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002680 pw.println(" mVolumes:");
2681
2682 final int N = mVolumes.size();
2683 for (int i = 0; i < N; i++) {
2684 final StorageVolume v = mVolumes.get(i);
2685 pw.print(" ");
2686 pw.println(v.toString());
2687 }
2688 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002689
2690 pw.println();
2691 pw.println(" mConnection:");
2692 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002695 /** {@inheritDoc} */
2696 public void monitor() {
2697 if (mConnector != null) {
2698 mConnector.monitor();
2699 }
2700 }
2701}