blob: aeeb4c5c4d14f0f9d03229e38e59d88686420cf8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800201 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
202 private final 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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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) {
Kenny Root51a573c2012-05-17 13:30:28 -0700498 for (;;) {
499 try {
500 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800501 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700502 } else {
503 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
504 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800505 }
Kenny Root51a573c2012-05-17 13:30:28 -0700506 } catch (InterruptedException e) {
507 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800508 }
San Mehat207e5382010-02-04 20:46:54 -0800509 }
San Mehat1f6301e2010-01-07 22:40:27 -0800510 }
Kenny Root02c87302010-07-01 08:10:18 -0700511
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700512 private void handleSystemReady() {
513 // Snapshot current volume states since it's not safe to call into vold
514 // while holding locks.
515 final HashMap<String, String> snapshot;
516 synchronized (mVolumesLock) {
517 snapshot = new HashMap<String, String>(mVolumeStates);
518 }
519
520 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
521 final String path = entry.getKey();
522 final String state = entry.getValue();
523
524 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
525 int rc = doMountVolume(path);
526 if (rc != StorageResultCode.OperationSucceeded) {
527 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
528 rc));
529 }
530 } else if (state.equals(Environment.MEDIA_SHARED)) {
531 /*
532 * Bootstrap UMS enabled state since vold indicates
533 * the volume is shared (runtime restart while ums enabled)
534 */
535 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
536 VolumeState.Shared);
537 }
538 }
539
540 // Push mounted state for all emulated storage
541 synchronized (mVolumesLock) {
542 for (StorageVolume volume : mVolumes) {
543 if (volume.isEmulated()) {
544 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
545 }
546 }
547 }
548
549 /*
550 * If UMS was connected on boot, send the connected event
551 * now that we're up.
552 */
553 if (mSendUmsConnectedOnBoot) {
554 sendUmsIntent(true);
555 mSendUmsConnectedOnBoot = false;
556 }
557 }
558
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700559 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
560 @Override
561 public void onReceive(Context context, Intent intent) {
562 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
563 if (userId == -1) return;
564 final UserHandle user = new UserHandle(userId);
565
566 final String action = intent.getAction();
567 if (Intent.ACTION_USER_ADDED.equals(action)) {
568 synchronized (mVolumesLock) {
569 createEmulatedVolumeForUserLocked(user);
570 }
571
572 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
573 synchronized (mVolumesLock) {
574 final List<StorageVolume> toRemove = Lists.newArrayList();
575 for (StorageVolume volume : mVolumes) {
576 if (user.equals(volume.getOwner())) {
577 toRemove.add(volume);
578 }
579 }
580 for (StorageVolume volume : toRemove) {
581 removeVolumeLocked(volume);
582 }
583 }
584 }
585 }
586 };
587
588 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
589 @Override
590 public void onReceive(Context context, Intent intent) {
591 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
592 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
593 notifyShareAvailabilityChange(available);
594 }
595 };
596
San Mehat4270e1e2010-01-29 05:32:19 -0800597 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
598 final IMountServiceListener mListener;
599
600 MountServiceBinderListener(IMountServiceListener listener) {
601 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700602
San Mehat91c77612010-01-07 10:39:41 -0800603 }
604
San Mehat4270e1e2010-01-29 05:32:19 -0800605 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700606 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700607 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800608 mListeners.remove(this);
609 mListener.asBinder().unlinkToDeath(this, 0);
610 }
611 }
612 }
613
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800614 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800615 // TODO: Add support for multiple share methods
616 if (!method.equals("ums")) {
617 throw new IllegalArgumentException(String.format("Method %s not supported", method));
618 }
619
San Mehat4270e1e2010-01-29 05:32:19 -0800620 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800621 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800622 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700623 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800624 }
San Mehat4270e1e2010-01-29 05:32:19 -0800625 }
626
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700627 private void updatePublicVolumeState(StorageVolume volume, String state) {
628 final String path = volume.getPath();
629 final String oldState;
630 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400631 oldState = mVolumeStates.put(path, state);
632 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700633
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400634 if (state.equals(oldState)) {
635 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
636 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800637 return;
638 }
San Mehatb1043402010-02-05 08:26:50 -0800639
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400640 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700641
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700642 // Tell PackageManager about changes to primary volume state, but only
643 // when not emulated.
644 if (volume.isPrimary() && !volume.isEmulated()) {
645 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
646 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400647
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700648 /*
649 * Some OBBs might have been unmounted when this volume was
650 * unmounted, so send a message to the handler to let it know to
651 * remove those from the list of mounted OBBS.
652 */
653 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
654 OBB_FLUSH_MOUNT_STATE, path));
655 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
656 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400657 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800658 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700659
San Mehat4270e1e2010-01-29 05:32:19 -0800660 synchronized (mListeners) {
661 for (int i = mListeners.size() -1; i >= 0; i--) {
662 MountServiceBinderListener bl = mListeners.get(i);
663 try {
San Mehatb1043402010-02-05 08:26:50 -0800664 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800665 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700666 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800667 mListeners.remove(i);
668 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700669 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800670 }
671 }
672 }
673 }
674
675 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800676 * Callback from NativeDaemonConnector
677 */
678 public void onDaemonConnected() {
679 /*
680 * Since we'll be calling back into the NativeDaemonConnector,
681 * we need to do our work in a new thread.
682 */
Kenny Root51a573c2012-05-17 13:30:28 -0700683 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600684 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800685 public void run() {
686 /**
687 * Determine media state and UMS detection status
688 */
San Mehat4270e1e2010-01-29 05:32:19 -0800689 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800690 final String[] vols = NativeDaemonEvent.filterMessageList(
691 mConnector.executeForList("volume", "list"),
692 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800693 for (String volstr : vols) {
694 String[] tok = volstr.split(" ");
695 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400696 String path = tok[1];
697 String state = Environment.MEDIA_REMOVED;
698
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700699 final StorageVolume volume;
700 synchronized (mVolumesLock) {
701 volume = mVolumesByPath.get(path);
702 }
703
San Mehat4270e1e2010-01-29 05:32:19 -0800704 int st = Integer.parseInt(tok[2]);
705 if (st == VolumeState.NoMedia) {
706 state = Environment.MEDIA_REMOVED;
707 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800708 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800709 } else if (st == VolumeState.Mounted) {
710 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700711 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800712 } else if (st == VolumeState.Shared) {
713 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700714 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800715 } else {
716 throw new Exception(String.format("Unexpected state %d", st));
717 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400718
719 if (state != null) {
720 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700721 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400722 }
San Mehat4270e1e2010-01-29 05:32:19 -0800723 }
724 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700725 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700726 final StorageVolume primary = getPrimaryPhysicalVolume();
727 if (primary != null) {
728 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
729 }
San Mehat4270e1e2010-01-29 05:32:19 -0800730 }
731
San Mehat207e5382010-02-04 20:46:54 -0800732 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600733 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800734 * the hounds!
735 */
Kenny Root51a573c2012-05-17 13:30:28 -0700736 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700737
738 // Let package manager load internal ASECs.
739 mPms.scanAvailableAsecs();
740
741 // Notify people waiting for ASECs to be scanned that it's done.
742 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800743 }
744 }.start();
745 }
746
747 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800748 * Callback from NativeDaemonConnector
749 */
750 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800751 if (DEBUG_EVENTS) {
752 StringBuilder builder = new StringBuilder();
753 builder.append("onEvent::");
754 builder.append(" raw= " + raw);
755 if (cooked != null) {
756 builder.append(" cooked = " );
757 for (String str : cooked) {
758 builder.append(" " + str);
759 }
760 }
San Mehata5078592010-03-25 09:36:54 -0700761 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800762 }
San Mehat4270e1e2010-01-29 05:32:19 -0800763 if (code == VoldResponseCode.VolumeStateChange) {
764 /*
765 * One of the volumes we're managing has changed state.
766 * Format: "NNN Volume <label> <path> state changed
767 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
768 */
769 notifyVolumeStateChange(
770 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
771 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800772 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
773 (code == VoldResponseCode.VolumeDiskRemoved) ||
774 (code == VoldResponseCode.VolumeBadRemoval)) {
775 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
776 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
777 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400778 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800779 final String label = cooked[2];
780 final String path = cooked[3];
781 int major = -1;
782 int minor = -1;
783
784 try {
785 String devComp = cooked[6].substring(1, cooked[6].length() -1);
786 String[] devTok = devComp.split(":");
787 major = Integer.parseInt(devTok[0]);
788 minor = Integer.parseInt(devTok[1]);
789 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700790 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800791 }
792
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700793 final StorageVolume volume;
794 final String state;
795 synchronized (mVolumesLock) {
796 volume = mVolumesByPath.get(path);
797 state = mVolumeStates.get(path);
798 }
799
San Mehat4270e1e2010-01-29 05:32:19 -0800800 if (code == VoldResponseCode.VolumeDiskInserted) {
801 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600802 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800803 public void run() {
804 try {
805 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800806 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700807 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800808 }
809 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700810 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800811 }
812 }
813 }.start();
814 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
815 /*
816 * This event gets trumped if we're already in BAD_REMOVAL state
817 */
818 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
819 return true;
820 }
821 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700822 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700823 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
824 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800825
San Mehata5078592010-03-25 09:36:54 -0700826 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700827 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400828 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800829 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700830 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800831 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700832 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400833 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800834
San Mehata5078592010-03-25 09:36:54 -0700835 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700836 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400837 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800838 } else {
San Mehata5078592010-03-25 09:36:54 -0700839 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800840 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400841
842 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700843 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400844 }
San Mehat4270e1e2010-01-29 05:32:19 -0800845 } else {
846 return false;
847 }
848
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400849 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800850 }
851
San Mehat207e5382010-02-04 20:46:54 -0800852 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700853 final StorageVolume volume;
854 final String state;
855 synchronized (mVolumesLock) {
856 volume = mVolumesByPath.get(path);
857 state = getVolumeState(path);
858 }
859
860 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800861
Mike Lockwooda5250c92011-05-23 13:44:04 -0400862 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800863
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500864 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700865 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700866 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500867 }
868
San Mehat4270e1e2010-01-29 05:32:19 -0800869 if (newState == VolumeState.Init) {
870 } else if (newState == VolumeState.NoMedia) {
871 // NoMedia is handled via Disk Remove events
872 } else if (newState == VolumeState.Idle) {
873 /*
874 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
875 * if we're in the process of enabling UMS
876 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700877 if (!state.equals(
878 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
879 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800880 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700881 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700882 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400883 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800884 }
885 } else if (newState == VolumeState.Pending) {
886 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700887 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700888 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400889 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800890 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700891 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700892 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400893 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800894 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400895 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800896 } else if (newState == VolumeState.Formatting) {
897 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700898 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800899 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700900 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
901 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800902
San Mehata5078592010-03-25 09:36:54 -0700903 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700904 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400905 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700906 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800907 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700908 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800909 return;
910 } else {
San Mehata5078592010-03-25 09:36:54 -0700911 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800912 }
913
Mike Lockwooda5250c92011-05-23 13:44:04 -0400914 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700915 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800916 }
917 }
918
San Mehat207e5382010-02-04 20:46:54 -0800919 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800920 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800921
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700922 final StorageVolume volume;
923 synchronized (mVolumesLock) {
924 volume = mVolumesByPath.get(path);
925 }
926
San Mehata5078592010-03-25 09:36:54 -0700927 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800928 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800929 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800930 } catch (NativeDaemonConnectorException e) {
931 /*
932 * Mount failed for some reason
933 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400934 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800935 int code = e.getCode();
936 if (code == VoldResponseCode.OpFailedNoMedia) {
937 /*
938 * Attempt to mount but no media inserted
939 */
San Mehatb1043402010-02-05 08:26:50 -0800940 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800941 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700942 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800943 /*
944 * Media is blank or does not contain a supported filesystem
945 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700946 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400947 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800948 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800949 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700950 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800951 /*
952 * Volume consistency check failed
953 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700954 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400955 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800956 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800957 } else {
San Mehatb1043402010-02-05 08:26:50 -0800958 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800959 }
960
961 /*
962 * Send broadcast intent (if required for the failure)
963 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400964 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700965 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800966 }
967 }
968
969 return rc;
970 }
971
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800972 /*
973 * If force is not set, we do not unmount if there are
974 * processes holding references to the volume about to be unmounted.
975 * If force is set, all the processes holding references need to be
976 * killed via the ActivityManager before actually unmounting the volume.
977 * This might even take a while and might be retried after timed delays
978 * to make sure we dont end up in an instable state and kill some core
979 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700980 * If removeEncryption is set, force is implied, and the system will remove any encryption
981 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800982 */
Ben Komalo13c71972011-09-07 16:35:56 -0700983 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800984 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800985 return VoldResponseCode.OpFailedVolNotMounted;
986 }
Kenny Rootaa485402010-09-14 14:49:41 -0700987
988 /*
989 * Force a GC to make sure AssetManagers in other threads of the
990 * system_server are cleaned up. We have to do this since AssetManager
991 * instances are kept as a WeakReference and it's possible we have files
992 * open on the external storage.
993 */
994 Runtime.getRuntime().gc();
995
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800996 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700997 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -0800998 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800999 final Command cmd = new Command("volume", "unmount", path);
1000 if (removeEncryption) {
1001 cmd.appendArg("force_and_revert");
1002 } else if (force) {
1003 cmd.appendArg("force");
1004 }
1005 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001006 // We unmounted the volume. None of the asec containers are available now.
1007 synchronized (mAsecMountSet) {
1008 mAsecMountSet.clear();
1009 }
San Mehatb1043402010-02-05 08:26:50 -08001010 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001011 } catch (NativeDaemonConnectorException e) {
1012 // Don't worry about mismatch in PackageManager since the
1013 // call back will handle the status changes any way.
1014 int code = e.getCode();
1015 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001016 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001017 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1018 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001019 } else {
San Mehatb1043402010-02-05 08:26:50 -08001020 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001021 }
1022 }
1023 }
1024
1025 private int doFormatVolume(String path) {
1026 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001027 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001028 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001029 } catch (NativeDaemonConnectorException e) {
1030 int code = e.getCode();
1031 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001032 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001033 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001034 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001035 } else {
San Mehatb1043402010-02-05 08:26:50 -08001036 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001037 }
1038 }
1039 }
1040
San Mehatb1043402010-02-05 08:26:50 -08001041 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001042 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001043 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001044 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001045 } catch (NativeDaemonConnectorException ex) {
1046 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1047 return false;
1048 }
San Mehatb1043402010-02-05 08:26:50 -08001049
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001050 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1051 return event.getMessage().endsWith("enabled");
1052 } else {
1053 return false;
San Mehatb1043402010-02-05 08:26:50 -08001054 }
San Mehatb1043402010-02-05 08:26:50 -08001055 }
1056
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001057 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001058 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001059 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001060 for (int i = mListeners.size() -1; i >= 0; i--) {
1061 MountServiceBinderListener bl = mListeners.get(i);
1062 try {
San Mehatb1043402010-02-05 08:26:50 -08001063 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001064 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001065 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001066 mListeners.remove(i);
1067 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001068 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001069 }
1070 }
1071 }
1072
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001073 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001074 sendUmsIntent(avail);
1075 } else {
1076 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001077 }
San Mehat2fe718a2010-03-11 12:01:49 -08001078
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001079 final StorageVolume primary = getPrimaryPhysicalVolume();
1080 if (avail == false && primary != null
1081 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1082 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001083 /*
1084 * USB mass storage disconnected while enabled
1085 */
1086 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001087 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001088 public void run() {
1089 try {
1090 int rc;
San Mehata5078592010-03-25 09:36:54 -07001091 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001092 doShareUnshareVolume(path, "ums", false);
1093 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001094 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001095 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1096 path, rc));
1097 }
1098 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001099 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001100 }
1101 }
1102 }.start();
1103 }
San Mehat4270e1e2010-01-29 05:32:19 -08001104 }
1105
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001106 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1107 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1108 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1109 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1110 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001111 }
1112
San Mehat6a965af22010-02-24 17:47:30 -08001113 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001114 mContext.sendBroadcastAsUser(
1115 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1116 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001117 }
1118
San Mehat207e5382010-02-04 20:46:54 -08001119 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001120 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1121 throw new SecurityException(String.format("Requires %s permission", perm));
1122 }
1123 }
1124
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001125 // Storage list XML tags
1126 private static final String TAG_STORAGE_LIST = "StorageList";
1127 private static final String TAG_STORAGE = "storage";
1128
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001129 private void readStorageListLocked() {
1130 mVolumes.clear();
1131 mVolumeStates.clear();
1132
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001133 Resources resources = mContext.getResources();
1134
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001135 int id = com.android.internal.R.xml.storage_list;
1136 XmlResourceParser parser = resources.getXml(id);
1137 AttributeSet attrs = Xml.asAttributeSet(parser);
1138
1139 try {
1140 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1141 while (true) {
1142 XmlUtils.nextElement(parser);
1143
1144 String element = parser.getName();
1145 if (element == null) break;
1146
1147 if (TAG_STORAGE.equals(element)) {
1148 TypedArray a = resources.obtainAttributes(attrs,
1149 com.android.internal.R.styleable.Storage);
1150
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001151 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001152 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001153 int descriptionId = a.getResourceId(
1154 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001155 CharSequence description = a.getText(
1156 com.android.internal.R.styleable.Storage_storageDescription);
1157 boolean primary = a.getBoolean(
1158 com.android.internal.R.styleable.Storage_primary, false);
1159 boolean removable = a.getBoolean(
1160 com.android.internal.R.styleable.Storage_removable, false);
1161 boolean emulated = a.getBoolean(
1162 com.android.internal.R.styleable.Storage_emulated, false);
1163 int mtpReserve = a.getInt(
1164 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001165 boolean allowMassStorage = a.getBoolean(
1166 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001167 // resource parser does not support longs, so XML value is in megabytes
1168 long maxFileSize = a.getInt(
1169 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001170
1171 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1172 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001173 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001174 " allowMassStorage: " + allowMassStorage +
1175 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001176
1177 if (emulated) {
1178 // For devices with emulated storage, we create separate
1179 // volumes for each known user.
1180 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1181 true, mtpReserve, false, maxFileSize, null);
1182
1183 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001184 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001185 createEmulatedVolumeForUserLocked(user.getUserHandle());
1186 }
1187
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001188 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001189 if (path == null || description == null) {
1190 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001191 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001192 final StorageVolume volume = new StorageVolume(new File(path),
1193 descriptionId, primary, removable, emulated, mtpReserve,
1194 allowMassStorage, maxFileSize, null);
1195 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001196 }
1197 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001198
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001199 a.recycle();
1200 }
1201 }
1202 } catch (XmlPullParserException e) {
1203 throw new RuntimeException(e);
1204 } catch (IOException e) {
1205 throw new RuntimeException(e);
1206 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001207 // Compute storage ID for each physical volume; emulated storage is
1208 // always 0 when defined.
1209 int index = isExternalStorageEmulated() ? 1 : 0;
1210 for (StorageVolume volume : mVolumes) {
1211 if (!volume.isEmulated()) {
1212 volume.setStorageId(index++);
1213 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001214 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001215 parser.close();
1216 }
1217 }
1218
San Mehat4270e1e2010-01-29 05:32:19 -08001219 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001220 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1221 * using {@link #mEmulatedTemplate} as template.
1222 */
1223 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1224 if (mEmulatedTemplate == null) {
1225 throw new IllegalStateException("Missing emulated volume multi-user template");
1226 }
1227
1228 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1229 final File path = userEnv.getExternalStorageDirectory();
1230 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1231 volume.setStorageId(0);
1232 addVolumeLocked(volume);
1233
1234 if (mSystemReady) {
1235 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1236 } else {
1237 // Place stub status for early callers to find
1238 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1239 }
1240 }
1241
1242 private void addVolumeLocked(StorageVolume volume) {
1243 Slog.d(TAG, "addVolumeLocked() " + volume);
1244 mVolumes.add(volume);
1245 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1246 if (existing != null) {
1247 throw new IllegalStateException(
1248 "Volume at " + volume.getPath() + " already exists: " + existing);
1249 }
1250 }
1251
1252 private void removeVolumeLocked(StorageVolume volume) {
1253 Slog.d(TAG, "removeVolumeLocked() " + volume);
1254 mVolumes.remove(volume);
1255 mVolumesByPath.remove(volume.getPath());
1256 mVolumeStates.remove(volume.getPath());
1257 }
1258
1259 private StorageVolume getPrimaryPhysicalVolume() {
1260 synchronized (mVolumesLock) {
1261 for (StorageVolume volume : mVolumes) {
1262 if (volume.isPrimary() && !volume.isEmulated()) {
1263 return volume;
1264 }
1265 }
1266 }
1267 return null;
1268 }
1269
1270 /**
San Mehat207e5382010-02-04 20:46:54 -08001271 * Constructs a new MountService instance
1272 *
1273 * @param context Binder context for this service
1274 */
1275 public MountService(Context context) {
1276 mContext = context;
1277
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001278 synchronized (mVolumesLock) {
1279 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001280 }
1281
San Mehat207e5382010-02-04 20:46:54 -08001282 // XXX: This will go away soon in favor of IMountServiceObserver
1283 mPms = (PackageManagerService) ServiceManager.getService("package");
1284
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001285 mHandlerThread = new HandlerThread("MountService");
1286 mHandlerThread.start();
1287 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1288
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001289 // Watch for user changes
1290 final IntentFilter userFilter = new IntentFilter();
1291 userFilter.addAction(Intent.ACTION_USER_ADDED);
1292 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1293 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1294
1295 // Watch for USB changes on primary volume
1296 final StorageVolume primary = getPrimaryPhysicalVolume();
1297 if (primary != null && primary.allowMassStorage()) {
1298 mContext.registerReceiver(
1299 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1300 }
1301
Kenny Roota02b8b02010-08-05 16:14:17 -07001302 // Add OBB Action Handler to MountService thread.
1303 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1304
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001305 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001306 * Create the connection to vold with a maximum queue of twice the
1307 * amount of containers we'd ever expect to have. This keeps an
1308 * "asec list" from blocking a thread repeatedly.
1309 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001310 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001311
Kenny Root305bcbf2010-09-03 07:56:38 -07001312 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001313 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001314
Kenny Root07714d42011-08-17 17:49:28 -07001315 // Add ourself to the Watchdog monitors if enabled.
1316 if (WATCHDOG_ENABLE) {
1317 Watchdog.getInstance().addMonitor(this);
1318 }
San Mehat207e5382010-02-04 20:46:54 -08001319 }
1320
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001321 public void systemReady() {
1322 mSystemReady = true;
1323 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1324 }
1325
San Mehat207e5382010-02-04 20:46:54 -08001326 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001327 * Exposed API calls below here
1328 */
1329
1330 public void registerListener(IMountServiceListener listener) {
1331 synchronized (mListeners) {
1332 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1333 try {
1334 listener.asBinder().linkToDeath(bl, 0);
1335 mListeners.add(bl);
1336 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001337 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001338 }
1339 }
1340 }
1341
1342 public void unregisterListener(IMountServiceListener listener) {
1343 synchronized (mListeners) {
1344 for(MountServiceBinderListener bl : mListeners) {
1345 if (bl.mListener == listener) {
1346 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001347 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001348 return;
1349 }
1350 }
1351 }
1352 }
1353
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001354 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001355 validatePermission(android.Manifest.permission.SHUTDOWN);
1356
San Mehata5078592010-03-25 09:36:54 -07001357 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001358 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001359 for (String path : mVolumeStates.keySet()) {
1360 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001361
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001362 if (state.equals(Environment.MEDIA_SHARED)) {
1363 /*
1364 * If the media is currently shared, unshare it.
1365 * XXX: This is still dangerous!. We should not
1366 * be rebooting at *all* if UMS is enabled, since
1367 * the UMS host could have dirty FAT cache entries
1368 * yet to flush.
1369 */
1370 setUsbMassStorageEnabled(false);
1371 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1372 /*
1373 * If the media is being checked, then we need to wait for
1374 * it to complete before being able to proceed.
1375 */
1376 // XXX: @hackbod - Should we disable the ANR timer here?
1377 int retries = 30;
1378 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1379 try {
1380 Thread.sleep(1000);
1381 } catch (InterruptedException iex) {
1382 Slog.e(TAG, "Interrupted while waiting for media", iex);
1383 break;
1384 }
1385 state = Environment.getExternalStorageState();
1386 }
1387 if (retries == 0) {
1388 Slog.e(TAG, "Timed out waiting for media to check");
1389 }
San Mehat91c77612010-01-07 10:39:41 -08001390 }
San Mehat91c77612010-01-07 10:39:41 -08001391
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001392 if (state.equals(Environment.MEDIA_MOUNTED)) {
1393 // Post a unmount message.
1394 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1395 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1396 } else if (observer != null) {
1397 /*
1398 * Observer is waiting for onShutDownComplete when we are done.
1399 * Since nothing will be done send notification directly so shutdown
1400 * sequence can continue.
1401 */
1402 try {
1403 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1404 } catch (RemoteException e) {
1405 Slog.w(TAG, "RemoteException when shutting down");
1406 }
1407 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001408 }
San Mehat4270e1e2010-01-29 05:32:19 -08001409 }
1410 }
1411
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001412 private boolean getUmsEnabling() {
1413 synchronized (mListeners) {
1414 return mUmsEnabling;
1415 }
1416 }
1417
1418 private void setUmsEnabling(boolean enable) {
1419 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001420 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001421 }
1422 }
1423
San Mehatb1043402010-02-05 08:26:50 -08001424 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001425 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001426
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001427 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001428 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001429 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001430 synchronized (mListeners) {
1431 return mUmsAvailable;
1432 }
San Mehatb1043402010-02-05 08:26:50 -08001433 }
1434
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001435 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001436 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001437 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001438
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001439 final StorageVolume primary = getPrimaryPhysicalVolume();
1440 if (primary == null) return;
1441
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001442 // TODO: Add support for multiple share methods
1443
1444 /*
1445 * If the volume is mounted and we're enabling then unmount it
1446 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001447 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001448 String vs = getVolumeState(path);
1449 String method = "ums";
1450 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1451 // Override for isUsbMassStorageEnabled()
1452 setUmsEnabling(enable);
1453 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1454 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1455 // Clear override
1456 setUmsEnabling(false);
1457 }
1458 /*
1459 * If we disabled UMS then mount the volume
1460 */
1461 if (!enable) {
1462 doShareUnshareVolume(path, method, enable);
1463 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001464 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001465 " after disabling share method " + method);
1466 /*
1467 * Even though the mount failed, the unshare didn't so don't indicate an error.
1468 * The mountVolume() call will have set the storage state and sent the necessary
1469 * broadcasts.
1470 */
1471 }
1472 }
San Mehatb1043402010-02-05 08:26:50 -08001473 }
1474
1475 public boolean isUsbMassStorageEnabled() {
1476 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001477
1478 final StorageVolume primary = getPrimaryPhysicalVolume();
1479 if (primary != null) {
1480 return doGetVolumeShared(primary.getPath(), "ums");
1481 } else {
1482 return false;
1483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001485
San Mehat7fd0fee2009-12-17 07:12:23 -08001486 /**
1487 * @return state of the volume at the specified mount point
1488 */
San Mehat4270e1e2010-01-29 05:32:19 -08001489 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001490 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001491 String state = mVolumeStates.get(mountPoint);
1492 if (state == null) {
1493 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001494 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1495 state = Environment.MEDIA_REMOVED;
1496 } else {
1497 throw new IllegalArgumentException();
1498 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001499 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001500
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001501 return state;
1502 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001503 }
1504
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001505 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001506 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001507 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001508 }
1509
San Mehat4270e1e2010-01-29 05:32:19 -08001510 public int mountVolume(String path) {
1511 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001512
San Mehat207e5382010-02-04 20:46:54 -08001513 waitForReady();
1514 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
Ben Komalo13c71972011-09-07 16:35:56 -07001517 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001518 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001519 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001521 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001522 if (DEBUG_UNMOUNT) {
1523 Slog.i(TAG, "Unmounting " + path
1524 + " force = " + force
1525 + " removeEncryption = " + removeEncryption);
1526 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001527 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1528 Environment.MEDIA_REMOVED.equals(volState) ||
1529 Environment.MEDIA_SHARED.equals(volState) ||
1530 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1531 // Media already unmounted or cannot be unmounted.
1532 // TODO return valid return code when adding observer call back.
1533 return;
1534 }
Ben Komalo13c71972011-09-07 16:35:56 -07001535 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001536 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538
San Mehat4270e1e2010-01-29 05:32:19 -08001539 public int formatVolume(String path) {
1540 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001541 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001542
San Mehat207e5382010-02-04 20:46:54 -08001543 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001546 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001547 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1548 waitForReady();
1549 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001550 final String[] r = NativeDaemonEvent.filterMessageList(
1551 mConnector.executeForList("storage", "users", path),
1552 VoldResponseCode.StorageUsersListResult);
1553
San Mehatc1b4ce92010-02-16 17:13:03 -08001554 // FMT: <pid> <process name>
1555 int[] data = new int[r.length];
1556 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001557 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001558 try {
1559 data[i] = Integer.parseInt(tok[0]);
1560 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001561 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001562 return new int[0];
1563 }
1564 }
1565 return data;
1566 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001567 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001568 return new int[0];
1569 }
1570 }
1571
San Mehatb1043402010-02-05 08:26:50 -08001572 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001573 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001574 if (primary != null) {
1575 boolean mounted = false;
1576 try {
1577 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
1578 } catch (IllegalStateException e) {
1579 }
1580
1581 if (!mounted) {
1582 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1583 }
San Mehatb1043402010-02-05 08:26:50 -08001584 }
1585 }
1586
San Mehat4270e1e2010-01-29 05:32:19 -08001587 public String[] getSecureContainerList() {
1588 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001589 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001590 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001591
San Mehat4270e1e2010-01-29 05:32:19 -08001592 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001593 return NativeDaemonEvent.filterMessageList(
1594 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001595 } catch (NativeDaemonConnectorException e) {
1596 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 }
San Mehat36972292010-01-06 11:06:32 -08001599
Kenny Root6dceb882012-04-12 14:23:49 -07001600 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1601 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001602 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001603 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001604 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001605
San Mehatb1043402010-02-05 08:26:50 -08001606 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001607 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001608 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1609 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001610 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001611 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001612 }
San Mehata181b212010-02-11 06:50:20 -08001613
1614 if (rc == StorageResultCode.OperationSucceeded) {
1615 synchronized (mAsecMountSet) {
1616 mAsecMountSet.add(id);
1617 }
1618 }
San Mehat4270e1e2010-01-29 05:32:19 -08001619 return rc;
San Mehat36972292010-01-06 11:06:32 -08001620 }
1621
San Mehat4270e1e2010-01-29 05:32:19 -08001622 public int finalizeSecureContainer(String id) {
1623 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001624 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001625
San Mehatb1043402010-02-05 08:26:50 -08001626 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001627 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001628 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001629 /*
1630 * Finalization does a remount, so no need
1631 * to update mAsecMountSet
1632 */
San Mehat4270e1e2010-01-29 05:32:19 -08001633 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001634 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001635 }
San Mehat4270e1e2010-01-29 05:32:19 -08001636 return rc;
San Mehat36972292010-01-06 11:06:32 -08001637 }
1638
Kenny Root6dceb882012-04-12 14:23:49 -07001639 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1640 validatePermission(android.Manifest.permission.ASEC_CREATE);
1641 warnOnNotMounted();
1642
1643 int rc = StorageResultCode.OperationSucceeded;
1644 try {
1645 mConnector.execute("asec", "fixperms", id, gid, filename);
1646 /*
1647 * Fix permissions does a remount, so no need to update
1648 * mAsecMountSet
1649 */
1650 } catch (NativeDaemonConnectorException e) {
1651 rc = StorageResultCode.OperationFailedInternalError;
1652 }
1653 return rc;
1654 }
1655
San Mehatd9709982010-02-18 11:43:03 -08001656 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001657 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001658 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001659 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001660
Kenny Rootaa485402010-09-14 14:49:41 -07001661 /*
1662 * Force a GC to make sure AssetManagers in other threads of the
1663 * system_server are cleaned up. We have to do this since AssetManager
1664 * instances are kept as a WeakReference and it's possible we have files
1665 * open on the external storage.
1666 */
1667 Runtime.getRuntime().gc();
1668
San Mehatb1043402010-02-05 08:26:50 -08001669 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001670 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001671 final Command cmd = new Command("asec", "destroy", id);
1672 if (force) {
1673 cmd.appendArg("force");
1674 }
1675 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001676 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001677 int code = e.getCode();
1678 if (code == VoldResponseCode.OpFailedStorageBusy) {
1679 rc = StorageResultCode.OperationFailedStorageBusy;
1680 } else {
1681 rc = StorageResultCode.OperationFailedInternalError;
1682 }
San Mehat02735bc2010-01-26 15:18:08 -08001683 }
San Mehata181b212010-02-11 06:50:20 -08001684
1685 if (rc == StorageResultCode.OperationSucceeded) {
1686 synchronized (mAsecMountSet) {
1687 if (mAsecMountSet.contains(id)) {
1688 mAsecMountSet.remove(id);
1689 }
1690 }
1691 }
1692
San Mehat4270e1e2010-01-29 05:32:19 -08001693 return rc;
San Mehat36972292010-01-06 11:06:32 -08001694 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001695
San Mehat4270e1e2010-01-29 05:32:19 -08001696 public int mountSecureContainer(String id, String key, int ownerUid) {
1697 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001698 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001699 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001700
San Mehata181b212010-02-11 06:50:20 -08001701 synchronized (mAsecMountSet) {
1702 if (mAsecMountSet.contains(id)) {
1703 return StorageResultCode.OperationFailedStorageMounted;
1704 }
1705 }
1706
San Mehatb1043402010-02-05 08:26:50 -08001707 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001708 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001709 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001710 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001711 int code = e.getCode();
1712 if (code != VoldResponseCode.OpFailedStorageBusy) {
1713 rc = StorageResultCode.OperationFailedInternalError;
1714 }
San Mehat02735bc2010-01-26 15:18:08 -08001715 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001716
1717 if (rc == StorageResultCode.OperationSucceeded) {
1718 synchronized (mAsecMountSet) {
1719 mAsecMountSet.add(id);
1720 }
1721 }
San Mehat4270e1e2010-01-29 05:32:19 -08001722 return rc;
San Mehat36972292010-01-06 11:06:32 -08001723 }
1724
San Mehatd9709982010-02-18 11:43:03 -08001725 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001726 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001727 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001728 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001729
San Mehat6cdd9c02010-02-09 14:45:20 -08001730 synchronized (mAsecMountSet) {
1731 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001732 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001733 }
1734 }
1735
Kenny Rootaa485402010-09-14 14:49:41 -07001736 /*
1737 * Force a GC to make sure AssetManagers in other threads of the
1738 * system_server are cleaned up. We have to do this since AssetManager
1739 * instances are kept as a WeakReference and it's possible we have files
1740 * open on the external storage.
1741 */
1742 Runtime.getRuntime().gc();
1743
San Mehatb1043402010-02-05 08:26:50 -08001744 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001745 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001746 final Command cmd = new Command("asec", "unmount", id);
1747 if (force) {
1748 cmd.appendArg("force");
1749 }
1750 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001751 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001752 int code = e.getCode();
1753 if (code == VoldResponseCode.OpFailedStorageBusy) {
1754 rc = StorageResultCode.OperationFailedStorageBusy;
1755 } else {
1756 rc = StorageResultCode.OperationFailedInternalError;
1757 }
San Mehat02735bc2010-01-26 15:18:08 -08001758 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001759
1760 if (rc == StorageResultCode.OperationSucceeded) {
1761 synchronized (mAsecMountSet) {
1762 mAsecMountSet.remove(id);
1763 }
1764 }
San Mehat4270e1e2010-01-29 05:32:19 -08001765 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001766 }
1767
San Mehat6cdd9c02010-02-09 14:45:20 -08001768 public boolean isSecureContainerMounted(String id) {
1769 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1770 waitForReady();
1771 warnOnNotMounted();
1772
1773 synchronized (mAsecMountSet) {
1774 return mAsecMountSet.contains(id);
1775 }
1776 }
1777
San Mehat4270e1e2010-01-29 05:32:19 -08001778 public int renameSecureContainer(String oldId, String newId) {
1779 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001780 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001781 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001782
San Mehata181b212010-02-11 06:50:20 -08001783 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001784 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001785 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001786 * changed while active, we must ensure both ids are not currently mounted.
1787 */
1788 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001789 return StorageResultCode.OperationFailedStorageMounted;
1790 }
1791 }
1792
San Mehatb1043402010-02-05 08:26:50 -08001793 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001794 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001795 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001796 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001797 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001798 }
San Mehata181b212010-02-11 06:50:20 -08001799
San Mehat4270e1e2010-01-29 05:32:19 -08001800 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001801 }
1802
San Mehat4270e1e2010-01-29 05:32:19 -08001803 public String getSecureContainerPath(String id) {
1804 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001805 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001806 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001807
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001808 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001809 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001810 event = mConnector.execute("asec", "path", id);
1811 event.checkCode(VoldResponseCode.AsecPathResult);
1812 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001813 } catch (NativeDaemonConnectorException e) {
1814 int code = e.getCode();
1815 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001816 Slog.i(TAG, String.format("Container '%s' not found", id));
1817 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001818 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001819 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001820 }
1821 }
San Mehat22dd86e2010-01-12 12:21:18 -08001822 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001823
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001824 public String getSecureContainerFilesystemPath(String id) {
1825 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1826 waitForReady();
1827 warnOnNotMounted();
1828
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001829 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001830 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001831 event = mConnector.execute("asec", "fspath", id);
1832 event.checkCode(VoldResponseCode.AsecPathResult);
1833 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001834 } catch (NativeDaemonConnectorException e) {
1835 int code = e.getCode();
1836 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1837 Slog.i(TAG, String.format("Container '%s' not found", id));
1838 return null;
1839 } else {
1840 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1841 }
1842 }
1843 }
1844
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001845 public void finishMediaUpdate() {
1846 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1847 }
Kenny Root02c87302010-07-01 08:10:18 -07001848
Kenny Roota02b8b02010-08-05 16:14:17 -07001849 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1850 if (callerUid == android.os.Process.SYSTEM_UID) {
1851 return true;
1852 }
1853
Kenny Root02c87302010-07-01 08:10:18 -07001854 if (packageName == null) {
1855 return false;
1856 }
1857
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001858 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001859
1860 if (DEBUG_OBB) {
1861 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1862 packageUid + ", callerUid = " + callerUid);
1863 }
1864
1865 return callerUid == packageUid;
1866 }
1867
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001868 public String getMountedObbPath(String rawPath) {
1869 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001870
Kenny Root02c87302010-07-01 08:10:18 -07001871 waitForReady();
1872 warnOnNotMounted();
1873
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001874 final ObbState state;
1875 synchronized (mObbPathToStateMap) {
1876 state = mObbPathToStateMap.get(rawPath);
1877 }
1878 if (state == null) {
1879 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1880 return null;
1881 }
1882
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001883 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001884 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001885 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001886 event.checkCode(VoldResponseCode.AsecPathResult);
1887 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001888 } catch (NativeDaemonConnectorException e) {
1889 int code = e.getCode();
1890 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001891 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001892 } else {
1893 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1894 }
1895 }
1896 }
1897
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001898 @Override
1899 public boolean isObbMounted(String rawPath) {
1900 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001901 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001902 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001903 }
Kenny Root02c87302010-07-01 08:10:18 -07001904 }
1905
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001906 @Override
1907 public void mountObb(
1908 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1909 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1910 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1911 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001912
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001913 final int callingUid = Binder.getCallingUid();
1914 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1915 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001916 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1917
1918 if (DEBUG_OBB)
1919 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001920 }
1921
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001922 @Override
1923 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1924 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1925
1926 final ObbState existingState;
1927 synchronized (mObbPathToStateMap) {
1928 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001929 }
1930
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001931 if (existingState != null) {
1932 // TODO: separate state object from request data
1933 final int callingUid = Binder.getCallingUid();
1934 final ObbState newState = new ObbState(
1935 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1936 final ObbAction action = new UnmountObbAction(newState, force);
1937 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001938
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001939 if (DEBUG_OBB)
1940 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1941 } else {
1942 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1943 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001944 }
1945
Ben Komalo444eca22011-09-01 15:17:44 -07001946 @Override
1947 public int getEncryptionState() {
1948 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1949 "no permission to access the crypt keeper");
1950
1951 waitForReady();
1952
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001953 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001954 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001955 event = mConnector.execute("cryptfs", "cryptocomplete");
1956 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001957 } catch (NumberFormatException e) {
1958 // Bad result - unexpected.
1959 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1960 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1961 } catch (NativeDaemonConnectorException e) {
1962 // Something bad happened.
1963 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1964 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1965 }
1966 }
1967
1968 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001969 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001970 if (TextUtils.isEmpty(password)) {
1971 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001972 }
1973
Jason parks8888c592011-01-20 22:46:41 -06001974 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1975 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001976
1977 waitForReady();
1978
1979 if (DEBUG_EVENTS) {
1980 Slog.i(TAG, "decrypting storage...");
1981 }
1982
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001983 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001984 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001985 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001986
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001987 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001988 if (code == 0) {
1989 // Decrypt was successful. Post a delayed message before restarting in order
1990 // to let the UI to clear itself
1991 mHandler.postDelayed(new Runnable() {
1992 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001993 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001994 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001995 } catch (NativeDaemonConnectorException e) {
1996 Slog.e(TAG, "problem executing in background", e);
1997 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001998 }
Jason parksf7b3cd42011-01-27 09:28:25 -06001999 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002000 }
2001
2002 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002003 } catch (NativeDaemonConnectorException e) {
2004 // Decryption failed
2005 return e.getCode();
2006 }
Jason parks5af0b912010-11-29 09:05:25 -06002007 }
2008
Jason parks56aa5322011-01-07 09:01:15 -06002009 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002010 if (TextUtils.isEmpty(password)) {
2011 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002012 }
2013
Jason parks8888c592011-01-20 22:46:41 -06002014 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2015 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002016
2017 waitForReady();
2018
2019 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002020 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002021 }
2022
2023 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002024 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002025 } catch (NativeDaemonConnectorException e) {
2026 // Encryption failed
2027 return e.getCode();
2028 }
2029
2030 return 0;
2031 }
2032
Jason parksf7b3cd42011-01-27 09:28:25 -06002033 public int changeEncryptionPassword(String password) {
2034 if (TextUtils.isEmpty(password)) {
2035 throw new IllegalArgumentException("password cannot be empty");
2036 }
2037
2038 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2039 "no permission to access the crypt keeper");
2040
2041 waitForReady();
2042
2043 if (DEBUG_EVENTS) {
2044 Slog.i(TAG, "changing encryption password...");
2045 }
2046
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002047 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002048 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002049 event = mConnector.execute("cryptfs", "changepw", password);
2050 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002051 } catch (NativeDaemonConnectorException e) {
2052 // Encryption failed
2053 return e.getCode();
2054 }
2055 }
2056
Christopher Tate32418be2011-10-10 13:51:12 -07002057 /**
2058 * Validate a user-supplied password string with cryptfs
2059 */
2060 @Override
2061 public int verifyEncryptionPassword(String password) throws RemoteException {
2062 // Only the system process is permitted to validate passwords
2063 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2064 throw new SecurityException("no permission to access the crypt keeper");
2065 }
2066
2067 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2068 "no permission to access the crypt keeper");
2069
2070 if (TextUtils.isEmpty(password)) {
2071 throw new IllegalArgumentException("password cannot be empty");
2072 }
2073
2074 waitForReady();
2075
2076 if (DEBUG_EVENTS) {
2077 Slog.i(TAG, "validating encryption password...");
2078 }
2079
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002080 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002081 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002082 event = mConnector.execute("cryptfs", "verifypw", password);
2083 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2084 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002085 } catch (NativeDaemonConnectorException e) {
2086 // Encryption failed
2087 return e.getCode();
2088 }
2089 }
2090
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002091 @Override
2092 public StorageVolume[] getVolumeList() {
2093 final int callingUserId = UserHandle.getCallingUserId();
2094 final boolean accessAll = (mContext.checkPermission(
2095 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2096 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2097
2098 synchronized (mVolumesLock) {
2099 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2100 for (StorageVolume volume : mVolumes) {
2101 final UserHandle owner = volume.getOwner();
2102 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2103 if (accessAll || ownerMatch) {
2104 filtered.add(volume);
2105 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002106 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002107 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002108 }
2109 }
2110
Kenny Rootaf9d6672010-10-08 09:21:39 -07002111 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2112 final IBinder binder = obbState.getBinder();
2113 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002114
Kenny Rootaf9d6672010-10-08 09:21:39 -07002115 if (obbStates == null) {
2116 obbStates = new ArrayList<ObbState>();
2117 mObbMounts.put(binder, obbStates);
2118 } else {
2119 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002120 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002121 throw new IllegalStateException("Attempt to add ObbState twice. "
2122 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002123 }
2124 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002125 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002126
2127 obbStates.add(obbState);
2128 try {
2129 obbState.link();
2130 } catch (RemoteException e) {
2131 /*
2132 * The binder died before we could link it, so clean up our state
2133 * and return failure.
2134 */
2135 obbStates.remove(obbState);
2136 if (obbStates.isEmpty()) {
2137 mObbMounts.remove(binder);
2138 }
2139
2140 // Rethrow the error so mountObb can get it
2141 throw e;
2142 }
2143
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002144 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002145 }
2146
Kenny Rootaf9d6672010-10-08 09:21:39 -07002147 private void removeObbStateLocked(ObbState obbState) {
2148 final IBinder binder = obbState.getBinder();
2149 final List<ObbState> obbStates = mObbMounts.get(binder);
2150 if (obbStates != null) {
2151 if (obbStates.remove(obbState)) {
2152 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002153 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154 if (obbStates.isEmpty()) {
2155 mObbMounts.remove(binder);
2156 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002157 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002158
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002159 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002160 }
2161
Kenny Roota02b8b02010-08-05 16:14:17 -07002162 private class ObbActionHandler extends Handler {
2163 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002164 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002165
2166 ObbActionHandler(Looper l) {
2167 super(l);
2168 }
2169
2170 @Override
2171 public void handleMessage(Message msg) {
2172 switch (msg.what) {
2173 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002174 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002175
2176 if (DEBUG_OBB)
2177 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2178
2179 // If a bind was already initiated we don't really
2180 // need to do anything. The pending install
2181 // will be processed later on.
2182 if (!mBound) {
2183 // If this is the only one pending we might
2184 // have to bind to the service again.
2185 if (!connectToService()) {
2186 Slog.e(TAG, "Failed to bind to media container service");
2187 action.handleError();
2188 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002189 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002190 }
Kenny Root735de3b2010-09-30 14:11:39 -07002191
Kenny Root735de3b2010-09-30 14:11:39 -07002192 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002193 break;
2194 }
2195 case OBB_MCS_BOUND: {
2196 if (DEBUG_OBB)
2197 Slog.i(TAG, "OBB_MCS_BOUND");
2198 if (msg.obj != null) {
2199 mContainerService = (IMediaContainerService) msg.obj;
2200 }
2201 if (mContainerService == null) {
2202 // Something seriously wrong. Bail out
2203 Slog.e(TAG, "Cannot bind to media container service");
2204 for (ObbAction action : mActions) {
2205 // Indicate service bind error
2206 action.handleError();
2207 }
2208 mActions.clear();
2209 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002210 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002211 if (action != null) {
2212 action.execute(this);
2213 }
2214 } else {
2215 // Should never happen ideally.
2216 Slog.w(TAG, "Empty queue");
2217 }
2218 break;
2219 }
2220 case OBB_MCS_RECONNECT: {
2221 if (DEBUG_OBB)
2222 Slog.i(TAG, "OBB_MCS_RECONNECT");
2223 if (mActions.size() > 0) {
2224 if (mBound) {
2225 disconnectService();
2226 }
2227 if (!connectToService()) {
2228 Slog.e(TAG, "Failed to bind to media container service");
2229 for (ObbAction action : mActions) {
2230 // Indicate service bind error
2231 action.handleError();
2232 }
2233 mActions.clear();
2234 }
2235 }
2236 break;
2237 }
2238 case OBB_MCS_UNBIND: {
2239 if (DEBUG_OBB)
2240 Slog.i(TAG, "OBB_MCS_UNBIND");
2241
2242 // Delete pending install
2243 if (mActions.size() > 0) {
2244 mActions.remove(0);
2245 }
2246 if (mActions.size() == 0) {
2247 if (mBound) {
2248 disconnectService();
2249 }
2250 } else {
2251 // There are more pending requests in queue.
2252 // Just post MCS_BOUND message to trigger processing
2253 // of next pending install.
2254 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2255 }
2256 break;
2257 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002258 case OBB_FLUSH_MOUNT_STATE: {
2259 final String path = (String) msg.obj;
2260
2261 if (DEBUG_OBB)
2262 Slog.i(TAG, "Flushing all OBB state for path " + path);
2263
2264 synchronized (mObbMounts) {
2265 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2266
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002267 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002268 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002269 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002270
2271 /*
2272 * If this entry's source file is in the volume path
2273 * that got unmounted, remove it because it's no
2274 * longer valid.
2275 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002276 if (state.canonicalPath.startsWith(path)) {
2277 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002278 }
2279 }
2280
2281 for (final ObbState obbState : obbStatesToRemove) {
2282 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002283 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002284
2285 removeObbStateLocked(obbState);
2286
2287 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002288 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002289 OnObbStateChangeListener.UNMOUNTED);
2290 } catch (RemoteException e) {
2291 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002292 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002293 }
2294 }
2295 }
2296 break;
2297 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002298 }
2299 }
2300
2301 private boolean connectToService() {
2302 if (DEBUG_OBB)
2303 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2304
2305 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2306 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2307 mBound = true;
2308 return true;
2309 }
2310 return false;
2311 }
2312
2313 private void disconnectService() {
2314 mContainerService = null;
2315 mBound = false;
2316 mContext.unbindService(mDefContainerConn);
2317 }
2318 }
2319
2320 abstract class ObbAction {
2321 private static final int MAX_RETRIES = 3;
2322 private int mRetries;
2323
2324 ObbState mObbState;
2325
2326 ObbAction(ObbState obbState) {
2327 mObbState = obbState;
2328 }
2329
2330 public void execute(ObbActionHandler handler) {
2331 try {
2332 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002333 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002334 mRetries++;
2335 if (mRetries > MAX_RETRIES) {
2336 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002337 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002338 handleError();
2339 return;
2340 } else {
2341 handleExecute();
2342 if (DEBUG_OBB)
2343 Slog.i(TAG, "Posting install MCS_UNBIND");
2344 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2345 }
2346 } catch (RemoteException e) {
2347 if (DEBUG_OBB)
2348 Slog.i(TAG, "Posting install MCS_RECONNECT");
2349 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2350 } catch (Exception e) {
2351 if (DEBUG_OBB)
2352 Slog.d(TAG, "Error handling OBB action", e);
2353 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002354 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002355 }
2356 }
2357
Kenny Root05105f72010-09-22 17:29:43 -07002358 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002359 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002360
2361 protected ObbInfo getObbInfo() throws IOException {
2362 ObbInfo obbInfo;
2363 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002364 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002365 } catch (RemoteException e) {
2366 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002367 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002368 obbInfo = null;
2369 }
2370 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002371 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002372 }
2373 return obbInfo;
2374 }
2375
Kenny Rootaf9d6672010-10-08 09:21:39 -07002376 protected void sendNewStatusOrIgnore(int status) {
2377 if (mObbState == null || mObbState.token == null) {
2378 return;
2379 }
2380
Kenny Root38cf8862010-09-26 14:18:51 -07002381 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002382 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002383 } catch (RemoteException e) {
2384 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2385 }
2386 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002387 }
2388
2389 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002390 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002391 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002392
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002393 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002394 super(obbState);
2395 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002396 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002397 }
2398
Jason parks5af0b912010-11-29 09:05:25 -06002399 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002400 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002401 waitForReady();
2402 warnOnNotMounted();
2403
Kenny Root38cf8862010-09-26 14:18:51 -07002404 final ObbInfo obbInfo = getObbInfo();
2405
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002406 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002407 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2408 + " which is owned by " + obbInfo.packageName);
2409 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2410 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002411 }
2412
Kenny Rootaf9d6672010-10-08 09:21:39 -07002413 final boolean isMounted;
2414 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002415 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002416 }
2417 if (isMounted) {
2418 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2419 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2420 return;
2421 }
2422
Kenny Rootaf9d6672010-10-08 09:21:39 -07002423 final String hashedKey;
2424 if (mKey == null) {
2425 hashedKey = "none";
2426 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002427 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002428 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2429
2430 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2431 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2432 SecretKey key = factory.generateSecret(ks);
2433 BigInteger bi = new BigInteger(key.getEncoded());
2434 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002435 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002436 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2437 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2438 return;
2439 } catch (InvalidKeySpecException e) {
2440 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2441 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002442 return;
2443 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444 }
Kenny Root38cf8862010-09-26 14:18:51 -07002445
Kenny Rootaf9d6672010-10-08 09:21:39 -07002446 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002447 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002448 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002449 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002450 } catch (NativeDaemonConnectorException e) {
2451 int code = e.getCode();
2452 if (code != VoldResponseCode.OpFailedStorageBusy) {
2453 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002454 }
2455 }
2456
Kenny Rootaf9d6672010-10-08 09:21:39 -07002457 if (rc == StorageResultCode.OperationSucceeded) {
2458 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002459 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002460
2461 synchronized (mObbMounts) {
2462 addObbStateLocked(mObbState);
2463 }
2464
2465 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002466 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002467 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002468
Kenny Rootaf9d6672010-10-08 09:21:39 -07002469 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002470 }
2471 }
2472
Jason parks5af0b912010-11-29 09:05:25 -06002473 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002474 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002475 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002476 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002477
2478 @Override
2479 public String toString() {
2480 StringBuilder sb = new StringBuilder();
2481 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002482 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002483 sb.append('}');
2484 return sb.toString();
2485 }
2486 }
2487
2488 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002489 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002490
2491 UnmountObbAction(ObbState obbState, boolean force) {
2492 super(obbState);
2493 mForceUnmount = force;
2494 }
2495
Jason parks5af0b912010-11-29 09:05:25 -06002496 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002497 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002498 waitForReady();
2499 warnOnNotMounted();
2500
Kenny Root38cf8862010-09-26 14:18:51 -07002501 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002502
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002503 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002504 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002505 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002506 }
Kenny Root38cf8862010-09-26 14:18:51 -07002507
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002508 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002509 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2510 return;
2511 }
2512
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002513 if (existingState.ownerGid != mObbState.ownerGid) {
2514 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2515 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002516 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2517 return;
2518 }
2519
Kenny Rootaf9d6672010-10-08 09:21:39 -07002520 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002521 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002522 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002523 if (mForceUnmount) {
2524 cmd.appendArg("force");
2525 }
2526 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002527 } catch (NativeDaemonConnectorException e) {
2528 int code = e.getCode();
2529 if (code == VoldResponseCode.OpFailedStorageBusy) {
2530 rc = StorageResultCode.OperationFailedStorageBusy;
2531 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2532 // If it's not mounted then we've already won.
2533 rc = StorageResultCode.OperationSucceeded;
2534 } else {
2535 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002536 }
2537 }
2538
Kenny Rootaf9d6672010-10-08 09:21:39 -07002539 if (rc == StorageResultCode.OperationSucceeded) {
2540 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002542 }
2543
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002545 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002546 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002547 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002548 }
2549 }
2550
Jason parks5af0b912010-11-29 09:05:25 -06002551 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002552 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002553 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002554 }
2555
2556 @Override
2557 public String toString() {
2558 StringBuilder sb = new StringBuilder();
2559 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002560 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002561 sb.append(",force=");
2562 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002563 sb.append('}');
2564 return sb.toString();
2565 }
Kenny Root02c87302010-07-01 08:10:18 -07002566 }
Kenny Root38cf8862010-09-26 14:18:51 -07002567
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002568 // @VisibleForTesting
2569 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2570 // TODO: allow caller to provide Environment for full testing
2571
2572 // Only adjust paths when storage is emulated
2573 if (!Environment.isExternalStorageEmulated()) {
2574 return canonicalPath;
2575 }
2576
2577 String path = canonicalPath.toString();
2578
2579 // First trim off any external storage prefix
2580 final UserEnvironment userEnv = new UserEnvironment(userId);
2581
2582 // /storage/emulated/0
2583 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2584 // /storage/emulated_legacy
2585 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2586 .toString();
2587
2588 if (path.startsWith(externalPath)) {
2589 path = path.substring(externalPath.length() + 1);
2590 } else if (path.startsWith(legacyExternalPath)) {
2591 path = path.substring(legacyExternalPath.length() + 1);
2592 } else {
2593 return canonicalPath;
2594 }
2595
2596 // Handle special OBB paths on emulated storage
2597 final String obbPath = "Android/obb";
2598 if (path.startsWith(obbPath)) {
2599 path = path.substring(obbPath.length() + 1);
2600
2601 if (forVold) {
2602 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2603 } else {
2604 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2605 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2606 }
2607 }
2608
2609 // Handle normal external storage paths
2610 if (forVold) {
2611 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2612 } else {
2613 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2614 }
2615 }
2616
Kenny Root38cf8862010-09-26 14:18:51 -07002617 @Override
2618 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2619 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2620 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2621 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2622 + " without permission " + android.Manifest.permission.DUMP);
2623 return;
2624 }
2625
Kenny Root38cf8862010-09-26 14:18:51 -07002626 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002627 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002628
Kenny Rootaf9d6672010-10-08 09:21:39 -07002629 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2630 while (binders.hasNext()) {
2631 Entry<IBinder, List<ObbState>> e = binders.next();
2632 pw.print(" Key="); pw.println(e.getKey().toString());
2633 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002634 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002635 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002636 }
2637 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002638
2639 pw.println("");
2640 pw.println(" mObbPathToStateMap:");
2641 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2642 while (maps.hasNext()) {
2643 final Entry<String, ObbState> e = maps.next();
2644 pw.print(" "); pw.print(e.getKey());
2645 pw.print(" -> "); pw.println(e.getValue().toString());
2646 }
Kenny Root38cf8862010-09-26 14:18:51 -07002647 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002648
2649 pw.println("");
2650
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002651 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002652 pw.println(" mVolumes:");
2653
2654 final int N = mVolumes.size();
2655 for (int i = 0; i < N; i++) {
2656 final StorageVolume v = mVolumes.get(i);
2657 pw.print(" ");
2658 pw.println(v.toString());
2659 }
2660 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002661
2662 pw.println();
2663 pw.println(" mConnection:");
2664 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002667 /** {@inheritDoc} */
2668 public void monitor() {
2669 if (mConnector != null) {
2670 mConnector.monitor();
2671 }
2672 }
2673}