blob: 1facb8093625361069706d028623674d666286c5 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070040import 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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkey1abdb712013-08-11 16:28:14 -0700193 // TODO: separate storage volumes on per-user basis
194
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800195 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700196 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
197 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800198 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700199 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
200 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800201 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700202 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
203
204 private volatile boolean mSystemReady = false;
205
San Mehat4270e1e2010-01-29 05:32:19 -0800206 private PackageManagerService mPms;
207 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700208 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800209 // Used as a lock for methods that register/unregister listeners.
210 final private ArrayList<MountServiceBinderListener> mListeners =
211 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800212 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
213 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800214 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800215
San Mehat6cdd9c02010-02-09 14:45:20 -0800216 /**
217 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800218 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800219 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800220 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800221
Kenny Root02c87302010-07-01 08:10:18 -0700222 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700223 * The size of the crypto algorithm key in bits for OBB files. Currently
224 * Twofish is used which takes 128-bit keys.
225 */
226 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
227
228 /**
229 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
230 * 1024 is reasonably secure and not too slow.
231 */
232 private static final int PBKDF2_HASH_ROUNDS = 1024;
233
234 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700235 * Mounted OBB tracking information. Used to track the current state of all
236 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700237 */
Kenny Root735de3b2010-09-30 14:11:39 -0700238 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700239
240 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700241 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
242
243 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700244 public ObbState(String rawPath, String canonicalPath, int callingUid,
245 IObbActionListener token, int nonce) {
246 this.rawPath = rawPath;
247 this.canonicalPath = canonicalPath.toString();
248
249 final int userId = UserHandle.getUserId(callingUid);
250 this.ownerPath = buildObbPath(canonicalPath, userId, false);
251 this.voldPath = buildObbPath(canonicalPath, userId, true);
252
253 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700254 this.token = token;
255 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700256 }
257
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700258 final String rawPath;
259 final String canonicalPath;
260 final String ownerPath;
261 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700263 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700264
Kenny Rootaf9d6672010-10-08 09:21:39 -0700265 // Token of remote Binder caller
266 final IObbActionListener token;
267
268 // Identifier to pass back to the token
269 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700270
Kenny Root735de3b2010-09-30 14:11:39 -0700271 public IBinder getBinder() {
272 return token.asBinder();
273 }
274
Kenny Roota02b8b02010-08-05 16:14:17 -0700275 @Override
276 public void binderDied() {
277 ObbAction action = new UnmountObbAction(this, true);
278 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700279 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700280
Kenny Root5919ac62010-10-05 09:49:40 -0700281 public void link() throws RemoteException {
282 getBinder().linkToDeath(this, 0);
283 }
284
285 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700286 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700287 }
Kenny Root38cf8862010-09-26 14:18:51 -0700288
289 @Override
290 public String toString() {
291 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700292 sb.append("rawPath=").append(rawPath);
293 sb.append(",canonicalPath=").append(canonicalPath);
294 sb.append(",ownerPath=").append(ownerPath);
295 sb.append(",voldPath=").append(voldPath);
296 sb.append(",ownerGid=").append(ownerGid);
297 sb.append(",token=").append(token);
298 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700299 sb.append('}');
300 return sb.toString();
301 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700302 }
303
304 // OBB Action Handler
305 final private ObbActionHandler mObbActionHandler;
306
307 // OBB action handler messages
308 private static final int OBB_RUN_ACTION = 1;
309 private static final int OBB_MCS_BOUND = 2;
310 private static final int OBB_MCS_UNBIND = 3;
311 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700312 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700313
314 /*
315 * Default Container Service information
316 */
317 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
318 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
319
320 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
321
322 class DefaultContainerConnection implements ServiceConnection {
323 public void onServiceConnected(ComponentName name, IBinder service) {
324 if (DEBUG_OBB)
325 Slog.i(TAG, "onServiceConnected");
326 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
327 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
328 }
329
330 public void onServiceDisconnected(ComponentName name) {
331 if (DEBUG_OBB)
332 Slog.i(TAG, "onServiceDisconnected");
333 }
334 };
335
336 // Used in the ObbActionHandler
337 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700338
339 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800340 private static final int H_UNMOUNT_PM_UPDATE = 1;
341 private static final int H_UNMOUNT_PM_DONE = 2;
342 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700343 private static final int H_SYSTEM_READY = 4;
344
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800345 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
346 private static final int MAX_UNMOUNT_RETRIES = 4;
347
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800348 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700349 final String path;
350 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700351 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800352 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353
Ben Komalo13c71972011-09-07 16:35:56 -0700354 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800355 retries = 0;
356 this.path = path;
357 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700358 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800360
361 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700362 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700363 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800364 }
365 }
366
367 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700368 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800369
370 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700371 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800372 this.method = method;
373 }
374
375 @Override
376 void handleFinished() {
377 super.handleFinished();
378 doShareUnshareVolume(path, method, true);
379 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800380 }
381
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800382 class ShutdownCallBack extends UnmountCallBack {
383 IMountShutdownObserver observer;
384 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700385 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800386 this.observer = observer;
387 }
388
389 @Override
390 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700391 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 if (observer != null) {
393 try {
394 observer.onShutDownComplete(ret);
395 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700396 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800397 }
398 }
399 }
400 }
401
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400402 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800403 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700404 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800405
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400406 MountServiceHandler(Looper l) {
407 super(l);
408 }
409
Jason parks5af0b912010-11-29 09:05:25 -0600410 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800411 public void handleMessage(Message msg) {
412 switch (msg.what) {
413 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700414 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800415 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
416 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700417 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800418 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700419 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700420 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700421 mUpdatingStatus = true;
422 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800423 }
424 break;
425 }
426 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700427 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700428 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700429 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800430 int size = mForceUnmounts.size();
431 int sizeArr[] = new int[size];
432 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700433 // Kill processes holding references first
434 ActivityManagerService ams = (ActivityManagerService)
435 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800436 for (int i = 0; i < size; i++) {
437 UnmountCallBack ucb = mForceUnmounts.get(i);
438 String path = ucb.path;
439 boolean done = false;
440 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800441 done = true;
442 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800443 int pids[] = getStorageUsers(path);
444 if (pids == null || pids.length == 0) {
445 done = true;
446 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800447 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800448 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700449 // Confirm if file references have been freed.
450 pids = getStorageUsers(path);
451 if (pids == null || pids.length == 0) {
452 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800453 }
454 }
455 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700456 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
457 // Retry again
458 Slog.i(TAG, "Retrying to kill storage users again");
459 mHandler.sendMessageDelayed(
460 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
461 ucb.retries++),
462 RETRY_UNMOUNT_DELAY);
463 } else {
464 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
465 Slog.i(TAG, "Failed to unmount media inspite of " +
466 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
467 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800468 sizeArr[sizeArrN++] = i;
469 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
470 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800471 }
472 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800473 // Remove already processed elements from list.
474 for (int i = (sizeArrN-1); i >= 0; i--) {
475 mForceUnmounts.remove(sizeArr[i]);
476 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800477 break;
478 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700479 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700480 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800481 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800482 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800483 break;
484 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700485 case H_SYSTEM_READY: {
486 try {
487 handleSystemReady();
488 } catch (Exception ex) {
489 Slog.e(TAG, "Boot-time mount exception", ex);
490 }
491 break;
492 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800493 }
494 }
495 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700496
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700497 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800498
Kenny Root51a573c2012-05-17 13:30:28 -0700499 void waitForAsecScan() {
500 waitForLatch(mAsecsScanned);
501 }
502
San Mehat207e5382010-02-04 20:46:54 -0800503 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700504 waitForLatch(mConnectedSignal);
505 }
506
507 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700508 for (;;) {
509 try {
510 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800511 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700512 } else {
513 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
514 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800515 }
Kenny Root51a573c2012-05-17 13:30:28 -0700516 } catch (InterruptedException e) {
517 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800518 }
San Mehat207e5382010-02-04 20:46:54 -0800519 }
San Mehat1f6301e2010-01-07 22:40:27 -0800520 }
Kenny Root02c87302010-07-01 08:10:18 -0700521
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700522 private void handleSystemReady() {
523 // Snapshot current volume states since it's not safe to call into vold
524 // while holding locks.
525 final HashMap<String, String> snapshot;
526 synchronized (mVolumesLock) {
527 snapshot = new HashMap<String, String>(mVolumeStates);
528 }
529
530 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
531 final String path = entry.getKey();
532 final String state = entry.getValue();
533
534 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
535 int rc = doMountVolume(path);
536 if (rc != StorageResultCode.OperationSucceeded) {
537 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
538 rc));
539 }
540 } else if (state.equals(Environment.MEDIA_SHARED)) {
541 /*
542 * Bootstrap UMS enabled state since vold indicates
543 * the volume is shared (runtime restart while ums enabled)
544 */
545 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
546 VolumeState.Shared);
547 }
548 }
549
550 // Push mounted state for all emulated storage
551 synchronized (mVolumesLock) {
552 for (StorageVolume volume : mVolumes) {
553 if (volume.isEmulated()) {
554 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
555 }
556 }
557 }
558
559 /*
560 * If UMS was connected on boot, send the connected event
561 * now that we're up.
562 */
563 if (mSendUmsConnectedOnBoot) {
564 sendUmsIntent(true);
565 mSendUmsConnectedOnBoot = false;
566 }
567 }
568
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700569 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
570 @Override
571 public void onReceive(Context context, Intent intent) {
572 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
573 if (userId == -1) return;
574 final UserHandle user = new UserHandle(userId);
575
576 final String action = intent.getAction();
577 if (Intent.ACTION_USER_ADDED.equals(action)) {
578 synchronized (mVolumesLock) {
579 createEmulatedVolumeForUserLocked(user);
580 }
581
582 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
583 synchronized (mVolumesLock) {
584 final List<StorageVolume> toRemove = Lists.newArrayList();
585 for (StorageVolume volume : mVolumes) {
586 if (user.equals(volume.getOwner())) {
587 toRemove.add(volume);
588 }
589 }
590 for (StorageVolume volume : toRemove) {
591 removeVolumeLocked(volume);
592 }
593 }
594 }
595 }
596 };
597
598 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
599 @Override
600 public void onReceive(Context context, Intent intent) {
601 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
602 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
603 notifyShareAvailabilityChange(available);
604 }
605 };
606
Svetoslava7452ee2013-03-20 12:06:59 -0700607 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
608 @Override
609 public void onReceive(Context context, Intent intent) {
610 waitForReady();
611 String action = intent.getAction();
612 // Since fstrim will be run on a daily basis we do not expect
613 // fstrim to be too long, so it is not interruptible. We will
614 // implement interruption only in case we see issues.
615 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
616 try {
617 // This method runs on the handler thread,
618 // so it is safe to directly call into vold.
619 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700620 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700621 } catch (NativeDaemonConnectorException ndce) {
622 Slog.e(TAG, "Failed to run fstrim!");
623 }
624 }
625 }
626 };
627
San Mehat4270e1e2010-01-29 05:32:19 -0800628 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
629 final IMountServiceListener mListener;
630
631 MountServiceBinderListener(IMountServiceListener listener) {
632 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700633
San Mehat91c77612010-01-07 10:39:41 -0800634 }
635
San Mehat4270e1e2010-01-29 05:32:19 -0800636 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700637 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700638 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800639 mListeners.remove(this);
640 mListener.asBinder().unlinkToDeath(this, 0);
641 }
642 }
643 }
644
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800645 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800646 // TODO: Add support for multiple share methods
647 if (!method.equals("ums")) {
648 throw new IllegalArgumentException(String.format("Method %s not supported", method));
649 }
650
San Mehat4270e1e2010-01-29 05:32:19 -0800651 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800652 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800653 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700654 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800655 }
San Mehat4270e1e2010-01-29 05:32:19 -0800656 }
657
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700658 private void updatePublicVolumeState(StorageVolume volume, String state) {
659 final String path = volume.getPath();
660 final String oldState;
661 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400662 oldState = mVolumeStates.put(path, state);
663 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700664
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400665 if (state.equals(oldState)) {
666 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
667 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800668 return;
669 }
San Mehatb1043402010-02-05 08:26:50 -0800670
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400671 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700672
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700673 // Tell PackageManager about changes to primary volume state, but only
674 // when not emulated.
675 if (volume.isPrimary() && !volume.isEmulated()) {
676 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
677 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400678
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700679 /*
680 * Some OBBs might have been unmounted when this volume was
681 * unmounted, so send a message to the handler to let it know to
682 * remove those from the list of mounted OBBS.
683 */
684 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
685 OBB_FLUSH_MOUNT_STATE, path));
686 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
687 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400688 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800689 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700690
San Mehat4270e1e2010-01-29 05:32:19 -0800691 synchronized (mListeners) {
692 for (int i = mListeners.size() -1; i >= 0; i--) {
693 MountServiceBinderListener bl = mListeners.get(i);
694 try {
San Mehatb1043402010-02-05 08:26:50 -0800695 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800696 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700697 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800698 mListeners.remove(i);
699 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700700 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800701 }
702 }
703 }
704 }
705
706 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800707 * Callback from NativeDaemonConnector
708 */
709 public void onDaemonConnected() {
710 /*
711 * Since we'll be calling back into the NativeDaemonConnector,
712 * we need to do our work in a new thread.
713 */
Kenny Root51a573c2012-05-17 13:30:28 -0700714 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600715 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800716 public void run() {
717 /**
718 * Determine media state and UMS detection status
719 */
San Mehat4270e1e2010-01-29 05:32:19 -0800720 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800721 final String[] vols = NativeDaemonEvent.filterMessageList(
722 mConnector.executeForList("volume", "list"),
723 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800724 for (String volstr : vols) {
725 String[] tok = volstr.split(" ");
726 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400727 String path = tok[1];
728 String state = Environment.MEDIA_REMOVED;
729
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700730 final StorageVolume volume;
731 synchronized (mVolumesLock) {
732 volume = mVolumesByPath.get(path);
733 }
734
San Mehat4270e1e2010-01-29 05:32:19 -0800735 int st = Integer.parseInt(tok[2]);
736 if (st == VolumeState.NoMedia) {
737 state = Environment.MEDIA_REMOVED;
738 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800739 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800740 } else if (st == VolumeState.Mounted) {
741 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700742 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800743 } else if (st == VolumeState.Shared) {
744 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700745 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800746 } else {
747 throw new Exception(String.format("Unexpected state %d", st));
748 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400749
750 if (state != null) {
751 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700752 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400753 }
San Mehat4270e1e2010-01-29 05:32:19 -0800754 }
755 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700756 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700757 final StorageVolume primary = getPrimaryPhysicalVolume();
758 if (primary != null) {
759 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
760 }
San Mehat4270e1e2010-01-29 05:32:19 -0800761 }
762
San Mehat207e5382010-02-04 20:46:54 -0800763 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600764 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800765 * the hounds!
766 */
Kenny Root51a573c2012-05-17 13:30:28 -0700767 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700768
769 // Let package manager load internal ASECs.
770 mPms.scanAvailableAsecs();
771
772 // Notify people waiting for ASECs to be scanned that it's done.
773 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800774 }
775 }.start();
776 }
777
778 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800779 * Callback from NativeDaemonConnector
780 */
781 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800782 if (DEBUG_EVENTS) {
783 StringBuilder builder = new StringBuilder();
784 builder.append("onEvent::");
785 builder.append(" raw= " + raw);
786 if (cooked != null) {
787 builder.append(" cooked = " );
788 for (String str : cooked) {
789 builder.append(" " + str);
790 }
791 }
San Mehata5078592010-03-25 09:36:54 -0700792 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800793 }
San Mehat4270e1e2010-01-29 05:32:19 -0800794 if (code == VoldResponseCode.VolumeStateChange) {
795 /*
796 * One of the volumes we're managing has changed state.
797 * Format: "NNN Volume <label> <path> state changed
798 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
799 */
800 notifyVolumeStateChange(
801 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
802 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800803 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
804 (code == VoldResponseCode.VolumeDiskRemoved) ||
805 (code == VoldResponseCode.VolumeBadRemoval)) {
806 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
807 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
808 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400809 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800810 final String label = cooked[2];
811 final String path = cooked[3];
812 int major = -1;
813 int minor = -1;
814
815 try {
816 String devComp = cooked[6].substring(1, cooked[6].length() -1);
817 String[] devTok = devComp.split(":");
818 major = Integer.parseInt(devTok[0]);
819 minor = Integer.parseInt(devTok[1]);
820 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700821 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800822 }
823
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700824 final StorageVolume volume;
825 final String state;
826 synchronized (mVolumesLock) {
827 volume = mVolumesByPath.get(path);
828 state = mVolumeStates.get(path);
829 }
830
San Mehat4270e1e2010-01-29 05:32:19 -0800831 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700832 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600833 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800834 public void run() {
835 try {
836 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800837 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700838 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800839 }
840 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700841 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800842 }
843 }
844 }.start();
845 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
846 /*
847 * This event gets trumped if we're already in BAD_REMOVAL state
848 */
849 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
850 return true;
851 }
852 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700853 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700854 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
855 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800856
San Mehata5078592010-03-25 09:36:54 -0700857 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700858 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400859 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800860 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700861 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800862 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700863 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200864 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800865
San Mehata5078592010-03-25 09:36:54 -0700866 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700867 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400868 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700869 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700870 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800871 } else {
San Mehata5078592010-03-25 09:36:54 -0700872 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800873 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400874
875 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700876 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400877 }
San Mehat4270e1e2010-01-29 05:32:19 -0800878 } else {
879 return false;
880 }
881
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400882 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800883 }
884
San Mehat207e5382010-02-04 20:46:54 -0800885 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700886 final StorageVolume volume;
887 final String state;
888 synchronized (mVolumesLock) {
889 volume = mVolumesByPath.get(path);
890 state = getVolumeState(path);
891 }
892
893 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800894
Mike Lockwooda5250c92011-05-23 13:44:04 -0400895 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800896
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500897 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700898 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700899 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500900 }
901
San Mehat4270e1e2010-01-29 05:32:19 -0800902 if (newState == VolumeState.Init) {
903 } else if (newState == VolumeState.NoMedia) {
904 // NoMedia is handled via Disk Remove events
905 } else if (newState == VolumeState.Idle) {
906 /*
907 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
908 * if we're in the process of enabling UMS
909 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700910 if (!state.equals(
911 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
912 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800913 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700914 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700915 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400916 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800917 }
918 } else if (newState == VolumeState.Pending) {
919 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700920 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700921 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400922 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800923 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700924 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700925 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400926 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800927 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400928 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800929 } else if (newState == VolumeState.Formatting) {
930 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700931 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800932 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700933 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
934 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800935
San Mehata5078592010-03-25 09:36:54 -0700936 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700937 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400938 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700939 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800940 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700941 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800942 return;
943 } else {
San Mehata5078592010-03-25 09:36:54 -0700944 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800945 }
946
Mike Lockwooda5250c92011-05-23 13:44:04 -0400947 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700948 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800949 }
950 }
951
San Mehat207e5382010-02-04 20:46:54 -0800952 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800953 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800954
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700955 final StorageVolume volume;
956 synchronized (mVolumesLock) {
957 volume = mVolumesByPath.get(path);
958 }
959
San Mehata5078592010-03-25 09:36:54 -0700960 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800961 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800962 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800963 } catch (NativeDaemonConnectorException e) {
964 /*
965 * Mount failed for some reason
966 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400967 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800968 int code = e.getCode();
969 if (code == VoldResponseCode.OpFailedNoMedia) {
970 /*
971 * Attempt to mount but no media inserted
972 */
San Mehatb1043402010-02-05 08:26:50 -0800973 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800974 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700975 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800976 /*
977 * Media is blank or does not contain a supported filesystem
978 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700979 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400980 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800981 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800982 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700983 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800984 /*
985 * Volume consistency check failed
986 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700987 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400988 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800989 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800990 } else {
San Mehatb1043402010-02-05 08:26:50 -0800991 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800992 }
993
994 /*
995 * Send broadcast intent (if required for the failure)
996 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400997 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700998 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800999 }
1000 }
1001
1002 return rc;
1003 }
1004
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001005 /*
1006 * If force is not set, we do not unmount if there are
1007 * processes holding references to the volume about to be unmounted.
1008 * If force is set, all the processes holding references need to be
1009 * killed via the ActivityManager before actually unmounting the volume.
1010 * This might even take a while and might be retried after timed delays
1011 * to make sure we dont end up in an instable state and kill some core
1012 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001013 * If removeEncryption is set, force is implied, and the system will remove any encryption
1014 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001015 */
Ben Komalo13c71972011-09-07 16:35:56 -07001016 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001017 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001018 return VoldResponseCode.OpFailedVolNotMounted;
1019 }
Kenny Rootaa485402010-09-14 14:49:41 -07001020
1021 /*
1022 * Force a GC to make sure AssetManagers in other threads of the
1023 * system_server are cleaned up. We have to do this since AssetManager
1024 * instances are kept as a WeakReference and it's possible we have files
1025 * open on the external storage.
1026 */
1027 Runtime.getRuntime().gc();
1028
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001029 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001030 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001031 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001032 final Command cmd = new Command("volume", "unmount", path);
1033 if (removeEncryption) {
1034 cmd.appendArg("force_and_revert");
1035 } else if (force) {
1036 cmd.appendArg("force");
1037 }
1038 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001039 // We unmounted the volume. None of the asec containers are available now.
1040 synchronized (mAsecMountSet) {
1041 mAsecMountSet.clear();
1042 }
San Mehatb1043402010-02-05 08:26:50 -08001043 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001044 } catch (NativeDaemonConnectorException e) {
1045 // Don't worry about mismatch in PackageManager since the
1046 // call back will handle the status changes any way.
1047 int code = e.getCode();
1048 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001049 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001050 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1051 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001052 } else {
San Mehatb1043402010-02-05 08:26:50 -08001053 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001054 }
1055 }
1056 }
1057
1058 private int doFormatVolume(String path) {
1059 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001060 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001061 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001062 } catch (NativeDaemonConnectorException e) {
1063 int code = e.getCode();
1064 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001065 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001066 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001067 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001068 } else {
San Mehatb1043402010-02-05 08:26:50 -08001069 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001070 }
1071 }
1072 }
1073
San Mehatb1043402010-02-05 08:26:50 -08001074 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001075 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001076 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001077 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001078 } catch (NativeDaemonConnectorException ex) {
1079 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1080 return false;
1081 }
San Mehatb1043402010-02-05 08:26:50 -08001082
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001083 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1084 return event.getMessage().endsWith("enabled");
1085 } else {
1086 return false;
San Mehatb1043402010-02-05 08:26:50 -08001087 }
San Mehatb1043402010-02-05 08:26:50 -08001088 }
1089
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001090 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001091 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001092 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001093 for (int i = mListeners.size() -1; i >= 0; i--) {
1094 MountServiceBinderListener bl = mListeners.get(i);
1095 try {
San Mehatb1043402010-02-05 08:26:50 -08001096 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001097 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001098 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001099 mListeners.remove(i);
1100 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001101 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001102 }
1103 }
1104 }
1105
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001106 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001107 sendUmsIntent(avail);
1108 } else {
1109 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001110 }
San Mehat2fe718a2010-03-11 12:01:49 -08001111
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001112 final StorageVolume primary = getPrimaryPhysicalVolume();
1113 if (avail == false && primary != null
1114 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1115 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001116 /*
1117 * USB mass storage disconnected while enabled
1118 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001119 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001120 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001121 public void run() {
1122 try {
1123 int rc;
San Mehata5078592010-03-25 09:36:54 -07001124 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001125 doShareUnshareVolume(path, "ums", false);
1126 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001127 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001128 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1129 path, rc));
1130 }
1131 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001132 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001133 }
1134 }
1135 }.start();
1136 }
San Mehat4270e1e2010-01-29 05:32:19 -08001137 }
1138
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001139 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1140 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1141 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1142 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1143 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001144 }
1145
San Mehat6a965af22010-02-24 17:47:30 -08001146 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001147 mContext.sendBroadcastAsUser(
1148 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1149 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001150 }
1151
San Mehat207e5382010-02-04 20:46:54 -08001152 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001153 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1154 throw new SecurityException(String.format("Requires %s permission", perm));
1155 }
1156 }
1157
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001158 // Storage list XML tags
1159 private static final String TAG_STORAGE_LIST = "StorageList";
1160 private static final String TAG_STORAGE = "storage";
1161
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001162 private void readStorageListLocked() {
1163 mVolumes.clear();
1164 mVolumeStates.clear();
1165
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001166 Resources resources = mContext.getResources();
1167
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001168 int id = com.android.internal.R.xml.storage_list;
1169 XmlResourceParser parser = resources.getXml(id);
1170 AttributeSet attrs = Xml.asAttributeSet(parser);
1171
1172 try {
1173 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1174 while (true) {
1175 XmlUtils.nextElement(parser);
1176
1177 String element = parser.getName();
1178 if (element == null) break;
1179
1180 if (TAG_STORAGE.equals(element)) {
1181 TypedArray a = resources.obtainAttributes(attrs,
1182 com.android.internal.R.styleable.Storage);
1183
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001184 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001185 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001186 int descriptionId = a.getResourceId(
1187 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001188 CharSequence description = a.getText(
1189 com.android.internal.R.styleable.Storage_storageDescription);
1190 boolean primary = a.getBoolean(
1191 com.android.internal.R.styleable.Storage_primary, false);
1192 boolean removable = a.getBoolean(
1193 com.android.internal.R.styleable.Storage_removable, false);
1194 boolean emulated = a.getBoolean(
1195 com.android.internal.R.styleable.Storage_emulated, false);
1196 int mtpReserve = a.getInt(
1197 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001198 boolean allowMassStorage = a.getBoolean(
1199 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001200 // resource parser does not support longs, so XML value is in megabytes
1201 long maxFileSize = a.getInt(
1202 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001203
1204 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1205 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001206 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001207 " allowMassStorage: " + allowMassStorage +
1208 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001209
1210 if (emulated) {
1211 // For devices with emulated storage, we create separate
1212 // volumes for each known user.
1213 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1214 true, mtpReserve, false, maxFileSize, null);
1215
1216 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001217 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001218 createEmulatedVolumeForUserLocked(user.getUserHandle());
1219 }
1220
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001221 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001222 if (path == null || description == null) {
1223 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001224 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001225 final StorageVolume volume = new StorageVolume(new File(path),
1226 descriptionId, primary, removable, emulated, mtpReserve,
1227 allowMassStorage, maxFileSize, null);
1228 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001229 }
1230 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001231
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001232 a.recycle();
1233 }
1234 }
1235 } catch (XmlPullParserException e) {
1236 throw new RuntimeException(e);
1237 } catch (IOException e) {
1238 throw new RuntimeException(e);
1239 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001240 // Compute storage ID for each physical volume; emulated storage is
1241 // always 0 when defined.
1242 int index = isExternalStorageEmulated() ? 1 : 0;
1243 for (StorageVolume volume : mVolumes) {
1244 if (!volume.isEmulated()) {
1245 volume.setStorageId(index++);
1246 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001247 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001248 parser.close();
1249 }
1250 }
1251
San Mehat4270e1e2010-01-29 05:32:19 -08001252 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001253 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1254 * using {@link #mEmulatedTemplate} as template.
1255 */
1256 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1257 if (mEmulatedTemplate == null) {
1258 throw new IllegalStateException("Missing emulated volume multi-user template");
1259 }
1260
1261 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1262 final File path = userEnv.getExternalStorageDirectory();
1263 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1264 volume.setStorageId(0);
1265 addVolumeLocked(volume);
1266
1267 if (mSystemReady) {
1268 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1269 } else {
1270 // Place stub status for early callers to find
1271 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1272 }
1273 }
1274
1275 private void addVolumeLocked(StorageVolume volume) {
1276 Slog.d(TAG, "addVolumeLocked() " + volume);
1277 mVolumes.add(volume);
1278 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1279 if (existing != null) {
1280 throw new IllegalStateException(
1281 "Volume at " + volume.getPath() + " already exists: " + existing);
1282 }
1283 }
1284
1285 private void removeVolumeLocked(StorageVolume volume) {
1286 Slog.d(TAG, "removeVolumeLocked() " + volume);
1287 mVolumes.remove(volume);
1288 mVolumesByPath.remove(volume.getPath());
1289 mVolumeStates.remove(volume.getPath());
1290 }
1291
1292 private StorageVolume getPrimaryPhysicalVolume() {
1293 synchronized (mVolumesLock) {
1294 for (StorageVolume volume : mVolumes) {
1295 if (volume.isPrimary() && !volume.isEmulated()) {
1296 return volume;
1297 }
1298 }
1299 }
1300 return null;
1301 }
1302
1303 /**
San Mehat207e5382010-02-04 20:46:54 -08001304 * Constructs a new MountService instance
1305 *
1306 * @param context Binder context for this service
1307 */
1308 public MountService(Context context) {
1309 mContext = context;
1310
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001311 synchronized (mVolumesLock) {
1312 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001313 }
1314
San Mehat207e5382010-02-04 20:46:54 -08001315 // XXX: This will go away soon in favor of IMountServiceObserver
1316 mPms = (PackageManagerService) ServiceManager.getService("package");
1317
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001318 HandlerThread hthread = new HandlerThread(TAG);
1319 hthread.start();
1320 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001321
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001322 // Watch for user changes
1323 final IntentFilter userFilter = new IntentFilter();
1324 userFilter.addAction(Intent.ACTION_USER_ADDED);
1325 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1326 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1327
1328 // Watch for USB changes on primary volume
1329 final StorageVolume primary = getPrimaryPhysicalVolume();
1330 if (primary != null && primary.allowMassStorage()) {
1331 mContext.registerReceiver(
1332 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1333 }
1334
Svetoslava7452ee2013-03-20 12:06:59 -07001335 // Watch for idle maintenance changes
1336 IntentFilter idleMaintenanceFilter = new IntentFilter();
1337 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1338 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1339 idleMaintenanceFilter, null, mHandler);
1340
Kenny Roota02b8b02010-08-05 16:14:17 -07001341 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001342 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001343
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001344 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001345 * Create the connection to vold with a maximum queue of twice the
1346 * amount of containers we'd ever expect to have. This keeps an
1347 * "asec list" from blocking a thread repeatedly.
1348 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001349 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001350
Kenny Root305bcbf2010-09-03 07:56:38 -07001351 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001352 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001353
Kenny Root07714d42011-08-17 17:49:28 -07001354 // Add ourself to the Watchdog monitors if enabled.
1355 if (WATCHDOG_ENABLE) {
1356 Watchdog.getInstance().addMonitor(this);
1357 }
San Mehat207e5382010-02-04 20:46:54 -08001358 }
1359
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001360 public void systemReady() {
1361 mSystemReady = true;
1362 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1363 }
1364
San Mehat207e5382010-02-04 20:46:54 -08001365 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001366 * Exposed API calls below here
1367 */
1368
1369 public void registerListener(IMountServiceListener listener) {
1370 synchronized (mListeners) {
1371 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1372 try {
1373 listener.asBinder().linkToDeath(bl, 0);
1374 mListeners.add(bl);
1375 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001376 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001377 }
1378 }
1379 }
1380
1381 public void unregisterListener(IMountServiceListener listener) {
1382 synchronized (mListeners) {
1383 for(MountServiceBinderListener bl : mListeners) {
1384 if (bl.mListener == listener) {
1385 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001386 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001387 return;
1388 }
1389 }
1390 }
1391 }
1392
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001393 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001394 validatePermission(android.Manifest.permission.SHUTDOWN);
1395
San Mehata5078592010-03-25 09:36:54 -07001396 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001397 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001398 for (String path : mVolumeStates.keySet()) {
1399 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001400
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001401 if (state.equals(Environment.MEDIA_SHARED)) {
1402 /*
1403 * If the media is currently shared, unshare it.
1404 * XXX: This is still dangerous!. We should not
1405 * be rebooting at *all* if UMS is enabled, since
1406 * the UMS host could have dirty FAT cache entries
1407 * yet to flush.
1408 */
1409 setUsbMassStorageEnabled(false);
1410 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1411 /*
1412 * If the media is being checked, then we need to wait for
1413 * it to complete before being able to proceed.
1414 */
1415 // XXX: @hackbod - Should we disable the ANR timer here?
1416 int retries = 30;
1417 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1418 try {
1419 Thread.sleep(1000);
1420 } catch (InterruptedException iex) {
1421 Slog.e(TAG, "Interrupted while waiting for media", iex);
1422 break;
1423 }
1424 state = Environment.getExternalStorageState();
1425 }
1426 if (retries == 0) {
1427 Slog.e(TAG, "Timed out waiting for media to check");
1428 }
San Mehat91c77612010-01-07 10:39:41 -08001429 }
San Mehat91c77612010-01-07 10:39:41 -08001430
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001431 if (state.equals(Environment.MEDIA_MOUNTED)) {
1432 // Post a unmount message.
1433 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1434 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1435 } else if (observer != null) {
1436 /*
1437 * Observer is waiting for onShutDownComplete when we are done.
1438 * Since nothing will be done send notification directly so shutdown
1439 * sequence can continue.
1440 */
1441 try {
1442 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1443 } catch (RemoteException e) {
1444 Slog.w(TAG, "RemoteException when shutting down");
1445 }
1446 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001447 }
San Mehat4270e1e2010-01-29 05:32:19 -08001448 }
1449 }
1450
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001451 private boolean getUmsEnabling() {
1452 synchronized (mListeners) {
1453 return mUmsEnabling;
1454 }
1455 }
1456
1457 private void setUmsEnabling(boolean enable) {
1458 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001459 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001460 }
1461 }
1462
San Mehatb1043402010-02-05 08:26:50 -08001463 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001464 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001465
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001466 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001467 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001468 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001469 synchronized (mListeners) {
1470 return mUmsAvailable;
1471 }
San Mehatb1043402010-02-05 08:26:50 -08001472 }
1473
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001474 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001475 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001476 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001477
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001478 final StorageVolume primary = getPrimaryPhysicalVolume();
1479 if (primary == null) return;
1480
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001481 // TODO: Add support for multiple share methods
1482
1483 /*
1484 * If the volume is mounted and we're enabling then unmount it
1485 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001486 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001487 String vs = getVolumeState(path);
1488 String method = "ums";
1489 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1490 // Override for isUsbMassStorageEnabled()
1491 setUmsEnabling(enable);
1492 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1493 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1494 // Clear override
1495 setUmsEnabling(false);
1496 }
1497 /*
1498 * If we disabled UMS then mount the volume
1499 */
1500 if (!enable) {
1501 doShareUnshareVolume(path, method, enable);
1502 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001503 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001504 " after disabling share method " + method);
1505 /*
1506 * Even though the mount failed, the unshare didn't so don't indicate an error.
1507 * The mountVolume() call will have set the storage state and sent the necessary
1508 * broadcasts.
1509 */
1510 }
1511 }
San Mehatb1043402010-02-05 08:26:50 -08001512 }
1513
1514 public boolean isUsbMassStorageEnabled() {
1515 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001516
1517 final StorageVolume primary = getPrimaryPhysicalVolume();
1518 if (primary != null) {
1519 return doGetVolumeShared(primary.getPath(), "ums");
1520 } else {
1521 return false;
1522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001524
San Mehat7fd0fee2009-12-17 07:12:23 -08001525 /**
1526 * @return state of the volume at the specified mount point
1527 */
San Mehat4270e1e2010-01-29 05:32:19 -08001528 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001529 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001530 String state = mVolumeStates.get(mountPoint);
1531 if (state == null) {
1532 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001533 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1534 state = Environment.MEDIA_REMOVED;
1535 } else {
1536 throw new IllegalArgumentException();
1537 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001538 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001539
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001540 return state;
1541 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001542 }
1543
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001544 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001545 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001546 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001547 }
1548
San Mehat4270e1e2010-01-29 05:32:19 -08001549 public int mountVolume(String path) {
1550 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001551
San Mehat207e5382010-02-04 20:46:54 -08001552 waitForReady();
1553 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555
Ben Komalo13c71972011-09-07 16:35:56 -07001556 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001557 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001558 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001560 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001561 if (DEBUG_UNMOUNT) {
1562 Slog.i(TAG, "Unmounting " + path
1563 + " force = " + force
1564 + " removeEncryption = " + removeEncryption);
1565 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001566 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1567 Environment.MEDIA_REMOVED.equals(volState) ||
1568 Environment.MEDIA_SHARED.equals(volState) ||
1569 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1570 // Media already unmounted or cannot be unmounted.
1571 // TODO return valid return code when adding observer call back.
1572 return;
1573 }
Ben Komalo13c71972011-09-07 16:35:56 -07001574 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001575 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
1577
San Mehat4270e1e2010-01-29 05:32:19 -08001578 public int formatVolume(String path) {
1579 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001580 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001581
San Mehat207e5382010-02-04 20:46:54 -08001582 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001585 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001586 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1587 waitForReady();
1588 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001589 final String[] r = NativeDaemonEvent.filterMessageList(
1590 mConnector.executeForList("storage", "users", path),
1591 VoldResponseCode.StorageUsersListResult);
1592
San Mehatc1b4ce92010-02-16 17:13:03 -08001593 // FMT: <pid> <process name>
1594 int[] data = new int[r.length];
1595 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001596 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001597 try {
1598 data[i] = Integer.parseInt(tok[0]);
1599 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001600 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001601 return new int[0];
1602 }
1603 }
1604 return data;
1605 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001606 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001607 return new int[0];
1608 }
1609 }
1610
San Mehatb1043402010-02-05 08:26:50 -08001611 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001612 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001613 if (primary != null) {
1614 boolean mounted = false;
1615 try {
1616 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001617 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001618 }
1619
1620 if (!mounted) {
1621 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1622 }
San Mehatb1043402010-02-05 08:26:50 -08001623 }
1624 }
1625
San Mehat4270e1e2010-01-29 05:32:19 -08001626 public String[] getSecureContainerList() {
1627 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001628 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001629 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001630
San Mehat4270e1e2010-01-29 05:32:19 -08001631 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001632 return NativeDaemonEvent.filterMessageList(
1633 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001634 } catch (NativeDaemonConnectorException e) {
1635 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637 }
San Mehat36972292010-01-06 11:06:32 -08001638
Kenny Root6dceb882012-04-12 14:23:49 -07001639 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1640 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001641 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001642 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001643 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001644
San Mehatb1043402010-02-05 08:26:50 -08001645 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001646 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001647 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1648 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001649 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001650 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001651 }
San Mehata181b212010-02-11 06:50:20 -08001652
1653 if (rc == StorageResultCode.OperationSucceeded) {
1654 synchronized (mAsecMountSet) {
1655 mAsecMountSet.add(id);
1656 }
1657 }
San Mehat4270e1e2010-01-29 05:32:19 -08001658 return rc;
San Mehat36972292010-01-06 11:06:32 -08001659 }
1660
San Mehat4270e1e2010-01-29 05:32:19 -08001661 public int finalizeSecureContainer(String id) {
1662 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001663 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001664
San Mehatb1043402010-02-05 08:26:50 -08001665 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001666 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001667 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001668 /*
1669 * Finalization does a remount, so no need
1670 * to update mAsecMountSet
1671 */
San Mehat4270e1e2010-01-29 05:32:19 -08001672 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001673 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001674 }
San Mehat4270e1e2010-01-29 05:32:19 -08001675 return rc;
San Mehat36972292010-01-06 11:06:32 -08001676 }
1677
Kenny Root6dceb882012-04-12 14:23:49 -07001678 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1679 validatePermission(android.Manifest.permission.ASEC_CREATE);
1680 warnOnNotMounted();
1681
1682 int rc = StorageResultCode.OperationSucceeded;
1683 try {
1684 mConnector.execute("asec", "fixperms", id, gid, filename);
1685 /*
1686 * Fix permissions does a remount, so no need to update
1687 * mAsecMountSet
1688 */
1689 } catch (NativeDaemonConnectorException e) {
1690 rc = StorageResultCode.OperationFailedInternalError;
1691 }
1692 return rc;
1693 }
1694
San Mehatd9709982010-02-18 11:43:03 -08001695 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001696 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001697 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001698 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001699
Kenny Rootaa485402010-09-14 14:49:41 -07001700 /*
1701 * Force a GC to make sure AssetManagers in other threads of the
1702 * system_server are cleaned up. We have to do this since AssetManager
1703 * instances are kept as a WeakReference and it's possible we have files
1704 * open on the external storage.
1705 */
1706 Runtime.getRuntime().gc();
1707
San Mehatb1043402010-02-05 08:26:50 -08001708 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001709 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001710 final Command cmd = new Command("asec", "destroy", id);
1711 if (force) {
1712 cmd.appendArg("force");
1713 }
1714 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001715 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001716 int code = e.getCode();
1717 if (code == VoldResponseCode.OpFailedStorageBusy) {
1718 rc = StorageResultCode.OperationFailedStorageBusy;
1719 } else {
1720 rc = StorageResultCode.OperationFailedInternalError;
1721 }
San Mehat02735bc2010-01-26 15:18:08 -08001722 }
San Mehata181b212010-02-11 06:50:20 -08001723
1724 if (rc == StorageResultCode.OperationSucceeded) {
1725 synchronized (mAsecMountSet) {
1726 if (mAsecMountSet.contains(id)) {
1727 mAsecMountSet.remove(id);
1728 }
1729 }
1730 }
1731
San Mehat4270e1e2010-01-29 05:32:19 -08001732 return rc;
San Mehat36972292010-01-06 11:06:32 -08001733 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001734
San Mehat4270e1e2010-01-29 05:32:19 -08001735 public int mountSecureContainer(String id, String key, int ownerUid) {
1736 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001737 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001738 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001739
San Mehata181b212010-02-11 06:50:20 -08001740 synchronized (mAsecMountSet) {
1741 if (mAsecMountSet.contains(id)) {
1742 return StorageResultCode.OperationFailedStorageMounted;
1743 }
1744 }
1745
San Mehatb1043402010-02-05 08:26:50 -08001746 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001747 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001748 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001749 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001750 int code = e.getCode();
1751 if (code != VoldResponseCode.OpFailedStorageBusy) {
1752 rc = StorageResultCode.OperationFailedInternalError;
1753 }
San Mehat02735bc2010-01-26 15:18:08 -08001754 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001755
1756 if (rc == StorageResultCode.OperationSucceeded) {
1757 synchronized (mAsecMountSet) {
1758 mAsecMountSet.add(id);
1759 }
1760 }
San Mehat4270e1e2010-01-29 05:32:19 -08001761 return rc;
San Mehat36972292010-01-06 11:06:32 -08001762 }
1763
San Mehatd9709982010-02-18 11:43:03 -08001764 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001765 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001766 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001767 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001768
San Mehat6cdd9c02010-02-09 14:45:20 -08001769 synchronized (mAsecMountSet) {
1770 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001771 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001772 }
1773 }
1774
Kenny Rootaa485402010-09-14 14:49:41 -07001775 /*
1776 * Force a GC to make sure AssetManagers in other threads of the
1777 * system_server are cleaned up. We have to do this since AssetManager
1778 * instances are kept as a WeakReference and it's possible we have files
1779 * open on the external storage.
1780 */
1781 Runtime.getRuntime().gc();
1782
San Mehatb1043402010-02-05 08:26:50 -08001783 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001784 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001785 final Command cmd = new Command("asec", "unmount", id);
1786 if (force) {
1787 cmd.appendArg("force");
1788 }
1789 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001790 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001791 int code = e.getCode();
1792 if (code == VoldResponseCode.OpFailedStorageBusy) {
1793 rc = StorageResultCode.OperationFailedStorageBusy;
1794 } else {
1795 rc = StorageResultCode.OperationFailedInternalError;
1796 }
San Mehat02735bc2010-01-26 15:18:08 -08001797 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001798
1799 if (rc == StorageResultCode.OperationSucceeded) {
1800 synchronized (mAsecMountSet) {
1801 mAsecMountSet.remove(id);
1802 }
1803 }
San Mehat4270e1e2010-01-29 05:32:19 -08001804 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001805 }
1806
San Mehat6cdd9c02010-02-09 14:45:20 -08001807 public boolean isSecureContainerMounted(String id) {
1808 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1809 waitForReady();
1810 warnOnNotMounted();
1811
1812 synchronized (mAsecMountSet) {
1813 return mAsecMountSet.contains(id);
1814 }
1815 }
1816
San Mehat4270e1e2010-01-29 05:32:19 -08001817 public int renameSecureContainer(String oldId, String newId) {
1818 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001819 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001820 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001821
San Mehata181b212010-02-11 06:50:20 -08001822 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001823 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001824 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001825 * changed while active, we must ensure both ids are not currently mounted.
1826 */
1827 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001828 return StorageResultCode.OperationFailedStorageMounted;
1829 }
1830 }
1831
San Mehatb1043402010-02-05 08:26:50 -08001832 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001833 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001834 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001835 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001836 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001837 }
San Mehata181b212010-02-11 06:50:20 -08001838
San Mehat4270e1e2010-01-29 05:32:19 -08001839 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001840 }
1841
San Mehat4270e1e2010-01-29 05:32:19 -08001842 public String getSecureContainerPath(String id) {
1843 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001844 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001845 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001846
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001847 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001848 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001849 event = mConnector.execute("asec", "path", id);
1850 event.checkCode(VoldResponseCode.AsecPathResult);
1851 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001852 } catch (NativeDaemonConnectorException e) {
1853 int code = e.getCode();
1854 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001855 Slog.i(TAG, String.format("Container '%s' not found", id));
1856 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001857 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001858 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001859 }
1860 }
San Mehat22dd86e2010-01-12 12:21:18 -08001861 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001862
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001863 public String getSecureContainerFilesystemPath(String id) {
1864 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1865 waitForReady();
1866 warnOnNotMounted();
1867
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001868 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001869 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001870 event = mConnector.execute("asec", "fspath", id);
1871 event.checkCode(VoldResponseCode.AsecPathResult);
1872 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001873 } catch (NativeDaemonConnectorException e) {
1874 int code = e.getCode();
1875 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1876 Slog.i(TAG, String.format("Container '%s' not found", id));
1877 return null;
1878 } else {
1879 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1880 }
1881 }
1882 }
1883
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001884 public void finishMediaUpdate() {
1885 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1886 }
Kenny Root02c87302010-07-01 08:10:18 -07001887
Kenny Roota02b8b02010-08-05 16:14:17 -07001888 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1889 if (callerUid == android.os.Process.SYSTEM_UID) {
1890 return true;
1891 }
1892
Kenny Root02c87302010-07-01 08:10:18 -07001893 if (packageName == null) {
1894 return false;
1895 }
1896
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001897 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001898
1899 if (DEBUG_OBB) {
1900 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1901 packageUid + ", callerUid = " + callerUid);
1902 }
1903
1904 return callerUid == packageUid;
1905 }
1906
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001907 public String getMountedObbPath(String rawPath) {
1908 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001909
Kenny Root02c87302010-07-01 08:10:18 -07001910 waitForReady();
1911 warnOnNotMounted();
1912
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001913 final ObbState state;
1914 synchronized (mObbPathToStateMap) {
1915 state = mObbPathToStateMap.get(rawPath);
1916 }
1917 if (state == null) {
1918 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1919 return null;
1920 }
1921
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001922 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001923 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001924 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001925 event.checkCode(VoldResponseCode.AsecPathResult);
1926 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001927 } catch (NativeDaemonConnectorException e) {
1928 int code = e.getCode();
1929 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001930 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001931 } else {
1932 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1933 }
1934 }
1935 }
1936
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001937 @Override
1938 public boolean isObbMounted(String rawPath) {
1939 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001941 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001942 }
Kenny Root02c87302010-07-01 08:10:18 -07001943 }
1944
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001945 @Override
1946 public void mountObb(
1947 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1948 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1949 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1950 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001951
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001952 final int callingUid = Binder.getCallingUid();
1953 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1954 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001955 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1956
1957 if (DEBUG_OBB)
1958 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001959 }
1960
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001961 @Override
1962 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1963 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1964
1965 final ObbState existingState;
1966 synchronized (mObbPathToStateMap) {
1967 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001968 }
1969
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001970 if (existingState != null) {
1971 // TODO: separate state object from request data
1972 final int callingUid = Binder.getCallingUid();
1973 final ObbState newState = new ObbState(
1974 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1975 final ObbAction action = new UnmountObbAction(newState, force);
1976 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001977
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001978 if (DEBUG_OBB)
1979 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1980 } else {
1981 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1982 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001983 }
1984
Ben Komalo444eca22011-09-01 15:17:44 -07001985 @Override
1986 public int getEncryptionState() {
1987 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1988 "no permission to access the crypt keeper");
1989
1990 waitForReady();
1991
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001992 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001993 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001994 event = mConnector.execute("cryptfs", "cryptocomplete");
1995 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001996 } catch (NumberFormatException e) {
1997 // Bad result - unexpected.
1998 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1999 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2000 } catch (NativeDaemonConnectorException e) {
2001 // Something bad happened.
2002 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2003 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2004 }
2005 }
2006
2007 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002008 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002009 if (TextUtils.isEmpty(password)) {
2010 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002011 }
2012
Jason parks8888c592011-01-20 22:46:41 -06002013 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2014 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002015
2016 waitForReady();
2017
2018 if (DEBUG_EVENTS) {
2019 Slog.i(TAG, "decrypting storage...");
2020 }
2021
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002022 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002023 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002024 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002025
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002026 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002027 if (code == 0) {
2028 // Decrypt was successful. Post a delayed message before restarting in order
2029 // to let the UI to clear itself
2030 mHandler.postDelayed(new Runnable() {
2031 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002033 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002034 } catch (NativeDaemonConnectorException e) {
2035 Slog.e(TAG, "problem executing in background", e);
2036 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002037 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002038 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002039 }
2040
2041 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002042 } catch (NativeDaemonConnectorException e) {
2043 // Decryption failed
2044 return e.getCode();
2045 }
Jason parks5af0b912010-11-29 09:05:25 -06002046 }
2047
Jason parks56aa5322011-01-07 09:01:15 -06002048 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002049 if (TextUtils.isEmpty(password)) {
2050 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002051 }
2052
Jason parks8888c592011-01-20 22:46:41 -06002053 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2054 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002055
2056 waitForReady();
2057
2058 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002059 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002060 }
2061
2062 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002063 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002064 } catch (NativeDaemonConnectorException e) {
2065 // Encryption failed
2066 return e.getCode();
2067 }
2068
2069 return 0;
2070 }
2071
Jason parksf7b3cd42011-01-27 09:28:25 -06002072 public int changeEncryptionPassword(String password) {
2073 if (TextUtils.isEmpty(password)) {
2074 throw new IllegalArgumentException("password cannot be empty");
2075 }
2076
2077 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2078 "no permission to access the crypt keeper");
2079
2080 waitForReady();
2081
2082 if (DEBUG_EVENTS) {
2083 Slog.i(TAG, "changing encryption password...");
2084 }
2085
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002086 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002087 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002088 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002089 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002090 } catch (NativeDaemonConnectorException e) {
2091 // Encryption failed
2092 return e.getCode();
2093 }
2094 }
2095
Christopher Tate32418be2011-10-10 13:51:12 -07002096 /**
2097 * Validate a user-supplied password string with cryptfs
2098 */
2099 @Override
2100 public int verifyEncryptionPassword(String password) throws RemoteException {
2101 // Only the system process is permitted to validate passwords
2102 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2103 throw new SecurityException("no permission to access the crypt keeper");
2104 }
2105
2106 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2107 "no permission to access the crypt keeper");
2108
2109 if (TextUtils.isEmpty(password)) {
2110 throw new IllegalArgumentException("password cannot be empty");
2111 }
2112
2113 waitForReady();
2114
2115 if (DEBUG_EVENTS) {
2116 Slog.i(TAG, "validating encryption password...");
2117 }
2118
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002119 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002120 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002121 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002122 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2123 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002124 } catch (NativeDaemonConnectorException e) {
2125 // Encryption failed
2126 return e.getCode();
2127 }
2128 }
2129
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002130 @Override
2131 public StorageVolume[] getVolumeList() {
2132 final int callingUserId = UserHandle.getCallingUserId();
2133 final boolean accessAll = (mContext.checkPermission(
2134 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2135 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2136
2137 synchronized (mVolumesLock) {
2138 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2139 for (StorageVolume volume : mVolumes) {
2140 final UserHandle owner = volume.getOwner();
2141 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2142 if (accessAll || ownerMatch) {
2143 filtered.add(volume);
2144 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002145 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002146 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002147 }
2148 }
2149
Kenny Rootaf9d6672010-10-08 09:21:39 -07002150 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2151 final IBinder binder = obbState.getBinder();
2152 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002153
Kenny Rootaf9d6672010-10-08 09:21:39 -07002154 if (obbStates == null) {
2155 obbStates = new ArrayList<ObbState>();
2156 mObbMounts.put(binder, obbStates);
2157 } else {
2158 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002159 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002160 throw new IllegalStateException("Attempt to add ObbState twice. "
2161 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002162 }
2163 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002164 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002165
2166 obbStates.add(obbState);
2167 try {
2168 obbState.link();
2169 } catch (RemoteException e) {
2170 /*
2171 * The binder died before we could link it, so clean up our state
2172 * and return failure.
2173 */
2174 obbStates.remove(obbState);
2175 if (obbStates.isEmpty()) {
2176 mObbMounts.remove(binder);
2177 }
2178
2179 // Rethrow the error so mountObb can get it
2180 throw e;
2181 }
2182
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002183 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002184 }
2185
Kenny Rootaf9d6672010-10-08 09:21:39 -07002186 private void removeObbStateLocked(ObbState obbState) {
2187 final IBinder binder = obbState.getBinder();
2188 final List<ObbState> obbStates = mObbMounts.get(binder);
2189 if (obbStates != null) {
2190 if (obbStates.remove(obbState)) {
2191 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002192 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002193 if (obbStates.isEmpty()) {
2194 mObbMounts.remove(binder);
2195 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002196 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002197
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002198 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002199 }
2200
Kenny Roota02b8b02010-08-05 16:14:17 -07002201 private class ObbActionHandler extends Handler {
2202 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002203 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002204
2205 ObbActionHandler(Looper l) {
2206 super(l);
2207 }
2208
2209 @Override
2210 public void handleMessage(Message msg) {
2211 switch (msg.what) {
2212 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002213 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002214
2215 if (DEBUG_OBB)
2216 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2217
2218 // If a bind was already initiated we don't really
2219 // need to do anything. The pending install
2220 // will be processed later on.
2221 if (!mBound) {
2222 // If this is the only one pending we might
2223 // have to bind to the service again.
2224 if (!connectToService()) {
2225 Slog.e(TAG, "Failed to bind to media container service");
2226 action.handleError();
2227 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002228 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002229 }
Kenny Root735de3b2010-09-30 14:11:39 -07002230
Kenny Root735de3b2010-09-30 14:11:39 -07002231 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002232 break;
2233 }
2234 case OBB_MCS_BOUND: {
2235 if (DEBUG_OBB)
2236 Slog.i(TAG, "OBB_MCS_BOUND");
2237 if (msg.obj != null) {
2238 mContainerService = (IMediaContainerService) msg.obj;
2239 }
2240 if (mContainerService == null) {
2241 // Something seriously wrong. Bail out
2242 Slog.e(TAG, "Cannot bind to media container service");
2243 for (ObbAction action : mActions) {
2244 // Indicate service bind error
2245 action.handleError();
2246 }
2247 mActions.clear();
2248 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002249 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002250 if (action != null) {
2251 action.execute(this);
2252 }
2253 } else {
2254 // Should never happen ideally.
2255 Slog.w(TAG, "Empty queue");
2256 }
2257 break;
2258 }
2259 case OBB_MCS_RECONNECT: {
2260 if (DEBUG_OBB)
2261 Slog.i(TAG, "OBB_MCS_RECONNECT");
2262 if (mActions.size() > 0) {
2263 if (mBound) {
2264 disconnectService();
2265 }
2266 if (!connectToService()) {
2267 Slog.e(TAG, "Failed to bind to media container service");
2268 for (ObbAction action : mActions) {
2269 // Indicate service bind error
2270 action.handleError();
2271 }
2272 mActions.clear();
2273 }
2274 }
2275 break;
2276 }
2277 case OBB_MCS_UNBIND: {
2278 if (DEBUG_OBB)
2279 Slog.i(TAG, "OBB_MCS_UNBIND");
2280
2281 // Delete pending install
2282 if (mActions.size() > 0) {
2283 mActions.remove(0);
2284 }
2285 if (mActions.size() == 0) {
2286 if (mBound) {
2287 disconnectService();
2288 }
2289 } else {
2290 // There are more pending requests in queue.
2291 // Just post MCS_BOUND message to trigger processing
2292 // of next pending install.
2293 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2294 }
2295 break;
2296 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002297 case OBB_FLUSH_MOUNT_STATE: {
2298 final String path = (String) msg.obj;
2299
2300 if (DEBUG_OBB)
2301 Slog.i(TAG, "Flushing all OBB state for path " + path);
2302
2303 synchronized (mObbMounts) {
2304 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2305
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002306 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002307 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002308 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002309
2310 /*
2311 * If this entry's source file is in the volume path
2312 * that got unmounted, remove it because it's no
2313 * longer valid.
2314 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002315 if (state.canonicalPath.startsWith(path)) {
2316 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 }
2318 }
2319
2320 for (final ObbState obbState : obbStatesToRemove) {
2321 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002322 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002323
2324 removeObbStateLocked(obbState);
2325
2326 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002327 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002328 OnObbStateChangeListener.UNMOUNTED);
2329 } catch (RemoteException e) {
2330 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002331 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002332 }
2333 }
2334 }
2335 break;
2336 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002337 }
2338 }
2339
2340 private boolean connectToService() {
2341 if (DEBUG_OBB)
2342 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2343
2344 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2345 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2346 mBound = true;
2347 return true;
2348 }
2349 return false;
2350 }
2351
2352 private void disconnectService() {
2353 mContainerService = null;
2354 mBound = false;
2355 mContext.unbindService(mDefContainerConn);
2356 }
2357 }
2358
2359 abstract class ObbAction {
2360 private static final int MAX_RETRIES = 3;
2361 private int mRetries;
2362
2363 ObbState mObbState;
2364
2365 ObbAction(ObbState obbState) {
2366 mObbState = obbState;
2367 }
2368
2369 public void execute(ObbActionHandler handler) {
2370 try {
2371 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002372 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002373 mRetries++;
2374 if (mRetries > MAX_RETRIES) {
2375 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002376 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002377 handleError();
2378 return;
2379 } else {
2380 handleExecute();
2381 if (DEBUG_OBB)
2382 Slog.i(TAG, "Posting install MCS_UNBIND");
2383 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2384 }
2385 } catch (RemoteException e) {
2386 if (DEBUG_OBB)
2387 Slog.i(TAG, "Posting install MCS_RECONNECT");
2388 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2389 } catch (Exception e) {
2390 if (DEBUG_OBB)
2391 Slog.d(TAG, "Error handling OBB action", e);
2392 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002393 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002394 }
2395 }
2396
Kenny Root05105f72010-09-22 17:29:43 -07002397 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002398 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002399
2400 protected ObbInfo getObbInfo() throws IOException {
2401 ObbInfo obbInfo;
2402 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002403 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002404 } catch (RemoteException e) {
2405 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002406 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002407 obbInfo = null;
2408 }
2409 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002410 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002411 }
2412 return obbInfo;
2413 }
2414
Kenny Rootaf9d6672010-10-08 09:21:39 -07002415 protected void sendNewStatusOrIgnore(int status) {
2416 if (mObbState == null || mObbState.token == null) {
2417 return;
2418 }
2419
Kenny Root38cf8862010-09-26 14:18:51 -07002420 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002422 } catch (RemoteException e) {
2423 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2424 }
2425 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002426 }
2427
2428 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002429 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002430 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002431
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002432 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002433 super(obbState);
2434 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002435 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002436 }
2437
Jason parks5af0b912010-11-29 09:05:25 -06002438 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002439 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002440 waitForReady();
2441 warnOnNotMounted();
2442
Kenny Root38cf8862010-09-26 14:18:51 -07002443 final ObbInfo obbInfo = getObbInfo();
2444
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002445 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002446 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2447 + " which is owned by " + obbInfo.packageName);
2448 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2449 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002450 }
2451
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 final boolean isMounted;
2453 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002454 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002455 }
2456 if (isMounted) {
2457 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2458 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2459 return;
2460 }
2461
Kenny Rootaf9d6672010-10-08 09:21:39 -07002462 final String hashedKey;
2463 if (mKey == null) {
2464 hashedKey = "none";
2465 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002466 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002467 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2468
2469 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2470 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2471 SecretKey key = factory.generateSecret(ks);
2472 BigInteger bi = new BigInteger(key.getEncoded());
2473 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002474 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002475 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2476 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2477 return;
2478 } catch (InvalidKeySpecException e) {
2479 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2480 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002481 return;
2482 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002483 }
Kenny Root38cf8862010-09-26 14:18:51 -07002484
Kenny Rootaf9d6672010-10-08 09:21:39 -07002485 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002486 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002487 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2488 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002489 } catch (NativeDaemonConnectorException e) {
2490 int code = e.getCode();
2491 if (code != VoldResponseCode.OpFailedStorageBusy) {
2492 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002493 }
2494 }
2495
Kenny Rootaf9d6672010-10-08 09:21:39 -07002496 if (rc == StorageResultCode.OperationSucceeded) {
2497 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002498 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002499
2500 synchronized (mObbMounts) {
2501 addObbStateLocked(mObbState);
2502 }
2503
2504 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002505 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002506 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002507
Kenny Rootaf9d6672010-10-08 09:21:39 -07002508 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002509 }
2510 }
2511
Jason parks5af0b912010-11-29 09:05:25 -06002512 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002513 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002514 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002515 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002516
2517 @Override
2518 public String toString() {
2519 StringBuilder sb = new StringBuilder();
2520 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002521 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002522 sb.append('}');
2523 return sb.toString();
2524 }
2525 }
2526
2527 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002528 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002529
2530 UnmountObbAction(ObbState obbState, boolean force) {
2531 super(obbState);
2532 mForceUnmount = force;
2533 }
2534
Jason parks5af0b912010-11-29 09:05:25 -06002535 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002536 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002537 waitForReady();
2538 warnOnNotMounted();
2539
Kenny Root38cf8862010-09-26 14:18:51 -07002540 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002541
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002542 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002543 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002544 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002545 }
Kenny Root38cf8862010-09-26 14:18:51 -07002546
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002547 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002548 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2549 return;
2550 }
2551
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002552 if (existingState.ownerGid != mObbState.ownerGid) {
2553 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2554 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002555 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2556 return;
2557 }
2558
Kenny Rootaf9d6672010-10-08 09:21:39 -07002559 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002560 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002561 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002562 if (mForceUnmount) {
2563 cmd.appendArg("force");
2564 }
2565 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002566 } catch (NativeDaemonConnectorException e) {
2567 int code = e.getCode();
2568 if (code == VoldResponseCode.OpFailedStorageBusy) {
2569 rc = StorageResultCode.OperationFailedStorageBusy;
2570 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2571 // If it's not mounted then we've already won.
2572 rc = StorageResultCode.OperationSucceeded;
2573 } else {
2574 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002575 }
2576 }
2577
Kenny Rootaf9d6672010-10-08 09:21:39 -07002578 if (rc == StorageResultCode.OperationSucceeded) {
2579 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002580 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002581 }
2582
Kenny Rootaf9d6672010-10-08 09:21:39 -07002583 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002584 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002585 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002586 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002587 }
2588 }
2589
Jason parks5af0b912010-11-29 09:05:25 -06002590 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002591 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002592 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002593 }
2594
2595 @Override
2596 public String toString() {
2597 StringBuilder sb = new StringBuilder();
2598 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002599 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002600 sb.append(",force=");
2601 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002602 sb.append('}');
2603 return sb.toString();
2604 }
Kenny Root02c87302010-07-01 08:10:18 -07002605 }
Kenny Root38cf8862010-09-26 14:18:51 -07002606
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002607 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002608 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2609 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002610 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002611
2612 // Only adjust paths when storage is emulated
2613 if (!Environment.isExternalStorageEmulated()) {
2614 return canonicalPath;
2615 }
2616
2617 String path = canonicalPath.toString();
2618
2619 // First trim off any external storage prefix
2620 final UserEnvironment userEnv = new UserEnvironment(userId);
2621
2622 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002623 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002624 // /storage/emulated_legacy
2625 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002626 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002627
2628 if (path.startsWith(externalPath)) {
2629 path = path.substring(externalPath.length() + 1);
2630 } else if (path.startsWith(legacyExternalPath)) {
2631 path = path.substring(legacyExternalPath.length() + 1);
2632 } else {
2633 return canonicalPath;
2634 }
2635
2636 // Handle special OBB paths on emulated storage
2637 final String obbPath = "Android/obb";
2638 if (path.startsWith(obbPath)) {
2639 path = path.substring(obbPath.length() + 1);
2640
2641 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002642 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002643 } else {
2644 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002645 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2646 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002647 }
2648 }
2649
2650 // Handle normal external storage paths
2651 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002652 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002653 } else {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002654 return new File(userEnv.getExternalDirs()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002655 }
2656 }
2657
Kenny Root38cf8862010-09-26 14:18:51 -07002658 @Override
2659 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2660 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2661 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2662 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2663 + " without permission " + android.Manifest.permission.DUMP);
2664 return;
2665 }
2666
Kenny Root38cf8862010-09-26 14:18:51 -07002667 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002668 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002669
Kenny Rootaf9d6672010-10-08 09:21:39 -07002670 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2671 while (binders.hasNext()) {
2672 Entry<IBinder, List<ObbState>> e = binders.next();
2673 pw.print(" Key="); pw.println(e.getKey().toString());
2674 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002675 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002676 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002677 }
2678 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002679
2680 pw.println("");
2681 pw.println(" mObbPathToStateMap:");
2682 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2683 while (maps.hasNext()) {
2684 final Entry<String, ObbState> e = maps.next();
2685 pw.print(" "); pw.print(e.getKey());
2686 pw.print(" -> "); pw.println(e.getValue().toString());
2687 }
Kenny Root38cf8862010-09-26 14:18:51 -07002688 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002689
2690 pw.println("");
2691
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002692 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002693 pw.println(" mVolumes:");
2694
2695 final int N = mVolumes.size();
2696 for (int i = 0; i < N; i++) {
2697 final StorageVolume v = mVolumes.get(i);
2698 pw.print(" ");
2699 pw.println(v.toString());
2700 }
2701 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002702
2703 pw.println();
2704 pw.println(" mConnection:");
2705 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002708 /** {@inheritDoc} */
2709 public void monitor() {
2710 if (mConnector != null) {
2711 mConnector.monitor();
2712 }
2713 }
2714}