blob: 82f8d434e01aa4e5e6c2be8eae9ea087f60b139e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Svetoslavf23b64d2013-04-25 14:45:54 -070039import android.os.Build;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import 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;
68import com.android.server.am.ActivityManagerService;
69import com.android.server.pm.PackageManagerService;
70import com.android.server.pm.UserManagerService;
71import com.google.android.collect.Lists;
72import com.google.android.collect.Maps;
73
Mike Lockwood2f6a3882011-05-09 19:08:06 -070074import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070075
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070076import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070077import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070078import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070080import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070081import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070082import java.security.spec.InvalidKeySpecException;
83import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080084import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070085import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080086import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070087import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070088import java.util.LinkedList;
89import java.util.List;
90import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070091import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070092import java.util.concurrent.CountDownLatch;
93import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Kenny Root3b1abba2010-10-13 15:00:07 -070095import javax.crypto.SecretKey;
96import javax.crypto.SecretKeyFactory;
97import javax.crypto.spec.PBEKeySpec;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099/**
San Mehatb1043402010-02-05 08:26:50 -0800100 * MountService implements back-end services for platform storage
101 * management.
102 * @hide - Applications should use android.os.storage.StorageManager
103 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700105class MountService extends IMountService.Stub
106 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600107
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700108 // TODO: listen for user creation/deletion
109
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800110 private static final boolean LOCAL_LOGD = false;
111 private static final boolean DEBUG_UNMOUNT = false;
112 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800113 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700114
Kenny Root07714d42011-08-17 17:49:28 -0700115 // Disable this since it messes up long-running cryptfs operations.
116 private static final boolean WATCHDOG_ENABLE = false;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "MountService";
119
Kenny Root305bcbf2010-09-03 07:56:38 -0700120 private static final String VOLD_TAG = "VoldConnector";
121
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700122 /** Maximum number of ASEC containers allowed to be mounted. */
123 private static final int MAX_CONTAINERS = 250;
124
San Mehat4270e1e2010-01-29 05:32:19 -0800125 /*
126 * Internal vold volume state constants
127 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800128 class VolumeState {
129 public static final int Init = -1;
130 public static final int NoMedia = 0;
131 public static final int Idle = 1;
132 public static final int Pending = 2;
133 public static final int Checking = 3;
134 public static final int Mounted = 4;
135 public static final int Unmounting = 5;
136 public static final int Formatting = 6;
137 public static final int Shared = 7;
138 public static final int SharedMnt = 8;
139 }
140
San Mehat4270e1e2010-01-29 05:32:19 -0800141 /*
142 * Internal vold response code constants
143 */
San Mehat22dd86e2010-01-12 12:21:18 -0800144 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800145 /*
146 * 100 series - Requestion action was initiated; expect another reply
147 * before proceeding with a new command.
148 */
San Mehat22dd86e2010-01-12 12:21:18 -0800149 public static final int VolumeListResult = 110;
150 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800151 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800152
San Mehat4270e1e2010-01-29 05:32:19 -0800153 /*
154 * 200 series - Requestion action has been successfully completed.
155 */
156 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800157 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800158 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800159
San Mehat4270e1e2010-01-29 05:32:19 -0800160 /*
161 * 400 series - Command was accepted, but the requested action
162 * did not take place.
163 */
164 public static final int OpFailedNoMedia = 401;
165 public static final int OpFailedMediaBlank = 402;
166 public static final int OpFailedMediaCorrupt = 403;
167 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800168 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700169 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800170
171 /*
172 * 600 series - Unsolicited broadcasts.
173 */
San Mehat22dd86e2010-01-12 12:21:18 -0800174 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800175 public static final int VolumeDiskInserted = 630;
176 public static final int VolumeDiskRemoved = 631;
177 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700178
179 /*
180 * 700 series - fstrim
181 */
182 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800183 }
184
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700185 private Context mContext;
186 private NativeDaemonConnector mConnector;
187
188 private final Object mVolumesLock = new Object();
189
190 /** When defined, base template for user-specific {@link StorageVolume}. */
191 private StorageVolume mEmulatedTemplate;
192
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800193 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700194 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
195 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700197 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
198 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700200 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
201
202 private volatile boolean mSystemReady = false;
203
San Mehat4270e1e2010-01-29 05:32:19 -0800204 private PackageManagerService mPms;
205 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700206 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800207 // Used as a lock for methods that register/unregister listeners.
208 final private ArrayList<MountServiceBinderListener> mListeners =
209 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800210 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
211 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800212 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800213
San Mehat6cdd9c02010-02-09 14:45:20 -0800214 /**
215 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800216 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800217 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800218 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800219
Kenny Root02c87302010-07-01 08:10:18 -0700220 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700221 * The size of the crypto algorithm key in bits for OBB files. Currently
222 * Twofish is used which takes 128-bit keys.
223 */
224 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
225
226 /**
227 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
228 * 1024 is reasonably secure and not too slow.
229 */
230 private static final int PBKDF2_HASH_ROUNDS = 1024;
231
232 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700233 * Mounted OBB tracking information. Used to track the current state of all
234 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700235 */
Kenny Root735de3b2010-09-30 14:11:39 -0700236 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700237
238 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700239 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
240
241 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700242 public ObbState(String rawPath, String canonicalPath, int callingUid,
243 IObbActionListener token, int nonce) {
244 this.rawPath = rawPath;
245 this.canonicalPath = canonicalPath.toString();
246
247 final int userId = UserHandle.getUserId(callingUid);
248 this.ownerPath = buildObbPath(canonicalPath, userId, false);
249 this.voldPath = buildObbPath(canonicalPath, userId, true);
250
251 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700252 this.token = token;
253 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700254 }
255
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700256 final String rawPath;
257 final String canonicalPath;
258 final String ownerPath;
259 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700260
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700261 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262
Kenny Rootaf9d6672010-10-08 09:21:39 -0700263 // Token of remote Binder caller
264 final IObbActionListener token;
265
266 // Identifier to pass back to the token
267 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
Kenny Root735de3b2010-09-30 14:11:39 -0700269 public IBinder getBinder() {
270 return token.asBinder();
271 }
272
Kenny Roota02b8b02010-08-05 16:14:17 -0700273 @Override
274 public void binderDied() {
275 ObbAction action = new UnmountObbAction(this, true);
276 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700277 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700278
Kenny Root5919ac62010-10-05 09:49:40 -0700279 public void link() throws RemoteException {
280 getBinder().linkToDeath(this, 0);
281 }
282
283 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700284 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700285 }
Kenny Root38cf8862010-09-26 14:18:51 -0700286
287 @Override
288 public String toString() {
289 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700290 sb.append("rawPath=").append(rawPath);
291 sb.append(",canonicalPath=").append(canonicalPath);
292 sb.append(",ownerPath=").append(ownerPath);
293 sb.append(",voldPath=").append(voldPath);
294 sb.append(",ownerGid=").append(ownerGid);
295 sb.append(",token=").append(token);
296 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700297 sb.append('}');
298 return sb.toString();
299 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700300 }
301
302 // OBB Action Handler
303 final private ObbActionHandler mObbActionHandler;
304
305 // OBB action handler messages
306 private static final int OBB_RUN_ACTION = 1;
307 private static final int OBB_MCS_BOUND = 2;
308 private static final int OBB_MCS_UNBIND = 3;
309 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700310 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700311
312 /*
313 * Default Container Service information
314 */
315 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
316 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
317
318 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
319
320 class DefaultContainerConnection implements ServiceConnection {
321 public void onServiceConnected(ComponentName name, IBinder service) {
322 if (DEBUG_OBB)
323 Slog.i(TAG, "onServiceConnected");
324 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
325 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
326 }
327
328 public void onServiceDisconnected(ComponentName name) {
329 if (DEBUG_OBB)
330 Slog.i(TAG, "onServiceDisconnected");
331 }
332 };
333
334 // Used in the ObbActionHandler
335 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700336
337 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 private static final int H_UNMOUNT_PM_UPDATE = 1;
339 private static final int H_UNMOUNT_PM_DONE = 2;
340 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700341 private static final int H_SYSTEM_READY = 4;
342
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
344 private static final int MAX_UNMOUNT_RETRIES = 4;
345
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700347 final String path;
348 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700349 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800351
Ben Komalo13c71972011-09-07 16:35:56 -0700352 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800353 retries = 0;
354 this.path = path;
355 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700356 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800357 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800358
359 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700360 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700361 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800362 }
363 }
364
365 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700366 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800367
368 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700369 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370 this.method = method;
371 }
372
373 @Override
374 void handleFinished() {
375 super.handleFinished();
376 doShareUnshareVolume(path, method, true);
377 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800378 }
379
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800380 class ShutdownCallBack extends UnmountCallBack {
381 IMountShutdownObserver observer;
382 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700383 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800384 this.observer = observer;
385 }
386
387 @Override
388 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700389 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800390 if (observer != null) {
391 try {
392 observer.onShutDownComplete(ret);
393 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700394 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800395 }
396 }
397 }
398 }
399
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400400 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700402 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400404 MountServiceHandler(Looper l) {
405 super(l);
406 }
407
Jason parks5af0b912010-11-29 09:05:25 -0600408 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 public void handleMessage(Message msg) {
410 switch (msg.what) {
411 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700412 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800413 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
414 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700415 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800416 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700417 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700419 mUpdatingStatus = true;
420 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 }
422 break;
423 }
424 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700425 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700426 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700427 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800428 int size = mForceUnmounts.size();
429 int sizeArr[] = new int[size];
430 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700431 // Kill processes holding references first
432 ActivityManagerService ams = (ActivityManagerService)
433 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 for (int i = 0; i < size; i++) {
435 UnmountCallBack ucb = mForceUnmounts.get(i);
436 String path = ucb.path;
437 boolean done = false;
438 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800439 done = true;
440 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800441 int pids[] = getStorageUsers(path);
442 if (pids == null || pids.length == 0) {
443 done = true;
444 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800445 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800446 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700447 // Confirm if file references have been freed.
448 pids = getStorageUsers(path);
449 if (pids == null || pids.length == 0) {
450 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800451 }
452 }
453 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700454 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
455 // Retry again
456 Slog.i(TAG, "Retrying to kill storage users again");
457 mHandler.sendMessageDelayed(
458 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
459 ucb.retries++),
460 RETRY_UNMOUNT_DELAY);
461 } else {
462 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
463 Slog.i(TAG, "Failed to unmount media inspite of " +
464 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
465 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800466 sizeArr[sizeArrN++] = i;
467 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
468 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800469 }
470 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800471 // Remove already processed elements from list.
472 for (int i = (sizeArrN-1); i >= 0; i--) {
473 mForceUnmounts.remove(sizeArr[i]);
474 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800475 break;
476 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700477 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700478 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800479 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800480 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800481 break;
482 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700483 case H_SYSTEM_READY: {
484 try {
485 handleSystemReady();
486 } catch (Exception ex) {
487 Slog.e(TAG, "Boot-time mount exception", ex);
488 }
489 break;
490 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800491 }
492 }
493 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700494
495 private final HandlerThread mHandlerThread;
496 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800497
Kenny Root51a573c2012-05-17 13:30:28 -0700498 void waitForAsecScan() {
499 waitForLatch(mAsecsScanned);
500 }
501
San Mehat207e5382010-02-04 20:46:54 -0800502 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700503 waitForLatch(mConnectedSignal);
504 }
505
506 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700507 for (;;) {
508 try {
509 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800510 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700511 } else {
512 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
513 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800514 }
Kenny Root51a573c2012-05-17 13:30:28 -0700515 } catch (InterruptedException e) {
516 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800517 }
San Mehat207e5382010-02-04 20:46:54 -0800518 }
San Mehat1f6301e2010-01-07 22:40:27 -0800519 }
Kenny Root02c87302010-07-01 08:10:18 -0700520
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700521 private void handleSystemReady() {
522 // Snapshot current volume states since it's not safe to call into vold
523 // while holding locks.
524 final HashMap<String, String> snapshot;
525 synchronized (mVolumesLock) {
526 snapshot = new HashMap<String, String>(mVolumeStates);
527 }
528
529 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
530 final String path = entry.getKey();
531 final String state = entry.getValue();
532
533 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
534 int rc = doMountVolume(path);
535 if (rc != StorageResultCode.OperationSucceeded) {
536 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
537 rc));
538 }
539 } else if (state.equals(Environment.MEDIA_SHARED)) {
540 /*
541 * Bootstrap UMS enabled state since vold indicates
542 * the volume is shared (runtime restart while ums enabled)
543 */
544 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
545 VolumeState.Shared);
546 }
547 }
548
549 // Push mounted state for all emulated storage
550 synchronized (mVolumesLock) {
551 for (StorageVolume volume : mVolumes) {
552 if (volume.isEmulated()) {
553 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
554 }
555 }
556 }
557
558 /*
559 * If UMS was connected on boot, send the connected event
560 * now that we're up.
561 */
562 if (mSendUmsConnectedOnBoot) {
563 sendUmsIntent(true);
564 mSendUmsConnectedOnBoot = false;
565 }
566 }
567
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700568 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
569 @Override
570 public void onReceive(Context context, Intent intent) {
571 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
572 if (userId == -1) return;
573 final UserHandle user = new UserHandle(userId);
574
575 final String action = intent.getAction();
576 if (Intent.ACTION_USER_ADDED.equals(action)) {
577 synchronized (mVolumesLock) {
578 createEmulatedVolumeForUserLocked(user);
579 }
580
581 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
582 synchronized (mVolumesLock) {
583 final List<StorageVolume> toRemove = Lists.newArrayList();
584 for (StorageVolume volume : mVolumes) {
585 if (user.equals(volume.getOwner())) {
586 toRemove.add(volume);
587 }
588 }
589 for (StorageVolume volume : toRemove) {
590 removeVolumeLocked(volume);
591 }
592 }
593 }
594 }
595 };
596
597 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
598 @Override
599 public void onReceive(Context context, Intent intent) {
600 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
601 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
602 notifyShareAvailabilityChange(available);
603 }
604 };
605
Svetoslava7452ee2013-03-20 12:06:59 -0700606 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
607 @Override
608 public void onReceive(Context context, Intent intent) {
609 waitForReady();
610 String action = intent.getAction();
611 // Since fstrim will be run on a daily basis we do not expect
612 // fstrim to be too long, so it is not interruptible. We will
613 // implement interruption only in case we see issues.
614 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
615 try {
616 // This method runs on the handler thread,
617 // so it is safe to directly call into vold.
618 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700619 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700620 } catch (NativeDaemonConnectorException ndce) {
621 Slog.e(TAG, "Failed to run fstrim!");
622 }
623 }
624 }
625 };
626
San Mehat4270e1e2010-01-29 05:32:19 -0800627 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
628 final IMountServiceListener mListener;
629
630 MountServiceBinderListener(IMountServiceListener listener) {
631 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700632
San Mehat91c77612010-01-07 10:39:41 -0800633 }
634
San Mehat4270e1e2010-01-29 05:32:19 -0800635 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700636 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700637 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800638 mListeners.remove(this);
639 mListener.asBinder().unlinkToDeath(this, 0);
640 }
641 }
642 }
643
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800644 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800645 // TODO: Add support for multiple share methods
646 if (!method.equals("ums")) {
647 throw new IllegalArgumentException(String.format("Method %s not supported", method));
648 }
649
San Mehat4270e1e2010-01-29 05:32:19 -0800650 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800651 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800652 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700653 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800654 }
San Mehat4270e1e2010-01-29 05:32:19 -0800655 }
656
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700657 private void updatePublicVolumeState(StorageVolume volume, String state) {
658 final String path = volume.getPath();
659 final String oldState;
660 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400661 oldState = mVolumeStates.put(path, state);
662 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700663
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400664 if (state.equals(oldState)) {
665 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
666 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800667 return;
668 }
San Mehatb1043402010-02-05 08:26:50 -0800669
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400670 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700671
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700672 // Tell PackageManager about changes to primary volume state, but only
673 // when not emulated.
674 if (volume.isPrimary() && !volume.isEmulated()) {
675 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
676 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400677
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700678 /*
679 * Some OBBs might have been unmounted when this volume was
680 * unmounted, so send a message to the handler to let it know to
681 * remove those from the list of mounted OBBS.
682 */
683 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
684 OBB_FLUSH_MOUNT_STATE, path));
685 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
686 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400687 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800688 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700689
San Mehat4270e1e2010-01-29 05:32:19 -0800690 synchronized (mListeners) {
691 for (int i = mListeners.size() -1; i >= 0; i--) {
692 MountServiceBinderListener bl = mListeners.get(i);
693 try {
San Mehatb1043402010-02-05 08:26:50 -0800694 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800695 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700696 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800697 mListeners.remove(i);
698 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700699 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800700 }
701 }
702 }
703 }
704
705 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800706 * Callback from NativeDaemonConnector
707 */
708 public void onDaemonConnected() {
709 /*
710 * Since we'll be calling back into the NativeDaemonConnector,
711 * we need to do our work in a new thread.
712 */
Kenny Root51a573c2012-05-17 13:30:28 -0700713 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600714 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800715 public void run() {
716 /**
717 * Determine media state and UMS detection status
718 */
San Mehat4270e1e2010-01-29 05:32:19 -0800719 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800720 final String[] vols = NativeDaemonEvent.filterMessageList(
721 mConnector.executeForList("volume", "list"),
722 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800723 for (String volstr : vols) {
724 String[] tok = volstr.split(" ");
725 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400726 String path = tok[1];
727 String state = Environment.MEDIA_REMOVED;
728
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700729 final StorageVolume volume;
730 synchronized (mVolumesLock) {
731 volume = mVolumesByPath.get(path);
732 }
733
San Mehat4270e1e2010-01-29 05:32:19 -0800734 int st = Integer.parseInt(tok[2]);
735 if (st == VolumeState.NoMedia) {
736 state = Environment.MEDIA_REMOVED;
737 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800738 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800739 } else if (st == VolumeState.Mounted) {
740 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700741 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800742 } else if (st == VolumeState.Shared) {
743 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700744 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800745 } else {
746 throw new Exception(String.format("Unexpected state %d", st));
747 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400748
749 if (state != null) {
750 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700751 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400752 }
San Mehat4270e1e2010-01-29 05:32:19 -0800753 }
754 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700755 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700756 final StorageVolume primary = getPrimaryPhysicalVolume();
757 if (primary != null) {
758 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
759 }
San Mehat4270e1e2010-01-29 05:32:19 -0800760 }
761
San Mehat207e5382010-02-04 20:46:54 -0800762 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600763 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800764 * the hounds!
765 */
Kenny Root51a573c2012-05-17 13:30:28 -0700766 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700767
768 // Let package manager load internal ASECs.
769 mPms.scanAvailableAsecs();
770
771 // Notify people waiting for ASECs to be scanned that it's done.
772 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800773 }
774 }.start();
775 }
776
777 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800778 * Callback from NativeDaemonConnector
779 */
780 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800781 if (DEBUG_EVENTS) {
782 StringBuilder builder = new StringBuilder();
783 builder.append("onEvent::");
784 builder.append(" raw= " + raw);
785 if (cooked != null) {
786 builder.append(" cooked = " );
787 for (String str : cooked) {
788 builder.append(" " + str);
789 }
790 }
San Mehata5078592010-03-25 09:36:54 -0700791 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800792 }
San Mehat4270e1e2010-01-29 05:32:19 -0800793 if (code == VoldResponseCode.VolumeStateChange) {
794 /*
795 * One of the volumes we're managing has changed state.
796 * Format: "NNN Volume <label> <path> state changed
797 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
798 */
799 notifyVolumeStateChange(
800 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
801 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800802 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
803 (code == VoldResponseCode.VolumeDiskRemoved) ||
804 (code == VoldResponseCode.VolumeBadRemoval)) {
805 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
806 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
807 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400808 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800809 final String label = cooked[2];
810 final String path = cooked[3];
811 int major = -1;
812 int minor = -1;
813
814 try {
815 String devComp = cooked[6].substring(1, cooked[6].length() -1);
816 String[] devTok = devComp.split(":");
817 major = Integer.parseInt(devTok[0]);
818 minor = Integer.parseInt(devTok[1]);
819 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700820 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800821 }
822
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700823 final StorageVolume volume;
824 final String state;
825 synchronized (mVolumesLock) {
826 volume = mVolumesByPath.get(path);
827 state = mVolumeStates.get(path);
828 }
829
San Mehat4270e1e2010-01-29 05:32:19 -0800830 if (code == VoldResponseCode.VolumeDiskInserted) {
831 new Thread() {
Jason parks5af0b912010-11-29 09:05:25 -0600832 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800833 public void run() {
834 try {
835 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800836 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700837 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800838 }
839 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700840 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800841 }
842 }
843 }.start();
844 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
845 /*
846 * This event gets trumped if we're already in BAD_REMOVAL state
847 */
848 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
849 return true;
850 }
851 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700852 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700853 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
854 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800855
San Mehata5078592010-03-25 09:36:54 -0700856 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700857 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400858 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800859 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700860 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800861 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700862 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400863 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800864
San Mehata5078592010-03-25 09:36:54 -0700865 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700866 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400867 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700868 } else if (code == VoldResponseCode.FstrimCompleted) {
869 if (Build.IS_DEBUGGABLE) {
870 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
871 }
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 */
1120 new Thread() {
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
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001319 mHandlerThread = new HandlerThread("MountService");
1320 mHandlerThread.start();
1321 mHandler = new MountServiceHandler(mHandlerThread.getLooper());
1322
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.
1343 mObbActionHandler = new ObbActionHandler(mHandlerThread.getLooper());
1344
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 {
Kenny Root6dceb882012-04-12 14:23:49 -07001648 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1649 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 Sharkeydd519fa2011-12-02 14:11:21 -08001749 mConnector.execute("asec", "mount", id, 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 Sharkeydd519fa2011-12-02 14:11:21 -08002025 event = mConnector.execute("cryptfs", "checkpw", 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 Sharkeydd519fa2011-12-02 14:11:21 -08002064 mConnector.execute("cryptfs", "enablecrypto", "inplace", 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 Sharkeydd519fa2011-12-02 14:11:21 -08002089 event = mConnector.execute("cryptfs", "changepw", password);
2090 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 Sharkeydd519fa2011-12-02 14:11:21 -08002122 event = mConnector.execute("cryptfs", "verifypw", password);
2123 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
2132 public StorageVolume[] getVolumeList() {
2133 final int callingUserId = UserHandle.getCallingUserId();
2134 final boolean accessAll = (mContext.checkPermission(
2135 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2136 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2137
2138 synchronized (mVolumesLock) {
2139 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2140 for (StorageVolume volume : mVolumes) {
2141 final UserHandle owner = volume.getOwner();
2142 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2143 if (accessAll || ownerMatch) {
2144 filtered.add(volume);
2145 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002146 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002147 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002148 }
2149 }
2150
Kenny Rootaf9d6672010-10-08 09:21:39 -07002151 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2152 final IBinder binder = obbState.getBinder();
2153 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002154
Kenny Rootaf9d6672010-10-08 09:21:39 -07002155 if (obbStates == null) {
2156 obbStates = new ArrayList<ObbState>();
2157 mObbMounts.put(binder, obbStates);
2158 } else {
2159 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002160 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002161 throw new IllegalStateException("Attempt to add ObbState twice. "
2162 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002163 }
2164 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002165 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002166
2167 obbStates.add(obbState);
2168 try {
2169 obbState.link();
2170 } catch (RemoteException e) {
2171 /*
2172 * The binder died before we could link it, so clean up our state
2173 * and return failure.
2174 */
2175 obbStates.remove(obbState);
2176 if (obbStates.isEmpty()) {
2177 mObbMounts.remove(binder);
2178 }
2179
2180 // Rethrow the error so mountObb can get it
2181 throw e;
2182 }
2183
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002184 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002185 }
2186
Kenny Rootaf9d6672010-10-08 09:21:39 -07002187 private void removeObbStateLocked(ObbState obbState) {
2188 final IBinder binder = obbState.getBinder();
2189 final List<ObbState> obbStates = mObbMounts.get(binder);
2190 if (obbStates != null) {
2191 if (obbStates.remove(obbState)) {
2192 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002193 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002194 if (obbStates.isEmpty()) {
2195 mObbMounts.remove(binder);
2196 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002197 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002198
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002199 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002200 }
2201
Kenny Roota02b8b02010-08-05 16:14:17 -07002202 private class ObbActionHandler extends Handler {
2203 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002204 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002205
2206 ObbActionHandler(Looper l) {
2207 super(l);
2208 }
2209
2210 @Override
2211 public void handleMessage(Message msg) {
2212 switch (msg.what) {
2213 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002214 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002215
2216 if (DEBUG_OBB)
2217 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2218
2219 // If a bind was already initiated we don't really
2220 // need to do anything. The pending install
2221 // will be processed later on.
2222 if (!mBound) {
2223 // If this is the only one pending we might
2224 // have to bind to the service again.
2225 if (!connectToService()) {
2226 Slog.e(TAG, "Failed to bind to media container service");
2227 action.handleError();
2228 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002229 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002230 }
Kenny Root735de3b2010-09-30 14:11:39 -07002231
Kenny Root735de3b2010-09-30 14:11:39 -07002232 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002233 break;
2234 }
2235 case OBB_MCS_BOUND: {
2236 if (DEBUG_OBB)
2237 Slog.i(TAG, "OBB_MCS_BOUND");
2238 if (msg.obj != null) {
2239 mContainerService = (IMediaContainerService) msg.obj;
2240 }
2241 if (mContainerService == null) {
2242 // Something seriously wrong. Bail out
2243 Slog.e(TAG, "Cannot bind to media container service");
2244 for (ObbAction action : mActions) {
2245 // Indicate service bind error
2246 action.handleError();
2247 }
2248 mActions.clear();
2249 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002250 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002251 if (action != null) {
2252 action.execute(this);
2253 }
2254 } else {
2255 // Should never happen ideally.
2256 Slog.w(TAG, "Empty queue");
2257 }
2258 break;
2259 }
2260 case OBB_MCS_RECONNECT: {
2261 if (DEBUG_OBB)
2262 Slog.i(TAG, "OBB_MCS_RECONNECT");
2263 if (mActions.size() > 0) {
2264 if (mBound) {
2265 disconnectService();
2266 }
2267 if (!connectToService()) {
2268 Slog.e(TAG, "Failed to bind to media container service");
2269 for (ObbAction action : mActions) {
2270 // Indicate service bind error
2271 action.handleError();
2272 }
2273 mActions.clear();
2274 }
2275 }
2276 break;
2277 }
2278 case OBB_MCS_UNBIND: {
2279 if (DEBUG_OBB)
2280 Slog.i(TAG, "OBB_MCS_UNBIND");
2281
2282 // Delete pending install
2283 if (mActions.size() > 0) {
2284 mActions.remove(0);
2285 }
2286 if (mActions.size() == 0) {
2287 if (mBound) {
2288 disconnectService();
2289 }
2290 } else {
2291 // There are more pending requests in queue.
2292 // Just post MCS_BOUND message to trigger processing
2293 // of next pending install.
2294 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2295 }
2296 break;
2297 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002298 case OBB_FLUSH_MOUNT_STATE: {
2299 final String path = (String) msg.obj;
2300
2301 if (DEBUG_OBB)
2302 Slog.i(TAG, "Flushing all OBB state for path " + path);
2303
2304 synchronized (mObbMounts) {
2305 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2306
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002307 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002308 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002309 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002310
2311 /*
2312 * If this entry's source file is in the volume path
2313 * that got unmounted, remove it because it's no
2314 * longer valid.
2315 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002316 if (state.canonicalPath.startsWith(path)) {
2317 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002318 }
2319 }
2320
2321 for (final ObbState obbState : obbStatesToRemove) {
2322 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002323 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002324
2325 removeObbStateLocked(obbState);
2326
2327 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002328 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002329 OnObbStateChangeListener.UNMOUNTED);
2330 } catch (RemoteException e) {
2331 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002332 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002333 }
2334 }
2335 }
2336 break;
2337 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002338 }
2339 }
2340
2341 private boolean connectToService() {
2342 if (DEBUG_OBB)
2343 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2344
2345 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2346 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2347 mBound = true;
2348 return true;
2349 }
2350 return false;
2351 }
2352
2353 private void disconnectService() {
2354 mContainerService = null;
2355 mBound = false;
2356 mContext.unbindService(mDefContainerConn);
2357 }
2358 }
2359
2360 abstract class ObbAction {
2361 private static final int MAX_RETRIES = 3;
2362 private int mRetries;
2363
2364 ObbState mObbState;
2365
2366 ObbAction(ObbState obbState) {
2367 mObbState = obbState;
2368 }
2369
2370 public void execute(ObbActionHandler handler) {
2371 try {
2372 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002373 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002374 mRetries++;
2375 if (mRetries > MAX_RETRIES) {
2376 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002377 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002378 handleError();
2379 return;
2380 } else {
2381 handleExecute();
2382 if (DEBUG_OBB)
2383 Slog.i(TAG, "Posting install MCS_UNBIND");
2384 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2385 }
2386 } catch (RemoteException e) {
2387 if (DEBUG_OBB)
2388 Slog.i(TAG, "Posting install MCS_RECONNECT");
2389 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2390 } catch (Exception e) {
2391 if (DEBUG_OBB)
2392 Slog.d(TAG, "Error handling OBB action", e);
2393 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002394 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002395 }
2396 }
2397
Kenny Root05105f72010-09-22 17:29:43 -07002398 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002399 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002400
2401 protected ObbInfo getObbInfo() throws IOException {
2402 ObbInfo obbInfo;
2403 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002404 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002405 } catch (RemoteException e) {
2406 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002407 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002408 obbInfo = null;
2409 }
2410 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002411 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002412 }
2413 return obbInfo;
2414 }
2415
Kenny Rootaf9d6672010-10-08 09:21:39 -07002416 protected void sendNewStatusOrIgnore(int status) {
2417 if (mObbState == null || mObbState.token == null) {
2418 return;
2419 }
2420
Kenny Root38cf8862010-09-26 14:18:51 -07002421 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002422 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002423 } catch (RemoteException e) {
2424 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2425 }
2426 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002427 }
2428
2429 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002430 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002431 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002432
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002433 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002434 super(obbState);
2435 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002436 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002437 }
2438
Jason parks5af0b912010-11-29 09:05:25 -06002439 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002440 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 waitForReady();
2442 warnOnNotMounted();
2443
Kenny Root38cf8862010-09-26 14:18:51 -07002444 final ObbInfo obbInfo = getObbInfo();
2445
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002446 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002447 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2448 + " which is owned by " + obbInfo.packageName);
2449 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2450 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002451 }
2452
Kenny Rootaf9d6672010-10-08 09:21:39 -07002453 final boolean isMounted;
2454 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002455 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002456 }
2457 if (isMounted) {
2458 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2459 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2460 return;
2461 }
2462
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463 final String hashedKey;
2464 if (mKey == null) {
2465 hashedKey = "none";
2466 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002467 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002468 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2469
2470 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2471 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2472 SecretKey key = factory.generateSecret(ks);
2473 BigInteger bi = new BigInteger(key.getEncoded());
2474 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002475 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002476 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2477 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2478 return;
2479 } catch (InvalidKeySpecException e) {
2480 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2481 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002482 return;
2483 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002484 }
Kenny Root38cf8862010-09-26 14:18:51 -07002485
Kenny Rootaf9d6672010-10-08 09:21:39 -07002486 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002487 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002488 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002489 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002490 } catch (NativeDaemonConnectorException e) {
2491 int code = e.getCode();
2492 if (code != VoldResponseCode.OpFailedStorageBusy) {
2493 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002494 }
2495 }
2496
Kenny Rootaf9d6672010-10-08 09:21:39 -07002497 if (rc == StorageResultCode.OperationSucceeded) {
2498 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002499 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002500
2501 synchronized (mObbMounts) {
2502 addObbStateLocked(mObbState);
2503 }
2504
2505 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002506 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002507 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002508
Kenny Rootaf9d6672010-10-08 09:21:39 -07002509 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002510 }
2511 }
2512
Jason parks5af0b912010-11-29 09:05:25 -06002513 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002514 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002515 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002516 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002517
2518 @Override
2519 public String toString() {
2520 StringBuilder sb = new StringBuilder();
2521 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002522 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002523 sb.append('}');
2524 return sb.toString();
2525 }
2526 }
2527
2528 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002529 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002530
2531 UnmountObbAction(ObbState obbState, boolean force) {
2532 super(obbState);
2533 mForceUnmount = force;
2534 }
2535
Jason parks5af0b912010-11-29 09:05:25 -06002536 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002537 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002538 waitForReady();
2539 warnOnNotMounted();
2540
Kenny Root38cf8862010-09-26 14:18:51 -07002541 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002542
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002543 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002544 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002545 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002546 }
Kenny Root38cf8862010-09-26 14:18:51 -07002547
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002548 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002549 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2550 return;
2551 }
2552
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002553 if (existingState.ownerGid != mObbState.ownerGid) {
2554 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2555 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002556 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2557 return;
2558 }
2559
Kenny Rootaf9d6672010-10-08 09:21:39 -07002560 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002561 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002562 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002563 if (mForceUnmount) {
2564 cmd.appendArg("force");
2565 }
2566 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002567 } catch (NativeDaemonConnectorException e) {
2568 int code = e.getCode();
2569 if (code == VoldResponseCode.OpFailedStorageBusy) {
2570 rc = StorageResultCode.OperationFailedStorageBusy;
2571 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2572 // If it's not mounted then we've already won.
2573 rc = StorageResultCode.OperationSucceeded;
2574 } else {
2575 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002576 }
2577 }
2578
Kenny Rootaf9d6672010-10-08 09:21:39 -07002579 if (rc == StorageResultCode.OperationSucceeded) {
2580 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002581 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002582 }
2583
Kenny Rootaf9d6672010-10-08 09:21:39 -07002584 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002585 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002586 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002587 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002588 }
2589 }
2590
Jason parks5af0b912010-11-29 09:05:25 -06002591 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002592 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002593 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002594 }
2595
2596 @Override
2597 public String toString() {
2598 StringBuilder sb = new StringBuilder();
2599 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002600 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002601 sb.append(",force=");
2602 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002603 sb.append('}');
2604 return sb.toString();
2605 }
Kenny Root02c87302010-07-01 08:10:18 -07002606 }
Kenny Root38cf8862010-09-26 14:18:51 -07002607
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002608 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002609 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2610 // TODO: allow caller to provide Environment for full testing
2611
2612 // Only adjust paths when storage is emulated
2613 if (!Environment.isExternalStorageEmulated()) {
2614 return canonicalPath;
2615 }
2616
2617 String path = canonicalPath.toString();
2618
2619 // First trim off any external storage prefix
2620 final UserEnvironment userEnv = new UserEnvironment(userId);
2621
2622 // /storage/emulated/0
2623 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2624 // /storage/emulated_legacy
2625 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2626 .toString();
2627
2628 if (path.startsWith(externalPath)) {
2629 path = path.substring(externalPath.length() + 1);
2630 } else if (path.startsWith(legacyExternalPath)) {
2631 path = path.substring(legacyExternalPath.length() + 1);
2632 } else {
2633 return canonicalPath;
2634 }
2635
2636 // Handle special OBB paths on emulated storage
2637 final String obbPath = "Android/obb";
2638 if (path.startsWith(obbPath)) {
2639 path = path.substring(obbPath.length() + 1);
2640
2641 if (forVold) {
2642 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2643 } else {
2644 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2645 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2646 }
2647 }
2648
2649 // Handle normal external storage paths
2650 if (forVold) {
2651 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2652 } else {
2653 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2654 }
2655 }
2656
Kenny Root38cf8862010-09-26 14:18:51 -07002657 @Override
2658 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2659 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2660 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2661 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2662 + " without permission " + android.Manifest.permission.DUMP);
2663 return;
2664 }
2665
Kenny Root38cf8862010-09-26 14:18:51 -07002666 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002667 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002668
Kenny Rootaf9d6672010-10-08 09:21:39 -07002669 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2670 while (binders.hasNext()) {
2671 Entry<IBinder, List<ObbState>> e = binders.next();
2672 pw.print(" Key="); pw.println(e.getKey().toString());
2673 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002674 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002675 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002676 }
2677 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002678
2679 pw.println("");
2680 pw.println(" mObbPathToStateMap:");
2681 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2682 while (maps.hasNext()) {
2683 final Entry<String, ObbState> e = maps.next();
2684 pw.print(" "); pw.print(e.getKey());
2685 pw.print(" -> "); pw.println(e.getValue().toString());
2686 }
Kenny Root38cf8862010-09-26 14:18:51 -07002687 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002688
2689 pw.println("");
2690
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002691 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002692 pw.println(" mVolumes:");
2693
2694 final int N = mVolumes.size();
2695 for (int i = 0; i < N; i++) {
2696 final StorageVolume v = mVolumes.get(i);
2697 pw.print(" ");
2698 pw.println(v.toString());
2699 }
2700 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002701
2702 pw.println();
2703 pw.println(" mConnection:");
2704 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002707 /** {@inheritDoc} */
2708 public void monitor() {
2709 if (mConnector != null) {
2710 mConnector.monitor();
2711 }
2712 }
2713}