blob: e670ef9ba621258f25ff529dbfa0f2272736b310 [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;
Svetoslavf23b64d2013-04-25 14:45:54 -070046import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070049import android.os.storage.IMountService;
50import android.os.storage.IMountServiceListener;
51import android.os.storage.IMountShutdownObserver;
52import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070053import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070054import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070055import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060056import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070058import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.Xml;
60
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080061import com.android.internal.annotations.GuardedBy;
62import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070063import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070064import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070065import com.android.internal.util.XmlUtils;
66import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070067import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070068import com.android.server.am.ActivityManagerService;
69import com.android.server.pm.PackageManagerService;
70import com.android.server.pm.UserManagerService;
71import com.google.android.collect.Lists;
72import com.google.android.collect.Maps;
73
Mike Lockwood2f6a3882011-05-09 19:08:06 -070074import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070075
Jeff Sharkeyb049e212012-09-07 23:16:01 -070076import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070078import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070080import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070081import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070082import java.security.spec.InvalidKeySpecException;
83import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080084import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070085import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080086import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070087import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070088import java.util.LinkedList;
89import java.util.List;
90import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070091import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070092import java.util.concurrent.CountDownLatch;
93import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Kenny Root3b1abba2010-10-13 15:00:07 -070095import javax.crypto.SecretKey;
96import javax.crypto.SecretKeyFactory;
97import javax.crypto.spec.PBEKeySpec;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099/**
San Mehatb1043402010-02-05 08:26:50 -0800100 * MountService implements back-end services for platform storage
101 * management.
102 * @hide - Applications should use android.os.storage.StorageManager
103 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700105class MountService extends IMountService.Stub
106 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600107
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700108 // TODO: listen for user creation/deletion
109
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800110 private static final boolean LOCAL_LOGD = false;
111 private static final boolean DEBUG_UNMOUNT = false;
112 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800113 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700114
Kenny Root07714d42011-08-17 17:49:28 -0700115 // Disable this since it messes up long-running cryptfs operations.
116 private static final boolean WATCHDOG_ENABLE = false;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "MountService";
119
Kenny Root305bcbf2010-09-03 07:56:38 -0700120 private static final String VOLD_TAG = "VoldConnector";
121
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700122 /** Maximum number of ASEC containers allowed to be mounted. */
123 private static final int MAX_CONTAINERS = 250;
124
San Mehat4270e1e2010-01-29 05:32:19 -0800125 /*
126 * Internal vold volume state constants
127 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800128 class VolumeState {
129 public static final int Init = -1;
130 public static final int NoMedia = 0;
131 public static final int Idle = 1;
132 public static final int Pending = 2;
133 public static final int Checking = 3;
134 public static final int Mounted = 4;
135 public static final int Unmounting = 5;
136 public static final int Formatting = 6;
137 public static final int Shared = 7;
138 public static final int SharedMnt = 8;
139 }
140
San Mehat4270e1e2010-01-29 05:32:19 -0800141 /*
142 * Internal vold response code constants
143 */
San Mehat22dd86e2010-01-12 12:21:18 -0800144 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800145 /*
146 * 100 series - Requestion action was initiated; expect another reply
147 * before proceeding with a new command.
148 */
San Mehat22dd86e2010-01-12 12:21:18 -0800149 public static final int VolumeListResult = 110;
150 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800151 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800152
San Mehat4270e1e2010-01-29 05:32:19 -0800153 /*
154 * 200 series - Requestion action has been successfully completed.
155 */
156 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800157 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800158 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800159
San Mehat4270e1e2010-01-29 05:32:19 -0800160 /*
161 * 400 series - Command was accepted, but the requested action
162 * did not take place.
163 */
164 public static final int OpFailedNoMedia = 401;
165 public static final int OpFailedMediaBlank = 402;
166 public static final int OpFailedMediaCorrupt = 403;
167 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800168 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700169 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800170
171 /*
172 * 600 series - Unsolicited broadcasts.
173 */
San Mehat22dd86e2010-01-12 12:21:18 -0800174 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int VolumeDiskInserted = 630;
176 public static final int VolumeDiskRemoved = 631;
177 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700178
179 /*
180 * 700 series - fstrim
181 */
182 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800183 }
184
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700185 private Context mContext;
186 private NativeDaemonConnector mConnector;
187
188 private final Object mVolumesLock = new Object();
189
190 /** When defined, base template for user-specific {@link StorageVolume}. */
191 private StorageVolume mEmulatedTemplate;
192
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800193 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700194 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
195 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700197 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
198 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700200 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
201
202 private volatile boolean mSystemReady = false;
203
San Mehat4270e1e2010-01-29 05:32:19 -0800204 private PackageManagerService mPms;
205 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700206 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800207 // Used as a lock for methods that register/unregister listeners.
208 final private ArrayList<MountServiceBinderListener> mListeners =
209 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800210 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
211 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800212 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800213
San Mehat6cdd9c02010-02-09 14:45:20 -0800214 /**
215 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800216 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800217 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800218 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800219
Kenny Root02c87302010-07-01 08:10:18 -0700220 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700221 * The size of the crypto algorithm key in bits for OBB files. Currently
222 * Twofish is used which takes 128-bit keys.
223 */
224 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
225
226 /**
227 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
228 * 1024 is reasonably secure and not too slow.
229 */
230 private static final int PBKDF2_HASH_ROUNDS = 1024;
231
232 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700233 * Mounted OBB tracking information. Used to track the current state of all
234 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700235 */
Kenny Root735de3b2010-09-30 14:11:39 -0700236 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700237
238 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700239 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
240
241 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700242 public ObbState(String rawPath, String canonicalPath, int callingUid,
243 IObbActionListener token, int nonce) {
244 this.rawPath = rawPath;
245 this.canonicalPath = canonicalPath.toString();
246
247 final int userId = UserHandle.getUserId(callingUid);
248 this.ownerPath = buildObbPath(canonicalPath, userId, false);
249 this.voldPath = buildObbPath(canonicalPath, userId, true);
250
251 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700252 this.token = token;
253 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700254 }
255
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700256 final String rawPath;
257 final String canonicalPath;
258 final String ownerPath;
259 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700260
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700261 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262
Kenny Rootaf9d6672010-10-08 09:21:39 -0700263 // Token of remote Binder caller
264 final IObbActionListener token;
265
266 // Identifier to pass back to the token
267 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
Kenny Root735de3b2010-09-30 14:11:39 -0700269 public IBinder getBinder() {
270 return token.asBinder();
271 }
272
Kenny Roota02b8b02010-08-05 16:14:17 -0700273 @Override
274 public void binderDied() {
275 ObbAction action = new UnmountObbAction(this, true);
276 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700277 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700278
Kenny Root5919ac62010-10-05 09:49:40 -0700279 public void link() throws RemoteException {
280 getBinder().linkToDeath(this, 0);
281 }
282
283 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700284 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700285 }
Kenny Root38cf8862010-09-26 14:18:51 -0700286
287 @Override
288 public String toString() {
289 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700290 sb.append("rawPath=").append(rawPath);
291 sb.append(",canonicalPath=").append(canonicalPath);
292 sb.append(",ownerPath=").append(ownerPath);
293 sb.append(",voldPath=").append(voldPath);
294 sb.append(",ownerGid=").append(ownerGid);
295 sb.append(",token=").append(token);
296 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700297 sb.append('}');
298 return sb.toString();
299 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700300 }
301
302 // OBB Action Handler
303 final private ObbActionHandler mObbActionHandler;
304
305 // OBB action handler messages
306 private static final int OBB_RUN_ACTION = 1;
307 private static final int OBB_MCS_BOUND = 2;
308 private static final int OBB_MCS_UNBIND = 3;
309 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700310 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700311
312 /*
313 * Default Container Service information
314 */
315 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
316 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
317
318 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
319
320 class DefaultContainerConnection implements ServiceConnection {
321 public void onServiceConnected(ComponentName name, IBinder service) {
322 if (DEBUG_OBB)
323 Slog.i(TAG, "onServiceConnected");
324 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
325 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
326 }
327
328 public void onServiceDisconnected(ComponentName name) {
329 if (DEBUG_OBB)
330 Slog.i(TAG, "onServiceDisconnected");
331 }
332 };
333
334 // Used in the ObbActionHandler
335 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700336
337 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 private static final int H_UNMOUNT_PM_UPDATE = 1;
339 private static final int H_UNMOUNT_PM_DONE = 2;
340 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700341 private static final int H_SYSTEM_READY = 4;
342
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
344 private static final int MAX_UNMOUNT_RETRIES = 4;
345
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700347 final String path;
348 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700349 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800351
Ben Komalo13c71972011-09-07 16:35:56 -0700352 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 retries = 0;
354 this.path = path;
355 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700356 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800357 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800358
359 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700360 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700361 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800362 }
363 }
364
365 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700366 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800367
368 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700369 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370 this.method = method;
371 }
372
373 @Override
374 void handleFinished() {
375 super.handleFinished();
376 doShareUnshareVolume(path, method, true);
377 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800378 }
379
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 class ShutdownCallBack extends UnmountCallBack {
381 IMountShutdownObserver observer;
382 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700383 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800384 this.observer = observer;
385 }
386
387 @Override
388 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700389 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800390 if (observer != null) {
391 try {
392 observer.onShutDownComplete(ret);
393 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700394 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800395 }
396 }
397 }
398 }
399
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400400 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700402 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400404 MountServiceHandler(Looper l) {
405 super(l);
406 }
407
Jason parks5af0b912010-11-29 09:05:25 -0600408 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 public void handleMessage(Message msg) {
410 switch (msg.what) {
411 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700412 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800413 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
414 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800416 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700417 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700419 mUpdatingStatus = true;
420 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 }
422 break;
423 }
424 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700425 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700426 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700427 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800428 int size = mForceUnmounts.size();
429 int sizeArr[] = new int[size];
430 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700431 // Kill processes holding references first
432 ActivityManagerService ams = (ActivityManagerService)
433 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 for (int i = 0; i < size; i++) {
435 UnmountCallBack ucb = mForceUnmounts.get(i);
436 String path = ucb.path;
437 boolean done = false;
438 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 done = true;
440 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800441 int pids[] = getStorageUsers(path);
442 if (pids == null || pids.length == 0) {
443 done = true;
444 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800445 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800446 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700447 // Confirm if file references have been freed.
448 pids = getStorageUsers(path);
449 if (pids == null || pids.length == 0) {
450 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800451 }
452 }
453 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700454 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
455 // Retry again
456 Slog.i(TAG, "Retrying to kill storage users again");
457 mHandler.sendMessageDelayed(
458 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
459 ucb.retries++),
460 RETRY_UNMOUNT_DELAY);
461 } else {
462 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
463 Slog.i(TAG, "Failed to unmount media inspite of " +
464 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
465 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800466 sizeArr[sizeArrN++] = i;
467 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
468 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800469 }
470 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800471 // Remove already processed elements from list.
472 for (int i = (sizeArrN-1); i >= 0; i--) {
473 mForceUnmounts.remove(sizeArr[i]);
474 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800475 break;
476 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700477 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700478 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800479 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800480 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800481 break;
482 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700483 case H_SYSTEM_READY: {
484 try {
485 handleSystemReady();
486 } catch (Exception ex) {
487 Slog.e(TAG, "Boot-time mount exception", ex);
488 }
489 break;
490 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800491 }
492 }
493 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700494
495 private final HandlerThread mHandlerThread;
496 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800497
Kenny Root51a573c2012-05-17 13:30:28 -0700498 void waitForAsecScan() {
499 waitForLatch(mAsecsScanned);
500 }
501
San Mehat207e5382010-02-04 20:46:54 -0800502 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700503 waitForLatch(mConnectedSignal);
504 }
505
506 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700507 for (;;) {
508 try {
509 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800510 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700511 } else {
512 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
513 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800514 }
Kenny Root51a573c2012-05-17 13:30:28 -0700515 } catch (InterruptedException e) {
516 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800517 }
San Mehat207e5382010-02-04 20:46:54 -0800518 }
San Mehat1f6301e2010-01-07 22:40:27 -0800519 }
Kenny Root02c87302010-07-01 08:10:18 -0700520
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700521 private void handleSystemReady() {
522 // Snapshot current volume states since it's not safe to call into vold
523 // while holding locks.
524 final HashMap<String, String> snapshot;
525 synchronized (mVolumesLock) {
526 snapshot = new HashMap<String, String>(mVolumeStates);
527 }
528
529 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
530 final String path = entry.getKey();
531 final String state = entry.getValue();
532
533 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
534 int rc = doMountVolume(path);
535 if (rc != StorageResultCode.OperationSucceeded) {
536 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
537 rc));
538 }
539 } else if (state.equals(Environment.MEDIA_SHARED)) {
540 /*
541 * Bootstrap UMS enabled state since vold indicates
542 * the volume is shared (runtime restart while ums enabled)
543 */
544 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
545 VolumeState.Shared);
546 }
547 }
548
549 // Push mounted state for all emulated storage
550 synchronized (mVolumesLock) {
551 for (StorageVolume volume : mVolumes) {
552 if (volume.isEmulated()) {
553 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
554 }
555 }
556 }
557
558 /*
559 * If UMS was connected on boot, send the connected event
560 * now that we're up.
561 */
562 if (mSendUmsConnectedOnBoot) {
563 sendUmsIntent(true);
564 mSendUmsConnectedOnBoot = false;
565 }
566 }
567
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700568 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
569 @Override
570 public void onReceive(Context context, Intent intent) {
571 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
572 if (userId == -1) return;
573 final UserHandle user = new UserHandle(userId);
574
575 final String action = intent.getAction();
576 if (Intent.ACTION_USER_ADDED.equals(action)) {
577 synchronized (mVolumesLock) {
578 createEmulatedVolumeForUserLocked(user);
579 }
580
581 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
582 synchronized (mVolumesLock) {
583 final List<StorageVolume> toRemove = Lists.newArrayList();
584 for (StorageVolume volume : mVolumes) {
585 if (user.equals(volume.getOwner())) {
586 toRemove.add(volume);
587 }
588 }
589 for (StorageVolume volume : toRemove) {
590 removeVolumeLocked(volume);
591 }
592 }
593 }
594 }
595 };
596
597 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
598 @Override
599 public void onReceive(Context context, Intent intent) {
600 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
601 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
602 notifyShareAvailabilityChange(available);
603 }
604 };
605
Svetoslava7452ee2013-03-20 12:06:59 -0700606 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
607 @Override
608 public void onReceive(Context context, Intent intent) {
609 waitForReady();
610 String action = intent.getAction();
611 // Since fstrim will be run on a daily basis we do not expect
612 // fstrim to be too long, so it is not interruptible. We will
613 // implement interruption only in case we see issues.
614 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
615 try {
616 // This method runs on the handler thread,
617 // so it is safe to directly call into vold.
618 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700619 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700620 } catch (NativeDaemonConnectorException ndce) {
621 Slog.e(TAG, "Failed to run fstrim!");
622 }
623 }
624 }
625 };
626
San Mehat4270e1e2010-01-29 05:32:19 -0800627 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
628 final IMountServiceListener mListener;
629
630 MountServiceBinderListener(IMountServiceListener listener) {
631 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700632
San Mehat91c77612010-01-07 10:39:41 -0800633 }
634
San Mehat4270e1e2010-01-29 05:32:19 -0800635 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700636 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700637 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800638 mListeners.remove(this);
639 mListener.asBinder().unlinkToDeath(this, 0);
640 }
641 }
642 }
643
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800644 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800645 // TODO: Add support for multiple share methods
646 if (!method.equals("ums")) {
647 throw new IllegalArgumentException(String.format("Method %s not supported", method));
648 }
649
San Mehat4270e1e2010-01-29 05:32:19 -0800650 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800651 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800652 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700653 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800654 }
San Mehat4270e1e2010-01-29 05:32:19 -0800655 }
656
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700657 private void updatePublicVolumeState(StorageVolume volume, String state) {
658 final String path = volume.getPath();
659 final String oldState;
660 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400661 oldState = mVolumeStates.put(path, state);
662 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700663
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400664 if (state.equals(oldState)) {
665 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
666 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800667 return;
668 }
San Mehatb1043402010-02-05 08:26:50 -0800669
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400670 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700671
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700672 // Tell PackageManager about changes to primary volume state, but only
673 // when not emulated.
674 if (volume.isPrimary() && !volume.isEmulated()) {
675 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
676 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400677
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700678 /*
679 * Some OBBs might have been unmounted when this volume was
680 * unmounted, so send a message to the handler to let it know to
681 * remove those from the list of mounted OBBS.
682 */
683 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
684 OBB_FLUSH_MOUNT_STATE, path));
685 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
686 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400687 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800688 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700689
San Mehat4270e1e2010-01-29 05:32:19 -0800690 synchronized (mListeners) {
691 for (int i = mListeners.size() -1; i >= 0; i--) {
692 MountServiceBinderListener bl = mListeners.get(i);
693 try {
San Mehatb1043402010-02-05 08:26:50 -0800694 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800695 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700696 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800697 mListeners.remove(i);
698 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700699 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800700 }
701 }
702 }
703 }
704
705 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800706 * Callback from NativeDaemonConnector
707 */
708 public void onDaemonConnected() {
709 /*
710 * Since we'll be calling back into the NativeDaemonConnector,
711 * we need to do our work in a new thread.
712 */
Kenny Root51a573c2012-05-17 13:30:28 -0700713 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600714 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800715 public void run() {
716 /**
717 * Determine media state and UMS detection status
718 */
San Mehat4270e1e2010-01-29 05:32:19 -0800719 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800720 final String[] vols = NativeDaemonEvent.filterMessageList(
721 mConnector.executeForList("volume", "list"),
722 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800723 for (String volstr : vols) {
724 String[] tok = volstr.split(" ");
725 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400726 String path = tok[1];
727 String state = Environment.MEDIA_REMOVED;
728
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700729 final StorageVolume volume;
730 synchronized (mVolumesLock) {
731 volume = mVolumesByPath.get(path);
732 }
733
San Mehat4270e1e2010-01-29 05:32:19 -0800734 int st = Integer.parseInt(tok[2]);
735 if (st == VolumeState.NoMedia) {
736 state = Environment.MEDIA_REMOVED;
737 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800738 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800739 } else if (st == VolumeState.Mounted) {
740 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700741 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800742 } else if (st == VolumeState.Shared) {
743 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700744 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800745 } else {
746 throw new Exception(String.format("Unexpected state %d", st));
747 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400748
749 if (state != null) {
750 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700751 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400752 }
San Mehat4270e1e2010-01-29 05:32:19 -0800753 }
754 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700755 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700756 final StorageVolume primary = getPrimaryPhysicalVolume();
757 if (primary != null) {
758 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
759 }
San Mehat4270e1e2010-01-29 05:32:19 -0800760 }
761
San Mehat207e5382010-02-04 20:46:54 -0800762 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600763 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800764 * the hounds!
765 */
Kenny Root51a573c2012-05-17 13:30:28 -0700766 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700767
768 // Let package manager load internal ASECs.
769 mPms.scanAvailableAsecs();
770
771 // Notify people waiting for ASECs to be scanned that it's done.
772 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800773 }
774 }.start();
775 }
776
777 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800778 * Callback from NativeDaemonConnector
779 */
780 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800781 if (DEBUG_EVENTS) {
782 StringBuilder builder = new StringBuilder();
783 builder.append("onEvent::");
784 builder.append(" raw= " + raw);
785 if (cooked != null) {
786 builder.append(" cooked = " );
787 for (String str : cooked) {
788 builder.append(" " + str);
789 }
790 }
San Mehata5078592010-03-25 09:36:54 -0700791 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800792 }
San Mehat4270e1e2010-01-29 05:32:19 -0800793 if (code == VoldResponseCode.VolumeStateChange) {
794 /*
795 * One of the volumes we're managing has changed state.
796 * Format: "NNN Volume <label> <path> state changed
797 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
798 */
799 notifyVolumeStateChange(
800 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
801 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800802 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
803 (code == VoldResponseCode.VolumeDiskRemoved) ||
804 (code == VoldResponseCode.VolumeBadRemoval)) {
805 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
806 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
807 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800809 final String label = cooked[2];
810 final String path = cooked[3];
811 int major = -1;
812 int minor = -1;
813
814 try {
815 String devComp = cooked[6].substring(1, cooked[6].length() -1);
816 String[] devTok = devComp.split(":");
817 major = Integer.parseInt(devTok[0]);
818 minor = Integer.parseInt(devTok[1]);
819 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700820 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800821 }
822
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700823 final StorageVolume volume;
824 final String state;
825 synchronized (mVolumesLock) {
826 volume = mVolumesByPath.get(path);
827 state = mVolumeStates.get(path);
828 }
829
San Mehat4270e1e2010-01-29 05:32:19 -0800830 if (code == VoldResponseCode.VolumeDiskInserted) {
831 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600832 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800833 public void run() {
834 try {
835 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800836 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700837 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800838 }
839 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700840 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800841 }
842 }
843 }.start();
844 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
845 /*
846 * This event gets trumped if we're already in BAD_REMOVAL state
847 */
848 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
849 return true;
850 }
851 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700852 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700853 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
854 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800855
San Mehata5078592010-03-25 09:36:54 -0700856 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700857 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400858 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800859 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700860 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800861 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700862 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200863 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800864
San Mehata5078592010-03-25 09:36:54 -0700865 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700866 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400867 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700868 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700869 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800870 } else {
San Mehata5078592010-03-25 09:36:54 -0700871 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800872 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400873
874 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700875 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400876 }
San Mehat4270e1e2010-01-29 05:32:19 -0800877 } else {
878 return false;
879 }
880
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400881 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800882 }
883
San Mehat207e5382010-02-04 20:46:54 -0800884 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700885 final StorageVolume volume;
886 final String state;
887 synchronized (mVolumesLock) {
888 volume = mVolumesByPath.get(path);
889 state = getVolumeState(path);
890 }
891
892 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800893
Mike Lockwooda5250c92011-05-23 13:44:04 -0400894 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800895
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500896 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700897 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700898 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500899 }
900
San Mehat4270e1e2010-01-29 05:32:19 -0800901 if (newState == VolumeState.Init) {
902 } else if (newState == VolumeState.NoMedia) {
903 // NoMedia is handled via Disk Remove events
904 } else if (newState == VolumeState.Idle) {
905 /*
906 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
907 * if we're in the process of enabling UMS
908 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700909 if (!state.equals(
910 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
911 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800912 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700913 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700914 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400915 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800916 }
917 } else if (newState == VolumeState.Pending) {
918 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700919 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700920 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400921 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800922 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700923 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700924 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400925 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800926 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400927 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800928 } else if (newState == VolumeState.Formatting) {
929 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700930 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800931 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700932 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
933 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800934
San Mehata5078592010-03-25 09:36:54 -0700935 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700936 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400937 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700938 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800939 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700940 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800941 return;
942 } else {
San Mehata5078592010-03-25 09:36:54 -0700943 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800944 }
945
Mike Lockwooda5250c92011-05-23 13:44:04 -0400946 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700947 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800948 }
949 }
950
San Mehat207e5382010-02-04 20:46:54 -0800951 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800952 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800953
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700954 final StorageVolume volume;
955 synchronized (mVolumesLock) {
956 volume = mVolumesByPath.get(path);
957 }
958
San Mehata5078592010-03-25 09:36:54 -0700959 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800960 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800961 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800962 } catch (NativeDaemonConnectorException e) {
963 /*
964 * Mount failed for some reason
965 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400966 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800967 int code = e.getCode();
968 if (code == VoldResponseCode.OpFailedNoMedia) {
969 /*
970 * Attempt to mount but no media inserted
971 */
San Mehatb1043402010-02-05 08:26:50 -0800972 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800973 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700974 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800975 /*
976 * Media is blank or does not contain a supported filesystem
977 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700978 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400979 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800980 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800981 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700982 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800983 /*
984 * Volume consistency check failed
985 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700986 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400987 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800988 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800989 } else {
San Mehatb1043402010-02-05 08:26:50 -0800990 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800991 }
992
993 /*
994 * Send broadcast intent (if required for the failure)
995 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400996 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700997 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800998 }
999 }
1000
1001 return rc;
1002 }
1003
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001004 /*
1005 * If force is not set, we do not unmount if there are
1006 * processes holding references to the volume about to be unmounted.
1007 * If force is set, all the processes holding references need to be
1008 * killed via the ActivityManager before actually unmounting the volume.
1009 * This might even take a while and might be retried after timed delays
1010 * to make sure we dont end up in an instable state and kill some core
1011 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001012 * If removeEncryption is set, force is implied, and the system will remove any encryption
1013 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001014 */
Ben Komalo13c71972011-09-07 16:35:56 -07001015 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001016 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001017 return VoldResponseCode.OpFailedVolNotMounted;
1018 }
Kenny Rootaa485402010-09-14 14:49:41 -07001019
1020 /*
1021 * Force a GC to make sure AssetManagers in other threads of the
1022 * system_server are cleaned up. We have to do this since AssetManager
1023 * instances are kept as a WeakReference and it's possible we have files
1024 * open on the external storage.
1025 */
1026 Runtime.getRuntime().gc();
1027
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001028 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001029 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001030 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001031 final Command cmd = new Command("volume", "unmount", path);
1032 if (removeEncryption) {
1033 cmd.appendArg("force_and_revert");
1034 } else if (force) {
1035 cmd.appendArg("force");
1036 }
1037 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001038 // We unmounted the volume. None of the asec containers are available now.
1039 synchronized (mAsecMountSet) {
1040 mAsecMountSet.clear();
1041 }
San Mehatb1043402010-02-05 08:26:50 -08001042 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001043 } catch (NativeDaemonConnectorException e) {
1044 // Don't worry about mismatch in PackageManager since the
1045 // call back will handle the status changes any way.
1046 int code = e.getCode();
1047 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001048 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001049 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1050 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001051 } else {
San Mehatb1043402010-02-05 08:26:50 -08001052 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001053 }
1054 }
1055 }
1056
1057 private int doFormatVolume(String path) {
1058 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001059 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001060 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001061 } catch (NativeDaemonConnectorException e) {
1062 int code = e.getCode();
1063 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001064 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001065 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001066 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001067 } else {
San Mehatb1043402010-02-05 08:26:50 -08001068 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001069 }
1070 }
1071 }
1072
San Mehatb1043402010-02-05 08:26:50 -08001073 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001074 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001075 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001076 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001077 } catch (NativeDaemonConnectorException ex) {
1078 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1079 return false;
1080 }
San Mehatb1043402010-02-05 08:26:50 -08001081
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001082 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1083 return event.getMessage().endsWith("enabled");
1084 } else {
1085 return false;
San Mehatb1043402010-02-05 08:26:50 -08001086 }
San Mehatb1043402010-02-05 08:26:50 -08001087 }
1088
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001089 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001090 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001091 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001092 for (int i = mListeners.size() -1; i >= 0; i--) {
1093 MountServiceBinderListener bl = mListeners.get(i);
1094 try {
San Mehatb1043402010-02-05 08:26:50 -08001095 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001096 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001097 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001098 mListeners.remove(i);
1099 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001100 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001101 }
1102 }
1103 }
1104
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001105 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001106 sendUmsIntent(avail);
1107 } else {
1108 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001109 }
San Mehat2fe718a2010-03-11 12:01:49 -08001110
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001111 final StorageVolume primary = getPrimaryPhysicalVolume();
1112 if (avail == false && primary != null
1113 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1114 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001115 /*
1116 * USB mass storage disconnected while enabled
1117 */
1118 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -06001119 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001120 public void run() {
1121 try {
1122 int rc;
San Mehata5078592010-03-25 09:36:54 -07001123 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001124 doShareUnshareVolume(path, "ums", false);
1125 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001126 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001127 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1128 path, rc));
1129 }
1130 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001131 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001132 }
1133 }
1134 }.start();
1135 }
San Mehat4270e1e2010-01-29 05:32:19 -08001136 }
1137
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001138 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1139 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1140 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1141 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1142 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001143 }
1144
San Mehat6a965af22010-02-24 17:47:30 -08001145 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001146 mContext.sendBroadcastAsUser(
1147 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1148 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001149 }
1150
San Mehat207e5382010-02-04 20:46:54 -08001151 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001152 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1153 throw new SecurityException(String.format("Requires %s permission", perm));
1154 }
1155 }
1156
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001157 // Storage list XML tags
1158 private static final String TAG_STORAGE_LIST = "StorageList";
1159 private static final String TAG_STORAGE = "storage";
1160
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001161 private void readStorageListLocked() {
1162 mVolumes.clear();
1163 mVolumeStates.clear();
1164
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001165 Resources resources = mContext.getResources();
1166
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001167 int id = com.android.internal.R.xml.storage_list;
1168 XmlResourceParser parser = resources.getXml(id);
1169 AttributeSet attrs = Xml.asAttributeSet(parser);
1170
1171 try {
1172 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1173 while (true) {
1174 XmlUtils.nextElement(parser);
1175
1176 String element = parser.getName();
1177 if (element == null) break;
1178
1179 if (TAG_STORAGE.equals(element)) {
1180 TypedArray a = resources.obtainAttributes(attrs,
1181 com.android.internal.R.styleable.Storage);
1182
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001183 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001184 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001185 int descriptionId = a.getResourceId(
1186 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001187 CharSequence description = a.getText(
1188 com.android.internal.R.styleable.Storage_storageDescription);
1189 boolean primary = a.getBoolean(
1190 com.android.internal.R.styleable.Storage_primary, false);
1191 boolean removable = a.getBoolean(
1192 com.android.internal.R.styleable.Storage_removable, false);
1193 boolean emulated = a.getBoolean(
1194 com.android.internal.R.styleable.Storage_emulated, false);
1195 int mtpReserve = a.getInt(
1196 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001197 boolean allowMassStorage = a.getBoolean(
1198 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001199 // resource parser does not support longs, so XML value is in megabytes
1200 long maxFileSize = a.getInt(
1201 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001202
1203 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1204 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001205 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001206 " allowMassStorage: " + allowMassStorage +
1207 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001208
1209 if (emulated) {
1210 // For devices with emulated storage, we create separate
1211 // volumes for each known user.
1212 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1213 true, mtpReserve, false, maxFileSize, null);
1214
1215 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001216 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001217 createEmulatedVolumeForUserLocked(user.getUserHandle());
1218 }
1219
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001220 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001221 if (path == null || description == null) {
1222 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001223 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001224 final StorageVolume volume = new StorageVolume(new File(path),
1225 descriptionId, primary, removable, emulated, mtpReserve,
1226 allowMassStorage, maxFileSize, null);
1227 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001228 }
1229 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001230
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001231 a.recycle();
1232 }
1233 }
1234 } catch (XmlPullParserException e) {
1235 throw new RuntimeException(e);
1236 } catch (IOException e) {
1237 throw new RuntimeException(e);
1238 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001239 // Compute storage ID for each physical volume; emulated storage is
1240 // always 0 when defined.
1241 int index = isExternalStorageEmulated() ? 1 : 0;
1242 for (StorageVolume volume : mVolumes) {
1243 if (!volume.isEmulated()) {
1244 volume.setStorageId(index++);
1245 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001246 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001247 parser.close();
1248 }
1249 }
1250
San Mehat4270e1e2010-01-29 05:32:19 -08001251 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001252 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1253 * using {@link #mEmulatedTemplate} as template.
1254 */
1255 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1256 if (mEmulatedTemplate == null) {
1257 throw new IllegalStateException("Missing emulated volume multi-user template");
1258 }
1259
1260 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1261 final File path = userEnv.getExternalStorageDirectory();
1262 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1263 volume.setStorageId(0);
1264 addVolumeLocked(volume);
1265
1266 if (mSystemReady) {
1267 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1268 } else {
1269 // Place stub status for early callers to find
1270 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1271 }
1272 }
1273
1274 private void addVolumeLocked(StorageVolume volume) {
1275 Slog.d(TAG, "addVolumeLocked() " + volume);
1276 mVolumes.add(volume);
1277 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1278 if (existing != null) {
1279 throw new IllegalStateException(
1280 "Volume at " + volume.getPath() + " already exists: " + existing);
1281 }
1282 }
1283
1284 private void removeVolumeLocked(StorageVolume volume) {
1285 Slog.d(TAG, "removeVolumeLocked() " + volume);
1286 mVolumes.remove(volume);
1287 mVolumesByPath.remove(volume.getPath());
1288 mVolumeStates.remove(volume.getPath());
1289 }
1290
1291 private StorageVolume getPrimaryPhysicalVolume() {
1292 synchronized (mVolumesLock) {
1293 for (StorageVolume volume : mVolumes) {
1294 if (volume.isPrimary() && !volume.isEmulated()) {
1295 return volume;
1296 }
1297 }
1298 }
1299 return null;
1300 }
1301
1302 /**
San Mehat207e5382010-02-04 20:46:54 -08001303 * Constructs a new MountService instance
1304 *
1305 * @param context Binder context for this service
1306 */
1307 public MountService(Context context) {
1308 mContext = context;
1309
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001310 synchronized (mVolumesLock) {
1311 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001312 }
1313
San Mehat207e5382010-02-04 20:46:54 -08001314 // XXX: This will go away soon in favor of IMountServiceObserver
1315 mPms = (PackageManagerService) ServiceManager.getService("package");
1316
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001317 mHandlerThread = new HandlerThread("MountService");
1318 mHandlerThread.start();
1319 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1320
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001321 // Watch for user changes
1322 final IntentFilter userFilter = new IntentFilter();
1323 userFilter.addAction(Intent.ACTION_USER_ADDED);
1324 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1325 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1326
1327 // Watch for USB changes on primary volume
1328 final StorageVolume primary = getPrimaryPhysicalVolume();
1329 if (primary != null && primary.allowMassStorage()) {
1330 mContext.registerReceiver(
1331 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1332 }
1333
Svetoslava7452ee2013-03-20 12:06:59 -07001334 // Watch for idle maintenance changes
1335 IntentFilter idleMaintenanceFilter = new IntentFilter();
1336 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1337 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1338 idleMaintenanceFilter, null, mHandler);
1339
Kenny Roota02b8b02010-08-05 16:14:17 -07001340 // Add OBB Action Handler to MountService thread.
1341 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1342
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001343 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001344 * Create the connection to vold with a maximum queue of twice the
1345 * amount of containers we'd ever expect to have. This keeps an
1346 * "asec list" from blocking a thread repeatedly.
1347 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001348 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001349
Kenny Root305bcbf2010-09-03 07:56:38 -07001350 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001351 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001352
Kenny Root07714d42011-08-17 17:49:28 -07001353 // Add ourself to the Watchdog monitors if enabled.
1354 if (WATCHDOG_ENABLE) {
1355 Watchdog.getInstance().addMonitor(this);
1356 }
San Mehat207e5382010-02-04 20:46:54 -08001357 }
1358
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001359 public void systemReady() {
1360 mSystemReady = true;
1361 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1362 }
1363
San Mehat207e5382010-02-04 20:46:54 -08001364 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001365 * Exposed API calls below here
1366 */
1367
1368 public void registerListener(IMountServiceListener listener) {
1369 synchronized (mListeners) {
1370 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1371 try {
1372 listener.asBinder().linkToDeath(bl, 0);
1373 mListeners.add(bl);
1374 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001375 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001376 }
1377 }
1378 }
1379
1380 public void unregisterListener(IMountServiceListener listener) {
1381 synchronized (mListeners) {
1382 for(MountServiceBinderListener bl : mListeners) {
1383 if (bl.mListener == listener) {
1384 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001385 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001386 return;
1387 }
1388 }
1389 }
1390 }
1391
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001392 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001393 validatePermission(android.Manifest.permission.SHUTDOWN);
1394
San Mehata5078592010-03-25 09:36:54 -07001395 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001396 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001397 for (String path : mVolumeStates.keySet()) {
1398 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001399
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001400 if (state.equals(Environment.MEDIA_SHARED)) {
1401 /*
1402 * If the media is currently shared, unshare it.
1403 * XXX: This is still dangerous!. We should not
1404 * be rebooting at *all* if UMS is enabled, since
1405 * the UMS host could have dirty FAT cache entries
1406 * yet to flush.
1407 */
1408 setUsbMassStorageEnabled(false);
1409 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1410 /*
1411 * If the media is being checked, then we need to wait for
1412 * it to complete before being able to proceed.
1413 */
1414 // XXX: @hackbod - Should we disable the ANR timer here?
1415 int retries = 30;
1416 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1417 try {
1418 Thread.sleep(1000);
1419 } catch (InterruptedException iex) {
1420 Slog.e(TAG, "Interrupted while waiting for media", iex);
1421 break;
1422 }
1423 state = Environment.getExternalStorageState();
1424 }
1425 if (retries == 0) {
1426 Slog.e(TAG, "Timed out waiting for media to check");
1427 }
San Mehat91c77612010-01-07 10:39:41 -08001428 }
San Mehat91c77612010-01-07 10:39:41 -08001429
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001430 if (state.equals(Environment.MEDIA_MOUNTED)) {
1431 // Post a unmount message.
1432 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1433 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1434 } else if (observer != null) {
1435 /*
1436 * Observer is waiting for onShutDownComplete when we are done.
1437 * Since nothing will be done send notification directly so shutdown
1438 * sequence can continue.
1439 */
1440 try {
1441 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1442 } catch (RemoteException e) {
1443 Slog.w(TAG, "RemoteException when shutting down");
1444 }
1445 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001446 }
San Mehat4270e1e2010-01-29 05:32:19 -08001447 }
1448 }
1449
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001450 private boolean getUmsEnabling() {
1451 synchronized (mListeners) {
1452 return mUmsEnabling;
1453 }
1454 }
1455
1456 private void setUmsEnabling(boolean enable) {
1457 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001458 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001459 }
1460 }
1461
San Mehatb1043402010-02-05 08:26:50 -08001462 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001463 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001464
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001465 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001466 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001467 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001468 synchronized (mListeners) {
1469 return mUmsAvailable;
1470 }
San Mehatb1043402010-02-05 08:26:50 -08001471 }
1472
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001473 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001474 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001475 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001476
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001477 final StorageVolume primary = getPrimaryPhysicalVolume();
1478 if (primary == null) return;
1479
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001480 // TODO: Add support for multiple share methods
1481
1482 /*
1483 * If the volume is mounted and we're enabling then unmount it
1484 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001485 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001486 String vs = getVolumeState(path);
1487 String method = "ums";
1488 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1489 // Override for isUsbMassStorageEnabled()
1490 setUmsEnabling(enable);
1491 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1492 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1493 // Clear override
1494 setUmsEnabling(false);
1495 }
1496 /*
1497 * If we disabled UMS then mount the volume
1498 */
1499 if (!enable) {
1500 doShareUnshareVolume(path, method, enable);
1501 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001502 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001503 " after disabling share method " + method);
1504 /*
1505 * Even though the mount failed, the unshare didn't so don't indicate an error.
1506 * The mountVolume() call will have set the storage state and sent the necessary
1507 * broadcasts.
1508 */
1509 }
1510 }
San Mehatb1043402010-02-05 08:26:50 -08001511 }
1512
1513 public boolean isUsbMassStorageEnabled() {
1514 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001515
1516 final StorageVolume primary = getPrimaryPhysicalVolume();
1517 if (primary != null) {
1518 return doGetVolumeShared(primary.getPath(), "ums");
1519 } else {
1520 return false;
1521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001523
San Mehat7fd0fee2009-12-17 07:12:23 -08001524 /**
1525 * @return state of the volume at the specified mount point
1526 */
San Mehat4270e1e2010-01-29 05:32:19 -08001527 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001528 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001529 String state = mVolumeStates.get(mountPoint);
1530 if (state == null) {
1531 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001532 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1533 state = Environment.MEDIA_REMOVED;
1534 } else {
1535 throw new IllegalArgumentException();
1536 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001537 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001538
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001539 return state;
1540 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001541 }
1542
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001543 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001544 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001545 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001546 }
1547
San Mehat4270e1e2010-01-29 05:32:19 -08001548 public int mountVolume(String path) {
1549 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001550
San Mehat207e5382010-02-04 20:46:54 -08001551 waitForReady();
1552 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554
Ben Komalo13c71972011-09-07 16:35:56 -07001555 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001556 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001557 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001559 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001560 if (DEBUG_UNMOUNT) {
1561 Slog.i(TAG, "Unmounting " + path
1562 + " force = " + force
1563 + " removeEncryption = " + removeEncryption);
1564 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001565 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1566 Environment.MEDIA_REMOVED.equals(volState) ||
1567 Environment.MEDIA_SHARED.equals(volState) ||
1568 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1569 // Media already unmounted or cannot be unmounted.
1570 // TODO return valid return code when adding observer call back.
1571 return;
1572 }
Ben Komalo13c71972011-09-07 16:35:56 -07001573 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001574 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576
San Mehat4270e1e2010-01-29 05:32:19 -08001577 public int formatVolume(String path) {
1578 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001579 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001580
San Mehat207e5382010-02-04 20:46:54 -08001581 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001584 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001585 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1586 waitForReady();
1587 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001588 final String[] r = NativeDaemonEvent.filterMessageList(
1589 mConnector.executeForList("storage", "users", path),
1590 VoldResponseCode.StorageUsersListResult);
1591
San Mehatc1b4ce92010-02-16 17:13:03 -08001592 // FMT: <pid> <process name>
1593 int[] data = new int[r.length];
1594 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001595 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001596 try {
1597 data[i] = Integer.parseInt(tok[0]);
1598 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001599 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001600 return new int[0];
1601 }
1602 }
1603 return data;
1604 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001605 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001606 return new int[0];
1607 }
1608 }
1609
San Mehatb1043402010-02-05 08:26:50 -08001610 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001611 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001612 if (primary != null) {
1613 boolean mounted = false;
1614 try {
1615 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001616 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001617 }
1618
1619 if (!mounted) {
1620 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1621 }
San Mehatb1043402010-02-05 08:26:50 -08001622 }
1623 }
1624
San Mehat4270e1e2010-01-29 05:32:19 -08001625 public String[] getSecureContainerList() {
1626 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001627 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001628 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001629
San Mehat4270e1e2010-01-29 05:32:19 -08001630 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001631 return NativeDaemonEvent.filterMessageList(
1632 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001633 } catch (NativeDaemonConnectorException e) {
1634 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 }
San Mehat36972292010-01-06 11:06:32 -08001637
Kenny Root6dceb882012-04-12 14:23:49 -07001638 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1639 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001640 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001641 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001642 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001643
San Mehatb1043402010-02-05 08:26:50 -08001644 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001645 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001646 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1647 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001648 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001649 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001650 }
San Mehata181b212010-02-11 06:50:20 -08001651
1652 if (rc == StorageResultCode.OperationSucceeded) {
1653 synchronized (mAsecMountSet) {
1654 mAsecMountSet.add(id);
1655 }
1656 }
San Mehat4270e1e2010-01-29 05:32:19 -08001657 return rc;
San Mehat36972292010-01-06 11:06:32 -08001658 }
1659
San Mehat4270e1e2010-01-29 05:32:19 -08001660 public int finalizeSecureContainer(String id) {
1661 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001662 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001663
San Mehatb1043402010-02-05 08:26:50 -08001664 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001665 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001666 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001667 /*
1668 * Finalization does a remount, so no need
1669 * to update mAsecMountSet
1670 */
San Mehat4270e1e2010-01-29 05:32:19 -08001671 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001672 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001673 }
San Mehat4270e1e2010-01-29 05:32:19 -08001674 return rc;
San Mehat36972292010-01-06 11:06:32 -08001675 }
1676
Kenny Root6dceb882012-04-12 14:23:49 -07001677 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1678 validatePermission(android.Manifest.permission.ASEC_CREATE);
1679 warnOnNotMounted();
1680
1681 int rc = StorageResultCode.OperationSucceeded;
1682 try {
1683 mConnector.execute("asec", "fixperms", id, gid, filename);
1684 /*
1685 * Fix permissions does a remount, so no need to update
1686 * mAsecMountSet
1687 */
1688 } catch (NativeDaemonConnectorException e) {
1689 rc = StorageResultCode.OperationFailedInternalError;
1690 }
1691 return rc;
1692 }
1693
San Mehatd9709982010-02-18 11:43:03 -08001694 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001695 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001696 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001697 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001698
Kenny Rootaa485402010-09-14 14:49:41 -07001699 /*
1700 * Force a GC to make sure AssetManagers in other threads of the
1701 * system_server are cleaned up. We have to do this since AssetManager
1702 * instances are kept as a WeakReference and it's possible we have files
1703 * open on the external storage.
1704 */
1705 Runtime.getRuntime().gc();
1706
San Mehatb1043402010-02-05 08:26:50 -08001707 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001708 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001709 final Command cmd = new Command("asec", "destroy", id);
1710 if (force) {
1711 cmd.appendArg("force");
1712 }
1713 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001714 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001715 int code = e.getCode();
1716 if (code == VoldResponseCode.OpFailedStorageBusy) {
1717 rc = StorageResultCode.OperationFailedStorageBusy;
1718 } else {
1719 rc = StorageResultCode.OperationFailedInternalError;
1720 }
San Mehat02735bc2010-01-26 15:18:08 -08001721 }
San Mehata181b212010-02-11 06:50:20 -08001722
1723 if (rc == StorageResultCode.OperationSucceeded) {
1724 synchronized (mAsecMountSet) {
1725 if (mAsecMountSet.contains(id)) {
1726 mAsecMountSet.remove(id);
1727 }
1728 }
1729 }
1730
San Mehat4270e1e2010-01-29 05:32:19 -08001731 return rc;
San Mehat36972292010-01-06 11:06:32 -08001732 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001733
San Mehat4270e1e2010-01-29 05:32:19 -08001734 public int mountSecureContainer(String id, String key, int ownerUid) {
1735 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001736 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001737 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001738
San Mehata181b212010-02-11 06:50:20 -08001739 synchronized (mAsecMountSet) {
1740 if (mAsecMountSet.contains(id)) {
1741 return StorageResultCode.OperationFailedStorageMounted;
1742 }
1743 }
1744
San Mehatb1043402010-02-05 08:26:50 -08001745 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001746 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001747 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001748 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001749 int code = e.getCode();
1750 if (code != VoldResponseCode.OpFailedStorageBusy) {
1751 rc = StorageResultCode.OperationFailedInternalError;
1752 }
San Mehat02735bc2010-01-26 15:18:08 -08001753 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001754
1755 if (rc == StorageResultCode.OperationSucceeded) {
1756 synchronized (mAsecMountSet) {
1757 mAsecMountSet.add(id);
1758 }
1759 }
San Mehat4270e1e2010-01-29 05:32:19 -08001760 return rc;
San Mehat36972292010-01-06 11:06:32 -08001761 }
1762
San Mehatd9709982010-02-18 11:43:03 -08001763 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001764 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001765 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001766 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001767
San Mehat6cdd9c02010-02-09 14:45:20 -08001768 synchronized (mAsecMountSet) {
1769 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001770 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001771 }
1772 }
1773
Kenny Rootaa485402010-09-14 14:49:41 -07001774 /*
1775 * Force a GC to make sure AssetManagers in other threads of the
1776 * system_server are cleaned up. We have to do this since AssetManager
1777 * instances are kept as a WeakReference and it's possible we have files
1778 * open on the external storage.
1779 */
1780 Runtime.getRuntime().gc();
1781
San Mehatb1043402010-02-05 08:26:50 -08001782 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001783 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001784 final Command cmd = new Command("asec", "unmount", id);
1785 if (force) {
1786 cmd.appendArg("force");
1787 }
1788 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001789 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001790 int code = e.getCode();
1791 if (code == VoldResponseCode.OpFailedStorageBusy) {
1792 rc = StorageResultCode.OperationFailedStorageBusy;
1793 } else {
1794 rc = StorageResultCode.OperationFailedInternalError;
1795 }
San Mehat02735bc2010-01-26 15:18:08 -08001796 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001797
1798 if (rc == StorageResultCode.OperationSucceeded) {
1799 synchronized (mAsecMountSet) {
1800 mAsecMountSet.remove(id);
1801 }
1802 }
San Mehat4270e1e2010-01-29 05:32:19 -08001803 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001804 }
1805
San Mehat6cdd9c02010-02-09 14:45:20 -08001806 public boolean isSecureContainerMounted(String id) {
1807 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1808 waitForReady();
1809 warnOnNotMounted();
1810
1811 synchronized (mAsecMountSet) {
1812 return mAsecMountSet.contains(id);
1813 }
1814 }
1815
San Mehat4270e1e2010-01-29 05:32:19 -08001816 public int renameSecureContainer(String oldId, String newId) {
1817 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001818 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001819 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001820
San Mehata181b212010-02-11 06:50:20 -08001821 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001822 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001823 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001824 * changed while active, we must ensure both ids are not currently mounted.
1825 */
1826 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001827 return StorageResultCode.OperationFailedStorageMounted;
1828 }
1829 }
1830
San Mehatb1043402010-02-05 08:26:50 -08001831 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001832 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001833 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001834 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001835 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001836 }
San Mehata181b212010-02-11 06:50:20 -08001837
San Mehat4270e1e2010-01-29 05:32:19 -08001838 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001839 }
1840
San Mehat4270e1e2010-01-29 05:32:19 -08001841 public String getSecureContainerPath(String id) {
1842 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001843 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001844 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001845
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001846 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001847 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001848 event = mConnector.execute("asec", "path", id);
1849 event.checkCode(VoldResponseCode.AsecPathResult);
1850 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001851 } catch (NativeDaemonConnectorException e) {
1852 int code = e.getCode();
1853 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001854 Slog.i(TAG, String.format("Container '%s' not found", id));
1855 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001856 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001857 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001858 }
1859 }
San Mehat22dd86e2010-01-12 12:21:18 -08001860 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001861
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001862 public String getSecureContainerFilesystemPath(String id) {
1863 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1864 waitForReady();
1865 warnOnNotMounted();
1866
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001867 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001868 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001869 event = mConnector.execute("asec", "fspath", id);
1870 event.checkCode(VoldResponseCode.AsecPathResult);
1871 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001872 } catch (NativeDaemonConnectorException e) {
1873 int code = e.getCode();
1874 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1875 Slog.i(TAG, String.format("Container '%s' not found", id));
1876 return null;
1877 } else {
1878 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1879 }
1880 }
1881 }
1882
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001883 public void finishMediaUpdate() {
1884 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1885 }
Kenny Root02c87302010-07-01 08:10:18 -07001886
Kenny Roota02b8b02010-08-05 16:14:17 -07001887 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1888 if (callerUid == android.os.Process.SYSTEM_UID) {
1889 return true;
1890 }
1891
Kenny Root02c87302010-07-01 08:10:18 -07001892 if (packageName == null) {
1893 return false;
1894 }
1895
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001896 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001897
1898 if (DEBUG_OBB) {
1899 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1900 packageUid + ", callerUid = " + callerUid);
1901 }
1902
1903 return callerUid == packageUid;
1904 }
1905
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001906 public String getMountedObbPath(String rawPath) {
1907 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001908
Kenny Root02c87302010-07-01 08:10:18 -07001909 waitForReady();
1910 warnOnNotMounted();
1911
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001912 final ObbState state;
1913 synchronized (mObbPathToStateMap) {
1914 state = mObbPathToStateMap.get(rawPath);
1915 }
1916 if (state == null) {
1917 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1918 return null;
1919 }
1920
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001921 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001922 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001923 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001924 event.checkCode(VoldResponseCode.AsecPathResult);
1925 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001926 } catch (NativeDaemonConnectorException e) {
1927 int code = e.getCode();
1928 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001929 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001930 } else {
1931 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1932 }
1933 }
1934 }
1935
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001936 @Override
1937 public boolean isObbMounted(String rawPath) {
1938 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001939 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001940 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001941 }
Kenny Root02c87302010-07-01 08:10:18 -07001942 }
1943
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001944 @Override
1945 public void mountObb(
1946 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1947 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1948 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1949 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001950
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001951 final int callingUid = Binder.getCallingUid();
1952 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1953 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001954 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1955
1956 if (DEBUG_OBB)
1957 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001958 }
1959
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001960 @Override
1961 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1962 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1963
1964 final ObbState existingState;
1965 synchronized (mObbPathToStateMap) {
1966 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001967 }
1968
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001969 if (existingState != null) {
1970 // TODO: separate state object from request data
1971 final int callingUid = Binder.getCallingUid();
1972 final ObbState newState = new ObbState(
1973 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1974 final ObbAction action = new UnmountObbAction(newState, force);
1975 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001976
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001977 if (DEBUG_OBB)
1978 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1979 } else {
1980 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1981 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001982 }
1983
Ben Komalo444eca22011-09-01 15:17:44 -07001984 @Override
1985 public int getEncryptionState() {
1986 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1987 "no permission to access the crypt keeper");
1988
1989 waitForReady();
1990
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001991 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001992 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001993 event = mConnector.execute("cryptfs", "cryptocomplete");
1994 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001995 } catch (NumberFormatException e) {
1996 // Bad result - unexpected.
1997 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1998 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1999 } catch (NativeDaemonConnectorException e) {
2000 // Something bad happened.
2001 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2002 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2003 }
2004 }
2005
2006 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002007 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002008 if (TextUtils.isEmpty(password)) {
2009 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002010 }
2011
Jason parks8888c592011-01-20 22:46:41 -06002012 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2013 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002014
2015 waitForReady();
2016
2017 if (DEBUG_EVENTS) {
2018 Slog.i(TAG, "decrypting storage...");
2019 }
2020
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002021 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002022 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002023 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002024
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002025 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002026 if (code == 0) {
2027 // Decrypt was successful. Post a delayed message before restarting in order
2028 // to let the UI to clear itself
2029 mHandler.postDelayed(new Runnable() {
2030 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002031 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002032 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002033 } catch (NativeDaemonConnectorException e) {
2034 Slog.e(TAG, "problem executing in background", e);
2035 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002036 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002037 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002038 }
2039
2040 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002041 } catch (NativeDaemonConnectorException e) {
2042 // Decryption failed
2043 return e.getCode();
2044 }
Jason parks5af0b912010-11-29 09:05:25 -06002045 }
2046
Jason parks56aa5322011-01-07 09:01:15 -06002047 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002048 if (TextUtils.isEmpty(password)) {
2049 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002050 }
2051
Jason parks8888c592011-01-20 22:46:41 -06002052 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2053 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002054
2055 waitForReady();
2056
2057 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002058 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002059 }
2060
2061 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002062 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002063 } catch (NativeDaemonConnectorException e) {
2064 // Encryption failed
2065 return e.getCode();
2066 }
2067
2068 return 0;
2069 }
2070
Jason parksf7b3cd42011-01-27 09:28:25 -06002071 public int changeEncryptionPassword(String password) {
2072 if (TextUtils.isEmpty(password)) {
2073 throw new IllegalArgumentException("password cannot be empty");
2074 }
2075
2076 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2077 "no permission to access the crypt keeper");
2078
2079 waitForReady();
2080
2081 if (DEBUG_EVENTS) {
2082 Slog.i(TAG, "changing encryption password...");
2083 }
2084
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002085 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002086 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002087 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002088 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002089 } catch (NativeDaemonConnectorException e) {
2090 // Encryption failed
2091 return e.getCode();
2092 }
2093 }
2094
Christopher Tate32418be2011-10-10 13:51:12 -07002095 /**
2096 * Validate a user-supplied password string with cryptfs
2097 */
2098 @Override
2099 public int verifyEncryptionPassword(String password) throws RemoteException {
2100 // Only the system process is permitted to validate passwords
2101 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2102 throw new SecurityException("no permission to access the crypt keeper");
2103 }
2104
2105 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2106 "no permission to access the crypt keeper");
2107
2108 if (TextUtils.isEmpty(password)) {
2109 throw new IllegalArgumentException("password cannot be empty");
2110 }
2111
2112 waitForReady();
2113
2114 if (DEBUG_EVENTS) {
2115 Slog.i(TAG, "validating encryption password...");
2116 }
2117
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002118 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002119 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002120 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002121 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2122 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002123 } catch (NativeDaemonConnectorException e) {
2124 // Encryption failed
2125 return e.getCode();
2126 }
2127 }
2128
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002129 @Override
2130 public StorageVolume[] getVolumeList() {
2131 final int callingUserId = UserHandle.getCallingUserId();
2132 final boolean accessAll = (mContext.checkPermission(
2133 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2134 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2135
2136 synchronized (mVolumesLock) {
2137 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2138 for (StorageVolume volume : mVolumes) {
2139 final UserHandle owner = volume.getOwner();
2140 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2141 if (accessAll || ownerMatch) {
2142 filtered.add(volume);
2143 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002144 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002145 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002146 }
2147 }
2148
Kenny Rootaf9d6672010-10-08 09:21:39 -07002149 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2150 final IBinder binder = obbState.getBinder();
2151 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002152
Kenny Rootaf9d6672010-10-08 09:21:39 -07002153 if (obbStates == null) {
2154 obbStates = new ArrayList<ObbState>();
2155 mObbMounts.put(binder, obbStates);
2156 } else {
2157 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002158 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002159 throw new IllegalStateException("Attempt to add ObbState twice. "
2160 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002161 }
2162 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002163 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002164
2165 obbStates.add(obbState);
2166 try {
2167 obbState.link();
2168 } catch (RemoteException e) {
2169 /*
2170 * The binder died before we could link it, so clean up our state
2171 * and return failure.
2172 */
2173 obbStates.remove(obbState);
2174 if (obbStates.isEmpty()) {
2175 mObbMounts.remove(binder);
2176 }
2177
2178 // Rethrow the error so mountObb can get it
2179 throw e;
2180 }
2181
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002182 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002183 }
2184
Kenny Rootaf9d6672010-10-08 09:21:39 -07002185 private void removeObbStateLocked(ObbState obbState) {
2186 final IBinder binder = obbState.getBinder();
2187 final List<ObbState> obbStates = mObbMounts.get(binder);
2188 if (obbStates != null) {
2189 if (obbStates.remove(obbState)) {
2190 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002191 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002192 if (obbStates.isEmpty()) {
2193 mObbMounts.remove(binder);
2194 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002195 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002196
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002197 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002198 }
2199
Kenny Roota02b8b02010-08-05 16:14:17 -07002200 private class ObbActionHandler extends Handler {
2201 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002202 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002203
2204 ObbActionHandler(Looper l) {
2205 super(l);
2206 }
2207
2208 @Override
2209 public void handleMessage(Message msg) {
2210 switch (msg.what) {
2211 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002212 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002213
2214 if (DEBUG_OBB)
2215 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2216
2217 // If a bind was already initiated we don't really
2218 // need to do anything. The pending install
2219 // will be processed later on.
2220 if (!mBound) {
2221 // If this is the only one pending we might
2222 // have to bind to the service again.
2223 if (!connectToService()) {
2224 Slog.e(TAG, "Failed to bind to media container service");
2225 action.handleError();
2226 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002227 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002228 }
Kenny Root735de3b2010-09-30 14:11:39 -07002229
Kenny Root735de3b2010-09-30 14:11:39 -07002230 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002231 break;
2232 }
2233 case OBB_MCS_BOUND: {
2234 if (DEBUG_OBB)
2235 Slog.i(TAG, "OBB_MCS_BOUND");
2236 if (msg.obj != null) {
2237 mContainerService = (IMediaContainerService) msg.obj;
2238 }
2239 if (mContainerService == null) {
2240 // Something seriously wrong. Bail out
2241 Slog.e(TAG, "Cannot bind to media container service");
2242 for (ObbAction action : mActions) {
2243 // Indicate service bind error
2244 action.handleError();
2245 }
2246 mActions.clear();
2247 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002248 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002249 if (action != null) {
2250 action.execute(this);
2251 }
2252 } else {
2253 // Should never happen ideally.
2254 Slog.w(TAG, "Empty queue");
2255 }
2256 break;
2257 }
2258 case OBB_MCS_RECONNECT: {
2259 if (DEBUG_OBB)
2260 Slog.i(TAG, "OBB_MCS_RECONNECT");
2261 if (mActions.size() > 0) {
2262 if (mBound) {
2263 disconnectService();
2264 }
2265 if (!connectToService()) {
2266 Slog.e(TAG, "Failed to bind to media container service");
2267 for (ObbAction action : mActions) {
2268 // Indicate service bind error
2269 action.handleError();
2270 }
2271 mActions.clear();
2272 }
2273 }
2274 break;
2275 }
2276 case OBB_MCS_UNBIND: {
2277 if (DEBUG_OBB)
2278 Slog.i(TAG, "OBB_MCS_UNBIND");
2279
2280 // Delete pending install
2281 if (mActions.size() > 0) {
2282 mActions.remove(0);
2283 }
2284 if (mActions.size() == 0) {
2285 if (mBound) {
2286 disconnectService();
2287 }
2288 } else {
2289 // There are more pending requests in queue.
2290 // Just post MCS_BOUND message to trigger processing
2291 // of next pending install.
2292 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2293 }
2294 break;
2295 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002296 case OBB_FLUSH_MOUNT_STATE: {
2297 final String path = (String) msg.obj;
2298
2299 if (DEBUG_OBB)
2300 Slog.i(TAG, "Flushing all OBB state for path " + path);
2301
2302 synchronized (mObbMounts) {
2303 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2304
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002305 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002307 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002308
2309 /*
2310 * If this entry's source file is in the volume path
2311 * that got unmounted, remove it because it's no
2312 * longer valid.
2313 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002314 if (state.canonicalPath.startsWith(path)) {
2315 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002316 }
2317 }
2318
2319 for (final ObbState obbState : obbStatesToRemove) {
2320 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002321 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002322
2323 removeObbStateLocked(obbState);
2324
2325 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002326 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002327 OnObbStateChangeListener.UNMOUNTED);
2328 } catch (RemoteException e) {
2329 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002330 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002331 }
2332 }
2333 }
2334 break;
2335 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002336 }
2337 }
2338
2339 private boolean connectToService() {
2340 if (DEBUG_OBB)
2341 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2342
2343 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2344 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2345 mBound = true;
2346 return true;
2347 }
2348 return false;
2349 }
2350
2351 private void disconnectService() {
2352 mContainerService = null;
2353 mBound = false;
2354 mContext.unbindService(mDefContainerConn);
2355 }
2356 }
2357
2358 abstract class ObbAction {
2359 private static final int MAX_RETRIES = 3;
2360 private int mRetries;
2361
2362 ObbState mObbState;
2363
2364 ObbAction(ObbState obbState) {
2365 mObbState = obbState;
2366 }
2367
2368 public void execute(ObbActionHandler handler) {
2369 try {
2370 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002371 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002372 mRetries++;
2373 if (mRetries > MAX_RETRIES) {
2374 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002375 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002376 handleError();
2377 return;
2378 } else {
2379 handleExecute();
2380 if (DEBUG_OBB)
2381 Slog.i(TAG, "Posting install MCS_UNBIND");
2382 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2383 }
2384 } catch (RemoteException e) {
2385 if (DEBUG_OBB)
2386 Slog.i(TAG, "Posting install MCS_RECONNECT");
2387 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2388 } catch (Exception e) {
2389 if (DEBUG_OBB)
2390 Slog.d(TAG, "Error handling OBB action", e);
2391 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002392 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002393 }
2394 }
2395
Kenny Root05105f72010-09-22 17:29:43 -07002396 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002397 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002398
2399 protected ObbInfo getObbInfo() throws IOException {
2400 ObbInfo obbInfo;
2401 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002402 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002403 } catch (RemoteException e) {
2404 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002405 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002406 obbInfo = null;
2407 }
2408 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002409 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002410 }
2411 return obbInfo;
2412 }
2413
Kenny Rootaf9d6672010-10-08 09:21:39 -07002414 protected void sendNewStatusOrIgnore(int status) {
2415 if (mObbState == null || mObbState.token == null) {
2416 return;
2417 }
2418
Kenny Root38cf8862010-09-26 14:18:51 -07002419 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002420 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002421 } catch (RemoteException e) {
2422 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2423 }
2424 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002425 }
2426
2427 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002428 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002429 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002430
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002431 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002432 super(obbState);
2433 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002434 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002435 }
2436
Jason parks5af0b912010-11-29 09:05:25 -06002437 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002438 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002439 waitForReady();
2440 warnOnNotMounted();
2441
Kenny Root38cf8862010-09-26 14:18:51 -07002442 final ObbInfo obbInfo = getObbInfo();
2443
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002444 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002445 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2446 + " which is owned by " + obbInfo.packageName);
2447 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2448 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002449 }
2450
Kenny Rootaf9d6672010-10-08 09:21:39 -07002451 final boolean isMounted;
2452 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002453 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002454 }
2455 if (isMounted) {
2456 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2457 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2458 return;
2459 }
2460
Kenny Rootaf9d6672010-10-08 09:21:39 -07002461 final String hashedKey;
2462 if (mKey == null) {
2463 hashedKey = "none";
2464 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002465 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002466 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2467
2468 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2469 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2470 SecretKey key = factory.generateSecret(ks);
2471 BigInteger bi = new BigInteger(key.getEncoded());
2472 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002473 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002474 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2475 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2476 return;
2477 } catch (InvalidKeySpecException e) {
2478 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2479 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002480 return;
2481 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002482 }
Kenny Root38cf8862010-09-26 14:18:51 -07002483
Kenny Rootaf9d6672010-10-08 09:21:39 -07002484 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002485 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002486 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2487 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002488 } catch (NativeDaemonConnectorException e) {
2489 int code = e.getCode();
2490 if (code != VoldResponseCode.OpFailedStorageBusy) {
2491 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002492 }
2493 }
2494
Kenny Rootaf9d6672010-10-08 09:21:39 -07002495 if (rc == StorageResultCode.OperationSucceeded) {
2496 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002497 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002498
2499 synchronized (mObbMounts) {
2500 addObbStateLocked(mObbState);
2501 }
2502
2503 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002504 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002505 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002506
Kenny Rootaf9d6672010-10-08 09:21:39 -07002507 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002508 }
2509 }
2510
Jason parks5af0b912010-11-29 09:05:25 -06002511 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002512 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002513 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002514 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002515
2516 @Override
2517 public String toString() {
2518 StringBuilder sb = new StringBuilder();
2519 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002520 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002521 sb.append('}');
2522 return sb.toString();
2523 }
2524 }
2525
2526 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002527 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002528
2529 UnmountObbAction(ObbState obbState, boolean force) {
2530 super(obbState);
2531 mForceUnmount = force;
2532 }
2533
Jason parks5af0b912010-11-29 09:05:25 -06002534 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002535 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002536 waitForReady();
2537 warnOnNotMounted();
2538
Kenny Root38cf8862010-09-26 14:18:51 -07002539 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002540
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002542 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002543 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 }
Kenny Root38cf8862010-09-26 14:18:51 -07002545
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002546 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002547 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2548 return;
2549 }
2550
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002551 if (existingState.ownerGid != mObbState.ownerGid) {
2552 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2553 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002554 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2555 return;
2556 }
2557
Kenny Rootaf9d6672010-10-08 09:21:39 -07002558 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002559 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002560 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002561 if (mForceUnmount) {
2562 cmd.appendArg("force");
2563 }
2564 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002565 } catch (NativeDaemonConnectorException e) {
2566 int code = e.getCode();
2567 if (code == VoldResponseCode.OpFailedStorageBusy) {
2568 rc = StorageResultCode.OperationFailedStorageBusy;
2569 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2570 // If it's not mounted then we've already won.
2571 rc = StorageResultCode.OperationSucceeded;
2572 } else {
2573 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002574 }
2575 }
2576
Kenny Rootaf9d6672010-10-08 09:21:39 -07002577 if (rc == StorageResultCode.OperationSucceeded) {
2578 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002579 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002580 }
2581
Kenny Rootaf9d6672010-10-08 09:21:39 -07002582 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002583 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002584 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002585 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002586 }
2587 }
2588
Jason parks5af0b912010-11-29 09:05:25 -06002589 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002590 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002591 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002592 }
2593
2594 @Override
2595 public String toString() {
2596 StringBuilder sb = new StringBuilder();
2597 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002598 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002599 sb.append(",force=");
2600 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002601 sb.append('}');
2602 return sb.toString();
2603 }
Kenny Root02c87302010-07-01 08:10:18 -07002604 }
Kenny Root38cf8862010-09-26 14:18:51 -07002605
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002606 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002607 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2608 // TODO: allow caller to provide Environment for full testing
2609
2610 // Only adjust paths when storage is emulated
2611 if (!Environment.isExternalStorageEmulated()) {
2612 return canonicalPath;
2613 }
2614
2615 String path = canonicalPath.toString();
2616
2617 // First trim off any external storage prefix
2618 final UserEnvironment userEnv = new UserEnvironment(userId);
2619
2620 // /storage/emulated/0
2621 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2622 // /storage/emulated_legacy
2623 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2624 .toString();
2625
2626 if (path.startsWith(externalPath)) {
2627 path = path.substring(externalPath.length() + 1);
2628 } else if (path.startsWith(legacyExternalPath)) {
2629 path = path.substring(legacyExternalPath.length() + 1);
2630 } else {
2631 return canonicalPath;
2632 }
2633
2634 // Handle special OBB paths on emulated storage
2635 final String obbPath = "Android/obb";
2636 if (path.startsWith(obbPath)) {
2637 path = path.substring(obbPath.length() + 1);
2638
2639 if (forVold) {
2640 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2641 } else {
2642 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2643 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2644 }
2645 }
2646
2647 // Handle normal external storage paths
2648 if (forVold) {
2649 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2650 } else {
2651 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2652 }
2653 }
2654
Kenny Root38cf8862010-09-26 14:18:51 -07002655 @Override
2656 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2657 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2658 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2659 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2660 + " without permission " + android.Manifest.permission.DUMP);
2661 return;
2662 }
2663
Kenny Root38cf8862010-09-26 14:18:51 -07002664 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002665 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002666
Kenny Rootaf9d6672010-10-08 09:21:39 -07002667 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2668 while (binders.hasNext()) {
2669 Entry<IBinder, List<ObbState>> e = binders.next();
2670 pw.print(" Key="); pw.println(e.getKey().toString());
2671 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002672 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002673 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002674 }
2675 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002676
2677 pw.println("");
2678 pw.println(" mObbPathToStateMap:");
2679 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2680 while (maps.hasNext()) {
2681 final Entry<String, ObbState> e = maps.next();
2682 pw.print(" "); pw.print(e.getKey());
2683 pw.print(" -> "); pw.println(e.getValue().toString());
2684 }
Kenny Root38cf8862010-09-26 14:18:51 -07002685 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002686
2687 pw.println("");
2688
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002689 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002690 pw.println(" mVolumes:");
2691
2692 final int N = mVolumes.size();
2693 for (int i = 0; i < N; i++) {
2694 final StorageVolume v = mVolumes.get(i);
2695 pw.print(" ");
2696 pw.println(v.toString());
2697 }
2698 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002699
2700 pw.println();
2701 pw.println(" mConnection:");
2702 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002705 /** {@inheritDoc} */
2706 public void monitor() {
2707 if (mConnector != null) {
2708 mConnector.monitor();
2709 }
2710 }
2711}