blob: 6ab86f5a3c4ecd4738bbd8385effdf9ebebef943 [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;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070064import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070065import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070066import com.android.internal.util.XmlUtils;
67import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070068import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070069import com.android.server.am.ActivityManagerService;
70import com.android.server.pm.PackageManagerService;
71import com.android.server.pm.UserManagerService;
72import com.google.android.collect.Lists;
73import com.google.android.collect.Maps;
74
Mike Lockwood2f6a3882011-05-09 19:08:06 -070075import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070076
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070077import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070078import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070079import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070080import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070081import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070082import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070083import java.security.spec.InvalidKeySpecException;
84import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080085import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070086import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080087import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070088import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070089import java.util.LinkedList;
90import java.util.List;
91import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070092import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070093import java.util.concurrent.CountDownLatch;
94import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Kenny Root3b1abba2010-10-13 15:00:07 -070096import javax.crypto.SecretKey;
97import javax.crypto.SecretKeyFactory;
98import javax.crypto.spec.PBEKeySpec;
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100/**
San Mehatb1043402010-02-05 08:26:50 -0800101 * MountService implements back-end services for platform storage
102 * management.
103 * @hide - Applications should use android.os.storage.StorageManager
104 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700106class MountService extends IMountService.Stub
107 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600108
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700109 // TODO: listen for user creation/deletion
110
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800111 private static final boolean LOCAL_LOGD = false;
112 private static final boolean DEBUG_UNMOUNT = false;
113 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800114 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700115
Kenny Root07714d42011-08-17 17:49:28 -0700116 // Disable this since it messes up long-running cryptfs operations.
117 private static final boolean WATCHDOG_ENABLE = false;
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final String TAG = "MountService";
120
Kenny Root305bcbf2010-09-03 07:56:38 -0700121 private static final String VOLD_TAG = "VoldConnector";
122
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700123 /** Maximum number of ASEC containers allowed to be mounted. */
124 private static final int MAX_CONTAINERS = 250;
125
San Mehat4270e1e2010-01-29 05:32:19 -0800126 /*
127 * Internal vold volume state constants
128 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800129 class VolumeState {
130 public static final int Init = -1;
131 public static final int NoMedia = 0;
132 public static final int Idle = 1;
133 public static final int Pending = 2;
134 public static final int Checking = 3;
135 public static final int Mounted = 4;
136 public static final int Unmounting = 5;
137 public static final int Formatting = 6;
138 public static final int Shared = 7;
139 public static final int SharedMnt = 8;
140 }
141
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * Internal vold response code constants
144 */
San Mehat22dd86e2010-01-12 12:21:18 -0800145 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800146 /*
147 * 100 series - Requestion action was initiated; expect another reply
148 * before proceeding with a new command.
149 */
San Mehat22dd86e2010-01-12 12:21:18 -0800150 public static final int VolumeListResult = 110;
151 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800152 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800153
San Mehat4270e1e2010-01-29 05:32:19 -0800154 /*
155 * 200 series - Requestion action has been successfully completed.
156 */
157 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800158 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800159 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800160
San Mehat4270e1e2010-01-29 05:32:19 -0800161 /*
162 * 400 series - Command was accepted, but the requested action
163 * did not take place.
164 */
165 public static final int OpFailedNoMedia = 401;
166 public static final int OpFailedMediaBlank = 402;
167 public static final int OpFailedMediaCorrupt = 403;
168 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800169 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700170 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800171
172 /*
173 * 600 series - Unsolicited broadcasts.
174 */
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800176 public static final int VolumeDiskInserted = 630;
177 public static final int VolumeDiskRemoved = 631;
178 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700179
180 /*
181 * 700 series - fstrim
182 */
183 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800184 }
185
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700186 private Context mContext;
187 private NativeDaemonConnector mConnector;
188
189 private final Object mVolumesLock = new Object();
190
191 /** When defined, base template for user-specific {@link StorageVolume}. */
192 private StorageVolume mEmulatedTemplate;
193
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700194 // TODO: separate storage volumes on per-user basis
195
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700197 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
198 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700200 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
201 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800202 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700203 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
204
205 private volatile boolean mSystemReady = false;
206
San Mehat4270e1e2010-01-29 05:32:19 -0800207 private PackageManagerService mPms;
208 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700209 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800210 // Used as a lock for methods that register/unregister listeners.
211 final private ArrayList<MountServiceBinderListener> mListeners =
212 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800213 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
214 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800215 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800216
San Mehat6cdd9c02010-02-09 14:45:20 -0800217 /**
218 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800219 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800220 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800221 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800222
Kenny Root02c87302010-07-01 08:10:18 -0700223 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700224 * The size of the crypto algorithm key in bits for OBB files. Currently
225 * Twofish is used which takes 128-bit keys.
226 */
227 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
228
229 /**
230 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
231 * 1024 is reasonably secure and not too slow.
232 */
233 private static final int PBKDF2_HASH_ROUNDS = 1024;
234
235 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700236 * Mounted OBB tracking information. Used to track the current state of all
237 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700238 */
Kenny Root735de3b2010-09-30 14:11:39 -0700239 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700240
241 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700242 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
243
244 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700245 public ObbState(String rawPath, String canonicalPath, int callingUid,
246 IObbActionListener token, int nonce) {
247 this.rawPath = rawPath;
248 this.canonicalPath = canonicalPath.toString();
249
250 final int userId = UserHandle.getUserId(callingUid);
251 this.ownerPath = buildObbPath(canonicalPath, userId, false);
252 this.voldPath = buildObbPath(canonicalPath, userId, true);
253
254 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700255 this.token = token;
256 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700257 }
258
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700259 final String rawPath;
260 final String canonicalPath;
261 final String ownerPath;
262 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700263
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700264 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700265
Kenny Rootaf9d6672010-10-08 09:21:39 -0700266 // Token of remote Binder caller
267 final IObbActionListener token;
268
269 // Identifier to pass back to the token
270 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700271
Kenny Root735de3b2010-09-30 14:11:39 -0700272 public IBinder getBinder() {
273 return token.asBinder();
274 }
275
Kenny Roota02b8b02010-08-05 16:14:17 -0700276 @Override
277 public void binderDied() {
278 ObbAction action = new UnmountObbAction(this, true);
279 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700280 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700281
Kenny Root5919ac62010-10-05 09:49:40 -0700282 public void link() throws RemoteException {
283 getBinder().linkToDeath(this, 0);
284 }
285
286 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700287 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700288 }
Kenny Root38cf8862010-09-26 14:18:51 -0700289
290 @Override
291 public String toString() {
292 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700293 sb.append("rawPath=").append(rawPath);
294 sb.append(",canonicalPath=").append(canonicalPath);
295 sb.append(",ownerPath=").append(ownerPath);
296 sb.append(",voldPath=").append(voldPath);
297 sb.append(",ownerGid=").append(ownerGid);
298 sb.append(",token=").append(token);
299 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700300 sb.append('}');
301 return sb.toString();
302 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700303 }
304
305 // OBB Action Handler
306 final private ObbActionHandler mObbActionHandler;
307
308 // OBB action handler messages
309 private static final int OBB_RUN_ACTION = 1;
310 private static final int OBB_MCS_BOUND = 2;
311 private static final int OBB_MCS_UNBIND = 3;
312 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700313 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700314
315 /*
316 * Default Container Service information
317 */
318 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
319 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
320
321 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
322
323 class DefaultContainerConnection implements ServiceConnection {
324 public void onServiceConnected(ComponentName name, IBinder service) {
325 if (DEBUG_OBB)
326 Slog.i(TAG, "onServiceConnected");
327 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
328 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
329 }
330
331 public void onServiceDisconnected(ComponentName name) {
332 if (DEBUG_OBB)
333 Slog.i(TAG, "onServiceDisconnected");
334 }
335 };
336
337 // Used in the ObbActionHandler
338 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700339
340 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800341 private static final int H_UNMOUNT_PM_UPDATE = 1;
342 private static final int H_UNMOUNT_PM_DONE = 2;
343 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700344 private static final int H_SYSTEM_READY = 4;
345
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
347 private static final int MAX_UNMOUNT_RETRIES = 4;
348
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700350 final String path;
351 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700352 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354
Ben Komalo13c71972011-09-07 16:35:56 -0700355 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800356 retries = 0;
357 this.path = path;
358 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700359 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800360 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800361
362 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700363 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700364 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800365 }
366 }
367
368 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700369 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370
371 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700372 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800373 this.method = method;
374 }
375
376 @Override
377 void handleFinished() {
378 super.handleFinished();
379 doShareUnshareVolume(path, method, true);
380 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800381 }
382
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 class ShutdownCallBack extends UnmountCallBack {
384 IMountShutdownObserver observer;
385 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700386 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 this.observer = observer;
388 }
389
390 @Override
391 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700392 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800393 if (observer != null) {
394 try {
395 observer.onShutDownComplete(ret);
396 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700397 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800398 }
399 }
400 }
401 }
402
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400403 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800404 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700405 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800406
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400407 MountServiceHandler(Looper l) {
408 super(l);
409 }
410
Jason parks5af0b912010-11-29 09:05:25 -0600411 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 public void handleMessage(Message msg) {
413 switch (msg.what) {
414 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800416 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
417 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800419 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700420 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700421 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700422 mUpdatingStatus = true;
423 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800424 }
425 break;
426 }
427 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700428 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700429 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700430 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800431 int size = mForceUnmounts.size();
432 int sizeArr[] = new int[size];
433 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700434 // Kill processes holding references first
435 ActivityManagerService ams = (ActivityManagerService)
436 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800437 for (int i = 0; i < size; i++) {
438 UnmountCallBack ucb = mForceUnmounts.get(i);
439 String path = ucb.path;
440 boolean done = false;
441 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800442 done = true;
443 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800444 int pids[] = getStorageUsers(path);
445 if (pids == null || pids.length == 0) {
446 done = true;
447 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800448 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800449 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700450 // Confirm if file references have been freed.
451 pids = getStorageUsers(path);
452 if (pids == null || pids.length == 0) {
453 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800454 }
455 }
456 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700457 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
458 // Retry again
459 Slog.i(TAG, "Retrying to kill storage users again");
460 mHandler.sendMessageDelayed(
461 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
462 ucb.retries++),
463 RETRY_UNMOUNT_DELAY);
464 } else {
465 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
466 Slog.i(TAG, "Failed to unmount media inspite of " +
467 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
468 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800469 sizeArr[sizeArrN++] = i;
470 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
471 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800472 }
473 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800474 // Remove already processed elements from list.
475 for (int i = (sizeArrN-1); i >= 0; i--) {
476 mForceUnmounts.remove(sizeArr[i]);
477 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800478 break;
479 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700480 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700481 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800482 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800483 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800484 break;
485 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700486 case H_SYSTEM_READY: {
487 try {
488 handleSystemReady();
489 } catch (Exception ex) {
490 Slog.e(TAG, "Boot-time mount exception", ex);
491 }
492 break;
493 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800494 }
495 }
496 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700497
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700498 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800499
Kenny Root51a573c2012-05-17 13:30:28 -0700500 void waitForAsecScan() {
501 waitForLatch(mAsecsScanned);
502 }
503
San Mehat207e5382010-02-04 20:46:54 -0800504 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700505 waitForLatch(mConnectedSignal);
506 }
507
508 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700509 for (;;) {
510 try {
511 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800512 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700513 } else {
514 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
515 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800516 }
Kenny Root51a573c2012-05-17 13:30:28 -0700517 } catch (InterruptedException e) {
518 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800519 }
San Mehat207e5382010-02-04 20:46:54 -0800520 }
San Mehat1f6301e2010-01-07 22:40:27 -0800521 }
Kenny Root02c87302010-07-01 08:10:18 -0700522
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700523 private void handleSystemReady() {
524 // Snapshot current volume states since it's not safe to call into vold
525 // while holding locks.
526 final HashMap<String, String> snapshot;
527 synchronized (mVolumesLock) {
528 snapshot = new HashMap<String, String>(mVolumeStates);
529 }
530
531 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
532 final String path = entry.getKey();
533 final String state = entry.getValue();
534
535 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
536 int rc = doMountVolume(path);
537 if (rc != StorageResultCode.OperationSucceeded) {
538 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
539 rc));
540 }
541 } else if (state.equals(Environment.MEDIA_SHARED)) {
542 /*
543 * Bootstrap UMS enabled state since vold indicates
544 * the volume is shared (runtime restart while ums enabled)
545 */
546 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
547 VolumeState.Shared);
548 }
549 }
550
551 // Push mounted state for all emulated storage
552 synchronized (mVolumesLock) {
553 for (StorageVolume volume : mVolumes) {
554 if (volume.isEmulated()) {
555 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
556 }
557 }
558 }
559
560 /*
561 * If UMS was connected on boot, send the connected event
562 * now that we're up.
563 */
564 if (mSendUmsConnectedOnBoot) {
565 sendUmsIntent(true);
566 mSendUmsConnectedOnBoot = false;
567 }
568 }
569
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700570 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
571 @Override
572 public void onReceive(Context context, Intent intent) {
573 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
574 if (userId == -1) return;
575 final UserHandle user = new UserHandle(userId);
576
577 final String action = intent.getAction();
578 if (Intent.ACTION_USER_ADDED.equals(action)) {
579 synchronized (mVolumesLock) {
580 createEmulatedVolumeForUserLocked(user);
581 }
582
583 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
584 synchronized (mVolumesLock) {
585 final List<StorageVolume> toRemove = Lists.newArrayList();
586 for (StorageVolume volume : mVolumes) {
587 if (user.equals(volume.getOwner())) {
588 toRemove.add(volume);
589 }
590 }
591 for (StorageVolume volume : toRemove) {
592 removeVolumeLocked(volume);
593 }
594 }
595 }
596 }
597 };
598
599 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
600 @Override
601 public void onReceive(Context context, Intent intent) {
602 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
603 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
604 notifyShareAvailabilityChange(available);
605 }
606 };
607
Svetoslava7452ee2013-03-20 12:06:59 -0700608 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
609 @Override
610 public void onReceive(Context context, Intent intent) {
611 waitForReady();
612 String action = intent.getAction();
613 // Since fstrim will be run on a daily basis we do not expect
614 // fstrim to be too long, so it is not interruptible. We will
615 // implement interruption only in case we see issues.
616 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
617 try {
618 // This method runs on the handler thread,
619 // so it is safe to directly call into vold.
620 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700621 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700622 } catch (NativeDaemonConnectorException ndce) {
623 Slog.e(TAG, "Failed to run fstrim!");
624 }
625 }
626 }
627 };
628
San Mehat4270e1e2010-01-29 05:32:19 -0800629 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
630 final IMountServiceListener mListener;
631
632 MountServiceBinderListener(IMountServiceListener listener) {
633 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700634
San Mehat91c77612010-01-07 10:39:41 -0800635 }
636
San Mehat4270e1e2010-01-29 05:32:19 -0800637 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700638 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700639 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800640 mListeners.remove(this);
641 mListener.asBinder().unlinkToDeath(this, 0);
642 }
643 }
644 }
645
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800646 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800647 // TODO: Add support for multiple share methods
648 if (!method.equals("ums")) {
649 throw new IllegalArgumentException(String.format("Method %s not supported", method));
650 }
651
San Mehat4270e1e2010-01-29 05:32:19 -0800652 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800653 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800654 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700655 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800656 }
San Mehat4270e1e2010-01-29 05:32:19 -0800657 }
658
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700659 private void updatePublicVolumeState(StorageVolume volume, String state) {
660 final String path = volume.getPath();
661 final String oldState;
662 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400663 oldState = mVolumeStates.put(path, state);
664 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700665
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400666 if (state.equals(oldState)) {
667 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
668 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800669 return;
670 }
San Mehatb1043402010-02-05 08:26:50 -0800671
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400672 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700673
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700674 // Tell PackageManager about changes to primary volume state, but only
675 // when not emulated.
676 if (volume.isPrimary() && !volume.isEmulated()) {
677 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
678 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400679
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700680 /*
681 * Some OBBs might have been unmounted when this volume was
682 * unmounted, so send a message to the handler to let it know to
683 * remove those from the list of mounted OBBS.
684 */
685 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
686 OBB_FLUSH_MOUNT_STATE, path));
687 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
688 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400689 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800690 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700691
San Mehat4270e1e2010-01-29 05:32:19 -0800692 synchronized (mListeners) {
693 for (int i = mListeners.size() -1; i >= 0; i--) {
694 MountServiceBinderListener bl = mListeners.get(i);
695 try {
San Mehatb1043402010-02-05 08:26:50 -0800696 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800697 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700698 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800699 mListeners.remove(i);
700 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700701 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800702 }
703 }
704 }
705 }
706
707 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800708 * Callback from NativeDaemonConnector
709 */
710 public void onDaemonConnected() {
711 /*
712 * Since we'll be calling back into the NativeDaemonConnector,
713 * we need to do our work in a new thread.
714 */
Kenny Root51a573c2012-05-17 13:30:28 -0700715 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600716 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800717 public void run() {
718 /**
719 * Determine media state and UMS detection status
720 */
San Mehat4270e1e2010-01-29 05:32:19 -0800721 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800722 final String[] vols = NativeDaemonEvent.filterMessageList(
723 mConnector.executeForList("volume", "list"),
724 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800725 for (String volstr : vols) {
726 String[] tok = volstr.split(" ");
727 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400728 String path = tok[1];
729 String state = Environment.MEDIA_REMOVED;
730
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700731 final StorageVolume volume;
732 synchronized (mVolumesLock) {
733 volume = mVolumesByPath.get(path);
734 }
735
San Mehat4270e1e2010-01-29 05:32:19 -0800736 int st = Integer.parseInt(tok[2]);
737 if (st == VolumeState.NoMedia) {
738 state = Environment.MEDIA_REMOVED;
739 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800740 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800741 } else if (st == VolumeState.Mounted) {
742 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700743 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800744 } else if (st == VolumeState.Shared) {
745 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700746 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800747 } else {
748 throw new Exception(String.format("Unexpected state %d", st));
749 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400750
751 if (state != null) {
752 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700753 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400754 }
San Mehat4270e1e2010-01-29 05:32:19 -0800755 }
756 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700757 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700758 final StorageVolume primary = getPrimaryPhysicalVolume();
759 if (primary != null) {
760 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
761 }
San Mehat4270e1e2010-01-29 05:32:19 -0800762 }
763
San Mehat207e5382010-02-04 20:46:54 -0800764 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600765 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800766 * the hounds!
767 */
Kenny Root51a573c2012-05-17 13:30:28 -0700768 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700769
770 // Let package manager load internal ASECs.
771 mPms.scanAvailableAsecs();
772
773 // Notify people waiting for ASECs to be scanned that it's done.
774 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800775 }
776 }.start();
777 }
778
779 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800780 * Callback from NativeDaemonConnector
781 */
782 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800783 if (DEBUG_EVENTS) {
784 StringBuilder builder = new StringBuilder();
785 builder.append("onEvent::");
786 builder.append(" raw= " + raw);
787 if (cooked != null) {
788 builder.append(" cooked = " );
789 for (String str : cooked) {
790 builder.append(" " + str);
791 }
792 }
San Mehata5078592010-03-25 09:36:54 -0700793 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800794 }
San Mehat4270e1e2010-01-29 05:32:19 -0800795 if (code == VoldResponseCode.VolumeStateChange) {
796 /*
797 * One of the volumes we're managing has changed state.
798 * Format: "NNN Volume <label> <path> state changed
799 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
800 */
801 notifyVolumeStateChange(
802 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
803 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800804 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
805 (code == VoldResponseCode.VolumeDiskRemoved) ||
806 (code == VoldResponseCode.VolumeBadRemoval)) {
807 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
808 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
809 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400810 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800811 final String label = cooked[2];
812 final String path = cooked[3];
813 int major = -1;
814 int minor = -1;
815
816 try {
817 String devComp = cooked[6].substring(1, cooked[6].length() -1);
818 String[] devTok = devComp.split(":");
819 major = Integer.parseInt(devTok[0]);
820 minor = Integer.parseInt(devTok[1]);
821 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700822 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800823 }
824
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700825 final StorageVolume volume;
826 final String state;
827 synchronized (mVolumesLock) {
828 volume = mVolumesByPath.get(path);
829 state = mVolumeStates.get(path);
830 }
831
San Mehat4270e1e2010-01-29 05:32:19 -0800832 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700833 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600834 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800835 public void run() {
836 try {
837 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800838 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700839 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800840 }
841 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700842 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800843 }
844 }
845 }.start();
846 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
847 /*
848 * This event gets trumped if we're already in BAD_REMOVAL state
849 */
850 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
851 return true;
852 }
853 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700854 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700855 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
856 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800857
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700859 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400860 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800861 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700862 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800863 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700864 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200865 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800866
San Mehata5078592010-03-25 09:36:54 -0700867 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700868 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400869 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700870 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700871 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800872 } else {
San Mehata5078592010-03-25 09:36:54 -0700873 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800874 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400875
876 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700877 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400878 }
San Mehat4270e1e2010-01-29 05:32:19 -0800879 } else {
880 return false;
881 }
882
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400883 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800884 }
885
San Mehat207e5382010-02-04 20:46:54 -0800886 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700887 final StorageVolume volume;
888 final String state;
889 synchronized (mVolumesLock) {
890 volume = mVolumesByPath.get(path);
891 state = getVolumeState(path);
892 }
893
894 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800895
Mike Lockwooda5250c92011-05-23 13:44:04 -0400896 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800897
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500898 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700899 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700900 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500901 }
902
San Mehat4270e1e2010-01-29 05:32:19 -0800903 if (newState == VolumeState.Init) {
904 } else if (newState == VolumeState.NoMedia) {
905 // NoMedia is handled via Disk Remove events
906 } else if (newState == VolumeState.Idle) {
907 /*
908 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
909 * if we're in the process of enabling UMS
910 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700911 if (!state.equals(
912 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
913 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800914 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700915 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700916 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400917 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800918 }
919 } else if (newState == VolumeState.Pending) {
920 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700921 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700922 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400923 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800924 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700925 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700926 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400927 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800928 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400929 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800930 } else if (newState == VolumeState.Formatting) {
931 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700932 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800933 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700934 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
935 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800936
San Mehata5078592010-03-25 09:36:54 -0700937 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700938 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400939 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700940 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800941 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700942 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800943 return;
944 } else {
San Mehata5078592010-03-25 09:36:54 -0700945 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800946 }
947
Mike Lockwooda5250c92011-05-23 13:44:04 -0400948 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700949 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800950 }
951 }
952
San Mehat207e5382010-02-04 20:46:54 -0800953 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800954 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800955
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700956 final StorageVolume volume;
957 synchronized (mVolumesLock) {
958 volume = mVolumesByPath.get(path);
959 }
960
San Mehata5078592010-03-25 09:36:54 -0700961 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800962 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800963 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800964 } catch (NativeDaemonConnectorException e) {
965 /*
966 * Mount failed for some reason
967 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400968 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800969 int code = e.getCode();
970 if (code == VoldResponseCode.OpFailedNoMedia) {
971 /*
972 * Attempt to mount but no media inserted
973 */
San Mehatb1043402010-02-05 08:26:50 -0800974 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800975 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700976 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800977 /*
978 * Media is blank or does not contain a supported filesystem
979 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700980 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400981 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800982 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800983 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700984 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800985 /*
986 * Volume consistency check failed
987 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700988 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400989 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800990 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800991 } else {
San Mehatb1043402010-02-05 08:26:50 -0800992 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800993 }
994
995 /*
996 * Send broadcast intent (if required for the failure)
997 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400998 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700999 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001000 }
1001 }
1002
1003 return rc;
1004 }
1005
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001006 /*
1007 * If force is not set, we do not unmount if there are
1008 * processes holding references to the volume about to be unmounted.
1009 * If force is set, all the processes holding references need to be
1010 * killed via the ActivityManager before actually unmounting the volume.
1011 * This might even take a while and might be retried after timed delays
1012 * to make sure we dont end up in an instable state and kill some core
1013 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001014 * If removeEncryption is set, force is implied, and the system will remove any encryption
1015 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001016 */
Ben Komalo13c71972011-09-07 16:35:56 -07001017 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001018 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001019 return VoldResponseCode.OpFailedVolNotMounted;
1020 }
Kenny Rootaa485402010-09-14 14:49:41 -07001021
1022 /*
1023 * Force a GC to make sure AssetManagers in other threads of the
1024 * system_server are cleaned up. We have to do this since AssetManager
1025 * instances are kept as a WeakReference and it's possible we have files
1026 * open on the external storage.
1027 */
1028 Runtime.getRuntime().gc();
1029
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001030 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001031 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001033 final Command cmd = new Command("volume", "unmount", path);
1034 if (removeEncryption) {
1035 cmd.appendArg("force_and_revert");
1036 } else if (force) {
1037 cmd.appendArg("force");
1038 }
1039 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001040 // We unmounted the volume. None of the asec containers are available now.
1041 synchronized (mAsecMountSet) {
1042 mAsecMountSet.clear();
1043 }
San Mehatb1043402010-02-05 08:26:50 -08001044 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001045 } catch (NativeDaemonConnectorException e) {
1046 // Don't worry about mismatch in PackageManager since the
1047 // call back will handle the status changes any way.
1048 int code = e.getCode();
1049 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001050 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001051 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1052 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001053 } else {
San Mehatb1043402010-02-05 08:26:50 -08001054 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001055 }
1056 }
1057 }
1058
1059 private int doFormatVolume(String path) {
1060 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001061 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001062 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001063 } catch (NativeDaemonConnectorException e) {
1064 int code = e.getCode();
1065 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001066 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001067 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001068 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001069 } else {
San Mehatb1043402010-02-05 08:26:50 -08001070 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001071 }
1072 }
1073 }
1074
San Mehatb1043402010-02-05 08:26:50 -08001075 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001076 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001077 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001078 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001079 } catch (NativeDaemonConnectorException ex) {
1080 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1081 return false;
1082 }
San Mehatb1043402010-02-05 08:26:50 -08001083
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001084 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1085 return event.getMessage().endsWith("enabled");
1086 } else {
1087 return false;
San Mehatb1043402010-02-05 08:26:50 -08001088 }
San Mehatb1043402010-02-05 08:26:50 -08001089 }
1090
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001091 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001092 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001093 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001094 for (int i = mListeners.size() -1; i >= 0; i--) {
1095 MountServiceBinderListener bl = mListeners.get(i);
1096 try {
San Mehatb1043402010-02-05 08:26:50 -08001097 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001098 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001099 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001100 mListeners.remove(i);
1101 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001102 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001103 }
1104 }
1105 }
1106
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001107 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001108 sendUmsIntent(avail);
1109 } else {
1110 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001111 }
San Mehat2fe718a2010-03-11 12:01:49 -08001112
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001113 final StorageVolume primary = getPrimaryPhysicalVolume();
1114 if (avail == false && primary != null
1115 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1116 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001117 /*
1118 * USB mass storage disconnected while enabled
1119 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001120 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001121 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001122 public void run() {
1123 try {
1124 int rc;
San Mehata5078592010-03-25 09:36:54 -07001125 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001126 doShareUnshareVolume(path, "ums", false);
1127 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001128 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001129 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1130 path, rc));
1131 }
1132 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001133 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001134 }
1135 }
1136 }.start();
1137 }
San Mehat4270e1e2010-01-29 05:32:19 -08001138 }
1139
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001140 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1141 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1142 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1143 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1144 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001145 }
1146
San Mehat6a965af22010-02-24 17:47:30 -08001147 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001148 mContext.sendBroadcastAsUser(
1149 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1150 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001151 }
1152
San Mehat207e5382010-02-04 20:46:54 -08001153 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001154 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1155 throw new SecurityException(String.format("Requires %s permission", perm));
1156 }
1157 }
1158
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001159 // Storage list XML tags
1160 private static final String TAG_STORAGE_LIST = "StorageList";
1161 private static final String TAG_STORAGE = "storage";
1162
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001163 private void readStorageListLocked() {
1164 mVolumes.clear();
1165 mVolumeStates.clear();
1166
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001167 Resources resources = mContext.getResources();
1168
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001169 int id = com.android.internal.R.xml.storage_list;
1170 XmlResourceParser parser = resources.getXml(id);
1171 AttributeSet attrs = Xml.asAttributeSet(parser);
1172
1173 try {
1174 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1175 while (true) {
1176 XmlUtils.nextElement(parser);
1177
1178 String element = parser.getName();
1179 if (element == null) break;
1180
1181 if (TAG_STORAGE.equals(element)) {
1182 TypedArray a = resources.obtainAttributes(attrs,
1183 com.android.internal.R.styleable.Storage);
1184
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001185 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001186 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001187 int descriptionId = a.getResourceId(
1188 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001189 CharSequence description = a.getText(
1190 com.android.internal.R.styleable.Storage_storageDescription);
1191 boolean primary = a.getBoolean(
1192 com.android.internal.R.styleable.Storage_primary, false);
1193 boolean removable = a.getBoolean(
1194 com.android.internal.R.styleable.Storage_removable, false);
1195 boolean emulated = a.getBoolean(
1196 com.android.internal.R.styleable.Storage_emulated, false);
1197 int mtpReserve = a.getInt(
1198 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001199 boolean allowMassStorage = a.getBoolean(
1200 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001201 // resource parser does not support longs, so XML value is in megabytes
1202 long maxFileSize = a.getInt(
1203 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001204
1205 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1206 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001207 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001208 " allowMassStorage: " + allowMassStorage +
1209 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001210
1211 if (emulated) {
1212 // For devices with emulated storage, we create separate
1213 // volumes for each known user.
1214 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1215 true, mtpReserve, false, maxFileSize, null);
1216
1217 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001218 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001219 createEmulatedVolumeForUserLocked(user.getUserHandle());
1220 }
1221
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001222 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001223 if (path == null || description == null) {
1224 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001225 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001226 final StorageVolume volume = new StorageVolume(new File(path),
1227 descriptionId, primary, removable, emulated, mtpReserve,
1228 allowMassStorage, maxFileSize, null);
1229 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001230 }
1231 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001232
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001233 a.recycle();
1234 }
1235 }
1236 } catch (XmlPullParserException e) {
1237 throw new RuntimeException(e);
1238 } catch (IOException e) {
1239 throw new RuntimeException(e);
1240 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001241 // Compute storage ID for each physical volume; emulated storage is
1242 // always 0 when defined.
1243 int index = isExternalStorageEmulated() ? 1 : 0;
1244 for (StorageVolume volume : mVolumes) {
1245 if (!volume.isEmulated()) {
1246 volume.setStorageId(index++);
1247 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001248 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001249 parser.close();
1250 }
1251 }
1252
San Mehat4270e1e2010-01-29 05:32:19 -08001253 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001254 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1255 * using {@link #mEmulatedTemplate} as template.
1256 */
1257 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1258 if (mEmulatedTemplate == null) {
1259 throw new IllegalStateException("Missing emulated volume multi-user template");
1260 }
1261
1262 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1263 final File path = userEnv.getExternalStorageDirectory();
1264 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1265 volume.setStorageId(0);
1266 addVolumeLocked(volume);
1267
1268 if (mSystemReady) {
1269 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1270 } else {
1271 // Place stub status for early callers to find
1272 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1273 }
1274 }
1275
1276 private void addVolumeLocked(StorageVolume volume) {
1277 Slog.d(TAG, "addVolumeLocked() " + volume);
1278 mVolumes.add(volume);
1279 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1280 if (existing != null) {
1281 throw new IllegalStateException(
1282 "Volume at " + volume.getPath() + " already exists: " + existing);
1283 }
1284 }
1285
1286 private void removeVolumeLocked(StorageVolume volume) {
1287 Slog.d(TAG, "removeVolumeLocked() " + volume);
1288 mVolumes.remove(volume);
1289 mVolumesByPath.remove(volume.getPath());
1290 mVolumeStates.remove(volume.getPath());
1291 }
1292
1293 private StorageVolume getPrimaryPhysicalVolume() {
1294 synchronized (mVolumesLock) {
1295 for (StorageVolume volume : mVolumes) {
1296 if (volume.isPrimary() && !volume.isEmulated()) {
1297 return volume;
1298 }
1299 }
1300 }
1301 return null;
1302 }
1303
1304 /**
San Mehat207e5382010-02-04 20:46:54 -08001305 * Constructs a new MountService instance
1306 *
1307 * @param context Binder context for this service
1308 */
1309 public MountService(Context context) {
1310 mContext = context;
1311
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001312 synchronized (mVolumesLock) {
1313 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001314 }
1315
San Mehat207e5382010-02-04 20:46:54 -08001316 // XXX: This will go away soon in favor of IMountServiceObserver
1317 mPms = (PackageManagerService) ServiceManager.getService("package");
1318
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001319 HandlerThread hthread = new HandlerThread(TAG);
1320 hthread.start();
1321 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001322
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001323 // Watch for user changes
1324 final IntentFilter userFilter = new IntentFilter();
1325 userFilter.addAction(Intent.ACTION_USER_ADDED);
1326 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1327 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1328
1329 // Watch for USB changes on primary volume
1330 final StorageVolume primary = getPrimaryPhysicalVolume();
1331 if (primary != null && primary.allowMassStorage()) {
1332 mContext.registerReceiver(
1333 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1334 }
1335
Svetoslava7452ee2013-03-20 12:06:59 -07001336 // Watch for idle maintenance changes
1337 IntentFilter idleMaintenanceFilter = new IntentFilter();
1338 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1339 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1340 idleMaintenanceFilter, null, mHandler);
1341
Kenny Roota02b8b02010-08-05 16:14:17 -07001342 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001343 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001344
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001345 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001346 * Create the connection to vold with a maximum queue of twice the
1347 * amount of containers we'd ever expect to have. This keeps an
1348 * "asec list" from blocking a thread repeatedly.
1349 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001350 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001351
Kenny Root305bcbf2010-09-03 07:56:38 -07001352 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001353 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001354
Kenny Root07714d42011-08-17 17:49:28 -07001355 // Add ourself to the Watchdog monitors if enabled.
1356 if (WATCHDOG_ENABLE) {
1357 Watchdog.getInstance().addMonitor(this);
1358 }
San Mehat207e5382010-02-04 20:46:54 -08001359 }
1360
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001361 public void systemReady() {
1362 mSystemReady = true;
1363 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1364 }
1365
San Mehat207e5382010-02-04 20:46:54 -08001366 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001367 * Exposed API calls below here
1368 */
1369
1370 public void registerListener(IMountServiceListener listener) {
1371 synchronized (mListeners) {
1372 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1373 try {
1374 listener.asBinder().linkToDeath(bl, 0);
1375 mListeners.add(bl);
1376 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001377 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001378 }
1379 }
1380 }
1381
1382 public void unregisterListener(IMountServiceListener listener) {
1383 synchronized (mListeners) {
1384 for(MountServiceBinderListener bl : mListeners) {
1385 if (bl.mListener == listener) {
1386 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001387 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001388 return;
1389 }
1390 }
1391 }
1392 }
1393
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001394 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001395 validatePermission(android.Manifest.permission.SHUTDOWN);
1396
San Mehata5078592010-03-25 09:36:54 -07001397 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001398 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001399 for (String path : mVolumeStates.keySet()) {
1400 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001401
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001402 if (state.equals(Environment.MEDIA_SHARED)) {
1403 /*
1404 * If the media is currently shared, unshare it.
1405 * XXX: This is still dangerous!. We should not
1406 * be rebooting at *all* if UMS is enabled, since
1407 * the UMS host could have dirty FAT cache entries
1408 * yet to flush.
1409 */
1410 setUsbMassStorageEnabled(false);
1411 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1412 /*
1413 * If the media is being checked, then we need to wait for
1414 * it to complete before being able to proceed.
1415 */
1416 // XXX: @hackbod - Should we disable the ANR timer here?
1417 int retries = 30;
1418 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1419 try {
1420 Thread.sleep(1000);
1421 } catch (InterruptedException iex) {
1422 Slog.e(TAG, "Interrupted while waiting for media", iex);
1423 break;
1424 }
1425 state = Environment.getExternalStorageState();
1426 }
1427 if (retries == 0) {
1428 Slog.e(TAG, "Timed out waiting for media to check");
1429 }
San Mehat91c77612010-01-07 10:39:41 -08001430 }
San Mehat91c77612010-01-07 10:39:41 -08001431
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001432 if (state.equals(Environment.MEDIA_MOUNTED)) {
1433 // Post a unmount message.
1434 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1435 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1436 } else if (observer != null) {
1437 /*
1438 * Observer is waiting for onShutDownComplete when we are done.
1439 * Since nothing will be done send notification directly so shutdown
1440 * sequence can continue.
1441 */
1442 try {
1443 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1444 } catch (RemoteException e) {
1445 Slog.w(TAG, "RemoteException when shutting down");
1446 }
1447 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001448 }
San Mehat4270e1e2010-01-29 05:32:19 -08001449 }
1450 }
1451
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001452 private boolean getUmsEnabling() {
1453 synchronized (mListeners) {
1454 return mUmsEnabling;
1455 }
1456 }
1457
1458 private void setUmsEnabling(boolean enable) {
1459 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001460 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001461 }
1462 }
1463
San Mehatb1043402010-02-05 08:26:50 -08001464 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001465 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001466
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001467 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001468 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001469 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001470 synchronized (mListeners) {
1471 return mUmsAvailable;
1472 }
San Mehatb1043402010-02-05 08:26:50 -08001473 }
1474
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001475 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001476 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001477 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001478
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001479 final StorageVolume primary = getPrimaryPhysicalVolume();
1480 if (primary == null) return;
1481
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001482 // TODO: Add support for multiple share methods
1483
1484 /*
1485 * If the volume is mounted and we're enabling then unmount it
1486 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001487 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001488 String vs = getVolumeState(path);
1489 String method = "ums";
1490 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1491 // Override for isUsbMassStorageEnabled()
1492 setUmsEnabling(enable);
1493 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1494 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1495 // Clear override
1496 setUmsEnabling(false);
1497 }
1498 /*
1499 * If we disabled UMS then mount the volume
1500 */
1501 if (!enable) {
1502 doShareUnshareVolume(path, method, enable);
1503 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001504 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001505 " after disabling share method " + method);
1506 /*
1507 * Even though the mount failed, the unshare didn't so don't indicate an error.
1508 * The mountVolume() call will have set the storage state and sent the necessary
1509 * broadcasts.
1510 */
1511 }
1512 }
San Mehatb1043402010-02-05 08:26:50 -08001513 }
1514
1515 public boolean isUsbMassStorageEnabled() {
1516 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001517
1518 final StorageVolume primary = getPrimaryPhysicalVolume();
1519 if (primary != null) {
1520 return doGetVolumeShared(primary.getPath(), "ums");
1521 } else {
1522 return false;
1523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001525
San Mehat7fd0fee2009-12-17 07:12:23 -08001526 /**
1527 * @return state of the volume at the specified mount point
1528 */
San Mehat4270e1e2010-01-29 05:32:19 -08001529 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001530 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001531 String state = mVolumeStates.get(mountPoint);
1532 if (state == null) {
1533 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001534 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1535 state = Environment.MEDIA_REMOVED;
1536 } else {
1537 throw new IllegalArgumentException();
1538 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001539 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001540
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001541 return state;
1542 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001543 }
1544
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001545 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001546 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001547 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001548 }
1549
San Mehat4270e1e2010-01-29 05:32:19 -08001550 public int mountVolume(String path) {
1551 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001552
San Mehat207e5382010-02-04 20:46:54 -08001553 waitForReady();
1554 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
Ben Komalo13c71972011-09-07 16:35:56 -07001557 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001558 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001559 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001561 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001562 if (DEBUG_UNMOUNT) {
1563 Slog.i(TAG, "Unmounting " + path
1564 + " force = " + force
1565 + " removeEncryption = " + removeEncryption);
1566 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001567 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1568 Environment.MEDIA_REMOVED.equals(volState) ||
1569 Environment.MEDIA_SHARED.equals(volState) ||
1570 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1571 // Media already unmounted or cannot be unmounted.
1572 // TODO return valid return code when adding observer call back.
1573 return;
1574 }
Ben Komalo13c71972011-09-07 16:35:56 -07001575 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001576 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578
San Mehat4270e1e2010-01-29 05:32:19 -08001579 public int formatVolume(String path) {
1580 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001581 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001582
San Mehat207e5382010-02-04 20:46:54 -08001583 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001586 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001587 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1588 waitForReady();
1589 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001590 final String[] r = NativeDaemonEvent.filterMessageList(
1591 mConnector.executeForList("storage", "users", path),
1592 VoldResponseCode.StorageUsersListResult);
1593
San Mehatc1b4ce92010-02-16 17:13:03 -08001594 // FMT: <pid> <process name>
1595 int[] data = new int[r.length];
1596 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001597 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001598 try {
1599 data[i] = Integer.parseInt(tok[0]);
1600 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001601 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001602 return new int[0];
1603 }
1604 }
1605 return data;
1606 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001607 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001608 return new int[0];
1609 }
1610 }
1611
San Mehatb1043402010-02-05 08:26:50 -08001612 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001613 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001614 if (primary != null) {
1615 boolean mounted = false;
1616 try {
1617 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001618 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001619 }
1620
1621 if (!mounted) {
1622 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1623 }
San Mehatb1043402010-02-05 08:26:50 -08001624 }
1625 }
1626
San Mehat4270e1e2010-01-29 05:32:19 -08001627 public String[] getSecureContainerList() {
1628 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001629 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001630 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001631
San Mehat4270e1e2010-01-29 05:32:19 -08001632 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001633 return NativeDaemonEvent.filterMessageList(
1634 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001635 } catch (NativeDaemonConnectorException e) {
1636 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638 }
San Mehat36972292010-01-06 11:06:32 -08001639
Kenny Root6dceb882012-04-12 14:23:49 -07001640 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1641 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001642 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001643 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001644 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001645
San Mehatb1043402010-02-05 08:26:50 -08001646 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001647 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001648 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1649 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001650 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001651 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001652 }
San Mehata181b212010-02-11 06:50:20 -08001653
1654 if (rc == StorageResultCode.OperationSucceeded) {
1655 synchronized (mAsecMountSet) {
1656 mAsecMountSet.add(id);
1657 }
1658 }
San Mehat4270e1e2010-01-29 05:32:19 -08001659 return rc;
San Mehat36972292010-01-06 11:06:32 -08001660 }
1661
San Mehat4270e1e2010-01-29 05:32:19 -08001662 public int finalizeSecureContainer(String id) {
1663 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001664 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001665
San Mehatb1043402010-02-05 08:26:50 -08001666 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001667 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001668 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001669 /*
1670 * Finalization does a remount, so no need
1671 * to update mAsecMountSet
1672 */
San Mehat4270e1e2010-01-29 05:32:19 -08001673 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001674 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001675 }
San Mehat4270e1e2010-01-29 05:32:19 -08001676 return rc;
San Mehat36972292010-01-06 11:06:32 -08001677 }
1678
Kenny Root6dceb882012-04-12 14:23:49 -07001679 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1680 validatePermission(android.Manifest.permission.ASEC_CREATE);
1681 warnOnNotMounted();
1682
1683 int rc = StorageResultCode.OperationSucceeded;
1684 try {
1685 mConnector.execute("asec", "fixperms", id, gid, filename);
1686 /*
1687 * Fix permissions does a remount, so no need to update
1688 * mAsecMountSet
1689 */
1690 } catch (NativeDaemonConnectorException e) {
1691 rc = StorageResultCode.OperationFailedInternalError;
1692 }
1693 return rc;
1694 }
1695
San Mehatd9709982010-02-18 11:43:03 -08001696 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001697 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001698 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001699 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001700
Kenny Rootaa485402010-09-14 14:49:41 -07001701 /*
1702 * Force a GC to make sure AssetManagers in other threads of the
1703 * system_server are cleaned up. We have to do this since AssetManager
1704 * instances are kept as a WeakReference and it's possible we have files
1705 * open on the external storage.
1706 */
1707 Runtime.getRuntime().gc();
1708
San Mehatb1043402010-02-05 08:26:50 -08001709 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001710 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001711 final Command cmd = new Command("asec", "destroy", id);
1712 if (force) {
1713 cmd.appendArg("force");
1714 }
1715 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001716 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001717 int code = e.getCode();
1718 if (code == VoldResponseCode.OpFailedStorageBusy) {
1719 rc = StorageResultCode.OperationFailedStorageBusy;
1720 } else {
1721 rc = StorageResultCode.OperationFailedInternalError;
1722 }
San Mehat02735bc2010-01-26 15:18:08 -08001723 }
San Mehata181b212010-02-11 06:50:20 -08001724
1725 if (rc == StorageResultCode.OperationSucceeded) {
1726 synchronized (mAsecMountSet) {
1727 if (mAsecMountSet.contains(id)) {
1728 mAsecMountSet.remove(id);
1729 }
1730 }
1731 }
1732
San Mehat4270e1e2010-01-29 05:32:19 -08001733 return rc;
San Mehat36972292010-01-06 11:06:32 -08001734 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001735
San Mehat4270e1e2010-01-29 05:32:19 -08001736 public int mountSecureContainer(String id, String key, int ownerUid) {
1737 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001738 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001739 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001740
San Mehata181b212010-02-11 06:50:20 -08001741 synchronized (mAsecMountSet) {
1742 if (mAsecMountSet.contains(id)) {
1743 return StorageResultCode.OperationFailedStorageMounted;
1744 }
1745 }
1746
San Mehatb1043402010-02-05 08:26:50 -08001747 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001748 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001749 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001750 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001751 int code = e.getCode();
1752 if (code != VoldResponseCode.OpFailedStorageBusy) {
1753 rc = StorageResultCode.OperationFailedInternalError;
1754 }
San Mehat02735bc2010-01-26 15:18:08 -08001755 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001756
1757 if (rc == StorageResultCode.OperationSucceeded) {
1758 synchronized (mAsecMountSet) {
1759 mAsecMountSet.add(id);
1760 }
1761 }
San Mehat4270e1e2010-01-29 05:32:19 -08001762 return rc;
San Mehat36972292010-01-06 11:06:32 -08001763 }
1764
San Mehatd9709982010-02-18 11:43:03 -08001765 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001766 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001767 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001768 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001769
San Mehat6cdd9c02010-02-09 14:45:20 -08001770 synchronized (mAsecMountSet) {
1771 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001772 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001773 }
1774 }
1775
Kenny Rootaa485402010-09-14 14:49:41 -07001776 /*
1777 * Force a GC to make sure AssetManagers in other threads of the
1778 * system_server are cleaned up. We have to do this since AssetManager
1779 * instances are kept as a WeakReference and it's possible we have files
1780 * open on the external storage.
1781 */
1782 Runtime.getRuntime().gc();
1783
San Mehatb1043402010-02-05 08:26:50 -08001784 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001785 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001786 final Command cmd = new Command("asec", "unmount", id);
1787 if (force) {
1788 cmd.appendArg("force");
1789 }
1790 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001791 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001792 int code = e.getCode();
1793 if (code == VoldResponseCode.OpFailedStorageBusy) {
1794 rc = StorageResultCode.OperationFailedStorageBusy;
1795 } else {
1796 rc = StorageResultCode.OperationFailedInternalError;
1797 }
San Mehat02735bc2010-01-26 15:18:08 -08001798 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001799
1800 if (rc == StorageResultCode.OperationSucceeded) {
1801 synchronized (mAsecMountSet) {
1802 mAsecMountSet.remove(id);
1803 }
1804 }
San Mehat4270e1e2010-01-29 05:32:19 -08001805 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001806 }
1807
San Mehat6cdd9c02010-02-09 14:45:20 -08001808 public boolean isSecureContainerMounted(String id) {
1809 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1810 waitForReady();
1811 warnOnNotMounted();
1812
1813 synchronized (mAsecMountSet) {
1814 return mAsecMountSet.contains(id);
1815 }
1816 }
1817
San Mehat4270e1e2010-01-29 05:32:19 -08001818 public int renameSecureContainer(String oldId, String newId) {
1819 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001820 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001821 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001822
San Mehata181b212010-02-11 06:50:20 -08001823 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001824 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001825 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001826 * changed while active, we must ensure both ids are not currently mounted.
1827 */
1828 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001829 return StorageResultCode.OperationFailedStorageMounted;
1830 }
1831 }
1832
San Mehatb1043402010-02-05 08:26:50 -08001833 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001834 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001835 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001836 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001837 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001838 }
San Mehata181b212010-02-11 06:50:20 -08001839
San Mehat4270e1e2010-01-29 05:32:19 -08001840 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001841 }
1842
San Mehat4270e1e2010-01-29 05:32:19 -08001843 public String getSecureContainerPath(String id) {
1844 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001845 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001846 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001847
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001848 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001849 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001850 event = mConnector.execute("asec", "path", id);
1851 event.checkCode(VoldResponseCode.AsecPathResult);
1852 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001853 } catch (NativeDaemonConnectorException e) {
1854 int code = e.getCode();
1855 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001856 Slog.i(TAG, String.format("Container '%s' not found", id));
1857 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001858 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001859 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001860 }
1861 }
San Mehat22dd86e2010-01-12 12:21:18 -08001862 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001863
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001864 public String getSecureContainerFilesystemPath(String id) {
1865 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1866 waitForReady();
1867 warnOnNotMounted();
1868
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001869 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001870 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001871 event = mConnector.execute("asec", "fspath", id);
1872 event.checkCode(VoldResponseCode.AsecPathResult);
1873 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001874 } catch (NativeDaemonConnectorException e) {
1875 int code = e.getCode();
1876 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1877 Slog.i(TAG, String.format("Container '%s' not found", id));
1878 return null;
1879 } else {
1880 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1881 }
1882 }
1883 }
1884
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001885 public void finishMediaUpdate() {
1886 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1887 }
Kenny Root02c87302010-07-01 08:10:18 -07001888
Kenny Roota02b8b02010-08-05 16:14:17 -07001889 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1890 if (callerUid == android.os.Process.SYSTEM_UID) {
1891 return true;
1892 }
1893
Kenny Root02c87302010-07-01 08:10:18 -07001894 if (packageName == null) {
1895 return false;
1896 }
1897
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001898 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001899
1900 if (DEBUG_OBB) {
1901 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1902 packageUid + ", callerUid = " + callerUid);
1903 }
1904
1905 return callerUid == packageUid;
1906 }
1907
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001908 public String getMountedObbPath(String rawPath) {
1909 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001910
Kenny Root02c87302010-07-01 08:10:18 -07001911 waitForReady();
1912 warnOnNotMounted();
1913
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001914 final ObbState state;
1915 synchronized (mObbPathToStateMap) {
1916 state = mObbPathToStateMap.get(rawPath);
1917 }
1918 if (state == null) {
1919 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1920 return null;
1921 }
1922
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001923 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001924 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001925 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001926 event.checkCode(VoldResponseCode.AsecPathResult);
1927 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001928 } catch (NativeDaemonConnectorException e) {
1929 int code = e.getCode();
1930 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001931 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001932 } else {
1933 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1934 }
1935 }
1936 }
1937
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001938 @Override
1939 public boolean isObbMounted(String rawPath) {
1940 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001941 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001942 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001943 }
Kenny Root02c87302010-07-01 08:10:18 -07001944 }
1945
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001946 @Override
1947 public void mountObb(
1948 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1949 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1950 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1951 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001952
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001953 final int callingUid = Binder.getCallingUid();
1954 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1955 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001956 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1957
1958 if (DEBUG_OBB)
1959 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001960 }
1961
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001962 @Override
1963 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1964 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1965
1966 final ObbState existingState;
1967 synchronized (mObbPathToStateMap) {
1968 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001969 }
1970
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001971 if (existingState != null) {
1972 // TODO: separate state object from request data
1973 final int callingUid = Binder.getCallingUid();
1974 final ObbState newState = new ObbState(
1975 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1976 final ObbAction action = new UnmountObbAction(newState, force);
1977 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001978
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001979 if (DEBUG_OBB)
1980 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1981 } else {
1982 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1983 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 }
1985
Ben Komalo444eca22011-09-01 15:17:44 -07001986 @Override
1987 public int getEncryptionState() {
1988 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1989 "no permission to access the crypt keeper");
1990
1991 waitForReady();
1992
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001993 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001994 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001995 event = mConnector.execute("cryptfs", "cryptocomplete");
1996 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001997 } catch (NumberFormatException e) {
1998 // Bad result - unexpected.
1999 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2000 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2001 } catch (NativeDaemonConnectorException e) {
2002 // Something bad happened.
2003 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2004 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2005 }
2006 }
2007
2008 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002009 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002010 if (TextUtils.isEmpty(password)) {
2011 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002012 }
2013
Jason parks8888c592011-01-20 22:46:41 -06002014 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2015 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002016
2017 waitForReady();
2018
2019 if (DEBUG_EVENTS) {
2020 Slog.i(TAG, "decrypting storage...");
2021 }
2022
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002023 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002024 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002025 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002026
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002027 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002028 if (code == 0) {
2029 // Decrypt was successful. Post a delayed message before restarting in order
2030 // to let the UI to clear itself
2031 mHandler.postDelayed(new Runnable() {
2032 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002033 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002034 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002035 } catch (NativeDaemonConnectorException e) {
2036 Slog.e(TAG, "problem executing in background", e);
2037 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002038 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002039 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002040 }
2041
2042 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002043 } catch (NativeDaemonConnectorException e) {
2044 // Decryption failed
2045 return e.getCode();
2046 }
Jason parks5af0b912010-11-29 09:05:25 -06002047 }
2048
Jason parks56aa5322011-01-07 09:01:15 -06002049 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002050 if (TextUtils.isEmpty(password)) {
2051 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002052 }
2053
Jason parks8888c592011-01-20 22:46:41 -06002054 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2055 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002056
2057 waitForReady();
2058
2059 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002060 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002061 }
2062
2063 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002064 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002065 } catch (NativeDaemonConnectorException e) {
2066 // Encryption failed
2067 return e.getCode();
2068 }
2069
2070 return 0;
2071 }
2072
Jason parksf7b3cd42011-01-27 09:28:25 -06002073 public int changeEncryptionPassword(String password) {
2074 if (TextUtils.isEmpty(password)) {
2075 throw new IllegalArgumentException("password cannot be empty");
2076 }
2077
2078 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2079 "no permission to access the crypt keeper");
2080
2081 waitForReady();
2082
2083 if (DEBUG_EVENTS) {
2084 Slog.i(TAG, "changing encryption password...");
2085 }
2086
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002087 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002088 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002089 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002090 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002091 } catch (NativeDaemonConnectorException e) {
2092 // Encryption failed
2093 return e.getCode();
2094 }
2095 }
2096
Christopher Tate32418be2011-10-10 13:51:12 -07002097 /**
2098 * Validate a user-supplied password string with cryptfs
2099 */
2100 @Override
2101 public int verifyEncryptionPassword(String password) throws RemoteException {
2102 // Only the system process is permitted to validate passwords
2103 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2104 throw new SecurityException("no permission to access the crypt keeper");
2105 }
2106
2107 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2108 "no permission to access the crypt keeper");
2109
2110 if (TextUtils.isEmpty(password)) {
2111 throw new IllegalArgumentException("password cannot be empty");
2112 }
2113
2114 waitForReady();
2115
2116 if (DEBUG_EVENTS) {
2117 Slog.i(TAG, "validating encryption password...");
2118 }
2119
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002120 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002121 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002122 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002123 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2124 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002125 } catch (NativeDaemonConnectorException e) {
2126 // Encryption failed
2127 return e.getCode();
2128 }
2129 }
2130
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002131 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002132 public int mkdirs(String callingPkg, String appPath) {
2133 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2134 final UserEnvironment userEnv = new UserEnvironment(userId);
2135
2136 // Validate that reported package name belongs to caller
2137 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2138 Context.APP_OPS_SERVICE);
2139 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2140
2141 try {
2142 appPath = new File(appPath).getCanonicalPath();
2143 } catch (IOException e) {
2144 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2145 return -1;
2146 }
2147
2148 // Try translating the app path into a vold path, but require that it
2149 // belong to the calling package.
2150 String voldPath = maybeTranslatePathForVold(appPath,
2151 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2152 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2153 if (voldPath != null) {
2154 try {
2155 mConnector.execute("volume", "mkdirs", voldPath);
2156 return 0;
2157 } catch (NativeDaemonConnectorException e) {
2158 return e.getCode();
2159 }
2160 }
2161
2162 voldPath = maybeTranslatePathForVold(appPath,
2163 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2164 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2165 if (voldPath != null) {
2166 try {
2167 mConnector.execute("volume", "mkdirs", voldPath);
2168 return 0;
2169 } catch (NativeDaemonConnectorException e) {
2170 return e.getCode();
2171 }
2172 }
2173
2174 throw new SecurityException("Invalid mkdirs path: " + appPath);
2175 }
2176
2177 /**
2178 * Translate the given path from an app-visible path to a vold-visible path,
2179 * but only if it's under the given whitelisted paths.
2180 *
2181 * @param path a canonicalized app-visible path.
2182 * @param appPaths list of app-visible paths that are allowed.
2183 * @param voldPaths list of vold-visible paths directly corresponding to the
2184 * allowed app-visible paths argument.
2185 * @return a vold-visible path representing the original path, or
2186 * {@code null} if the given path didn't have an app-to-vold
2187 * mapping.
2188 */
2189 @VisibleForTesting
2190 public static String maybeTranslatePathForVold(
2191 String path, File[] appPaths, File[] voldPaths) {
2192 if (appPaths.length != voldPaths.length) {
2193 throw new IllegalStateException("Paths must be 1:1 mapping");
2194 }
2195
2196 for (int i = 0; i < appPaths.length; i++) {
2197 final String appPath = appPaths[i].getAbsolutePath();
2198 if (path.startsWith(appPath)) {
2199 path = new File(voldPaths[i], path.substring(appPath.length() + 1))
2200 .getAbsolutePath();
2201 if (!path.endsWith("/")) {
2202 path = path + "/";
2203 }
2204 return path;
2205 }
2206 }
2207 return null;
2208 }
2209
2210 @Override
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002211 public StorageVolume[] getVolumeList() {
2212 final int callingUserId = UserHandle.getCallingUserId();
2213 final boolean accessAll = (mContext.checkPermission(
2214 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2215 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2216
2217 synchronized (mVolumesLock) {
2218 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2219 for (StorageVolume volume : mVolumes) {
2220 final UserHandle owner = volume.getOwner();
2221 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2222 if (accessAll || ownerMatch) {
2223 filtered.add(volume);
2224 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002225 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002226 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002227 }
2228 }
2229
Kenny Rootaf9d6672010-10-08 09:21:39 -07002230 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2231 final IBinder binder = obbState.getBinder();
2232 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002233
Kenny Rootaf9d6672010-10-08 09:21:39 -07002234 if (obbStates == null) {
2235 obbStates = new ArrayList<ObbState>();
2236 mObbMounts.put(binder, obbStates);
2237 } else {
2238 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002239 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002240 throw new IllegalStateException("Attempt to add ObbState twice. "
2241 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002242 }
2243 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002244 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002245
2246 obbStates.add(obbState);
2247 try {
2248 obbState.link();
2249 } catch (RemoteException e) {
2250 /*
2251 * The binder died before we could link it, so clean up our state
2252 * and return failure.
2253 */
2254 obbStates.remove(obbState);
2255 if (obbStates.isEmpty()) {
2256 mObbMounts.remove(binder);
2257 }
2258
2259 // Rethrow the error so mountObb can get it
2260 throw e;
2261 }
2262
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002263 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002264 }
2265
Kenny Rootaf9d6672010-10-08 09:21:39 -07002266 private void removeObbStateLocked(ObbState obbState) {
2267 final IBinder binder = obbState.getBinder();
2268 final List<ObbState> obbStates = mObbMounts.get(binder);
2269 if (obbStates != null) {
2270 if (obbStates.remove(obbState)) {
2271 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002272 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002273 if (obbStates.isEmpty()) {
2274 mObbMounts.remove(binder);
2275 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002276 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002277
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002278 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002279 }
2280
Kenny Roota02b8b02010-08-05 16:14:17 -07002281 private class ObbActionHandler extends Handler {
2282 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002283 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002284
2285 ObbActionHandler(Looper l) {
2286 super(l);
2287 }
2288
2289 @Override
2290 public void handleMessage(Message msg) {
2291 switch (msg.what) {
2292 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002293 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002294
2295 if (DEBUG_OBB)
2296 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2297
2298 // If a bind was already initiated we don't really
2299 // need to do anything. The pending install
2300 // will be processed later on.
2301 if (!mBound) {
2302 // If this is the only one pending we might
2303 // have to bind to the service again.
2304 if (!connectToService()) {
2305 Slog.e(TAG, "Failed to bind to media container service");
2306 action.handleError();
2307 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002308 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002309 }
Kenny Root735de3b2010-09-30 14:11:39 -07002310
Kenny Root735de3b2010-09-30 14:11:39 -07002311 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002312 break;
2313 }
2314 case OBB_MCS_BOUND: {
2315 if (DEBUG_OBB)
2316 Slog.i(TAG, "OBB_MCS_BOUND");
2317 if (msg.obj != null) {
2318 mContainerService = (IMediaContainerService) msg.obj;
2319 }
2320 if (mContainerService == null) {
2321 // Something seriously wrong. Bail out
2322 Slog.e(TAG, "Cannot bind to media container service");
2323 for (ObbAction action : mActions) {
2324 // Indicate service bind error
2325 action.handleError();
2326 }
2327 mActions.clear();
2328 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002329 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002330 if (action != null) {
2331 action.execute(this);
2332 }
2333 } else {
2334 // Should never happen ideally.
2335 Slog.w(TAG, "Empty queue");
2336 }
2337 break;
2338 }
2339 case OBB_MCS_RECONNECT: {
2340 if (DEBUG_OBB)
2341 Slog.i(TAG, "OBB_MCS_RECONNECT");
2342 if (mActions.size() > 0) {
2343 if (mBound) {
2344 disconnectService();
2345 }
2346 if (!connectToService()) {
2347 Slog.e(TAG, "Failed to bind to media container service");
2348 for (ObbAction action : mActions) {
2349 // Indicate service bind error
2350 action.handleError();
2351 }
2352 mActions.clear();
2353 }
2354 }
2355 break;
2356 }
2357 case OBB_MCS_UNBIND: {
2358 if (DEBUG_OBB)
2359 Slog.i(TAG, "OBB_MCS_UNBIND");
2360
2361 // Delete pending install
2362 if (mActions.size() > 0) {
2363 mActions.remove(0);
2364 }
2365 if (mActions.size() == 0) {
2366 if (mBound) {
2367 disconnectService();
2368 }
2369 } else {
2370 // There are more pending requests in queue.
2371 // Just post MCS_BOUND message to trigger processing
2372 // of next pending install.
2373 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2374 }
2375 break;
2376 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002377 case OBB_FLUSH_MOUNT_STATE: {
2378 final String path = (String) msg.obj;
2379
2380 if (DEBUG_OBB)
2381 Slog.i(TAG, "Flushing all OBB state for path " + path);
2382
2383 synchronized (mObbMounts) {
2384 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2385
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002386 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002387 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002388 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002389
2390 /*
2391 * If this entry's source file is in the volume path
2392 * that got unmounted, remove it because it's no
2393 * longer valid.
2394 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 if (state.canonicalPath.startsWith(path)) {
2396 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002397 }
2398 }
2399
2400 for (final ObbState obbState : obbStatesToRemove) {
2401 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002402 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002403
2404 removeObbStateLocked(obbState);
2405
2406 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002407 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002408 OnObbStateChangeListener.UNMOUNTED);
2409 } catch (RemoteException e) {
2410 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002411 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002412 }
2413 }
2414 }
2415 break;
2416 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002417 }
2418 }
2419
2420 private boolean connectToService() {
2421 if (DEBUG_OBB)
2422 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2423
2424 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2425 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2426 mBound = true;
2427 return true;
2428 }
2429 return false;
2430 }
2431
2432 private void disconnectService() {
2433 mContainerService = null;
2434 mBound = false;
2435 mContext.unbindService(mDefContainerConn);
2436 }
2437 }
2438
2439 abstract class ObbAction {
2440 private static final int MAX_RETRIES = 3;
2441 private int mRetries;
2442
2443 ObbState mObbState;
2444
2445 ObbAction(ObbState obbState) {
2446 mObbState = obbState;
2447 }
2448
2449 public void execute(ObbActionHandler handler) {
2450 try {
2451 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002452 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002453 mRetries++;
2454 if (mRetries > MAX_RETRIES) {
2455 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002456 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002457 handleError();
2458 return;
2459 } else {
2460 handleExecute();
2461 if (DEBUG_OBB)
2462 Slog.i(TAG, "Posting install MCS_UNBIND");
2463 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2464 }
2465 } catch (RemoteException e) {
2466 if (DEBUG_OBB)
2467 Slog.i(TAG, "Posting install MCS_RECONNECT");
2468 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2469 } catch (Exception e) {
2470 if (DEBUG_OBB)
2471 Slog.d(TAG, "Error handling OBB action", e);
2472 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002473 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002474 }
2475 }
2476
Kenny Root05105f72010-09-22 17:29:43 -07002477 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002478 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002479
2480 protected ObbInfo getObbInfo() throws IOException {
2481 ObbInfo obbInfo;
2482 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002483 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002484 } catch (RemoteException e) {
2485 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002486 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002487 obbInfo = null;
2488 }
2489 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002490 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002491 }
2492 return obbInfo;
2493 }
2494
Kenny Rootaf9d6672010-10-08 09:21:39 -07002495 protected void sendNewStatusOrIgnore(int status) {
2496 if (mObbState == null || mObbState.token == null) {
2497 return;
2498 }
2499
Kenny Root38cf8862010-09-26 14:18:51 -07002500 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002501 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002502 } catch (RemoteException e) {
2503 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2504 }
2505 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002506 }
2507
2508 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002509 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002510 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002511
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002512 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002513 super(obbState);
2514 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002515 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002516 }
2517
Jason parks5af0b912010-11-29 09:05:25 -06002518 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002519 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002520 waitForReady();
2521 warnOnNotMounted();
2522
Kenny Root38cf8862010-09-26 14:18:51 -07002523 final ObbInfo obbInfo = getObbInfo();
2524
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002525 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002526 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2527 + " which is owned by " + obbInfo.packageName);
2528 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2529 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002530 }
2531
Kenny Rootaf9d6672010-10-08 09:21:39 -07002532 final boolean isMounted;
2533 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002534 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002535 }
2536 if (isMounted) {
2537 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2538 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2539 return;
2540 }
2541
Kenny Rootaf9d6672010-10-08 09:21:39 -07002542 final String hashedKey;
2543 if (mKey == null) {
2544 hashedKey = "none";
2545 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002546 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002547 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2548
2549 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2550 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2551 SecretKey key = factory.generateSecret(ks);
2552 BigInteger bi = new BigInteger(key.getEncoded());
2553 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002554 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002555 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2556 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2557 return;
2558 } catch (InvalidKeySpecException e) {
2559 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2560 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002561 return;
2562 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002563 }
Kenny Root38cf8862010-09-26 14:18:51 -07002564
Kenny Rootaf9d6672010-10-08 09:21:39 -07002565 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002566 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002567 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2568 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002569 } catch (NativeDaemonConnectorException e) {
2570 int code = e.getCode();
2571 if (code != VoldResponseCode.OpFailedStorageBusy) {
2572 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002573 }
2574 }
2575
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 if (rc == StorageResultCode.OperationSucceeded) {
2577 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002578 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002579
2580 synchronized (mObbMounts) {
2581 addObbStateLocked(mObbState);
2582 }
2583
2584 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002585 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002586 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002587
Kenny Rootaf9d6672010-10-08 09:21:39 -07002588 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002589 }
2590 }
2591
Jason parks5af0b912010-11-29 09:05:25 -06002592 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002593 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002594 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002595 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002596
2597 @Override
2598 public String toString() {
2599 StringBuilder sb = new StringBuilder();
2600 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002601 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002602 sb.append('}');
2603 return sb.toString();
2604 }
2605 }
2606
2607 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002608 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002609
2610 UnmountObbAction(ObbState obbState, boolean force) {
2611 super(obbState);
2612 mForceUnmount = force;
2613 }
2614
Jason parks5af0b912010-11-29 09:05:25 -06002615 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002616 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002617 waitForReady();
2618 warnOnNotMounted();
2619
Kenny Root38cf8862010-09-26 14:18:51 -07002620 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002621
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002622 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002623 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002624 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002625 }
Kenny Root38cf8862010-09-26 14:18:51 -07002626
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002627 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002628 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2629 return;
2630 }
2631
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002632 if (existingState.ownerGid != mObbState.ownerGid) {
2633 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2634 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002635 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2636 return;
2637 }
2638
Kenny Rootaf9d6672010-10-08 09:21:39 -07002639 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002640 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002641 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002642 if (mForceUnmount) {
2643 cmd.appendArg("force");
2644 }
2645 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002646 } catch (NativeDaemonConnectorException e) {
2647 int code = e.getCode();
2648 if (code == VoldResponseCode.OpFailedStorageBusy) {
2649 rc = StorageResultCode.OperationFailedStorageBusy;
2650 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2651 // If it's not mounted then we've already won.
2652 rc = StorageResultCode.OperationSucceeded;
2653 } else {
2654 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002655 }
2656 }
2657
Kenny Rootaf9d6672010-10-08 09:21:39 -07002658 if (rc == StorageResultCode.OperationSucceeded) {
2659 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002660 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002661 }
2662
Kenny Rootaf9d6672010-10-08 09:21:39 -07002663 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002664 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002665 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002666 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002667 }
2668 }
2669
Jason parks5af0b912010-11-29 09:05:25 -06002670 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002671 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002672 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002673 }
2674
2675 @Override
2676 public String toString() {
2677 StringBuilder sb = new StringBuilder();
2678 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002679 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002680 sb.append(",force=");
2681 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002682 sb.append('}');
2683 return sb.toString();
2684 }
Kenny Root02c87302010-07-01 08:10:18 -07002685 }
Kenny Root38cf8862010-09-26 14:18:51 -07002686
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002687 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002688 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2689 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002690 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002691
2692 // Only adjust paths when storage is emulated
2693 if (!Environment.isExternalStorageEmulated()) {
2694 return canonicalPath;
2695 }
2696
2697 String path = canonicalPath.toString();
2698
2699 // First trim off any external storage prefix
2700 final UserEnvironment userEnv = new UserEnvironment(userId);
2701
2702 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002703 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002704 // /storage/emulated_legacy
2705 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002706 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002707
2708 if (path.startsWith(externalPath)) {
2709 path = path.substring(externalPath.length() + 1);
2710 } else if (path.startsWith(legacyExternalPath)) {
2711 path = path.substring(legacyExternalPath.length() + 1);
2712 } else {
2713 return canonicalPath;
2714 }
2715
2716 // Handle special OBB paths on emulated storage
2717 final String obbPath = "Android/obb";
2718 if (path.startsWith(obbPath)) {
2719 path = path.substring(obbPath.length() + 1);
2720
2721 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002722 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002723 } else {
2724 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002725 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2726 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002727 }
2728 }
2729
2730 // Handle normal external storage paths
2731 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002732 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002733 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002734 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002735 }
2736 }
2737
Kenny Root38cf8862010-09-26 14:18:51 -07002738 @Override
2739 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2740 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2741 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2742 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2743 + " without permission " + android.Manifest.permission.DUMP);
2744 return;
2745 }
2746
Kenny Root38cf8862010-09-26 14:18:51 -07002747 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002748 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002749
Kenny Rootaf9d6672010-10-08 09:21:39 -07002750 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2751 while (binders.hasNext()) {
2752 Entry<IBinder, List<ObbState>> e = binders.next();
2753 pw.print(" Key="); pw.println(e.getKey().toString());
2754 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002755 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002756 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002757 }
2758 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002759
2760 pw.println("");
2761 pw.println(" mObbPathToStateMap:");
2762 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2763 while (maps.hasNext()) {
2764 final Entry<String, ObbState> e = maps.next();
2765 pw.print(" "); pw.print(e.getKey());
2766 pw.print(" -> "); pw.println(e.getValue().toString());
2767 }
Kenny Root38cf8862010-09-26 14:18:51 -07002768 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002769
2770 pw.println("");
2771
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002772 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002773 pw.println(" mVolumes:");
2774
2775 final int N = mVolumes.size();
2776 for (int i = 0; i < N; i++) {
2777 final StorageVolume v = mVolumes.get(i);
2778 pw.print(" ");
2779 pw.println(v.toString());
2780 }
2781 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002782
2783 pw.println();
2784 pw.println(" mConnection:");
2785 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002788 /** {@inheritDoc} */
2789 public void monitor() {
2790 if (mConnector != null) {
2791 mConnector.monitor();
2792 }
2793 }
2794}