blob: 2e0c977d2ec58fe07e14d65b212590e4e0dea50d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e212012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040040import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070041import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080043import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080044import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080045import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070047import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070048import android.os.storage.IMountService;
49import android.os.storage.IMountServiceListener;
50import android.os.storage.IMountShutdownObserver;
51import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070052import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070053import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070054import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060055import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070057import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.Xml;
59
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080060import com.android.internal.annotations.GuardedBy;
61import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070062import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070063import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070064import com.android.internal.util.XmlUtils;
65import com.android.server.NativeDaemonConnector.Command;
66import com.android.server.am.ActivityManagerService;
67import com.android.server.pm.PackageManagerService;
68import com.android.server.pm.UserManagerService;
69import com.google.android.collect.Lists;
70import com.google.android.collect.Maps;
71
Mike Lockwood2f6a3882011-05-09 19:08:06 -070072import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070073
Jeff Sharkeyb049e212012-09-07 23:16:01 -070074import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070075import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070076import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070078import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070079import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070080import java.security.spec.InvalidKeySpecException;
81import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080082import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070083import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080084import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070085import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070086import java.util.LinkedList;
87import java.util.List;
88import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070089import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070090import java.util.concurrent.CountDownLatch;
91import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
Kenny Root3b1abba2010-10-13 15:00:07 -070093import javax.crypto.SecretKey;
94import javax.crypto.SecretKeyFactory;
95import javax.crypto.spec.PBEKeySpec;
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097/**
San Mehatb1043402010-02-05 08:26:50 -080098 * MountService implements back-end services for platform storage
99 * management.
100 * @hide - Applications should use android.os.storage.StorageManager
101 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700103class MountService extends IMountService.Stub
104 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600105
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700106 // TODO: listen for user creation/deletion
107
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800108 private static final boolean LOCAL_LOGD = false;
109 private static final boolean DEBUG_UNMOUNT = false;
110 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800111 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700112
Kenny Root07714d42011-08-17 17:49:28 -0700113 // Disable this since it messes up long-running cryptfs operations.
114 private static final boolean WATCHDOG_ENABLE = false;
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private static final String TAG = "MountService";
117
Kenny Root305bcbf2010-09-03 07:56:38 -0700118 private static final String VOLD_TAG = "VoldConnector";
119
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700120 /** Maximum number of ASEC containers allowed to be mounted. */
121 private static final int MAX_CONTAINERS = 250;
122
San Mehat4270e1e2010-01-29 05:32:19 -0800123 /*
124 * Internal vold volume state constants
125 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800126 class VolumeState {
127 public static final int Init = -1;
128 public static final int NoMedia = 0;
129 public static final int Idle = 1;
130 public static final int Pending = 2;
131 public static final int Checking = 3;
132 public static final int Mounted = 4;
133 public static final int Unmounting = 5;
134 public static final int Formatting = 6;
135 public static final int Shared = 7;
136 public static final int SharedMnt = 8;
137 }
138
San Mehat4270e1e2010-01-29 05:32:19 -0800139 /*
140 * Internal vold response code constants
141 */
San Mehat22dd86e2010-01-12 12:21:18 -0800142 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800143 /*
144 * 100 series - Requestion action was initiated; expect another reply
145 * before proceeding with a new command.
146 */
San Mehat22dd86e2010-01-12 12:21:18 -0800147 public static final int VolumeListResult = 110;
148 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800149 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800150
San Mehat4270e1e2010-01-29 05:32:19 -0800151 /*
152 * 200 series - Requestion action has been successfully completed.
153 */
154 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800155 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800156 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800157
San Mehat4270e1e2010-01-29 05:32:19 -0800158 /*
159 * 400 series - Command was accepted, but the requested action
160 * did not take place.
161 */
162 public static final int OpFailedNoMedia = 401;
163 public static final int OpFailedMediaBlank = 402;
164 public static final int OpFailedMediaCorrupt = 403;
165 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800166 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700167 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800168
169 /*
170 * 600 series - Unsolicited broadcasts.
171 */
San Mehat22dd86e2010-01-12 12:21:18 -0800172 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800173 public static final int VolumeDiskInserted = 630;
174 public static final int VolumeDiskRemoved = 631;
175 public static final int VolumeBadRemoval = 632;
176 }
177
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700178 private Context mContext;
179 private NativeDaemonConnector mConnector;
180
181 private final Object mVolumesLock = new Object();
182
183 /** When defined, base template for user-specific {@link StorageVolume}. */
184 private StorageVolume mEmulatedTemplate;
185
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800186 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700187 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
188 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800189 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700190 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
191 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700193 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
194
195 private volatile boolean mSystemReady = false;
196
San Mehat4270e1e2010-01-29 05:32:19 -0800197 private PackageManagerService mPms;
198 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700199 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800200 // Used as a lock for methods that register/unregister listeners.
201 final private ArrayList<MountServiceBinderListener> mListeners =
202 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800203 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
204 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800205 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800206
San Mehat6cdd9c02010-02-09 14:45:20 -0800207 /**
208 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800209 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800210 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800211 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800212
Kenny Root02c87302010-07-01 08:10:18 -0700213 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700214 * The size of the crypto algorithm key in bits for OBB files. Currently
215 * Twofish is used which takes 128-bit keys.
216 */
217 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
218
219 /**
220 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
221 * 1024 is reasonably secure and not too slow.
222 */
223 private static final int PBKDF2_HASH_ROUNDS = 1024;
224
225 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700226 * Mounted OBB tracking information. Used to track the current state of all
227 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700228 */
Kenny Root735de3b2010-09-30 14:11:39 -0700229 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700230
231 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700232 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
233
234 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700235 public ObbState(String rawPath, String canonicalPath, int callingUid,
236 IObbActionListener token, int nonce) {
237 this.rawPath = rawPath;
238 this.canonicalPath = canonicalPath.toString();
239
240 final int userId = UserHandle.getUserId(callingUid);
241 this.ownerPath = buildObbPath(canonicalPath, userId, false);
242 this.voldPath = buildObbPath(canonicalPath, userId, true);
243
244 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700245 this.token = token;
246 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700247 }
248
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700249 final String rawPath;
250 final String canonicalPath;
251 final String ownerPath;
252 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700253
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700254 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700255
Kenny Rootaf9d6672010-10-08 09:21:39 -0700256 // Token of remote Binder caller
257 final IObbActionListener token;
258
259 // Identifier to pass back to the token
260 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700261
Kenny Root735de3b2010-09-30 14:11:39 -0700262 public IBinder getBinder() {
263 return token.asBinder();
264 }
265
Kenny Roota02b8b02010-08-05 16:14:17 -0700266 @Override
267 public void binderDied() {
268 ObbAction action = new UnmountObbAction(this, true);
269 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700270 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700271
Kenny Root5919ac62010-10-05 09:49:40 -0700272 public void link() throws RemoteException {
273 getBinder().linkToDeath(this, 0);
274 }
275
276 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700277 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700278 }
Kenny Root38cf8862010-09-26 14:18:51 -0700279
280 @Override
281 public String toString() {
282 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700283 sb.append("rawPath=").append(rawPath);
284 sb.append(",canonicalPath=").append(canonicalPath);
285 sb.append(",ownerPath=").append(ownerPath);
286 sb.append(",voldPath=").append(voldPath);
287 sb.append(",ownerGid=").append(ownerGid);
288 sb.append(",token=").append(token);
289 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700290 sb.append('}');
291 return sb.toString();
292 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700293 }
294
295 // OBB Action Handler
296 final private ObbActionHandler mObbActionHandler;
297
298 // OBB action handler messages
299 private static final int OBB_RUN_ACTION = 1;
300 private static final int OBB_MCS_BOUND = 2;
301 private static final int OBB_MCS_UNBIND = 3;
302 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700303 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700304
305 /*
306 * Default Container Service information
307 */
308 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
309 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
310
311 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
312
313 class DefaultContainerConnection implements ServiceConnection {
314 public void onServiceConnected(ComponentName name, IBinder service) {
315 if (DEBUG_OBB)
316 Slog.i(TAG, "onServiceConnected");
317 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
318 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
319 }
320
321 public void onServiceDisconnected(ComponentName name) {
322 if (DEBUG_OBB)
323 Slog.i(TAG, "onServiceDisconnected");
324 }
325 };
326
327 // Used in the ObbActionHandler
328 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700329
330 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800331 private static final int H_UNMOUNT_PM_UPDATE = 1;
332 private static final int H_UNMOUNT_PM_DONE = 2;
333 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700334 private static final int H_SYSTEM_READY = 4;
335
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800336 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
337 private static final int MAX_UNMOUNT_RETRIES = 4;
338
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800339 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700340 final String path;
341 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700342 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800344
Ben Komalo13c71972011-09-07 16:35:56 -0700345 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 retries = 0;
347 this.path = path;
348 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700349 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800351
352 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700353 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700354 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800355 }
356 }
357
358 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700359 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800360
361 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700362 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800363 this.method = method;
364 }
365
366 @Override
367 void handleFinished() {
368 super.handleFinished();
369 doShareUnshareVolume(path, method, true);
370 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800371 }
372
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800373 class ShutdownCallBack extends UnmountCallBack {
374 IMountShutdownObserver observer;
375 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700376 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800377 this.observer = observer;
378 }
379
380 @Override
381 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700382 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 if (observer != null) {
384 try {
385 observer.onShutDownComplete(ret);
386 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700387 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800388 }
389 }
390 }
391 }
392
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400393 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800394 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700395 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800396
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400397 MountServiceHandler(Looper l) {
398 super(l);
399 }
400
Jason parks5af0b912010-11-29 09:05:25 -0600401 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800402 public void handleMessage(Message msg) {
403 switch (msg.what) {
404 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700405 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800406 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
407 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700408 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800409 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700410 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700411 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700412 mUpdatingStatus = true;
413 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800414 }
415 break;
416 }
417 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700419 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700420 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800421 int size = mForceUnmounts.size();
422 int sizeArr[] = new int[size];
423 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700424 // Kill processes holding references first
425 ActivityManagerService ams = (ActivityManagerService)
426 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800427 for (int i = 0; i < size; i++) {
428 UnmountCallBack ucb = mForceUnmounts.get(i);
429 String path = ucb.path;
430 boolean done = false;
431 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800432 done = true;
433 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 int pids[] = getStorageUsers(path);
435 if (pids == null || pids.length == 0) {
436 done = true;
437 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800438 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800439 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700440 // Confirm if file references have been freed.
441 pids = getStorageUsers(path);
442 if (pids == null || pids.length == 0) {
443 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800444 }
445 }
446 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700447 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
448 // Retry again
449 Slog.i(TAG, "Retrying to kill storage users again");
450 mHandler.sendMessageDelayed(
451 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
452 ucb.retries++),
453 RETRY_UNMOUNT_DELAY);
454 } else {
455 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
456 Slog.i(TAG, "Failed to unmount media inspite of " +
457 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
458 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800459 sizeArr[sizeArrN++] = i;
460 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
461 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800462 }
463 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800464 // Remove already processed elements from list.
465 for (int i = (sizeArrN-1); i >= 0; i--) {
466 mForceUnmounts.remove(sizeArr[i]);
467 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800468 break;
469 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700470 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700471 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800472 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800473 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800474 break;
475 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700476 case H_SYSTEM_READY: {
477 try {
478 handleSystemReady();
479 } catch (Exception ex) {
480 Slog.e(TAG, "Boot-time mount exception", ex);
481 }
482 break;
483 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800484 }
485 }
486 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700487
488 private final HandlerThread mHandlerThread;
489 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800490
Kenny Root51a573c2012-05-17 13:30:28 -0700491 void waitForAsecScan() {
492 waitForLatch(mAsecsScanned);
493 }
494
San Mehat207e5382010-02-04 20:46:54 -0800495 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700496 waitForLatch(mConnectedSignal);
497 }
498
499 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700500 for (;;) {
501 try {
502 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800503 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700504 } else {
505 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
506 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800507 }
Kenny Root51a573c2012-05-17 13:30:28 -0700508 } catch (InterruptedException e) {
509 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800510 }
San Mehat207e5382010-02-04 20:46:54 -0800511 }
San Mehat1f6301e2010-01-07 22:40:27 -0800512 }
Kenny Root02c87302010-07-01 08:10:18 -0700513
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700514 private void handleSystemReady() {
515 // Snapshot current volume states since it's not safe to call into vold
516 // while holding locks.
517 final HashMap<String, String> snapshot;
518 synchronized (mVolumesLock) {
519 snapshot = new HashMap<String, String>(mVolumeStates);
520 }
521
522 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
523 final String path = entry.getKey();
524 final String state = entry.getValue();
525
526 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
527 int rc = doMountVolume(path);
528 if (rc != StorageResultCode.OperationSucceeded) {
529 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
530 rc));
531 }
532 } else if (state.equals(Environment.MEDIA_SHARED)) {
533 /*
534 * Bootstrap UMS enabled state since vold indicates
535 * the volume is shared (runtime restart while ums enabled)
536 */
537 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
538 VolumeState.Shared);
539 }
540 }
541
542 // Push mounted state for all emulated storage
543 synchronized (mVolumesLock) {
544 for (StorageVolume volume : mVolumes) {
545 if (volume.isEmulated()) {
546 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
547 }
548 }
549 }
550
551 /*
552 * If UMS was connected on boot, send the connected event
553 * now that we're up.
554 */
555 if (mSendUmsConnectedOnBoot) {
556 sendUmsIntent(true);
557 mSendUmsConnectedOnBoot = false;
558 }
559 }
560
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700561 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
562 @Override
563 public void onReceive(Context context, Intent intent) {
564 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
565 if (userId == -1) return;
566 final UserHandle user = new UserHandle(userId);
567
568 final String action = intent.getAction();
569 if (Intent.ACTION_USER_ADDED.equals(action)) {
570 synchronized (mVolumesLock) {
571 createEmulatedVolumeForUserLocked(user);
572 }
573
574 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
575 synchronized (mVolumesLock) {
576 final List<StorageVolume> toRemove = Lists.newArrayList();
577 for (StorageVolume volume : mVolumes) {
578 if (user.equals(volume.getOwner())) {
579 toRemove.add(volume);
580 }
581 }
582 for (StorageVolume volume : toRemove) {
583 removeVolumeLocked(volume);
584 }
585 }
586 }
587 }
588 };
589
590 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
591 @Override
592 public void onReceive(Context context, Intent intent) {
593 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
594 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
595 notifyShareAvailabilityChange(available);
596 }
597 };
598
San Mehat4270e1e2010-01-29 05:32:19 -0800599 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
600 final IMountServiceListener mListener;
601
602 MountServiceBinderListener(IMountServiceListener listener) {
603 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700604
San Mehat91c77612010-01-07 10:39:41 -0800605 }
606
San Mehat4270e1e2010-01-29 05:32:19 -0800607 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700608 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700609 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800610 mListeners.remove(this);
611 mListener.asBinder().unlinkToDeath(this, 0);
612 }
613 }
614 }
615
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800616 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800617 // TODO: Add support for multiple share methods
618 if (!method.equals("ums")) {
619 throw new IllegalArgumentException(String.format("Method %s not supported", method));
620 }
621
San Mehat4270e1e2010-01-29 05:32:19 -0800622 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800623 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800624 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700625 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800626 }
San Mehat4270e1e2010-01-29 05:32:19 -0800627 }
628
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700629 private void updatePublicVolumeState(StorageVolume volume, String state) {
630 final String path = volume.getPath();
631 final String oldState;
632 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400633 oldState = mVolumeStates.put(path, state);
634 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700635
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400636 if (state.equals(oldState)) {
637 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
638 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800639 return;
640 }
San Mehatb1043402010-02-05 08:26:50 -0800641
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400642 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700643
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700644 // Tell PackageManager about changes to primary volume state, but only
645 // when not emulated.
646 if (volume.isPrimary() && !volume.isEmulated()) {
647 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
648 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400649
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700650 /*
651 * Some OBBs might have been unmounted when this volume was
652 * unmounted, so send a message to the handler to let it know to
653 * remove those from the list of mounted OBBS.
654 */
655 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
656 OBB_FLUSH_MOUNT_STATE, path));
657 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
658 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400659 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800660 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700661
San Mehat4270e1e2010-01-29 05:32:19 -0800662 synchronized (mListeners) {
663 for (int i = mListeners.size() -1; i >= 0; i--) {
664 MountServiceBinderListener bl = mListeners.get(i);
665 try {
San Mehatb1043402010-02-05 08:26:50 -0800666 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800667 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700668 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800669 mListeners.remove(i);
670 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700671 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800672 }
673 }
674 }
675 }
676
677 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800678 * Callback from NativeDaemonConnector
679 */
680 public void onDaemonConnected() {
681 /*
682 * Since we'll be calling back into the NativeDaemonConnector,
683 * we need to do our work in a new thread.
684 */
Kenny Root51a573c2012-05-17 13:30:28 -0700685 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600686 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800687 public void run() {
688 /**
689 * Determine media state and UMS detection status
690 */
San Mehat4270e1e2010-01-29 05:32:19 -0800691 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800692 final String[] vols = NativeDaemonEvent.filterMessageList(
693 mConnector.executeForList("volume", "list"),
694 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800695 for (String volstr : vols) {
696 String[] tok = volstr.split(" ");
697 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400698 String path = tok[1];
699 String state = Environment.MEDIA_REMOVED;
700
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700701 final StorageVolume volume;
702 synchronized (mVolumesLock) {
703 volume = mVolumesByPath.get(path);
704 }
705
San Mehat4270e1e2010-01-29 05:32:19 -0800706 int st = Integer.parseInt(tok[2]);
707 if (st == VolumeState.NoMedia) {
708 state = Environment.MEDIA_REMOVED;
709 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800710 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800711 } else if (st == VolumeState.Mounted) {
712 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700713 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800714 } else if (st == VolumeState.Shared) {
715 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700716 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800717 } else {
718 throw new Exception(String.format("Unexpected state %d", st));
719 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400720
721 if (state != null) {
722 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700723 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400724 }
San Mehat4270e1e2010-01-29 05:32:19 -0800725 }
726 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700727 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700728 final StorageVolume primary = getPrimaryPhysicalVolume();
729 if (primary != null) {
730 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
731 }
San Mehat4270e1e2010-01-29 05:32:19 -0800732 }
733
San Mehat207e5382010-02-04 20:46:54 -0800734 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600735 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800736 * the hounds!
737 */
Kenny Root51a573c2012-05-17 13:30:28 -0700738 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700739
740 // Let package manager load internal ASECs.
741 mPms.scanAvailableAsecs();
742
743 // Notify people waiting for ASECs to be scanned that it's done.
744 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800745 }
746 }.start();
747 }
748
749 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800750 * Callback from NativeDaemonConnector
751 */
752 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800753 if (DEBUG_EVENTS) {
754 StringBuilder builder = new StringBuilder();
755 builder.append("onEvent::");
756 builder.append(" raw= " + raw);
757 if (cooked != null) {
758 builder.append(" cooked = " );
759 for (String str : cooked) {
760 builder.append(" " + str);
761 }
762 }
San Mehata5078592010-03-25 09:36:54 -0700763 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800764 }
San Mehat4270e1e2010-01-29 05:32:19 -0800765 if (code == VoldResponseCode.VolumeStateChange) {
766 /*
767 * One of the volumes we're managing has changed state.
768 * Format: "NNN Volume <label> <path> state changed
769 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
770 */
771 notifyVolumeStateChange(
772 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
773 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800774 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
775 (code == VoldResponseCode.VolumeDiskRemoved) ||
776 (code == VoldResponseCode.VolumeBadRemoval)) {
777 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
778 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
779 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400780 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800781 final String label = cooked[2];
782 final String path = cooked[3];
783 int major = -1;
784 int minor = -1;
785
786 try {
787 String devComp = cooked[6].substring(1, cooked[6].length() -1);
788 String[] devTok = devComp.split(":");
789 major = Integer.parseInt(devTok[0]);
790 minor = Integer.parseInt(devTok[1]);
791 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700792 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800793 }
794
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700795 final StorageVolume volume;
796 final String state;
797 synchronized (mVolumesLock) {
798 volume = mVolumesByPath.get(path);
799 state = mVolumeStates.get(path);
800 }
801
San Mehat4270e1e2010-01-29 05:32:19 -0800802 if (code == VoldResponseCode.VolumeDiskInserted) {
803 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600804 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800805 public void run() {
806 try {
807 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800808 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700809 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800810 }
811 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700812 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800813 }
814 }
815 }.start();
816 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
817 /*
818 * This event gets trumped if we're already in BAD_REMOVAL state
819 */
820 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
821 return true;
822 }
823 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700824 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700825 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
826 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800827
San Mehata5078592010-03-25 09:36:54 -0700828 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700829 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400830 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800831 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700832 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800833 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700834 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400835 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800836
San Mehata5078592010-03-25 09:36:54 -0700837 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700838 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400839 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800840 } else {
San Mehata5078592010-03-25 09:36:54 -0700841 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800842 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400843
844 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700845 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400846 }
San Mehat4270e1e2010-01-29 05:32:19 -0800847 } else {
848 return false;
849 }
850
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400851 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800852 }
853
San Mehat207e5382010-02-04 20:46:54 -0800854 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700855 final StorageVolume volume;
856 final String state;
857 synchronized (mVolumesLock) {
858 volume = mVolumesByPath.get(path);
859 state = getVolumeState(path);
860 }
861
862 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800863
Mike Lockwooda5250c92011-05-23 13:44:04 -0400864 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800865
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500866 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700867 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700868 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500869 }
870
San Mehat4270e1e2010-01-29 05:32:19 -0800871 if (newState == VolumeState.Init) {
872 } else if (newState == VolumeState.NoMedia) {
873 // NoMedia is handled via Disk Remove events
874 } else if (newState == VolumeState.Idle) {
875 /*
876 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
877 * if we're in the process of enabling UMS
878 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700879 if (!state.equals(
880 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
881 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800882 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700883 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700884 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400885 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800886 }
887 } else if (newState == VolumeState.Pending) {
888 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700889 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700890 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400891 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800892 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700893 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700894 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400895 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800896 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400897 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800898 } else if (newState == VolumeState.Formatting) {
899 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700900 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800901 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700902 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
903 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800904
San Mehata5078592010-03-25 09:36:54 -0700905 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700906 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400907 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700908 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800909 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700910 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800911 return;
912 } else {
San Mehata5078592010-03-25 09:36:54 -0700913 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800914 }
915
Mike Lockwooda5250c92011-05-23 13:44:04 -0400916 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700917 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800918 }
919 }
920
San Mehat207e5382010-02-04 20:46:54 -0800921 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800922 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800923
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700924 final StorageVolume volume;
925 synchronized (mVolumesLock) {
926 volume = mVolumesByPath.get(path);
927 }
928
San Mehata5078592010-03-25 09:36:54 -0700929 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800930 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800931 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800932 } catch (NativeDaemonConnectorException e) {
933 /*
934 * Mount failed for some reason
935 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400936 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800937 int code = e.getCode();
938 if (code == VoldResponseCode.OpFailedNoMedia) {
939 /*
940 * Attempt to mount but no media inserted
941 */
San Mehatb1043402010-02-05 08:26:50 -0800942 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800943 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700944 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800945 /*
946 * Media is blank or does not contain a supported filesystem
947 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700948 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400949 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800950 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800951 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700952 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800953 /*
954 * Volume consistency check failed
955 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700956 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400957 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800958 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800959 } else {
San Mehatb1043402010-02-05 08:26:50 -0800960 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800961 }
962
963 /*
964 * Send broadcast intent (if required for the failure)
965 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400966 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700967 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800968 }
969 }
970
971 return rc;
972 }
973
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800974 /*
975 * If force is not set, we do not unmount if there are
976 * processes holding references to the volume about to be unmounted.
977 * If force is set, all the processes holding references need to be
978 * killed via the ActivityManager before actually unmounting the volume.
979 * This might even take a while and might be retried after timed delays
980 * to make sure we dont end up in an instable state and kill some core
981 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -0700982 * If removeEncryption is set, force is implied, and the system will remove any encryption
983 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800984 */
Ben Komalo13c71972011-09-07 16:35:56 -0700985 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -0800986 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -0800987 return VoldResponseCode.OpFailedVolNotMounted;
988 }
Kenny Rootaa485402010-09-14 14:49:41 -0700989
990 /*
991 * Force a GC to make sure AssetManagers in other threads of the
992 * system_server are cleaned up. We have to do this since AssetManager
993 * instances are kept as a WeakReference and it's possible we have files
994 * open on the external storage.
995 */
996 Runtime.getRuntime().gc();
997
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800998 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700999 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001000 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001001 final Command cmd = new Command("volume", "unmount", path);
1002 if (removeEncryption) {
1003 cmd.appendArg("force_and_revert");
1004 } else if (force) {
1005 cmd.appendArg("force");
1006 }
1007 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001008 // We unmounted the volume. None of the asec containers are available now.
1009 synchronized (mAsecMountSet) {
1010 mAsecMountSet.clear();
1011 }
San Mehatb1043402010-02-05 08:26:50 -08001012 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001013 } catch (NativeDaemonConnectorException e) {
1014 // Don't worry about mismatch in PackageManager since the
1015 // call back will handle the status changes any way.
1016 int code = e.getCode();
1017 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001018 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001019 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1020 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001021 } else {
San Mehatb1043402010-02-05 08:26:50 -08001022 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001023 }
1024 }
1025 }
1026
1027 private int doFormatVolume(String path) {
1028 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001029 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001030 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001031 } catch (NativeDaemonConnectorException e) {
1032 int code = e.getCode();
1033 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001034 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001035 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001036 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001037 } else {
San Mehatb1043402010-02-05 08:26:50 -08001038 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001039 }
1040 }
1041 }
1042
San Mehatb1043402010-02-05 08:26:50 -08001043 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001044 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001045 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001046 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001047 } catch (NativeDaemonConnectorException ex) {
1048 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1049 return false;
1050 }
San Mehatb1043402010-02-05 08:26:50 -08001051
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001052 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1053 return event.getMessage().endsWith("enabled");
1054 } else {
1055 return false;
San Mehatb1043402010-02-05 08:26:50 -08001056 }
San Mehatb1043402010-02-05 08:26:50 -08001057 }
1058
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001059 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001060 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001061 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001062 for (int i = mListeners.size() -1; i >= 0; i--) {
1063 MountServiceBinderListener bl = mListeners.get(i);
1064 try {
San Mehatb1043402010-02-05 08:26:50 -08001065 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001066 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001067 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001068 mListeners.remove(i);
1069 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001070 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001071 }
1072 }
1073 }
1074
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001075 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001076 sendUmsIntent(avail);
1077 } else {
1078 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001079 }
San Mehat2fe718a2010-03-11 12:01:49 -08001080
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001081 final StorageVolume primary = getPrimaryPhysicalVolume();
1082 if (avail == false && primary != null
1083 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1084 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001085 /*
1086 * USB mass storage disconnected while enabled
1087 */
1088 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001089 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001090 public void run() {
1091 try {
1092 int rc;
San Mehata5078592010-03-25 09:36:54 -07001093 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001094 doShareUnshareVolume(path, "ums", false);
1095 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001096 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001097 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1098 path, rc));
1099 }
1100 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001101 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001102 }
1103 }
1104 }.start();
1105 }
San Mehat4270e1e2010-01-29 05:32:19 -08001106 }
1107
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001108 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1109 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1110 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1111 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1112 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001113 }
1114
San Mehat6a965af22010-02-24 17:47:30 -08001115 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001116 mContext.sendBroadcastAsUser(
1117 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1118 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001119 }
1120
San Mehat207e5382010-02-04 20:46:54 -08001121 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001122 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1123 throw new SecurityException(String.format("Requires %s permission", perm));
1124 }
1125 }
1126
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001127 // Storage list XML tags
1128 private static final String TAG_STORAGE_LIST = "StorageList";
1129 private static final String TAG_STORAGE = "storage";
1130
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001131 private void readStorageListLocked() {
1132 mVolumes.clear();
1133 mVolumeStates.clear();
1134
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001135 Resources resources = mContext.getResources();
1136
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001137 int id = com.android.internal.R.xml.storage_list;
1138 XmlResourceParser parser = resources.getXml(id);
1139 AttributeSet attrs = Xml.asAttributeSet(parser);
1140
1141 try {
1142 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1143 while (true) {
1144 XmlUtils.nextElement(parser);
1145
1146 String element = parser.getName();
1147 if (element == null) break;
1148
1149 if (TAG_STORAGE.equals(element)) {
1150 TypedArray a = resources.obtainAttributes(attrs,
1151 com.android.internal.R.styleable.Storage);
1152
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001153 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001154 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001155 int descriptionId = a.getResourceId(
1156 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001157 CharSequence description = a.getText(
1158 com.android.internal.R.styleable.Storage_storageDescription);
1159 boolean primary = a.getBoolean(
1160 com.android.internal.R.styleable.Storage_primary, false);
1161 boolean removable = a.getBoolean(
1162 com.android.internal.R.styleable.Storage_removable, false);
1163 boolean emulated = a.getBoolean(
1164 com.android.internal.R.styleable.Storage_emulated, false);
1165 int mtpReserve = a.getInt(
1166 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001167 boolean allowMassStorage = a.getBoolean(
1168 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001169 // resource parser does not support longs, so XML value is in megabytes
1170 long maxFileSize = a.getInt(
1171 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001172
1173 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1174 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001175 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001176 " allowMassStorage: " + allowMassStorage +
1177 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001178
1179 if (emulated) {
1180 // For devices with emulated storage, we create separate
1181 // volumes for each known user.
1182 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1183 true, mtpReserve, false, maxFileSize, null);
1184
1185 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001186 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001187 createEmulatedVolumeForUserLocked(user.getUserHandle());
1188 }
1189
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001190 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001191 if (path == null || description == null) {
1192 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001193 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001194 final StorageVolume volume = new StorageVolume(new File(path),
1195 descriptionId, primary, removable, emulated, mtpReserve,
1196 allowMassStorage, maxFileSize, null);
1197 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001198 }
1199 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001200
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001201 a.recycle();
1202 }
1203 }
1204 } catch (XmlPullParserException e) {
1205 throw new RuntimeException(e);
1206 } catch (IOException e) {
1207 throw new RuntimeException(e);
1208 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001209 // Compute storage ID for each physical volume; emulated storage is
1210 // always 0 when defined.
1211 int index = isExternalStorageEmulated() ? 1 : 0;
1212 for (StorageVolume volume : mVolumes) {
1213 if (!volume.isEmulated()) {
1214 volume.setStorageId(index++);
1215 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001216 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001217 parser.close();
1218 }
1219 }
1220
San Mehat4270e1e2010-01-29 05:32:19 -08001221 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001222 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1223 * using {@link #mEmulatedTemplate} as template.
1224 */
1225 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1226 if (mEmulatedTemplate == null) {
1227 throw new IllegalStateException("Missing emulated volume multi-user template");
1228 }
1229
1230 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1231 final File path = userEnv.getExternalStorageDirectory();
1232 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1233 volume.setStorageId(0);
1234 addVolumeLocked(volume);
1235
1236 if (mSystemReady) {
1237 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1238 } else {
1239 // Place stub status for early callers to find
1240 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1241 }
1242 }
1243
1244 private void addVolumeLocked(StorageVolume volume) {
1245 Slog.d(TAG, "addVolumeLocked() " + volume);
1246 mVolumes.add(volume);
1247 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1248 if (existing != null) {
1249 throw new IllegalStateException(
1250 "Volume at " + volume.getPath() + " already exists: " + existing);
1251 }
1252 }
1253
1254 private void removeVolumeLocked(StorageVolume volume) {
1255 Slog.d(TAG, "removeVolumeLocked() " + volume);
1256 mVolumes.remove(volume);
1257 mVolumesByPath.remove(volume.getPath());
1258 mVolumeStates.remove(volume.getPath());
1259 }
1260
1261 private StorageVolume getPrimaryPhysicalVolume() {
1262 synchronized (mVolumesLock) {
1263 for (StorageVolume volume : mVolumes) {
1264 if (volume.isPrimary() && !volume.isEmulated()) {
1265 return volume;
1266 }
1267 }
1268 }
1269 return null;
1270 }
1271
1272 /**
San Mehat207e5382010-02-04 20:46:54 -08001273 * Constructs a new MountService instance
1274 *
1275 * @param context Binder context for this service
1276 */
1277 public MountService(Context context) {
1278 mContext = context;
1279
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001280 synchronized (mVolumesLock) {
1281 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001282 }
1283
San Mehat207e5382010-02-04 20:46:54 -08001284 // XXX: This will go away soon in favor of IMountServiceObserver
1285 mPms = (PackageManagerService) ServiceManager.getService("package");
1286
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001287 mHandlerThread = new HandlerThread("MountService");
1288 mHandlerThread.start();
1289 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1290
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001291 // Watch for user changes
1292 final IntentFilter userFilter = new IntentFilter();
1293 userFilter.addAction(Intent.ACTION_USER_ADDED);
1294 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1295 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1296
1297 // Watch for USB changes on primary volume
1298 final StorageVolume primary = getPrimaryPhysicalVolume();
1299 if (primary != null && primary.allowMassStorage()) {
1300 mContext.registerReceiver(
1301 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1302 }
1303
Kenny Roota02b8b02010-08-05 16:14:17 -07001304 // Add OBB Action Handler to MountService thread.
1305 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1306
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001307 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001308 * Create the connection to vold with a maximum queue of twice the
1309 * amount of containers we'd ever expect to have. This keeps an
1310 * "asec list" from blocking a thread repeatedly.
1311 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001312 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001313
Kenny Root305bcbf2010-09-03 07:56:38 -07001314 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001315 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001316
Kenny Root07714d42011-08-17 17:49:28 -07001317 // Add ourself to the Watchdog monitors if enabled.
1318 if (WATCHDOG_ENABLE) {
1319 Watchdog.getInstance().addMonitor(this);
1320 }
San Mehat207e5382010-02-04 20:46:54 -08001321 }
1322
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001323 public void systemReady() {
1324 mSystemReady = true;
1325 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1326 }
1327
San Mehat207e5382010-02-04 20:46:54 -08001328 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001329 * Exposed API calls below here
1330 */
1331
1332 public void registerListener(IMountServiceListener listener) {
1333 synchronized (mListeners) {
1334 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1335 try {
1336 listener.asBinder().linkToDeath(bl, 0);
1337 mListeners.add(bl);
1338 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001339 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001340 }
1341 }
1342 }
1343
1344 public void unregisterListener(IMountServiceListener listener) {
1345 synchronized (mListeners) {
1346 for(MountServiceBinderListener bl : mListeners) {
1347 if (bl.mListener == listener) {
1348 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001349 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001350 return;
1351 }
1352 }
1353 }
1354 }
1355
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001356 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001357 validatePermission(android.Manifest.permission.SHUTDOWN);
1358
San Mehata5078592010-03-25 09:36:54 -07001359 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001360 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001361 for (String path : mVolumeStates.keySet()) {
1362 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001363
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001364 if (state.equals(Environment.MEDIA_SHARED)) {
1365 /*
1366 * If the media is currently shared, unshare it.
1367 * XXX: This is still dangerous!. We should not
1368 * be rebooting at *all* if UMS is enabled, since
1369 * the UMS host could have dirty FAT cache entries
1370 * yet to flush.
1371 */
1372 setUsbMassStorageEnabled(false);
1373 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1374 /*
1375 * If the media is being checked, then we need to wait for
1376 * it to complete before being able to proceed.
1377 */
1378 // XXX: @hackbod - Should we disable the ANR timer here?
1379 int retries = 30;
1380 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1381 try {
1382 Thread.sleep(1000);
1383 } catch (InterruptedException iex) {
1384 Slog.e(TAG, "Interrupted while waiting for media", iex);
1385 break;
1386 }
1387 state = Environment.getExternalStorageState();
1388 }
1389 if (retries == 0) {
1390 Slog.e(TAG, "Timed out waiting for media to check");
1391 }
San Mehat91c77612010-01-07 10:39:41 -08001392 }
San Mehat91c77612010-01-07 10:39:41 -08001393
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001394 if (state.equals(Environment.MEDIA_MOUNTED)) {
1395 // Post a unmount message.
1396 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1397 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1398 } else if (observer != null) {
1399 /*
1400 * Observer is waiting for onShutDownComplete when we are done.
1401 * Since nothing will be done send notification directly so shutdown
1402 * sequence can continue.
1403 */
1404 try {
1405 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1406 } catch (RemoteException e) {
1407 Slog.w(TAG, "RemoteException when shutting down");
1408 }
1409 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001410 }
San Mehat4270e1e2010-01-29 05:32:19 -08001411 }
1412 }
1413
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001414 private boolean getUmsEnabling() {
1415 synchronized (mListeners) {
1416 return mUmsEnabling;
1417 }
1418 }
1419
1420 private void setUmsEnabling(boolean enable) {
1421 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001422 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001423 }
1424 }
1425
San Mehatb1043402010-02-05 08:26:50 -08001426 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001427 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001428
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001429 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001430 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001431 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001432 synchronized (mListeners) {
1433 return mUmsAvailable;
1434 }
San Mehatb1043402010-02-05 08:26:50 -08001435 }
1436
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001437 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001438 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001439 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001440
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001441 final StorageVolume primary = getPrimaryPhysicalVolume();
1442 if (primary == null) return;
1443
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001444 // TODO: Add support for multiple share methods
1445
1446 /*
1447 * If the volume is mounted and we're enabling then unmount it
1448 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001449 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001450 String vs = getVolumeState(path);
1451 String method = "ums";
1452 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1453 // Override for isUsbMassStorageEnabled()
1454 setUmsEnabling(enable);
1455 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1456 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1457 // Clear override
1458 setUmsEnabling(false);
1459 }
1460 /*
1461 * If we disabled UMS then mount the volume
1462 */
1463 if (!enable) {
1464 doShareUnshareVolume(path, method, enable);
1465 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001466 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001467 " after disabling share method " + method);
1468 /*
1469 * Even though the mount failed, the unshare didn't so don't indicate an error.
1470 * The mountVolume() call will have set the storage state and sent the necessary
1471 * broadcasts.
1472 */
1473 }
1474 }
San Mehatb1043402010-02-05 08:26:50 -08001475 }
1476
1477 public boolean isUsbMassStorageEnabled() {
1478 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001479
1480 final StorageVolume primary = getPrimaryPhysicalVolume();
1481 if (primary != null) {
1482 return doGetVolumeShared(primary.getPath(), "ums");
1483 } else {
1484 return false;
1485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001487
San Mehat7fd0fee2009-12-17 07:12:23 -08001488 /**
1489 * @return state of the volume at the specified mount point
1490 */
San Mehat4270e1e2010-01-29 05:32:19 -08001491 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001492 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001493 String state = mVolumeStates.get(mountPoint);
1494 if (state == null) {
1495 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001496 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1497 state = Environment.MEDIA_REMOVED;
1498 } else {
1499 throw new IllegalArgumentException();
1500 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001501 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001502
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001503 return state;
1504 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001505 }
1506
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001507 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001508 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001509 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001510 }
1511
San Mehat4270e1e2010-01-29 05:32:19 -08001512 public int mountVolume(String path) {
1513 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001514
San Mehat207e5382010-02-04 20:46:54 -08001515 waitForReady();
1516 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Ben Komalo13c71972011-09-07 16:35:56 -07001519 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001520 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001521 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001523 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001524 if (DEBUG_UNMOUNT) {
1525 Slog.i(TAG, "Unmounting " + path
1526 + " force = " + force
1527 + " removeEncryption = " + removeEncryption);
1528 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001529 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1530 Environment.MEDIA_REMOVED.equals(volState) ||
1531 Environment.MEDIA_SHARED.equals(volState) ||
1532 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1533 // Media already unmounted or cannot be unmounted.
1534 // TODO return valid return code when adding observer call back.
1535 return;
1536 }
Ben Komalo13c71972011-09-07 16:35:56 -07001537 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001538 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
San Mehat4270e1e2010-01-29 05:32:19 -08001541 public int formatVolume(String path) {
1542 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001543 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001544
San Mehat207e5382010-02-04 20:46:54 -08001545 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001548 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001549 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1550 waitForReady();
1551 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001552 final String[] r = NativeDaemonEvent.filterMessageList(
1553 mConnector.executeForList("storage", "users", path),
1554 VoldResponseCode.StorageUsersListResult);
1555
San Mehatc1b4ce92010-02-16 17:13:03 -08001556 // FMT: <pid> <process name>
1557 int[] data = new int[r.length];
1558 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001559 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001560 try {
1561 data[i] = Integer.parseInt(tok[0]);
1562 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001563 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001564 return new int[0];
1565 }
1566 }
1567 return data;
1568 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001569 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001570 return new int[0];
1571 }
1572 }
1573
San Mehatb1043402010-02-05 08:26:50 -08001574 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001575 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001576 if (primary != null) {
1577 boolean mounted = false;
1578 try {
1579 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
1580 } catch (IllegalStateException e) {
1581 }
1582
1583 if (!mounted) {
1584 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1585 }
San Mehatb1043402010-02-05 08:26:50 -08001586 }
1587 }
1588
San Mehat4270e1e2010-01-29 05:32:19 -08001589 public String[] getSecureContainerList() {
1590 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001591 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001592 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001593
San Mehat4270e1e2010-01-29 05:32:19 -08001594 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001595 return NativeDaemonEvent.filterMessageList(
1596 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001597 } catch (NativeDaemonConnectorException e) {
1598 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 }
San Mehat36972292010-01-06 11:06:32 -08001601
Kenny Root6dceb882012-04-12 14:23:49 -07001602 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1603 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001604 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001605 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001606 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001607
San Mehatb1043402010-02-05 08:26:50 -08001608 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001609 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001610 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1611 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001612 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001613 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001614 }
San Mehata181b212010-02-11 06:50:20 -08001615
1616 if (rc == StorageResultCode.OperationSucceeded) {
1617 synchronized (mAsecMountSet) {
1618 mAsecMountSet.add(id);
1619 }
1620 }
San Mehat4270e1e2010-01-29 05:32:19 -08001621 return rc;
San Mehat36972292010-01-06 11:06:32 -08001622 }
1623
San Mehat4270e1e2010-01-29 05:32:19 -08001624 public int finalizeSecureContainer(String id) {
1625 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001626 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001627
San Mehatb1043402010-02-05 08:26:50 -08001628 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001629 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001630 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001631 /*
1632 * Finalization does a remount, so no need
1633 * to update mAsecMountSet
1634 */
San Mehat4270e1e2010-01-29 05:32:19 -08001635 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001636 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001637 }
San Mehat4270e1e2010-01-29 05:32:19 -08001638 return rc;
San Mehat36972292010-01-06 11:06:32 -08001639 }
1640
Kenny Root6dceb882012-04-12 14:23:49 -07001641 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1642 validatePermission(android.Manifest.permission.ASEC_CREATE);
1643 warnOnNotMounted();
1644
1645 int rc = StorageResultCode.OperationSucceeded;
1646 try {
1647 mConnector.execute("asec", "fixperms", id, gid, filename);
1648 /*
1649 * Fix permissions does a remount, so no need to update
1650 * mAsecMountSet
1651 */
1652 } catch (NativeDaemonConnectorException e) {
1653 rc = StorageResultCode.OperationFailedInternalError;
1654 }
1655 return rc;
1656 }
1657
San Mehatd9709982010-02-18 11:43:03 -08001658 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001659 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001660 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001661 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001662
Kenny Rootaa485402010-09-14 14:49:41 -07001663 /*
1664 * Force a GC to make sure AssetManagers in other threads of the
1665 * system_server are cleaned up. We have to do this since AssetManager
1666 * instances are kept as a WeakReference and it's possible we have files
1667 * open on the external storage.
1668 */
1669 Runtime.getRuntime().gc();
1670
San Mehatb1043402010-02-05 08:26:50 -08001671 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001672 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001673 final Command cmd = new Command("asec", "destroy", id);
1674 if (force) {
1675 cmd.appendArg("force");
1676 }
1677 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001678 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001679 int code = e.getCode();
1680 if (code == VoldResponseCode.OpFailedStorageBusy) {
1681 rc = StorageResultCode.OperationFailedStorageBusy;
1682 } else {
1683 rc = StorageResultCode.OperationFailedInternalError;
1684 }
San Mehat02735bc2010-01-26 15:18:08 -08001685 }
San Mehata181b212010-02-11 06:50:20 -08001686
1687 if (rc == StorageResultCode.OperationSucceeded) {
1688 synchronized (mAsecMountSet) {
1689 if (mAsecMountSet.contains(id)) {
1690 mAsecMountSet.remove(id);
1691 }
1692 }
1693 }
1694
San Mehat4270e1e2010-01-29 05:32:19 -08001695 return rc;
San Mehat36972292010-01-06 11:06:32 -08001696 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001697
San Mehat4270e1e2010-01-29 05:32:19 -08001698 public int mountSecureContainer(String id, String key, int ownerUid) {
1699 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001700 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001701 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001702
San Mehata181b212010-02-11 06:50:20 -08001703 synchronized (mAsecMountSet) {
1704 if (mAsecMountSet.contains(id)) {
1705 return StorageResultCode.OperationFailedStorageMounted;
1706 }
1707 }
1708
San Mehatb1043402010-02-05 08:26:50 -08001709 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001710 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001711 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001712 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001713 int code = e.getCode();
1714 if (code != VoldResponseCode.OpFailedStorageBusy) {
1715 rc = StorageResultCode.OperationFailedInternalError;
1716 }
San Mehat02735bc2010-01-26 15:18:08 -08001717 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001718
1719 if (rc == StorageResultCode.OperationSucceeded) {
1720 synchronized (mAsecMountSet) {
1721 mAsecMountSet.add(id);
1722 }
1723 }
San Mehat4270e1e2010-01-29 05:32:19 -08001724 return rc;
San Mehat36972292010-01-06 11:06:32 -08001725 }
1726
San Mehatd9709982010-02-18 11:43:03 -08001727 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001728 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001729 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001730 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001731
San Mehat6cdd9c02010-02-09 14:45:20 -08001732 synchronized (mAsecMountSet) {
1733 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001734 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001735 }
1736 }
1737
Kenny Rootaa485402010-09-14 14:49:41 -07001738 /*
1739 * Force a GC to make sure AssetManagers in other threads of the
1740 * system_server are cleaned up. We have to do this since AssetManager
1741 * instances are kept as a WeakReference and it's possible we have files
1742 * open on the external storage.
1743 */
1744 Runtime.getRuntime().gc();
1745
San Mehatb1043402010-02-05 08:26:50 -08001746 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001747 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001748 final Command cmd = new Command("asec", "unmount", id);
1749 if (force) {
1750 cmd.appendArg("force");
1751 }
1752 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001753 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001754 int code = e.getCode();
1755 if (code == VoldResponseCode.OpFailedStorageBusy) {
1756 rc = StorageResultCode.OperationFailedStorageBusy;
1757 } else {
1758 rc = StorageResultCode.OperationFailedInternalError;
1759 }
San Mehat02735bc2010-01-26 15:18:08 -08001760 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001761
1762 if (rc == StorageResultCode.OperationSucceeded) {
1763 synchronized (mAsecMountSet) {
1764 mAsecMountSet.remove(id);
1765 }
1766 }
San Mehat4270e1e2010-01-29 05:32:19 -08001767 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001768 }
1769
San Mehat6cdd9c02010-02-09 14:45:20 -08001770 public boolean isSecureContainerMounted(String id) {
1771 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1772 waitForReady();
1773 warnOnNotMounted();
1774
1775 synchronized (mAsecMountSet) {
1776 return mAsecMountSet.contains(id);
1777 }
1778 }
1779
San Mehat4270e1e2010-01-29 05:32:19 -08001780 public int renameSecureContainer(String oldId, String newId) {
1781 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001782 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001783 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001784
San Mehata181b212010-02-11 06:50:20 -08001785 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001786 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001787 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001788 * changed while active, we must ensure both ids are not currently mounted.
1789 */
1790 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001791 return StorageResultCode.OperationFailedStorageMounted;
1792 }
1793 }
1794
San Mehatb1043402010-02-05 08:26:50 -08001795 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001796 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001797 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001798 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001799 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001800 }
San Mehata181b212010-02-11 06:50:20 -08001801
San Mehat4270e1e2010-01-29 05:32:19 -08001802 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001803 }
1804
San Mehat4270e1e2010-01-29 05:32:19 -08001805 public String getSecureContainerPath(String id) {
1806 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001807 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001808 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001809
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001810 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001811 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001812 event = mConnector.execute("asec", "path", id);
1813 event.checkCode(VoldResponseCode.AsecPathResult);
1814 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001815 } catch (NativeDaemonConnectorException e) {
1816 int code = e.getCode();
1817 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001818 Slog.i(TAG, String.format("Container '%s' not found", id));
1819 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001820 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001821 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001822 }
1823 }
San Mehat22dd86e2010-01-12 12:21:18 -08001824 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001825
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001826 public String getSecureContainerFilesystemPath(String id) {
1827 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1828 waitForReady();
1829 warnOnNotMounted();
1830
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001831 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001832 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001833 event = mConnector.execute("asec", "fspath", id);
1834 event.checkCode(VoldResponseCode.AsecPathResult);
1835 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001836 } catch (NativeDaemonConnectorException e) {
1837 int code = e.getCode();
1838 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1839 Slog.i(TAG, String.format("Container '%s' not found", id));
1840 return null;
1841 } else {
1842 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1843 }
1844 }
1845 }
1846
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001847 public void finishMediaUpdate() {
1848 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1849 }
Kenny Root02c87302010-07-01 08:10:18 -07001850
Kenny Roota02b8b02010-08-05 16:14:17 -07001851 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1852 if (callerUid == android.os.Process.SYSTEM_UID) {
1853 return true;
1854 }
1855
Kenny Root02c87302010-07-01 08:10:18 -07001856 if (packageName == null) {
1857 return false;
1858 }
1859
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001860 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001861
1862 if (DEBUG_OBB) {
1863 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1864 packageUid + ", callerUid = " + callerUid);
1865 }
1866
1867 return callerUid == packageUid;
1868 }
1869
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001870 public String getMountedObbPath(String rawPath) {
1871 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001872
Kenny Root02c87302010-07-01 08:10:18 -07001873 waitForReady();
1874 warnOnNotMounted();
1875
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001876 final ObbState state;
1877 synchronized (mObbPathToStateMap) {
1878 state = mObbPathToStateMap.get(rawPath);
1879 }
1880 if (state == null) {
1881 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1882 return null;
1883 }
1884
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001885 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001886 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001887 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001888 event.checkCode(VoldResponseCode.AsecPathResult);
1889 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001890 } catch (NativeDaemonConnectorException e) {
1891 int code = e.getCode();
1892 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001893 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001894 } else {
1895 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1896 }
1897 }
1898 }
1899
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001900 @Override
1901 public boolean isObbMounted(String rawPath) {
1902 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001903 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001904 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001905 }
Kenny Root02c87302010-07-01 08:10:18 -07001906 }
1907
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001908 @Override
1909 public void mountObb(
1910 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1911 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1912 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1913 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001914
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001915 final int callingUid = Binder.getCallingUid();
1916 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1917 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001918 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1919
1920 if (DEBUG_OBB)
1921 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001922 }
1923
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001924 @Override
1925 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1926 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1927
1928 final ObbState existingState;
1929 synchronized (mObbPathToStateMap) {
1930 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001931 }
1932
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001933 if (existingState != null) {
1934 // TODO: separate state object from request data
1935 final int callingUid = Binder.getCallingUid();
1936 final ObbState newState = new ObbState(
1937 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1938 final ObbAction action = new UnmountObbAction(newState, force);
1939 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001940
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001941 if (DEBUG_OBB)
1942 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1943 } else {
1944 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1945 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001946 }
1947
Ben Komalo444eca22011-09-01 15:17:44 -07001948 @Override
1949 public int getEncryptionState() {
1950 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1951 "no permission to access the crypt keeper");
1952
1953 waitForReady();
1954
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001955 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001956 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001957 event = mConnector.execute("cryptfs", "cryptocomplete");
1958 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001959 } catch (NumberFormatException e) {
1960 // Bad result - unexpected.
1961 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1962 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1963 } catch (NativeDaemonConnectorException e) {
1964 // Something bad happened.
1965 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1966 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1967 }
1968 }
1969
1970 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001971 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001972 if (TextUtils.isEmpty(password)) {
1973 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001974 }
1975
Jason parks8888c592011-01-20 22:46:41 -06001976 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1977 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06001978
1979 waitForReady();
1980
1981 if (DEBUG_EVENTS) {
1982 Slog.i(TAG, "decrypting storage...");
1983 }
1984
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001985 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06001986 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001987 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06001988
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01001989 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06001990 if (code == 0) {
1991 // Decrypt was successful. Post a delayed message before restarting in order
1992 // to let the UI to clear itself
1993 mHandler.postDelayed(new Runnable() {
1994 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001995 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001996 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001997 } catch (NativeDaemonConnectorException e) {
1998 Slog.e(TAG, "problem executing in background", e);
1999 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002000 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002001 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002002 }
2003
2004 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002005 } catch (NativeDaemonConnectorException e) {
2006 // Decryption failed
2007 return e.getCode();
2008 }
Jason parks5af0b912010-11-29 09:05:25 -06002009 }
2010
Jason parks56aa5322011-01-07 09:01:15 -06002011 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002012 if (TextUtils.isEmpty(password)) {
2013 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002014 }
2015
Jason parks8888c592011-01-20 22:46:41 -06002016 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2017 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002018
2019 waitForReady();
2020
2021 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002022 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002023 }
2024
2025 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002026 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002027 } catch (NativeDaemonConnectorException e) {
2028 // Encryption failed
2029 return e.getCode();
2030 }
2031
2032 return 0;
2033 }
2034
Jason parksf7b3cd42011-01-27 09:28:25 -06002035 public int changeEncryptionPassword(String password) {
2036 if (TextUtils.isEmpty(password)) {
2037 throw new IllegalArgumentException("password cannot be empty");
2038 }
2039
2040 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2041 "no permission to access the crypt keeper");
2042
2043 waitForReady();
2044
2045 if (DEBUG_EVENTS) {
2046 Slog.i(TAG, "changing encryption password...");
2047 }
2048
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002049 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002050 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002051 event = mConnector.execute("cryptfs", "changepw", password);
2052 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002053 } catch (NativeDaemonConnectorException e) {
2054 // Encryption failed
2055 return e.getCode();
2056 }
2057 }
2058
Christopher Tate32418be2011-10-10 13:51:12 -07002059 /**
2060 * Validate a user-supplied password string with cryptfs
2061 */
2062 @Override
2063 public int verifyEncryptionPassword(String password) throws RemoteException {
2064 // Only the system process is permitted to validate passwords
2065 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2066 throw new SecurityException("no permission to access the crypt keeper");
2067 }
2068
2069 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2070 "no permission to access the crypt keeper");
2071
2072 if (TextUtils.isEmpty(password)) {
2073 throw new IllegalArgumentException("password cannot be empty");
2074 }
2075
2076 waitForReady();
2077
2078 if (DEBUG_EVENTS) {
2079 Slog.i(TAG, "validating encryption password...");
2080 }
2081
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002082 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002083 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002084 event = mConnector.execute("cryptfs", "verifypw", password);
2085 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2086 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002087 } catch (NativeDaemonConnectorException e) {
2088 // Encryption failed
2089 return e.getCode();
2090 }
2091 }
2092
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002093 @Override
2094 public StorageVolume[] getVolumeList() {
2095 final int callingUserId = UserHandle.getCallingUserId();
2096 final boolean accessAll = (mContext.checkPermission(
2097 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2098 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2099
2100 synchronized (mVolumesLock) {
2101 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2102 for (StorageVolume volume : mVolumes) {
2103 final UserHandle owner = volume.getOwner();
2104 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2105 if (accessAll || ownerMatch) {
2106 filtered.add(volume);
2107 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002108 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002109 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002110 }
2111 }
2112
Kenny Rootaf9d6672010-10-08 09:21:39 -07002113 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2114 final IBinder binder = obbState.getBinder();
2115 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002116
Kenny Rootaf9d6672010-10-08 09:21:39 -07002117 if (obbStates == null) {
2118 obbStates = new ArrayList<ObbState>();
2119 mObbMounts.put(binder, obbStates);
2120 } else {
2121 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002122 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002123 throw new IllegalStateException("Attempt to add ObbState twice. "
2124 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002125 }
2126 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002127 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002128
2129 obbStates.add(obbState);
2130 try {
2131 obbState.link();
2132 } catch (RemoteException e) {
2133 /*
2134 * The binder died before we could link it, so clean up our state
2135 * and return failure.
2136 */
2137 obbStates.remove(obbState);
2138 if (obbStates.isEmpty()) {
2139 mObbMounts.remove(binder);
2140 }
2141
2142 // Rethrow the error so mountObb can get it
2143 throw e;
2144 }
2145
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002146 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002147 }
2148
Kenny Rootaf9d6672010-10-08 09:21:39 -07002149 private void removeObbStateLocked(ObbState obbState) {
2150 final IBinder binder = obbState.getBinder();
2151 final List<ObbState> obbStates = mObbMounts.get(binder);
2152 if (obbStates != null) {
2153 if (obbStates.remove(obbState)) {
2154 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002155 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002156 if (obbStates.isEmpty()) {
2157 mObbMounts.remove(binder);
2158 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002159 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002160
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002161 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002162 }
2163
Kenny Roota02b8b02010-08-05 16:14:17 -07002164 private class ObbActionHandler extends Handler {
2165 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002166 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002167
2168 ObbActionHandler(Looper l) {
2169 super(l);
2170 }
2171
2172 @Override
2173 public void handleMessage(Message msg) {
2174 switch (msg.what) {
2175 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002176 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002177
2178 if (DEBUG_OBB)
2179 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2180
2181 // If a bind was already initiated we don't really
2182 // need to do anything. The pending install
2183 // will be processed later on.
2184 if (!mBound) {
2185 // If this is the only one pending we might
2186 // have to bind to the service again.
2187 if (!connectToService()) {
2188 Slog.e(TAG, "Failed to bind to media container service");
2189 action.handleError();
2190 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002191 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002192 }
Kenny Root735de3b2010-09-30 14:11:39 -07002193
Kenny Root735de3b2010-09-30 14:11:39 -07002194 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002195 break;
2196 }
2197 case OBB_MCS_BOUND: {
2198 if (DEBUG_OBB)
2199 Slog.i(TAG, "OBB_MCS_BOUND");
2200 if (msg.obj != null) {
2201 mContainerService = (IMediaContainerService) msg.obj;
2202 }
2203 if (mContainerService == null) {
2204 // Something seriously wrong. Bail out
2205 Slog.e(TAG, "Cannot bind to media container service");
2206 for (ObbAction action : mActions) {
2207 // Indicate service bind error
2208 action.handleError();
2209 }
2210 mActions.clear();
2211 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002212 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002213 if (action != null) {
2214 action.execute(this);
2215 }
2216 } else {
2217 // Should never happen ideally.
2218 Slog.w(TAG, "Empty queue");
2219 }
2220 break;
2221 }
2222 case OBB_MCS_RECONNECT: {
2223 if (DEBUG_OBB)
2224 Slog.i(TAG, "OBB_MCS_RECONNECT");
2225 if (mActions.size() > 0) {
2226 if (mBound) {
2227 disconnectService();
2228 }
2229 if (!connectToService()) {
2230 Slog.e(TAG, "Failed to bind to media container service");
2231 for (ObbAction action : mActions) {
2232 // Indicate service bind error
2233 action.handleError();
2234 }
2235 mActions.clear();
2236 }
2237 }
2238 break;
2239 }
2240 case OBB_MCS_UNBIND: {
2241 if (DEBUG_OBB)
2242 Slog.i(TAG, "OBB_MCS_UNBIND");
2243
2244 // Delete pending install
2245 if (mActions.size() > 0) {
2246 mActions.remove(0);
2247 }
2248 if (mActions.size() == 0) {
2249 if (mBound) {
2250 disconnectService();
2251 }
2252 } else {
2253 // There are more pending requests in queue.
2254 // Just post MCS_BOUND message to trigger processing
2255 // of next pending install.
2256 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2257 }
2258 break;
2259 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002260 case OBB_FLUSH_MOUNT_STATE: {
2261 final String path = (String) msg.obj;
2262
2263 if (DEBUG_OBB)
2264 Slog.i(TAG, "Flushing all OBB state for path " + path);
2265
2266 synchronized (mObbMounts) {
2267 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2268
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002269 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002270 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002271 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272
2273 /*
2274 * If this entry's source file is in the volume path
2275 * that got unmounted, remove it because it's no
2276 * longer valid.
2277 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002278 if (state.canonicalPath.startsWith(path)) {
2279 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002280 }
2281 }
2282
2283 for (final ObbState obbState : obbStatesToRemove) {
2284 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002285 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002286
2287 removeObbStateLocked(obbState);
2288
2289 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002290 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002291 OnObbStateChangeListener.UNMOUNTED);
2292 } catch (RemoteException e) {
2293 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002294 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002295 }
2296 }
2297 }
2298 break;
2299 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002300 }
2301 }
2302
2303 private boolean connectToService() {
2304 if (DEBUG_OBB)
2305 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2306
2307 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2308 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2309 mBound = true;
2310 return true;
2311 }
2312 return false;
2313 }
2314
2315 private void disconnectService() {
2316 mContainerService = null;
2317 mBound = false;
2318 mContext.unbindService(mDefContainerConn);
2319 }
2320 }
2321
2322 abstract class ObbAction {
2323 private static final int MAX_RETRIES = 3;
2324 private int mRetries;
2325
2326 ObbState mObbState;
2327
2328 ObbAction(ObbState obbState) {
2329 mObbState = obbState;
2330 }
2331
2332 public void execute(ObbActionHandler handler) {
2333 try {
2334 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002335 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002336 mRetries++;
2337 if (mRetries > MAX_RETRIES) {
2338 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002339 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002340 handleError();
2341 return;
2342 } else {
2343 handleExecute();
2344 if (DEBUG_OBB)
2345 Slog.i(TAG, "Posting install MCS_UNBIND");
2346 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2347 }
2348 } catch (RemoteException e) {
2349 if (DEBUG_OBB)
2350 Slog.i(TAG, "Posting install MCS_RECONNECT");
2351 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2352 } catch (Exception e) {
2353 if (DEBUG_OBB)
2354 Slog.d(TAG, "Error handling OBB action", e);
2355 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002356 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002357 }
2358 }
2359
Kenny Root05105f72010-09-22 17:29:43 -07002360 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002361 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002362
2363 protected ObbInfo getObbInfo() throws IOException {
2364 ObbInfo obbInfo;
2365 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002366 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002367 } catch (RemoteException e) {
2368 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002369 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002370 obbInfo = null;
2371 }
2372 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002373 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002374 }
2375 return obbInfo;
2376 }
2377
Kenny Rootaf9d6672010-10-08 09:21:39 -07002378 protected void sendNewStatusOrIgnore(int status) {
2379 if (mObbState == null || mObbState.token == null) {
2380 return;
2381 }
2382
Kenny Root38cf8862010-09-26 14:18:51 -07002383 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002384 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002385 } catch (RemoteException e) {
2386 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2387 }
2388 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002389 }
2390
2391 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002392 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002393 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002394
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002396 super(obbState);
2397 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002398 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002399 }
2400
Jason parks5af0b912010-11-29 09:05:25 -06002401 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002402 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002403 waitForReady();
2404 warnOnNotMounted();
2405
Kenny Root38cf8862010-09-26 14:18:51 -07002406 final ObbInfo obbInfo = getObbInfo();
2407
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002408 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2410 + " which is owned by " + obbInfo.packageName);
2411 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2412 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002413 }
2414
Kenny Rootaf9d6672010-10-08 09:21:39 -07002415 final boolean isMounted;
2416 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002417 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002418 }
2419 if (isMounted) {
2420 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2421 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2422 return;
2423 }
2424
Kenny Rootaf9d6672010-10-08 09:21:39 -07002425 final String hashedKey;
2426 if (mKey == null) {
2427 hashedKey = "none";
2428 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002429 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002430 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2431
2432 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2433 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2434 SecretKey key = factory.generateSecret(ks);
2435 BigInteger bi = new BigInteger(key.getEncoded());
2436 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002437 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002438 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2439 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2440 return;
2441 } catch (InvalidKeySpecException e) {
2442 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2443 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002444 return;
2445 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002446 }
Kenny Root38cf8862010-09-26 14:18:51 -07002447
Kenny Rootaf9d6672010-10-08 09:21:39 -07002448 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002449 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002450 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002451 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 } catch (NativeDaemonConnectorException e) {
2453 int code = e.getCode();
2454 if (code != VoldResponseCode.OpFailedStorageBusy) {
2455 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002456 }
2457 }
2458
Kenny Rootaf9d6672010-10-08 09:21:39 -07002459 if (rc == StorageResultCode.OperationSucceeded) {
2460 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002461 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002462
2463 synchronized (mObbMounts) {
2464 addObbStateLocked(mObbState);
2465 }
2466
2467 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002468 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002469 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002470
Kenny Rootaf9d6672010-10-08 09:21:39 -07002471 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002472 }
2473 }
2474
Jason parks5af0b912010-11-29 09:05:25 -06002475 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002476 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002477 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002478 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002479
2480 @Override
2481 public String toString() {
2482 StringBuilder sb = new StringBuilder();
2483 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002484 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002485 sb.append('}');
2486 return sb.toString();
2487 }
2488 }
2489
2490 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002491 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002492
2493 UnmountObbAction(ObbState obbState, boolean force) {
2494 super(obbState);
2495 mForceUnmount = force;
2496 }
2497
Jason parks5af0b912010-11-29 09:05:25 -06002498 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002499 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002500 waitForReady();
2501 warnOnNotMounted();
2502
Kenny Root38cf8862010-09-26 14:18:51 -07002503 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002504
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002505 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002506 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002507 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002508 }
Kenny Root38cf8862010-09-26 14:18:51 -07002509
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002510 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002511 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2512 return;
2513 }
2514
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002515 if (existingState.ownerGid != mObbState.ownerGid) {
2516 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2517 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002518 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2519 return;
2520 }
2521
Kenny Rootaf9d6672010-10-08 09:21:39 -07002522 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002523 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002524 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002525 if (mForceUnmount) {
2526 cmd.appendArg("force");
2527 }
2528 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002529 } catch (NativeDaemonConnectorException e) {
2530 int code = e.getCode();
2531 if (code == VoldResponseCode.OpFailedStorageBusy) {
2532 rc = StorageResultCode.OperationFailedStorageBusy;
2533 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2534 // If it's not mounted then we've already won.
2535 rc = StorageResultCode.OperationSucceeded;
2536 } else {
2537 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002538 }
2539 }
2540
Kenny Rootaf9d6672010-10-08 09:21:39 -07002541 if (rc == StorageResultCode.OperationSucceeded) {
2542 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002543 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002544 }
2545
Kenny Rootaf9d6672010-10-08 09:21:39 -07002546 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002547 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002548 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002549 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002550 }
2551 }
2552
Jason parks5af0b912010-11-29 09:05:25 -06002553 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002554 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002555 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002556 }
2557
2558 @Override
2559 public String toString() {
2560 StringBuilder sb = new StringBuilder();
2561 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002562 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002563 sb.append(",force=");
2564 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002565 sb.append('}');
2566 return sb.toString();
2567 }
Kenny Root02c87302010-07-01 08:10:18 -07002568 }
Kenny Root38cf8862010-09-26 14:18:51 -07002569
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002570 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002571 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2572 // TODO: allow caller to provide Environment for full testing
2573
2574 // Only adjust paths when storage is emulated
2575 if (!Environment.isExternalStorageEmulated()) {
2576 return canonicalPath;
2577 }
2578
2579 String path = canonicalPath.toString();
2580
2581 // First trim off any external storage prefix
2582 final UserEnvironment userEnv = new UserEnvironment(userId);
2583
2584 // /storage/emulated/0
2585 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2586 // /storage/emulated_legacy
2587 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2588 .toString();
2589
2590 if (path.startsWith(externalPath)) {
2591 path = path.substring(externalPath.length() + 1);
2592 } else if (path.startsWith(legacyExternalPath)) {
2593 path = path.substring(legacyExternalPath.length() + 1);
2594 } else {
2595 return canonicalPath;
2596 }
2597
2598 // Handle special OBB paths on emulated storage
2599 final String obbPath = "Android/obb";
2600 if (path.startsWith(obbPath)) {
2601 path = path.substring(obbPath.length() + 1);
2602
2603 if (forVold) {
2604 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2605 } else {
2606 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2607 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2608 }
2609 }
2610
2611 // Handle normal external storage paths
2612 if (forVold) {
2613 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2614 } else {
2615 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2616 }
2617 }
2618
Kenny Root38cf8862010-09-26 14:18:51 -07002619 @Override
2620 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2621 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2622 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2623 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2624 + " without permission " + android.Manifest.permission.DUMP);
2625 return;
2626 }
2627
Kenny Root38cf8862010-09-26 14:18:51 -07002628 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002629 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002630
Kenny Rootaf9d6672010-10-08 09:21:39 -07002631 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2632 while (binders.hasNext()) {
2633 Entry<IBinder, List<ObbState>> e = binders.next();
2634 pw.print(" Key="); pw.println(e.getKey().toString());
2635 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002636 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002637 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002638 }
2639 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002640
2641 pw.println("");
2642 pw.println(" mObbPathToStateMap:");
2643 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2644 while (maps.hasNext()) {
2645 final Entry<String, ObbState> e = maps.next();
2646 pw.print(" "); pw.print(e.getKey());
2647 pw.print(" -> "); pw.println(e.getValue().toString());
2648 }
Kenny Root38cf8862010-09-26 14:18:51 -07002649 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002650
2651 pw.println("");
2652
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002653 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002654 pw.println(" mVolumes:");
2655
2656 final int N = mVolumes.size();
2657 for (int i = 0; i < N; i++) {
2658 final StorageVolume v = mVolumes.get(i);
2659 pw.print(" ");
2660 pw.println(v.toString());
2661 }
2662 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002663
2664 pw.println();
2665 pw.println(" mConnection:");
2666 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002669 /** {@inheritDoc} */
2670 public void monitor() {
2671 if (mConnector != null) {
2672 mConnector.monitor();
2673 }
2674 }
2675}