blob: c512bc1845030bddc0cf44309811c5e36385beaa [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 Sharkeyb049e212012-09-07 23:16:01 -070060import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070061import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070062import com.android.internal.util.XmlUtils;
63import com.android.server.NativeDaemonConnector.Command;
64import com.android.server.am.ActivityManagerService;
65import com.android.server.pm.PackageManagerService;
66import com.android.server.pm.UserManagerService;
67import com.google.android.collect.Lists;
68import com.google.android.collect.Maps;
69
Mike Lockwood2f6a3882011-05-09 19:08:06 -070070import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070071
Jeff Sharkeyb049e212012-09-07 23:16:01 -070072import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070073import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070074import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070076import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070077import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070078import java.security.spec.InvalidKeySpecException;
79import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080080import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070081import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080082import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070083import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070084import java.util.LinkedList;
85import java.util.List;
86import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070087import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070088import java.util.concurrent.CountDownLatch;
89import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Kenny Root3b1abba2010-10-13 15:00:07 -070091import javax.crypto.SecretKey;
92import javax.crypto.SecretKeyFactory;
93import javax.crypto.spec.PBEKeySpec;
94
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095/**
San Mehatb1043402010-02-05 08:26:50 -080096 * MountService implements back-end services for platform storage
97 * management.
98 * @hide - Applications should use android.os.storage.StorageManager
99 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700101class MountService extends IMountService.Stub
102 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600103
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700104 // TODO: listen for user creation/deletion
105
106 private static final boolean LOCAL_LOGD = true;
107 private static final boolean DEBUG_UNMOUNT = true;
108 private static final boolean DEBUG_EVENTS = true;
Kenny Rootb7db2722011-01-25 16:39:35 -0800109 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700110
Kenny Root07714d42011-08-17 17:49:28 -0700111 // Disable this since it messes up long-running cryptfs operations.
112 private static final boolean WATCHDOG_ENABLE = false;
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private static final String TAG = "MountService";
115
Kenny Root305bcbf2010-09-03 07:56:38 -0700116 private static final String VOLD_TAG = "VoldConnector";
117
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700118 /** Maximum number of ASEC containers allowed to be mounted. */
119 private static final int MAX_CONTAINERS = 250;
120
San Mehat4270e1e2010-01-29 05:32:19 -0800121 /*
122 * Internal vold volume state constants
123 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800124 class VolumeState {
125 public static final int Init = -1;
126 public static final int NoMedia = 0;
127 public static final int Idle = 1;
128 public static final int Pending = 2;
129 public static final int Checking = 3;
130 public static final int Mounted = 4;
131 public static final int Unmounting = 5;
132 public static final int Formatting = 6;
133 public static final int Shared = 7;
134 public static final int SharedMnt = 8;
135 }
136
San Mehat4270e1e2010-01-29 05:32:19 -0800137 /*
138 * Internal vold response code constants
139 */
San Mehat22dd86e2010-01-12 12:21:18 -0800140 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800141 /*
142 * 100 series - Requestion action was initiated; expect another reply
143 * before proceeding with a new command.
144 */
San Mehat22dd86e2010-01-12 12:21:18 -0800145 public static final int VolumeListResult = 110;
146 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800147 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800148
San Mehat4270e1e2010-01-29 05:32:19 -0800149 /*
150 * 200 series - Requestion action has been successfully completed.
151 */
152 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800153 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800154 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800155
San Mehat4270e1e2010-01-29 05:32:19 -0800156 /*
157 * 400 series - Command was accepted, but the requested action
158 * did not take place.
159 */
160 public static final int OpFailedNoMedia = 401;
161 public static final int OpFailedMediaBlank = 402;
162 public static final int OpFailedMediaCorrupt = 403;
163 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800164 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700165 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800166
167 /*
168 * 600 series - Unsolicited broadcasts.
169 */
San Mehat22dd86e2010-01-12 12:21:18 -0800170 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800171 public static final int VolumeDiskInserted = 630;
172 public static final int VolumeDiskRemoved = 631;
173 public static final int VolumeBadRemoval = 632;
174 }
175
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700176 private Context mContext;
177 private NativeDaemonConnector mConnector;
178
179 private final Object mVolumesLock = new Object();
180
181 /** When defined, base template for user-specific {@link StorageVolume}. */
182 private StorageVolume mEmulatedTemplate;
183
184 // @GuardedBy("mVolumesLock")
185 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
186 /** Map from path to {@link StorageVolume} */
187 // @GuardedBy("mVolumesLock")
188 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
189 /** Map from path to state */
190 // @GuardedBy("mVolumesLock")
191 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
192
193 private volatile boolean mSystemReady = false;
194
San Mehat4270e1e2010-01-29 05:32:19 -0800195 private PackageManagerService mPms;
196 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700197 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800198 // Used as a lock for methods that register/unregister listeners.
199 final private ArrayList<MountServiceBinderListener> mListeners =
200 new ArrayList<MountServiceBinderListener>();
Kenny Root51a573c2012-05-17 13:30:28 -0700201 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
202 private CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800203 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800204
San Mehat6cdd9c02010-02-09 14:45:20 -0800205 /**
206 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800207 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800208 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800209 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800210
Kenny Root02c87302010-07-01 08:10:18 -0700211 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700212 * The size of the crypto algorithm key in bits for OBB files. Currently
213 * Twofish is used which takes 128-bit keys.
214 */
215 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
216
217 /**
218 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
219 * 1024 is reasonably secure and not too slow.
220 */
221 private static final int PBKDF2_HASH_ROUNDS = 1024;
222
223 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700224 * Mounted OBB tracking information. Used to track the current state of all
225 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700226 */
Kenny Root735de3b2010-09-30 14:11:39 -0700227 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700228
229 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700230 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
231
232 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700233 public ObbState(String rawPath, String canonicalPath, int callingUid,
234 IObbActionListener token, int nonce) {
235 this.rawPath = rawPath;
236 this.canonicalPath = canonicalPath.toString();
237
238 final int userId = UserHandle.getUserId(callingUid);
239 this.ownerPath = buildObbPath(canonicalPath, userId, false);
240 this.voldPath = buildObbPath(canonicalPath, userId, true);
241
242 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700243 this.token = token;
244 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700245 }
246
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700247 final String rawPath;
248 final String canonicalPath;
249 final String ownerPath;
250 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700251
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700252 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700253
Kenny Rootaf9d6672010-10-08 09:21:39 -0700254 // Token of remote Binder caller
255 final IObbActionListener token;
256
257 // Identifier to pass back to the token
258 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700259
Kenny Root735de3b2010-09-30 14:11:39 -0700260 public IBinder getBinder() {
261 return token.asBinder();
262 }
263
Kenny Roota02b8b02010-08-05 16:14:17 -0700264 @Override
265 public void binderDied() {
266 ObbAction action = new UnmountObbAction(this, true);
267 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700268 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700269
Kenny Root5919ac62010-10-05 09:49:40 -0700270 public void link() throws RemoteException {
271 getBinder().linkToDeath(this, 0);
272 }
273
274 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700275 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700276 }
Kenny Root38cf8862010-09-26 14:18:51 -0700277
278 @Override
279 public String toString() {
280 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700281 sb.append("rawPath=").append(rawPath);
282 sb.append(",canonicalPath=").append(canonicalPath);
283 sb.append(",ownerPath=").append(ownerPath);
284 sb.append(",voldPath=").append(voldPath);
285 sb.append(",ownerGid=").append(ownerGid);
286 sb.append(",token=").append(token);
287 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700288 sb.append('}');
289 return sb.toString();
290 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700291 }
292
293 // OBB Action Handler
294 final private ObbActionHandler mObbActionHandler;
295
296 // OBB action handler messages
297 private static final int OBB_RUN_ACTION = 1;
298 private static final int OBB_MCS_BOUND = 2;
299 private static final int OBB_MCS_UNBIND = 3;
300 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700301 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700302
303 /*
304 * Default Container Service information
305 */
306 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
307 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
308
309 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
310
311 class DefaultContainerConnection implements ServiceConnection {
312 public void onServiceConnected(ComponentName name, IBinder service) {
313 if (DEBUG_OBB)
314 Slog.i(TAG, "onServiceConnected");
315 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
316 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
317 }
318
319 public void onServiceDisconnected(ComponentName name) {
320 if (DEBUG_OBB)
321 Slog.i(TAG, "onServiceDisconnected");
322 }
323 };
324
325 // Used in the ObbActionHandler
326 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700327
328 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800329 private static final int H_UNMOUNT_PM_UPDATE = 1;
330 private static final int H_UNMOUNT_PM_DONE = 2;
331 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700332 private static final int H_SYSTEM_READY = 4;
333
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800334 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
335 private static final int MAX_UNMOUNT_RETRIES = 4;
336
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800337 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700338 final String path;
339 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700340 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800341 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800342
Ben Komalo13c71972011-09-07 16:35:56 -0700343 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800344 retries = 0;
345 this.path = path;
346 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700347 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800348 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800349
350 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700351 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700352 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800353 }
354 }
355
356 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700357 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800358
359 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700360 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800361 this.method = method;
362 }
363
364 @Override
365 void handleFinished() {
366 super.handleFinished();
367 doShareUnshareVolume(path, method, true);
368 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800369 }
370
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800371 class ShutdownCallBack extends UnmountCallBack {
372 IMountShutdownObserver observer;
373 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700374 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800375 this.observer = observer;
376 }
377
378 @Override
379 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700380 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800381 if (observer != null) {
382 try {
383 observer.onShutDownComplete(ret);
384 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700385 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800386 }
387 }
388 }
389 }
390
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400391 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800392 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700393 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800394
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400395 MountServiceHandler(Looper l) {
396 super(l);
397 }
398
Jason parks5af0b912010-11-29 09:05:25 -0600399 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800400 public void handleMessage(Message msg) {
401 switch (msg.what) {
402 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700403 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800404 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
405 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700406 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800407 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700408 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700409 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700410 mUpdatingStatus = true;
411 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 }
413 break;
414 }
415 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700416 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700417 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700418 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 int size = mForceUnmounts.size();
420 int sizeArr[] = new int[size];
421 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700422 // Kill processes holding references first
423 ActivityManagerService ams = (ActivityManagerService)
424 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800425 for (int i = 0; i < size; i++) {
426 UnmountCallBack ucb = mForceUnmounts.get(i);
427 String path = ucb.path;
428 boolean done = false;
429 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800430 done = true;
431 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800432 int pids[] = getStorageUsers(path);
433 if (pids == null || pids.length == 0) {
434 done = true;
435 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800436 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800437 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700438 // Confirm if file references have been freed.
439 pids = getStorageUsers(path);
440 if (pids == null || pids.length == 0) {
441 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800442 }
443 }
444 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700445 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
446 // Retry again
447 Slog.i(TAG, "Retrying to kill storage users again");
448 mHandler.sendMessageDelayed(
449 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
450 ucb.retries++),
451 RETRY_UNMOUNT_DELAY);
452 } else {
453 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
454 Slog.i(TAG, "Failed to unmount media inspite of " +
455 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
456 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800457 sizeArr[sizeArrN++] = i;
458 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
459 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800460 }
461 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800462 // Remove already processed elements from list.
463 for (int i = (sizeArrN-1); i >= 0; i--) {
464 mForceUnmounts.remove(sizeArr[i]);
465 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800466 break;
467 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700468 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700469 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800470 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800471 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800472 break;
473 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700474 case H_SYSTEM_READY: {
475 try {
476 handleSystemReady();
477 } catch (Exception ex) {
478 Slog.e(TAG, "Boot-time mount exception", ex);
479 }
480 break;
481 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800482 }
483 }
484 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700485
486 private final HandlerThread mHandlerThread;
487 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800488
Kenny Root51a573c2012-05-17 13:30:28 -0700489 void waitForAsecScan() {
490 waitForLatch(mAsecsScanned);
491 }
492
San Mehat207e5382010-02-04 20:46:54 -0800493 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700494 waitForLatch(mConnectedSignal);
495 }
496
497 private void waitForLatch(CountDownLatch latch) {
498 if (latch == null) {
499 return;
500 }
501
502 for (;;) {
503 try {
504 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800505 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700506 } else {
507 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
508 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800509 }
Kenny Root51a573c2012-05-17 13:30:28 -0700510 } catch (InterruptedException e) {
511 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800512 }
San Mehat207e5382010-02-04 20:46:54 -0800513 }
San Mehat1f6301e2010-01-07 22:40:27 -0800514 }
Kenny Root02c87302010-07-01 08:10:18 -0700515
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700516 private void handleSystemReady() {
517 // Snapshot current volume states since it's not safe to call into vold
518 // while holding locks.
519 final HashMap<String, String> snapshot;
520 synchronized (mVolumesLock) {
521 snapshot = new HashMap<String, String>(mVolumeStates);
522 }
523
524 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
525 final String path = entry.getKey();
526 final String state = entry.getValue();
527
528 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
529 int rc = doMountVolume(path);
530 if (rc != StorageResultCode.OperationSucceeded) {
531 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
532 rc));
533 }
534 } else if (state.equals(Environment.MEDIA_SHARED)) {
535 /*
536 * Bootstrap UMS enabled state since vold indicates
537 * the volume is shared (runtime restart while ums enabled)
538 */
539 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
540 VolumeState.Shared);
541 }
542 }
543
544 // Push mounted state for all emulated storage
545 synchronized (mVolumesLock) {
546 for (StorageVolume volume : mVolumes) {
547 if (volume.isEmulated()) {
548 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
549 }
550 }
551 }
552
553 /*
554 * If UMS was connected on boot, send the connected event
555 * now that we're up.
556 */
557 if (mSendUmsConnectedOnBoot) {
558 sendUmsIntent(true);
559 mSendUmsConnectedOnBoot = false;
560 }
561 }
562
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700563 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
564 @Override
565 public void onReceive(Context context, Intent intent) {
566 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
567 if (userId == -1) return;
568 final UserHandle user = new UserHandle(userId);
569
570 final String action = intent.getAction();
571 if (Intent.ACTION_USER_ADDED.equals(action)) {
572 synchronized (mVolumesLock) {
573 createEmulatedVolumeForUserLocked(user);
574 }
575
576 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
577 synchronized (mVolumesLock) {
578 final List<StorageVolume> toRemove = Lists.newArrayList();
579 for (StorageVolume volume : mVolumes) {
580 if (user.equals(volume.getOwner())) {
581 toRemove.add(volume);
582 }
583 }
584 for (StorageVolume volume : toRemove) {
585 removeVolumeLocked(volume);
586 }
587 }
588 }
589 }
590 };
591
592 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
593 @Override
594 public void onReceive(Context context, Intent intent) {
595 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
596 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
597 notifyShareAvailabilityChange(available);
598 }
599 };
600
San Mehat4270e1e2010-01-29 05:32:19 -0800601 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
602 final IMountServiceListener mListener;
603
604 MountServiceBinderListener(IMountServiceListener listener) {
605 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700606
San Mehat91c77612010-01-07 10:39:41 -0800607 }
608
San Mehat4270e1e2010-01-29 05:32:19 -0800609 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700610 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700611 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800612 mListeners.remove(this);
613 mListener.asBinder().unlinkToDeath(this, 0);
614 }
615 }
616 }
617
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800618 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800619 // TODO: Add support for multiple share methods
620 if (!method.equals("ums")) {
621 throw new IllegalArgumentException(String.format("Method %s not supported", method));
622 }
623
San Mehat4270e1e2010-01-29 05:32:19 -0800624 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800625 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800626 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700627 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800628 }
San Mehat4270e1e2010-01-29 05:32:19 -0800629 }
630
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700631 private void updatePublicVolumeState(StorageVolume volume, String state) {
632 final String path = volume.getPath();
633 final String oldState;
634 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400635 oldState = mVolumeStates.put(path, state);
636 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700637
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400638 if (state.equals(oldState)) {
639 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
640 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800641 return;
642 }
San Mehatb1043402010-02-05 08:26:50 -0800643
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400644 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700645
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700646 // Tell PackageManager about changes to primary volume state, but only
647 // when not emulated.
648 if (volume.isPrimary() && !volume.isEmulated()) {
649 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
650 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400651
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700652 /*
653 * Some OBBs might have been unmounted when this volume was
654 * unmounted, so send a message to the handler to let it know to
655 * remove those from the list of mounted OBBS.
656 */
657 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
658 OBB_FLUSH_MOUNT_STATE, path));
659 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
660 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400661 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800662 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700663
San Mehat4270e1e2010-01-29 05:32:19 -0800664 synchronized (mListeners) {
665 for (int i = mListeners.size() -1; i >= 0; i--) {
666 MountServiceBinderListener bl = mListeners.get(i);
667 try {
San Mehatb1043402010-02-05 08:26:50 -0800668 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800669 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700670 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800671 mListeners.remove(i);
672 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700673 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800674 }
675 }
676 }
677 }
678
679 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800680 * Callback from NativeDaemonConnector
681 */
682 public void onDaemonConnected() {
683 /*
684 * Since we'll be calling back into the NativeDaemonConnector,
685 * we need to do our work in a new thread.
686 */
Kenny Root51a573c2012-05-17 13:30:28 -0700687 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600688 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800689 public void run() {
690 /**
691 * Determine media state and UMS detection status
692 */
San Mehat4270e1e2010-01-29 05:32:19 -0800693 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800694 final String[] vols = NativeDaemonEvent.filterMessageList(
695 mConnector.executeForList("volume", "list"),
696 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800697 for (String volstr : vols) {
698 String[] tok = volstr.split(" ");
699 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400700 String path = tok[1];
701 String state = Environment.MEDIA_REMOVED;
702
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700703 final StorageVolume volume;
704 synchronized (mVolumesLock) {
705 volume = mVolumesByPath.get(path);
706 }
707
San Mehat4270e1e2010-01-29 05:32:19 -0800708 int st = Integer.parseInt(tok[2]);
709 if (st == VolumeState.NoMedia) {
710 state = Environment.MEDIA_REMOVED;
711 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800712 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800713 } else if (st == VolumeState.Mounted) {
714 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700715 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800716 } else if (st == VolumeState.Shared) {
717 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700718 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800719 } else {
720 throw new Exception(String.format("Unexpected state %d", st));
721 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400722
723 if (state != null) {
724 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700725 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400726 }
San Mehat4270e1e2010-01-29 05:32:19 -0800727 }
728 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700729 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700730 final StorageVolume primary = getPrimaryPhysicalVolume();
731 if (primary != null) {
732 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
733 }
San Mehat4270e1e2010-01-29 05:32:19 -0800734 }
735
San Mehat207e5382010-02-04 20:46:54 -0800736 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600737 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800738 * the hounds!
739 */
Kenny Root51a573c2012-05-17 13:30:28 -0700740 mConnectedSignal.countDown();
741 mConnectedSignal = null;
742
743 // Let package manager load internal ASECs.
744 mPms.scanAvailableAsecs();
745
746 // Notify people waiting for ASECs to be scanned that it's done.
747 mAsecsScanned.countDown();
748 mAsecsScanned = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800749 }
750 }.start();
751 }
752
753 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800754 * Callback from NativeDaemonConnector
755 */
756 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800757 if (DEBUG_EVENTS) {
758 StringBuilder builder = new StringBuilder();
759 builder.append("onEvent::");
760 builder.append(" raw= " + raw);
761 if (cooked != null) {
762 builder.append(" cooked = " );
763 for (String str : cooked) {
764 builder.append(" " + str);
765 }
766 }
San Mehata5078592010-03-25 09:36:54 -0700767 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800768 }
San Mehat4270e1e2010-01-29 05:32:19 -0800769 if (code == VoldResponseCode.VolumeStateChange) {
770 /*
771 * One of the volumes we're managing has changed state.
772 * Format: "NNN Volume <label> <path> state changed
773 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
774 */
775 notifyVolumeStateChange(
776 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
777 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800778 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
779 (code == VoldResponseCode.VolumeDiskRemoved) ||
780 (code == VoldResponseCode.VolumeBadRemoval)) {
781 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
782 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
783 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400784 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800785 final String label = cooked[2];
786 final String path = cooked[3];
787 int major = -1;
788 int minor = -1;
789
790 try {
791 String devComp = cooked[6].substring(1, cooked[6].length() -1);
792 String[] devTok = devComp.split(":");
793 major = Integer.parseInt(devTok[0]);
794 minor = Integer.parseInt(devTok[1]);
795 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700796 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800797 }
798
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700799 final StorageVolume volume;
800 final String state;
801 synchronized (mVolumesLock) {
802 volume = mVolumesByPath.get(path);
803 state = mVolumeStates.get(path);
804 }
805
San Mehat4270e1e2010-01-29 05:32:19 -0800806 if (code == VoldResponseCode.VolumeDiskInserted) {
807 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600808 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800809 public void run() {
810 try {
811 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800812 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700813 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800814 }
815 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700816 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800817 }
818 }
819 }.start();
820 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
821 /*
822 * This event gets trumped if we're already in BAD_REMOVAL state
823 */
824 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
825 return true;
826 }
827 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700828 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700829 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
830 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800831
San Mehata5078592010-03-25 09:36:54 -0700832 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700833 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400834 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800835 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700836 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800837 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700838 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400839 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800840
San Mehata5078592010-03-25 09:36:54 -0700841 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700842 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400843 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800844 } else {
San Mehata5078592010-03-25 09:36:54 -0700845 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800846 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400847
848 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700849 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400850 }
San Mehat4270e1e2010-01-29 05:32:19 -0800851 } else {
852 return false;
853 }
854
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400855 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800856 }
857
San Mehat207e5382010-02-04 20:46:54 -0800858 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700859 final StorageVolume volume;
860 final String state;
861 synchronized (mVolumesLock) {
862 volume = mVolumesByPath.get(path);
863 state = getVolumeState(path);
864 }
865
866 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800867
Mike Lockwooda5250c92011-05-23 13:44:04 -0400868 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800869
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500870 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700871 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700872 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500873 }
874
San Mehat4270e1e2010-01-29 05:32:19 -0800875 if (newState == VolumeState.Init) {
876 } else if (newState == VolumeState.NoMedia) {
877 // NoMedia is handled via Disk Remove events
878 } else if (newState == VolumeState.Idle) {
879 /*
880 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
881 * if we're in the process of enabling UMS
882 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700883 if (!state.equals(
884 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
885 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800886 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700887 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700888 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400889 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800890 }
891 } else if (newState == VolumeState.Pending) {
892 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700893 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700894 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400895 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800896 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700897 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700898 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400899 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800900 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400901 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800902 } else if (newState == VolumeState.Formatting) {
903 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700904 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800905 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700906 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
907 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800908
San Mehata5078592010-03-25 09:36:54 -0700909 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700910 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400911 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700912 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800913 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700914 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800915 return;
916 } else {
San Mehata5078592010-03-25 09:36:54 -0700917 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800918 }
919
Mike Lockwooda5250c92011-05-23 13:44:04 -0400920 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700921 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800922 }
923 }
924
San Mehat207e5382010-02-04 20:46:54 -0800925 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800926 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800927
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700928 final StorageVolume volume;
929 synchronized (mVolumesLock) {
930 volume = mVolumesByPath.get(path);
931 }
932
San Mehata5078592010-03-25 09:36:54 -0700933 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800934 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800935 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800936 } catch (NativeDaemonConnectorException e) {
937 /*
938 * Mount failed for some reason
939 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400940 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800941 int code = e.getCode();
942 if (code == VoldResponseCode.OpFailedNoMedia) {
943 /*
944 * Attempt to mount but no media inserted
945 */
San Mehatb1043402010-02-05 08:26:50 -0800946 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800947 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700948 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800949 /*
950 * Media is blank or does not contain a supported filesystem
951 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700952 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400953 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800954 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800955 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700956 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800957 /*
958 * Volume consistency check failed
959 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700960 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400961 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800962 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800963 } else {
San Mehatb1043402010-02-05 08:26:50 -0800964 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800965 }
966
967 /*
968 * Send broadcast intent (if required for the failure)
969 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400970 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700971 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800972 }
973 }
974
975 return rc;
976 }
977
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800978 /*
979 * If force is not set, we do not unmount if there are
980 * processes holding references to the volume about to be unmounted.
981 * If force is set, all the processes holding references need to be
982 * killed via the ActivityManager before actually unmounting the volume.
983 * This might even take a while and might be retried after timed delays
984 * to make sure we dont end up in an instable state and kill some core
985 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700986 * If removeEncryption is set, force is implied, and the system will remove any encryption
987 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800988 */
Ben Komalo13c71972011-09-07 16:35:56 -0700989 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800990 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800991 return VoldResponseCode.OpFailedVolNotMounted;
992 }
Kenny Rootaa485402010-09-14 14:49:41 -0700993
994 /*
995 * Force a GC to make sure AssetManagers in other threads of the
996 * system_server are cleaned up. We have to do this since AssetManager
997 * instances are kept as a WeakReference and it's possible we have files
998 * open on the external storage.
999 */
1000 Runtime.getRuntime().gc();
1001
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001002 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001003 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001004 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001005 final Command cmd = new Command("volume", "unmount", path);
1006 if (removeEncryption) {
1007 cmd.appendArg("force_and_revert");
1008 } else if (force) {
1009 cmd.appendArg("force");
1010 }
1011 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001012 // We unmounted the volume. None of the asec containers are available now.
1013 synchronized (mAsecMountSet) {
1014 mAsecMountSet.clear();
1015 }
San Mehatb1043402010-02-05 08:26:50 -08001016 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001017 } catch (NativeDaemonConnectorException e) {
1018 // Don't worry about mismatch in PackageManager since the
1019 // call back will handle the status changes any way.
1020 int code = e.getCode();
1021 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001022 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001023 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1024 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001025 } else {
San Mehatb1043402010-02-05 08:26:50 -08001026 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001027 }
1028 }
1029 }
1030
1031 private int doFormatVolume(String path) {
1032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001033 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001034 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001035 } catch (NativeDaemonConnectorException e) {
1036 int code = e.getCode();
1037 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001038 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001039 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001040 return StorageResultCode.OperationFailedMediaCorrupt;
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
San Mehatb1043402010-02-05 08:26:50 -08001047 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001048 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001049 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001050 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001051 } catch (NativeDaemonConnectorException ex) {
1052 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1053 return false;
1054 }
San Mehatb1043402010-02-05 08:26:50 -08001055
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001056 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1057 return event.getMessage().endsWith("enabled");
1058 } else {
1059 return false;
San Mehatb1043402010-02-05 08:26:50 -08001060 }
San Mehatb1043402010-02-05 08:26:50 -08001061 }
1062
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001063 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001064 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001065 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001066 for (int i = mListeners.size() -1; i >= 0; i--) {
1067 MountServiceBinderListener bl = mListeners.get(i);
1068 try {
San Mehatb1043402010-02-05 08:26:50 -08001069 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001070 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001071 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001072 mListeners.remove(i);
1073 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001074 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001075 }
1076 }
1077 }
1078
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001079 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001080 sendUmsIntent(avail);
1081 } else {
1082 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001083 }
San Mehat2fe718a2010-03-11 12:01:49 -08001084
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001085 final StorageVolume primary = getPrimaryPhysicalVolume();
1086 if (avail == false && primary != null
1087 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1088 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001089 /*
1090 * USB mass storage disconnected while enabled
1091 */
1092 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001093 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001094 public void run() {
1095 try {
1096 int rc;
San Mehata5078592010-03-25 09:36:54 -07001097 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001098 doShareUnshareVolume(path, "ums", false);
1099 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001100 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001101 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1102 path, rc));
1103 }
1104 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001105 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001106 }
1107 }
1108 }.start();
1109 }
San Mehat4270e1e2010-01-29 05:32:19 -08001110 }
1111
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001112 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1113 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1114 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1115 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1116 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001117 }
1118
San Mehat6a965af22010-02-24 17:47:30 -08001119 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001120 mContext.sendBroadcastAsUser(
1121 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1122 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001123 }
1124
San Mehat207e5382010-02-04 20:46:54 -08001125 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001126 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1127 throw new SecurityException(String.format("Requires %s permission", perm));
1128 }
1129 }
1130
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001131 // Storage list XML tags
1132 private static final String TAG_STORAGE_LIST = "StorageList";
1133 private static final String TAG_STORAGE = "storage";
1134
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001135 private void readStorageListLocked() {
1136 mVolumes.clear();
1137 mVolumeStates.clear();
1138
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001139 Resources resources = mContext.getResources();
1140
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001141 int id = com.android.internal.R.xml.storage_list;
1142 XmlResourceParser parser = resources.getXml(id);
1143 AttributeSet attrs = Xml.asAttributeSet(parser);
1144
1145 try {
1146 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1147 while (true) {
1148 XmlUtils.nextElement(parser);
1149
1150 String element = parser.getName();
1151 if (element == null) break;
1152
1153 if (TAG_STORAGE.equals(element)) {
1154 TypedArray a = resources.obtainAttributes(attrs,
1155 com.android.internal.R.styleable.Storage);
1156
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001157 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001158 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001159 int descriptionId = a.getResourceId(
1160 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001161 CharSequence description = a.getText(
1162 com.android.internal.R.styleable.Storage_storageDescription);
1163 boolean primary = a.getBoolean(
1164 com.android.internal.R.styleable.Storage_primary, false);
1165 boolean removable = a.getBoolean(
1166 com.android.internal.R.styleable.Storage_removable, false);
1167 boolean emulated = a.getBoolean(
1168 com.android.internal.R.styleable.Storage_emulated, false);
1169 int mtpReserve = a.getInt(
1170 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001171 boolean allowMassStorage = a.getBoolean(
1172 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001173 // resource parser does not support longs, so XML value is in megabytes
1174 long maxFileSize = a.getInt(
1175 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001176
1177 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1178 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001179 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001180 " allowMassStorage: " + allowMassStorage +
1181 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001182
1183 if (emulated) {
1184 // For devices with emulated storage, we create separate
1185 // volumes for each known user.
1186 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1187 true, mtpReserve, false, maxFileSize, null);
1188
1189 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001190 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001191 createEmulatedVolumeForUserLocked(user.getUserHandle());
1192 }
1193
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001194 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001195 if (path == null || description == null) {
1196 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001197 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001198 final StorageVolume volume = new StorageVolume(new File(path),
1199 descriptionId, primary, removable, emulated, mtpReserve,
1200 allowMassStorage, maxFileSize, null);
1201 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001202 }
1203 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001204
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001205 a.recycle();
1206 }
1207 }
1208 } catch (XmlPullParserException e) {
1209 throw new RuntimeException(e);
1210 } catch (IOException e) {
1211 throw new RuntimeException(e);
1212 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001213 // Compute storage ID for each physical volume; emulated storage is
1214 // always 0 when defined.
1215 int index = isExternalStorageEmulated() ? 1 : 0;
1216 for (StorageVolume volume : mVolumes) {
1217 if (!volume.isEmulated()) {
1218 volume.setStorageId(index++);
1219 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001220 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001221 parser.close();
1222 }
1223 }
1224
San Mehat4270e1e2010-01-29 05:32:19 -08001225 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001226 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1227 * using {@link #mEmulatedTemplate} as template.
1228 */
1229 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1230 if (mEmulatedTemplate == null) {
1231 throw new IllegalStateException("Missing emulated volume multi-user template");
1232 }
1233
1234 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1235 final File path = userEnv.getExternalStorageDirectory();
1236 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1237 volume.setStorageId(0);
1238 addVolumeLocked(volume);
1239
1240 if (mSystemReady) {
1241 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1242 } else {
1243 // Place stub status for early callers to find
1244 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1245 }
1246 }
1247
1248 private void addVolumeLocked(StorageVolume volume) {
1249 Slog.d(TAG, "addVolumeLocked() " + volume);
1250 mVolumes.add(volume);
1251 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1252 if (existing != null) {
1253 throw new IllegalStateException(
1254 "Volume at " + volume.getPath() + " already exists: " + existing);
1255 }
1256 }
1257
1258 private void removeVolumeLocked(StorageVolume volume) {
1259 Slog.d(TAG, "removeVolumeLocked() " + volume);
1260 mVolumes.remove(volume);
1261 mVolumesByPath.remove(volume.getPath());
1262 mVolumeStates.remove(volume.getPath());
1263 }
1264
1265 private StorageVolume getPrimaryPhysicalVolume() {
1266 synchronized (mVolumesLock) {
1267 for (StorageVolume volume : mVolumes) {
1268 if (volume.isPrimary() && !volume.isEmulated()) {
1269 return volume;
1270 }
1271 }
1272 }
1273 return null;
1274 }
1275
1276 /**
San Mehat207e5382010-02-04 20:46:54 -08001277 * Constructs a new MountService instance
1278 *
1279 * @param context Binder context for this service
1280 */
1281 public MountService(Context context) {
1282 mContext = context;
1283
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001284 synchronized (mVolumesLock) {
1285 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001286 }
1287
San Mehat207e5382010-02-04 20:46:54 -08001288 // XXX: This will go away soon in favor of IMountServiceObserver
1289 mPms = (PackageManagerService) ServiceManager.getService("package");
1290
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001291 mHandlerThread = new HandlerThread("MountService");
1292 mHandlerThread.start();
1293 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1294
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001295 // Watch for user changes
1296 final IntentFilter userFilter = new IntentFilter();
1297 userFilter.addAction(Intent.ACTION_USER_ADDED);
1298 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1299 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1300
1301 // Watch for USB changes on primary volume
1302 final StorageVolume primary = getPrimaryPhysicalVolume();
1303 if (primary != null && primary.allowMassStorage()) {
1304 mContext.registerReceiver(
1305 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1306 }
1307
Kenny Roota02b8b02010-08-05 16:14:17 -07001308 // Add OBB Action Handler to MountService thread.
1309 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1310
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001311 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001312 * Create the connection to vold with a maximum queue of twice the
1313 * amount of containers we'd ever expect to have. This keeps an
1314 * "asec list" from blocking a thread repeatedly.
1315 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001316 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001317
Kenny Root305bcbf2010-09-03 07:56:38 -07001318 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001319 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001320
Kenny Root07714d42011-08-17 17:49:28 -07001321 // Add ourself to the Watchdog monitors if enabled.
1322 if (WATCHDOG_ENABLE) {
1323 Watchdog.getInstance().addMonitor(this);
1324 }
San Mehat207e5382010-02-04 20:46:54 -08001325 }
1326
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001327 public void systemReady() {
1328 mSystemReady = true;
1329 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1330 }
1331
San Mehat207e5382010-02-04 20:46:54 -08001332 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001333 * Exposed API calls below here
1334 */
1335
1336 public void registerListener(IMountServiceListener listener) {
1337 synchronized (mListeners) {
1338 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1339 try {
1340 listener.asBinder().linkToDeath(bl, 0);
1341 mListeners.add(bl);
1342 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001343 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001344 }
1345 }
1346 }
1347
1348 public void unregisterListener(IMountServiceListener listener) {
1349 synchronized (mListeners) {
1350 for(MountServiceBinderListener bl : mListeners) {
1351 if (bl.mListener == listener) {
1352 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001353 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001354 return;
1355 }
1356 }
1357 }
1358 }
1359
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001360 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001361 validatePermission(android.Manifest.permission.SHUTDOWN);
1362
San Mehata5078592010-03-25 09:36:54 -07001363 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001364 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001365 for (String path : mVolumeStates.keySet()) {
1366 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001367
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001368 if (state.equals(Environment.MEDIA_SHARED)) {
1369 /*
1370 * If the media is currently shared, unshare it.
1371 * XXX: This is still dangerous!. We should not
1372 * be rebooting at *all* if UMS is enabled, since
1373 * the UMS host could have dirty FAT cache entries
1374 * yet to flush.
1375 */
1376 setUsbMassStorageEnabled(false);
1377 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1378 /*
1379 * If the media is being checked, then we need to wait for
1380 * it to complete before being able to proceed.
1381 */
1382 // XXX: @hackbod - Should we disable the ANR timer here?
1383 int retries = 30;
1384 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1385 try {
1386 Thread.sleep(1000);
1387 } catch (InterruptedException iex) {
1388 Slog.e(TAG, "Interrupted while waiting for media", iex);
1389 break;
1390 }
1391 state = Environment.getExternalStorageState();
1392 }
1393 if (retries == 0) {
1394 Slog.e(TAG, "Timed out waiting for media to check");
1395 }
San Mehat91c77612010-01-07 10:39:41 -08001396 }
San Mehat91c77612010-01-07 10:39:41 -08001397
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001398 if (state.equals(Environment.MEDIA_MOUNTED)) {
1399 // Post a unmount message.
1400 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1401 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1402 } else if (observer != null) {
1403 /*
1404 * Observer is waiting for onShutDownComplete when we are done.
1405 * Since nothing will be done send notification directly so shutdown
1406 * sequence can continue.
1407 */
1408 try {
1409 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1410 } catch (RemoteException e) {
1411 Slog.w(TAG, "RemoteException when shutting down");
1412 }
1413 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001414 }
San Mehat4270e1e2010-01-29 05:32:19 -08001415 }
1416 }
1417
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001418 private boolean getUmsEnabling() {
1419 synchronized (mListeners) {
1420 return mUmsEnabling;
1421 }
1422 }
1423
1424 private void setUmsEnabling(boolean enable) {
1425 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001426 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001427 }
1428 }
1429
San Mehatb1043402010-02-05 08:26:50 -08001430 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001431 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001432
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001433 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001434 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001435 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001436 synchronized (mListeners) {
1437 return mUmsAvailable;
1438 }
San Mehatb1043402010-02-05 08:26:50 -08001439 }
1440
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001441 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001442 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001443 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001444
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001445 final StorageVolume primary = getPrimaryPhysicalVolume();
1446 if (primary == null) return;
1447
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001448 // TODO: Add support for multiple share methods
1449
1450 /*
1451 * If the volume is mounted and we're enabling then unmount it
1452 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001453 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001454 String vs = getVolumeState(path);
1455 String method = "ums";
1456 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1457 // Override for isUsbMassStorageEnabled()
1458 setUmsEnabling(enable);
1459 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1460 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1461 // Clear override
1462 setUmsEnabling(false);
1463 }
1464 /*
1465 * If we disabled UMS then mount the volume
1466 */
1467 if (!enable) {
1468 doShareUnshareVolume(path, method, enable);
1469 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001470 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001471 " after disabling share method " + method);
1472 /*
1473 * Even though the mount failed, the unshare didn't so don't indicate an error.
1474 * The mountVolume() call will have set the storage state and sent the necessary
1475 * broadcasts.
1476 */
1477 }
1478 }
San Mehatb1043402010-02-05 08:26:50 -08001479 }
1480
1481 public boolean isUsbMassStorageEnabled() {
1482 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001483
1484 final StorageVolume primary = getPrimaryPhysicalVolume();
1485 if (primary != null) {
1486 return doGetVolumeShared(primary.getPath(), "ums");
1487 } else {
1488 return false;
1489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001491
San Mehat7fd0fee2009-12-17 07:12:23 -08001492 /**
1493 * @return state of the volume at the specified mount point
1494 */
San Mehat4270e1e2010-01-29 05:32:19 -08001495 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001496 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001497 String state = mVolumeStates.get(mountPoint);
1498 if (state == null) {
1499 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001500 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1501 state = Environment.MEDIA_REMOVED;
1502 } else {
1503 throw new IllegalArgumentException();
1504 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001505 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001506
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001507 return state;
1508 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001509 }
1510
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001511 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001512 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001513 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001514 }
1515
San Mehat4270e1e2010-01-29 05:32:19 -08001516 public int mountVolume(String path) {
1517 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001518
San Mehat207e5382010-02-04 20:46:54 -08001519 waitForReady();
1520 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
Ben Komalo13c71972011-09-07 16:35:56 -07001523 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001524 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001525 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001527 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001528 if (DEBUG_UNMOUNT) {
1529 Slog.i(TAG, "Unmounting " + path
1530 + " force = " + force
1531 + " removeEncryption = " + removeEncryption);
1532 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001533 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1534 Environment.MEDIA_REMOVED.equals(volState) ||
1535 Environment.MEDIA_SHARED.equals(volState) ||
1536 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1537 // Media already unmounted or cannot be unmounted.
1538 // TODO return valid return code when adding observer call back.
1539 return;
1540 }
Ben Komalo13c71972011-09-07 16:35:56 -07001541 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001542 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544
San Mehat4270e1e2010-01-29 05:32:19 -08001545 public int formatVolume(String path) {
1546 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001547 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001548
San Mehat207e5382010-02-04 20:46:54 -08001549 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001552 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001553 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1554 waitForReady();
1555 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001556 final String[] r = NativeDaemonEvent.filterMessageList(
1557 mConnector.executeForList("storage", "users", path),
1558 VoldResponseCode.StorageUsersListResult);
1559
San Mehatc1b4ce92010-02-16 17:13:03 -08001560 // FMT: <pid> <process name>
1561 int[] data = new int[r.length];
1562 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001563 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001564 try {
1565 data[i] = Integer.parseInt(tok[0]);
1566 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001567 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001568 return new int[0];
1569 }
1570 }
1571 return data;
1572 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001573 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001574 return new int[0];
1575 }
1576 }
1577
San Mehatb1043402010-02-05 08:26:50 -08001578 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001579 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001580 if (primary != null) {
1581 boolean mounted = false;
1582 try {
1583 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
1584 } catch (IllegalStateException e) {
1585 }
1586
1587 if (!mounted) {
1588 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1589 }
San Mehatb1043402010-02-05 08:26:50 -08001590 }
1591 }
1592
San Mehat4270e1e2010-01-29 05:32:19 -08001593 public String[] getSecureContainerList() {
1594 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001595 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001596 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001597
San Mehat4270e1e2010-01-29 05:32:19 -08001598 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001599 return NativeDaemonEvent.filterMessageList(
1600 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001601 } catch (NativeDaemonConnectorException e) {
1602 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604 }
San Mehat36972292010-01-06 11:06:32 -08001605
Kenny Root6dceb882012-04-12 14:23:49 -07001606 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1607 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001608 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001609 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001610 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001611
San Mehatb1043402010-02-05 08:26:50 -08001612 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001613 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001614 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1615 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001616 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001617 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001618 }
San Mehata181b212010-02-11 06:50:20 -08001619
1620 if (rc == StorageResultCode.OperationSucceeded) {
1621 synchronized (mAsecMountSet) {
1622 mAsecMountSet.add(id);
1623 }
1624 }
San Mehat4270e1e2010-01-29 05:32:19 -08001625 return rc;
San Mehat36972292010-01-06 11:06:32 -08001626 }
1627
San Mehat4270e1e2010-01-29 05:32:19 -08001628 public int finalizeSecureContainer(String id) {
1629 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001630 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001631
San Mehatb1043402010-02-05 08:26:50 -08001632 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001633 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001634 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001635 /*
1636 * Finalization does a remount, so no need
1637 * to update mAsecMountSet
1638 */
San Mehat4270e1e2010-01-29 05:32:19 -08001639 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001640 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001641 }
San Mehat4270e1e2010-01-29 05:32:19 -08001642 return rc;
San Mehat36972292010-01-06 11:06:32 -08001643 }
1644
Kenny Root6dceb882012-04-12 14:23:49 -07001645 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1646 validatePermission(android.Manifest.permission.ASEC_CREATE);
1647 warnOnNotMounted();
1648
1649 int rc = StorageResultCode.OperationSucceeded;
1650 try {
1651 mConnector.execute("asec", "fixperms", id, gid, filename);
1652 /*
1653 * Fix permissions does a remount, so no need to update
1654 * mAsecMountSet
1655 */
1656 } catch (NativeDaemonConnectorException e) {
1657 rc = StorageResultCode.OperationFailedInternalError;
1658 }
1659 return rc;
1660 }
1661
San Mehatd9709982010-02-18 11:43:03 -08001662 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001663 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001664 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001665 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001666
Kenny Rootaa485402010-09-14 14:49:41 -07001667 /*
1668 * Force a GC to make sure AssetManagers in other threads of the
1669 * system_server are cleaned up. We have to do this since AssetManager
1670 * instances are kept as a WeakReference and it's possible we have files
1671 * open on the external storage.
1672 */
1673 Runtime.getRuntime().gc();
1674
San Mehatb1043402010-02-05 08:26:50 -08001675 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001676 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001677 final Command cmd = new Command("asec", "destroy", id);
1678 if (force) {
1679 cmd.appendArg("force");
1680 }
1681 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001682 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001683 int code = e.getCode();
1684 if (code == VoldResponseCode.OpFailedStorageBusy) {
1685 rc = StorageResultCode.OperationFailedStorageBusy;
1686 } else {
1687 rc = StorageResultCode.OperationFailedInternalError;
1688 }
San Mehat02735bc2010-01-26 15:18:08 -08001689 }
San Mehata181b212010-02-11 06:50:20 -08001690
1691 if (rc == StorageResultCode.OperationSucceeded) {
1692 synchronized (mAsecMountSet) {
1693 if (mAsecMountSet.contains(id)) {
1694 mAsecMountSet.remove(id);
1695 }
1696 }
1697 }
1698
San Mehat4270e1e2010-01-29 05:32:19 -08001699 return rc;
San Mehat36972292010-01-06 11:06:32 -08001700 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001701
San Mehat4270e1e2010-01-29 05:32:19 -08001702 public int mountSecureContainer(String id, String key, int ownerUid) {
1703 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001704 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001705 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001706
San Mehata181b212010-02-11 06:50:20 -08001707 synchronized (mAsecMountSet) {
1708 if (mAsecMountSet.contains(id)) {
1709 return StorageResultCode.OperationFailedStorageMounted;
1710 }
1711 }
1712
San Mehatb1043402010-02-05 08:26:50 -08001713 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001714 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001715 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001716 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001717 int code = e.getCode();
1718 if (code != VoldResponseCode.OpFailedStorageBusy) {
1719 rc = StorageResultCode.OperationFailedInternalError;
1720 }
San Mehat02735bc2010-01-26 15:18:08 -08001721 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001722
1723 if (rc == StorageResultCode.OperationSucceeded) {
1724 synchronized (mAsecMountSet) {
1725 mAsecMountSet.add(id);
1726 }
1727 }
San Mehat4270e1e2010-01-29 05:32:19 -08001728 return rc;
San Mehat36972292010-01-06 11:06:32 -08001729 }
1730
San Mehatd9709982010-02-18 11:43:03 -08001731 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001732 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001733 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001734 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001735
San Mehat6cdd9c02010-02-09 14:45:20 -08001736 synchronized (mAsecMountSet) {
1737 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001738 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001739 }
1740 }
1741
Kenny Rootaa485402010-09-14 14:49:41 -07001742 /*
1743 * Force a GC to make sure AssetManagers in other threads of the
1744 * system_server are cleaned up. We have to do this since AssetManager
1745 * instances are kept as a WeakReference and it's possible we have files
1746 * open on the external storage.
1747 */
1748 Runtime.getRuntime().gc();
1749
San Mehatb1043402010-02-05 08:26:50 -08001750 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001751 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001752 final Command cmd = new Command("asec", "unmount", id);
1753 if (force) {
1754 cmd.appendArg("force");
1755 }
1756 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001757 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001758 int code = e.getCode();
1759 if (code == VoldResponseCode.OpFailedStorageBusy) {
1760 rc = StorageResultCode.OperationFailedStorageBusy;
1761 } else {
1762 rc = StorageResultCode.OperationFailedInternalError;
1763 }
San Mehat02735bc2010-01-26 15:18:08 -08001764 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001765
1766 if (rc == StorageResultCode.OperationSucceeded) {
1767 synchronized (mAsecMountSet) {
1768 mAsecMountSet.remove(id);
1769 }
1770 }
San Mehat4270e1e2010-01-29 05:32:19 -08001771 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001772 }
1773
San Mehat6cdd9c02010-02-09 14:45:20 -08001774 public boolean isSecureContainerMounted(String id) {
1775 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1776 waitForReady();
1777 warnOnNotMounted();
1778
1779 synchronized (mAsecMountSet) {
1780 return mAsecMountSet.contains(id);
1781 }
1782 }
1783
San Mehat4270e1e2010-01-29 05:32:19 -08001784 public int renameSecureContainer(String oldId, String newId) {
1785 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001786 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001787 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001788
San Mehata181b212010-02-11 06:50:20 -08001789 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001790 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001791 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001792 * changed while active, we must ensure both ids are not currently mounted.
1793 */
1794 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001795 return StorageResultCode.OperationFailedStorageMounted;
1796 }
1797 }
1798
San Mehatb1043402010-02-05 08:26:50 -08001799 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001800 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001801 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001802 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001803 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001804 }
San Mehata181b212010-02-11 06:50:20 -08001805
San Mehat4270e1e2010-01-29 05:32:19 -08001806 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001807 }
1808
San Mehat4270e1e2010-01-29 05:32:19 -08001809 public String getSecureContainerPath(String id) {
1810 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001811 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001812 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001813
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001814 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001815 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001816 event = mConnector.execute("asec", "path", id);
1817 event.checkCode(VoldResponseCode.AsecPathResult);
1818 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001819 } catch (NativeDaemonConnectorException e) {
1820 int code = e.getCode();
1821 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001822 Slog.i(TAG, String.format("Container '%s' not found", id));
1823 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001824 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001825 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001826 }
1827 }
San Mehat22dd86e2010-01-12 12:21:18 -08001828 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001829
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001830 public String getSecureContainerFilesystemPath(String id) {
1831 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1832 waitForReady();
1833 warnOnNotMounted();
1834
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001835 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001836 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001837 event = mConnector.execute("asec", "fspath", id);
1838 event.checkCode(VoldResponseCode.AsecPathResult);
1839 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001840 } catch (NativeDaemonConnectorException e) {
1841 int code = e.getCode();
1842 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1843 Slog.i(TAG, String.format("Container '%s' not found", id));
1844 return null;
1845 } else {
1846 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1847 }
1848 }
1849 }
1850
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001851 public void finishMediaUpdate() {
1852 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1853 }
Kenny Root02c87302010-07-01 08:10:18 -07001854
Kenny Roota02b8b02010-08-05 16:14:17 -07001855 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1856 if (callerUid == android.os.Process.SYSTEM_UID) {
1857 return true;
1858 }
1859
Kenny Root02c87302010-07-01 08:10:18 -07001860 if (packageName == null) {
1861 return false;
1862 }
1863
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001864 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001865
1866 if (DEBUG_OBB) {
1867 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1868 packageUid + ", callerUid = " + callerUid);
1869 }
1870
1871 return callerUid == packageUid;
1872 }
1873
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001874 public String getMountedObbPath(String rawPath) {
1875 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001876
Kenny Root02c87302010-07-01 08:10:18 -07001877 waitForReady();
1878 warnOnNotMounted();
1879
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001880 final ObbState state;
1881 synchronized (mObbPathToStateMap) {
1882 state = mObbPathToStateMap.get(rawPath);
1883 }
1884 if (state == null) {
1885 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1886 return null;
1887 }
1888
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001889 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001890 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001891 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001892 event.checkCode(VoldResponseCode.AsecPathResult);
1893 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001894 } catch (NativeDaemonConnectorException e) {
1895 int code = e.getCode();
1896 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001897 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001898 } else {
1899 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1900 }
1901 }
1902 }
1903
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001904 @Override
1905 public boolean isObbMounted(String rawPath) {
1906 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001907 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001908 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001909 }
Kenny Root02c87302010-07-01 08:10:18 -07001910 }
1911
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001912 @Override
1913 public void mountObb(
1914 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1915 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1916 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1917 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001918
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001919 final int callingUid = Binder.getCallingUid();
1920 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1921 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001922 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1923
1924 if (DEBUG_OBB)
1925 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001926 }
1927
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001928 @Override
1929 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1930 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1931
1932 final ObbState existingState;
1933 synchronized (mObbPathToStateMap) {
1934 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001935 }
1936
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001937 if (existingState != null) {
1938 // TODO: separate state object from request data
1939 final int callingUid = Binder.getCallingUid();
1940 final ObbState newState = new ObbState(
1941 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1942 final ObbAction action = new UnmountObbAction(newState, force);
1943 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001944
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001945 if (DEBUG_OBB)
1946 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1947 } else {
1948 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1949 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001950 }
1951
Ben Komalo444eca22011-09-01 15:17:44 -07001952 @Override
1953 public int getEncryptionState() {
1954 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1955 "no permission to access the crypt keeper");
1956
1957 waitForReady();
1958
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001959 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001960 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001961 event = mConnector.execute("cryptfs", "cryptocomplete");
1962 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001963 } catch (NumberFormatException e) {
1964 // Bad result - unexpected.
1965 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1966 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1967 } catch (NativeDaemonConnectorException e) {
1968 // Something bad happened.
1969 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1970 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1971 }
1972 }
1973
1974 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001975 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001976 if (TextUtils.isEmpty(password)) {
1977 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001978 }
1979
Jason parks8888c592011-01-20 22:46:41 -06001980 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1981 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001982
1983 waitForReady();
1984
1985 if (DEBUG_EVENTS) {
1986 Slog.i(TAG, "decrypting storage...");
1987 }
1988
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001989 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001990 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001991 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001992
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001993 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001994 if (code == 0) {
1995 // Decrypt was successful. Post a delayed message before restarting in order
1996 // to let the UI to clear itself
1997 mHandler.postDelayed(new Runnable() {
1998 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001999 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002000 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002001 } catch (NativeDaemonConnectorException e) {
2002 Slog.e(TAG, "problem executing in background", e);
2003 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002004 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002005 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002006 }
2007
2008 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002009 } catch (NativeDaemonConnectorException e) {
2010 // Decryption failed
2011 return e.getCode();
2012 }
Jason parks5af0b912010-11-29 09:05:25 -06002013 }
2014
Jason parks56aa5322011-01-07 09:01:15 -06002015 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002016 if (TextUtils.isEmpty(password)) {
2017 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002018 }
2019
Jason parks8888c592011-01-20 22:46:41 -06002020 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2021 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002022
2023 waitForReady();
2024
2025 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002026 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002027 }
2028
2029 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002030 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002031 } catch (NativeDaemonConnectorException e) {
2032 // Encryption failed
2033 return e.getCode();
2034 }
2035
2036 return 0;
2037 }
2038
Jason parksf7b3cd42011-01-27 09:28:25 -06002039 public int changeEncryptionPassword(String password) {
2040 if (TextUtils.isEmpty(password)) {
2041 throw new IllegalArgumentException("password cannot be empty");
2042 }
2043
2044 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2045 "no permission to access the crypt keeper");
2046
2047 waitForReady();
2048
2049 if (DEBUG_EVENTS) {
2050 Slog.i(TAG, "changing encryption password...");
2051 }
2052
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002053 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002054 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002055 event = mConnector.execute("cryptfs", "changepw", password);
2056 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002057 } catch (NativeDaemonConnectorException e) {
2058 // Encryption failed
2059 return e.getCode();
2060 }
2061 }
2062
Christopher Tate32418be2011-10-10 13:51:12 -07002063 /**
2064 * Validate a user-supplied password string with cryptfs
2065 */
2066 @Override
2067 public int verifyEncryptionPassword(String password) throws RemoteException {
2068 // Only the system process is permitted to validate passwords
2069 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2070 throw new SecurityException("no permission to access the crypt keeper");
2071 }
2072
2073 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2074 "no permission to access the crypt keeper");
2075
2076 if (TextUtils.isEmpty(password)) {
2077 throw new IllegalArgumentException("password cannot be empty");
2078 }
2079
2080 waitForReady();
2081
2082 if (DEBUG_EVENTS) {
2083 Slog.i(TAG, "validating encryption password...");
2084 }
2085
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002086 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002087 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002088 event = mConnector.execute("cryptfs", "verifypw", password);
2089 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2090 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002091 } catch (NativeDaemonConnectorException e) {
2092 // Encryption failed
2093 return e.getCode();
2094 }
2095 }
2096
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002097 @Override
2098 public StorageVolume[] getVolumeList() {
2099 final int callingUserId = UserHandle.getCallingUserId();
2100 final boolean accessAll = (mContext.checkPermission(
2101 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2102 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2103
2104 synchronized (mVolumesLock) {
2105 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2106 for (StorageVolume volume : mVolumes) {
2107 final UserHandle owner = volume.getOwner();
2108 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2109 if (accessAll || ownerMatch) {
2110 filtered.add(volume);
2111 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002112 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002113 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002114 }
2115 }
2116
Kenny Rootaf9d6672010-10-08 09:21:39 -07002117 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2118 final IBinder binder = obbState.getBinder();
2119 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002120
Kenny Rootaf9d6672010-10-08 09:21:39 -07002121 if (obbStates == null) {
2122 obbStates = new ArrayList<ObbState>();
2123 mObbMounts.put(binder, obbStates);
2124 } else {
2125 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002126 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002127 throw new IllegalStateException("Attempt to add ObbState twice. "
2128 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002129 }
2130 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002131 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002132
2133 obbStates.add(obbState);
2134 try {
2135 obbState.link();
2136 } catch (RemoteException e) {
2137 /*
2138 * The binder died before we could link it, so clean up our state
2139 * and return failure.
2140 */
2141 obbStates.remove(obbState);
2142 if (obbStates.isEmpty()) {
2143 mObbMounts.remove(binder);
2144 }
2145
2146 // Rethrow the error so mountObb can get it
2147 throw e;
2148 }
2149
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002150 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002151 }
2152
Kenny Rootaf9d6672010-10-08 09:21:39 -07002153 private void removeObbStateLocked(ObbState obbState) {
2154 final IBinder binder = obbState.getBinder();
2155 final List<ObbState> obbStates = mObbMounts.get(binder);
2156 if (obbStates != null) {
2157 if (obbStates.remove(obbState)) {
2158 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002159 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002160 if (obbStates.isEmpty()) {
2161 mObbMounts.remove(binder);
2162 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002163 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002164
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002165 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002166 }
2167
Kenny Roota02b8b02010-08-05 16:14:17 -07002168 private class ObbActionHandler extends Handler {
2169 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002170 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002171
2172 ObbActionHandler(Looper l) {
2173 super(l);
2174 }
2175
2176 @Override
2177 public void handleMessage(Message msg) {
2178 switch (msg.what) {
2179 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002180 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002181
2182 if (DEBUG_OBB)
2183 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2184
2185 // If a bind was already initiated we don't really
2186 // need to do anything. The pending install
2187 // will be processed later on.
2188 if (!mBound) {
2189 // If this is the only one pending we might
2190 // have to bind to the service again.
2191 if (!connectToService()) {
2192 Slog.e(TAG, "Failed to bind to media container service");
2193 action.handleError();
2194 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002195 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002196 }
Kenny Root735de3b2010-09-30 14:11:39 -07002197
Kenny Root735de3b2010-09-30 14:11:39 -07002198 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002199 break;
2200 }
2201 case OBB_MCS_BOUND: {
2202 if (DEBUG_OBB)
2203 Slog.i(TAG, "OBB_MCS_BOUND");
2204 if (msg.obj != null) {
2205 mContainerService = (IMediaContainerService) msg.obj;
2206 }
2207 if (mContainerService == null) {
2208 // Something seriously wrong. Bail out
2209 Slog.e(TAG, "Cannot bind to media container service");
2210 for (ObbAction action : mActions) {
2211 // Indicate service bind error
2212 action.handleError();
2213 }
2214 mActions.clear();
2215 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002216 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002217 if (action != null) {
2218 action.execute(this);
2219 }
2220 } else {
2221 // Should never happen ideally.
2222 Slog.w(TAG, "Empty queue");
2223 }
2224 break;
2225 }
2226 case OBB_MCS_RECONNECT: {
2227 if (DEBUG_OBB)
2228 Slog.i(TAG, "OBB_MCS_RECONNECT");
2229 if (mActions.size() > 0) {
2230 if (mBound) {
2231 disconnectService();
2232 }
2233 if (!connectToService()) {
2234 Slog.e(TAG, "Failed to bind to media container service");
2235 for (ObbAction action : mActions) {
2236 // Indicate service bind error
2237 action.handleError();
2238 }
2239 mActions.clear();
2240 }
2241 }
2242 break;
2243 }
2244 case OBB_MCS_UNBIND: {
2245 if (DEBUG_OBB)
2246 Slog.i(TAG, "OBB_MCS_UNBIND");
2247
2248 // Delete pending install
2249 if (mActions.size() > 0) {
2250 mActions.remove(0);
2251 }
2252 if (mActions.size() == 0) {
2253 if (mBound) {
2254 disconnectService();
2255 }
2256 } else {
2257 // There are more pending requests in queue.
2258 // Just post MCS_BOUND message to trigger processing
2259 // of next pending install.
2260 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2261 }
2262 break;
2263 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002264 case OBB_FLUSH_MOUNT_STATE: {
2265 final String path = (String) msg.obj;
2266
2267 if (DEBUG_OBB)
2268 Slog.i(TAG, "Flushing all OBB state for path " + path);
2269
2270 synchronized (mObbMounts) {
2271 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2272
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002273 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002274 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002275 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002276
2277 /*
2278 * If this entry's source file is in the volume path
2279 * that got unmounted, remove it because it's no
2280 * longer valid.
2281 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002282 if (state.canonicalPath.startsWith(path)) {
2283 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002284 }
2285 }
2286
2287 for (final ObbState obbState : obbStatesToRemove) {
2288 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002289 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002290
2291 removeObbStateLocked(obbState);
2292
2293 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002294 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002295 OnObbStateChangeListener.UNMOUNTED);
2296 } catch (RemoteException e) {
2297 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002298 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002299 }
2300 }
2301 }
2302 break;
2303 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002304 }
2305 }
2306
2307 private boolean connectToService() {
2308 if (DEBUG_OBB)
2309 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2310
2311 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2312 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2313 mBound = true;
2314 return true;
2315 }
2316 return false;
2317 }
2318
2319 private void disconnectService() {
2320 mContainerService = null;
2321 mBound = false;
2322 mContext.unbindService(mDefContainerConn);
2323 }
2324 }
2325
2326 abstract class ObbAction {
2327 private static final int MAX_RETRIES = 3;
2328 private int mRetries;
2329
2330 ObbState mObbState;
2331
2332 ObbAction(ObbState obbState) {
2333 mObbState = obbState;
2334 }
2335
2336 public void execute(ObbActionHandler handler) {
2337 try {
2338 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002339 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002340 mRetries++;
2341 if (mRetries > MAX_RETRIES) {
2342 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002343 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002344 handleError();
2345 return;
2346 } else {
2347 handleExecute();
2348 if (DEBUG_OBB)
2349 Slog.i(TAG, "Posting install MCS_UNBIND");
2350 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2351 }
2352 } catch (RemoteException e) {
2353 if (DEBUG_OBB)
2354 Slog.i(TAG, "Posting install MCS_RECONNECT");
2355 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2356 } catch (Exception e) {
2357 if (DEBUG_OBB)
2358 Slog.d(TAG, "Error handling OBB action", e);
2359 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002360 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002361 }
2362 }
2363
Kenny Root05105f72010-09-22 17:29:43 -07002364 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002365 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002366
2367 protected ObbInfo getObbInfo() throws IOException {
2368 ObbInfo obbInfo;
2369 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002370 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002371 } catch (RemoteException e) {
2372 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002373 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002374 obbInfo = null;
2375 }
2376 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002377 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002378 }
2379 return obbInfo;
2380 }
2381
Kenny Rootaf9d6672010-10-08 09:21:39 -07002382 protected void sendNewStatusOrIgnore(int status) {
2383 if (mObbState == null || mObbState.token == null) {
2384 return;
2385 }
2386
Kenny Root38cf8862010-09-26 14:18:51 -07002387 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002388 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002389 } catch (RemoteException e) {
2390 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2391 }
2392 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002393 }
2394
2395 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002396 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002397 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002398
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002399 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002400 super(obbState);
2401 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002402 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002403 }
2404
Jason parks5af0b912010-11-29 09:05:25 -06002405 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002406 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002407 waitForReady();
2408 warnOnNotMounted();
2409
Kenny Root38cf8862010-09-26 14:18:51 -07002410 final ObbInfo obbInfo = getObbInfo();
2411
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002412 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002413 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2414 + " which is owned by " + obbInfo.packageName);
2415 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2416 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002417 }
2418
Kenny Rootaf9d6672010-10-08 09:21:39 -07002419 final boolean isMounted;
2420 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002422 }
2423 if (isMounted) {
2424 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2425 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2426 return;
2427 }
2428
Kenny Rootaf9d6672010-10-08 09:21:39 -07002429 final String hashedKey;
2430 if (mKey == null) {
2431 hashedKey = "none";
2432 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002433 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002434 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2435
2436 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2437 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2438 SecretKey key = factory.generateSecret(ks);
2439 BigInteger bi = new BigInteger(key.getEncoded());
2440 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002442 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2443 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2444 return;
2445 } catch (InvalidKeySpecException e) {
2446 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2447 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002448 return;
2449 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002450 }
Kenny Root38cf8862010-09-26 14:18:51 -07002451
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002453 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002454 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002455 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002456 } catch (NativeDaemonConnectorException e) {
2457 int code = e.getCode();
2458 if (code != VoldResponseCode.OpFailedStorageBusy) {
2459 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002460 }
2461 }
2462
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463 if (rc == StorageResultCode.OperationSucceeded) {
2464 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002465 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002466
2467 synchronized (mObbMounts) {
2468 addObbStateLocked(mObbState);
2469 }
2470
2471 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002472 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002473 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002474
Kenny Rootaf9d6672010-10-08 09:21:39 -07002475 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002476 }
2477 }
2478
Jason parks5af0b912010-11-29 09:05:25 -06002479 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002480 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002481 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002482 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002483
2484 @Override
2485 public String toString() {
2486 StringBuilder sb = new StringBuilder();
2487 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002488 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002489 sb.append('}');
2490 return sb.toString();
2491 }
2492 }
2493
2494 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002495 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002496
2497 UnmountObbAction(ObbState obbState, boolean force) {
2498 super(obbState);
2499 mForceUnmount = force;
2500 }
2501
Jason parks5af0b912010-11-29 09:05:25 -06002502 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002503 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002504 waitForReady();
2505 warnOnNotMounted();
2506
Kenny Root38cf8862010-09-26 14:18:51 -07002507 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002508
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002509 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002510 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002511 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002512 }
Kenny Root38cf8862010-09-26 14:18:51 -07002513
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002514 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002515 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2516 return;
2517 }
2518
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002519 if (existingState.ownerGid != mObbState.ownerGid) {
2520 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2521 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002522 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2523 return;
2524 }
2525
Kenny Rootaf9d6672010-10-08 09:21:39 -07002526 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002527 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002528 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002529 if (mForceUnmount) {
2530 cmd.appendArg("force");
2531 }
2532 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002533 } catch (NativeDaemonConnectorException e) {
2534 int code = e.getCode();
2535 if (code == VoldResponseCode.OpFailedStorageBusy) {
2536 rc = StorageResultCode.OperationFailedStorageBusy;
2537 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2538 // If it's not mounted then we've already won.
2539 rc = StorageResultCode.OperationSucceeded;
2540 } else {
2541 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002542 }
2543 }
2544
Kenny Rootaf9d6672010-10-08 09:21:39 -07002545 if (rc == StorageResultCode.OperationSucceeded) {
2546 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002547 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002548 }
2549
Kenny Rootaf9d6672010-10-08 09:21:39 -07002550 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002551 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002552 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002553 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002554 }
2555 }
2556
Jason parks5af0b912010-11-29 09:05:25 -06002557 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002558 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002559 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002560 }
2561
2562 @Override
2563 public String toString() {
2564 StringBuilder sb = new StringBuilder();
2565 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002566 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002567 sb.append(",force=");
2568 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002569 sb.append('}');
2570 return sb.toString();
2571 }
Kenny Root02c87302010-07-01 08:10:18 -07002572 }
Kenny Root38cf8862010-09-26 14:18:51 -07002573
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002574 // @VisibleForTesting
2575 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2576 // TODO: allow caller to provide Environment for full testing
2577
2578 // Only adjust paths when storage is emulated
2579 if (!Environment.isExternalStorageEmulated()) {
2580 return canonicalPath;
2581 }
2582
2583 String path = canonicalPath.toString();
2584
2585 // First trim off any external storage prefix
2586 final UserEnvironment userEnv = new UserEnvironment(userId);
2587
2588 // /storage/emulated/0
2589 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2590 // /storage/emulated_legacy
2591 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2592 .toString();
2593
2594 if (path.startsWith(externalPath)) {
2595 path = path.substring(externalPath.length() + 1);
2596 } else if (path.startsWith(legacyExternalPath)) {
2597 path = path.substring(legacyExternalPath.length() + 1);
2598 } else {
2599 return canonicalPath;
2600 }
2601
2602 // Handle special OBB paths on emulated storage
2603 final String obbPath = "Android/obb";
2604 if (path.startsWith(obbPath)) {
2605 path = path.substring(obbPath.length() + 1);
2606
2607 if (forVold) {
2608 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2609 } else {
2610 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2611 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2612 }
2613 }
2614
2615 // Handle normal external storage paths
2616 if (forVold) {
2617 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2618 } else {
2619 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2620 }
2621 }
2622
Kenny Root38cf8862010-09-26 14:18:51 -07002623 @Override
2624 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2625 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2626 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2627 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2628 + " without permission " + android.Manifest.permission.DUMP);
2629 return;
2630 }
2631
Kenny Root38cf8862010-09-26 14:18:51 -07002632 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002633 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002634
Kenny Rootaf9d6672010-10-08 09:21:39 -07002635 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2636 while (binders.hasNext()) {
2637 Entry<IBinder, List<ObbState>> e = binders.next();
2638 pw.print(" Key="); pw.println(e.getKey().toString());
2639 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002640 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002641 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002642 }
2643 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002644
2645 pw.println("");
2646 pw.println(" mObbPathToStateMap:");
2647 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2648 while (maps.hasNext()) {
2649 final Entry<String, ObbState> e = maps.next();
2650 pw.print(" "); pw.print(e.getKey());
2651 pw.print(" -> "); pw.println(e.getValue().toString());
2652 }
Kenny Root38cf8862010-09-26 14:18:51 -07002653 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002654
2655 pw.println("");
2656
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002657 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002658 pw.println(" mVolumes:");
2659
2660 final int N = mVolumes.size();
2661 for (int i = 0; i < N; i++) {
2662 final StorageVolume v = mVolumes.get(i);
2663 pw.print(" ");
2664 pw.println(v.toString());
2665 }
2666 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002667
2668 pw.println();
2669 pw.println(" mConnection:");
2670 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002673 /** {@inheritDoc} */
2674 public void monitor() {
2675 if (mConnector != null) {
2676 mConnector.monitor();
2677 }
2678 }
2679}