blob: 9f4000019fbb13e2c7a575e02454e93d485adafe [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Kenny Roota02b8b02010-08-05 16:14:17 -070040import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040041import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080042import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080043import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080044import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070047import android.os.storage.IMountService;
48import android.os.storage.IMountServiceListener;
49import android.os.storage.IMountShutdownObserver;
50import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070051import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070052import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070053import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060054import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070055import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070056import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.util.Xml;
58
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080059import com.android.internal.annotations.GuardedBy;
60import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070061import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070062import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070063import com.android.internal.util.XmlUtils;
64import com.android.server.NativeDaemonConnector.Command;
65import com.android.server.am.ActivityManagerService;
66import com.android.server.pm.PackageManagerService;
67import com.android.server.pm.UserManagerService;
68import com.google.android.collect.Lists;
69import com.google.android.collect.Maps;
70
Mike Lockwood2f6a3882011-05-09 19:08:06 -070071import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070072
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070073import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070074import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070075import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070076import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070077import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070078import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070079import java.security.spec.InvalidKeySpecException;
80import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080081import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070082import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080083import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070084import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070085import java.util.LinkedList;
86import java.util.List;
87import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070088import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070089import java.util.concurrent.CountDownLatch;
90import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Kenny Root3b1abba2010-10-13 15:00:07 -070092import javax.crypto.SecretKey;
93import javax.crypto.SecretKeyFactory;
94import javax.crypto.spec.PBEKeySpec;
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096/**
San Mehatb1043402010-02-05 08:26:50 -080097 * MountService implements back-end services for platform storage
98 * management.
99 * @hide - Applications should use android.os.storage.StorageManager
100 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700102class MountService extends IMountService.Stub
103 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600104
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700105 // TODO: listen for user creation/deletion
106
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800107 private static final boolean LOCAL_LOGD = false;
108 private static final boolean DEBUG_UNMOUNT = false;
109 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800110 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700111
Kenny Root07714d42011-08-17 17:49:28 -0700112 // Disable this since it messes up long-running cryptfs operations.
113 private static final boolean WATCHDOG_ENABLE = false;
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 private static final String TAG = "MountService";
116
Kenny Root305bcbf2010-09-03 07:56:38 -0700117 private static final String VOLD_TAG = "VoldConnector";
118
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700119 /** Maximum number of ASEC containers allowed to be mounted. */
120 private static final int MAX_CONTAINERS = 250;
121
San Mehat4270e1e2010-01-29 05:32:19 -0800122 /*
123 * Internal vold volume state constants
124 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800125 class VolumeState {
126 public static final int Init = -1;
127 public static final int NoMedia = 0;
128 public static final int Idle = 1;
129 public static final int Pending = 2;
130 public static final int Checking = 3;
131 public static final int Mounted = 4;
132 public static final int Unmounting = 5;
133 public static final int Formatting = 6;
134 public static final int Shared = 7;
135 public static final int SharedMnt = 8;
136 }
137
San Mehat4270e1e2010-01-29 05:32:19 -0800138 /*
139 * Internal vold response code constants
140 */
San Mehat22dd86e2010-01-12 12:21:18 -0800141 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800142 /*
143 * 100 series - Requestion action was initiated; expect another reply
144 * before proceeding with a new command.
145 */
San Mehat22dd86e2010-01-12 12:21:18 -0800146 public static final int VolumeListResult = 110;
147 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800148 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800149
San Mehat4270e1e2010-01-29 05:32:19 -0800150 /*
151 * 200 series - Requestion action has been successfully completed.
152 */
153 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800154 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800155 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800156
San Mehat4270e1e2010-01-29 05:32:19 -0800157 /*
158 * 400 series - Command was accepted, but the requested action
159 * did not take place.
160 */
161 public static final int OpFailedNoMedia = 401;
162 public static final int OpFailedMediaBlank = 402;
163 public static final int OpFailedMediaCorrupt = 403;
164 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800165 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700166 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800167
168 /*
169 * 600 series - Unsolicited broadcasts.
170 */
San Mehat22dd86e2010-01-12 12:21:18 -0800171 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800172 public static final int VolumeDiskInserted = 630;
173 public static final int VolumeDiskRemoved = 631;
174 public static final int VolumeBadRemoval = 632;
175 }
176
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700177 private Context mContext;
178 private NativeDaemonConnector mConnector;
179
180 private final Object mVolumesLock = new Object();
181
182 /** When defined, base template for user-specific {@link StorageVolume}. */
183 private StorageVolume mEmulatedTemplate;
184
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800185 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700186 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
187 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800188 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700189 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
190 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800191 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700192 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
193
194 private volatile boolean mSystemReady = false;
195
San Mehat4270e1e2010-01-29 05:32:19 -0800196 private PackageManagerService mPms;
197 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700198 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800199 // Used as a lock for methods that register/unregister listeners.
200 final private ArrayList<MountServiceBinderListener> mListeners =
201 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800202 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
203 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800204 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800205
San Mehat6cdd9c02010-02-09 14:45:20 -0800206 /**
207 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800208 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800209 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800210 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800211
Kenny Root02c87302010-07-01 08:10:18 -0700212 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700213 * The size of the crypto algorithm key in bits for OBB files. Currently
214 * Twofish is used which takes 128-bit keys.
215 */
216 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
217
218 /**
219 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
220 * 1024 is reasonably secure and not too slow.
221 */
222 private static final int PBKDF2_HASH_ROUNDS = 1024;
223
224 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700225 * Mounted OBB tracking information. Used to track the current state of all
226 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700227 */
Kenny Root735de3b2010-09-30 14:11:39 -0700228 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700229
230 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700231 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
232
233 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700234 public ObbState(String rawPath, String canonicalPath, int callingUid,
235 IObbActionListener token, int nonce) {
236 this.rawPath = rawPath;
237 this.canonicalPath = canonicalPath.toString();
238
239 final int userId = UserHandle.getUserId(callingUid);
240 this.ownerPath = buildObbPath(canonicalPath, userId, false);
241 this.voldPath = buildObbPath(canonicalPath, userId, true);
242
243 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700244 this.token = token;
245 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700246 }
247
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700248 final String rawPath;
249 final String canonicalPath;
250 final String ownerPath;
251 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700252
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700253 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700254
Kenny Rootaf9d6672010-10-08 09:21:39 -0700255 // Token of remote Binder caller
256 final IObbActionListener token;
257
258 // Identifier to pass back to the token
259 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700260
Kenny Root735de3b2010-09-30 14:11:39 -0700261 public IBinder getBinder() {
262 return token.asBinder();
263 }
264
Kenny Roota02b8b02010-08-05 16:14:17 -0700265 @Override
266 public void binderDied() {
267 ObbAction action = new UnmountObbAction(this, true);
268 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700269 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700270
Kenny Root5919ac62010-10-05 09:49:40 -0700271 public void link() throws RemoteException {
272 getBinder().linkToDeath(this, 0);
273 }
274
275 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700276 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700277 }
Kenny Root38cf8862010-09-26 14:18:51 -0700278
279 @Override
280 public String toString() {
281 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700282 sb.append("rawPath=").append(rawPath);
283 sb.append(",canonicalPath=").append(canonicalPath);
284 sb.append(",ownerPath=").append(ownerPath);
285 sb.append(",voldPath=").append(voldPath);
286 sb.append(",ownerGid=").append(ownerGid);
287 sb.append(",token=").append(token);
288 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700289 sb.append('}');
290 return sb.toString();
291 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700292 }
293
294 // OBB Action Handler
295 final private ObbActionHandler mObbActionHandler;
296
297 // OBB action handler messages
298 private static final int OBB_RUN_ACTION = 1;
299 private static final int OBB_MCS_BOUND = 2;
300 private static final int OBB_MCS_UNBIND = 3;
301 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700302 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700303
304 /*
305 * Default Container Service information
306 */
307 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
308 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
309
310 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
311
312 class DefaultContainerConnection implements ServiceConnection {
313 public void onServiceConnected(ComponentName name, IBinder service) {
314 if (DEBUG_OBB)
315 Slog.i(TAG, "onServiceConnected");
316 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
317 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
318 }
319
320 public void onServiceDisconnected(ComponentName name) {
321 if (DEBUG_OBB)
322 Slog.i(TAG, "onServiceDisconnected");
323 }
324 };
325
326 // Used in the ObbActionHandler
327 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700328
329 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800330 private static final int H_UNMOUNT_PM_UPDATE = 1;
331 private static final int H_UNMOUNT_PM_DONE = 2;
332 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700333 private static final int H_SYSTEM_READY = 4;
334
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800335 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
336 private static final int MAX_UNMOUNT_RETRIES = 4;
337
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800338 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700339 final String path;
340 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700341 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800342 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800343
Ben Komalo13c71972011-09-07 16:35:56 -0700344 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800345 retries = 0;
346 this.path = path;
347 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700348 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800350
351 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700352 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700353 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800354 }
355 }
356
357 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700358 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800359
360 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700361 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800362 this.method = method;
363 }
364
365 @Override
366 void handleFinished() {
367 super.handleFinished();
368 doShareUnshareVolume(path, method, true);
369 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800370 }
371
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800372 class ShutdownCallBack extends UnmountCallBack {
373 IMountShutdownObserver observer;
374 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700375 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800376 this.observer = observer;
377 }
378
379 @Override
380 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700381 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800382 if (observer != null) {
383 try {
384 observer.onShutDownComplete(ret);
385 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700386 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800387 }
388 }
389 }
390 }
391
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400392 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800393 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700394 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800395
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400396 MountServiceHandler(Looper l) {
397 super(l);
398 }
399
Jason parks5af0b912010-11-29 09:05:25 -0600400 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800401 public void handleMessage(Message msg) {
402 switch (msg.what) {
403 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700404 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800405 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
406 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700407 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800408 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700409 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700410 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700411 mUpdatingStatus = true;
412 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800413 }
414 break;
415 }
416 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700417 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700419 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800420 int size = mForceUnmounts.size();
421 int sizeArr[] = new int[size];
422 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700423 // Kill processes holding references first
424 ActivityManagerService ams = (ActivityManagerService)
425 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800426 for (int i = 0; i < size; i++) {
427 UnmountCallBack ucb = mForceUnmounts.get(i);
428 String path = ucb.path;
429 boolean done = false;
430 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800431 done = true;
432 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800433 int pids[] = getStorageUsers(path);
434 if (pids == null || pids.length == 0) {
435 done = true;
436 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800437 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800438 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700439 // Confirm if file references have been freed.
440 pids = getStorageUsers(path);
441 if (pids == null || pids.length == 0) {
442 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800443 }
444 }
445 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700446 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
447 // Retry again
448 Slog.i(TAG, "Retrying to kill storage users again");
449 mHandler.sendMessageDelayed(
450 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
451 ucb.retries++),
452 RETRY_UNMOUNT_DELAY);
453 } else {
454 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
455 Slog.i(TAG, "Failed to unmount media inspite of " +
456 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
457 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800458 sizeArr[sizeArrN++] = i;
459 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
460 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800461 }
462 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800463 // Remove already processed elements from list.
464 for (int i = (sizeArrN-1); i >= 0; i--) {
465 mForceUnmounts.remove(sizeArr[i]);
466 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800467 break;
468 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700469 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700470 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800471 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800472 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800473 break;
474 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700475 case H_SYSTEM_READY: {
476 try {
477 handleSystemReady();
478 } catch (Exception ex) {
479 Slog.e(TAG, "Boot-time mount exception", ex);
480 }
481 break;
482 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800483 }
484 }
485 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700486
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700487 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800488
Kenny Root51a573c2012-05-17 13:30:28 -0700489 void waitForAsecScan() {
490 waitForLatch(mAsecsScanned);
491 }
492
San Mehat207e5382010-02-04 20:46:54 -0800493 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700494 waitForLatch(mConnectedSignal);
495 }
496
497 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700498 for (;;) {
499 try {
500 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800501 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700502 } else {
503 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
504 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800505 }
Kenny Root51a573c2012-05-17 13:30:28 -0700506 } catch (InterruptedException e) {
507 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800508 }
San Mehat207e5382010-02-04 20:46:54 -0800509 }
San Mehat1f6301e2010-01-07 22:40:27 -0800510 }
Kenny Root02c87302010-07-01 08:10:18 -0700511
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700512 private void handleSystemReady() {
513 // Snapshot current volume states since it's not safe to call into vold
514 // while holding locks.
515 final HashMap<String, String> snapshot;
516 synchronized (mVolumesLock) {
517 snapshot = new HashMap<String, String>(mVolumeStates);
518 }
519
520 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
521 final String path = entry.getKey();
522 final String state = entry.getValue();
523
524 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
525 int rc = doMountVolume(path);
526 if (rc != StorageResultCode.OperationSucceeded) {
527 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
528 rc));
529 }
530 } else if (state.equals(Environment.MEDIA_SHARED)) {
531 /*
532 * Bootstrap UMS enabled state since vold indicates
533 * the volume is shared (runtime restart while ums enabled)
534 */
535 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
536 VolumeState.Shared);
537 }
538 }
539
540 // Push mounted state for all emulated storage
541 synchronized (mVolumesLock) {
542 for (StorageVolume volume : mVolumes) {
543 if (volume.isEmulated()) {
544 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
545 }
546 }
547 }
548
549 /*
550 * If UMS was connected on boot, send the connected event
551 * now that we're up.
552 */
553 if (mSendUmsConnectedOnBoot) {
554 sendUmsIntent(true);
555 mSendUmsConnectedOnBoot = false;
556 }
557 }
558
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700559 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
560 @Override
561 public void onReceive(Context context, Intent intent) {
562 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
563 if (userId == -1) return;
564 final UserHandle user = new UserHandle(userId);
565
566 final String action = intent.getAction();
567 if (Intent.ACTION_USER_ADDED.equals(action)) {
568 synchronized (mVolumesLock) {
569 createEmulatedVolumeForUserLocked(user);
570 }
571
572 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
573 synchronized (mVolumesLock) {
574 final List<StorageVolume> toRemove = Lists.newArrayList();
575 for (StorageVolume volume : mVolumes) {
576 if (user.equals(volume.getOwner())) {
577 toRemove.add(volume);
578 }
579 }
580 for (StorageVolume volume : toRemove) {
581 removeVolumeLocked(volume);
582 }
583 }
584 }
585 }
586 };
587
588 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
589 @Override
590 public void onReceive(Context context, Intent intent) {
591 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
592 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
593 notifyShareAvailabilityChange(available);
594 }
595 };
596
Svetoslava7452ee2013-03-20 12:06:59 -0700597 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
598 @Override
599 public void onReceive(Context context, Intent intent) {
600 waitForReady();
601 String action = intent.getAction();
602 // Since fstrim will be run on a daily basis we do not expect
603 // fstrim to be too long, so it is not interruptible. We will
604 // implement interruption only in case we see issues.
605 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
606 try {
607 // This method runs on the handler thread,
608 // so it is safe to directly call into vold.
609 mConnector.execute("fstrim", "dotrim");
610 } catch (NativeDaemonConnectorException ndce) {
611 Slog.e(TAG, "Failed to run fstrim!");
612 }
613 }
614 }
615 };
616
San Mehat4270e1e2010-01-29 05:32:19 -0800617 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
618 final IMountServiceListener mListener;
619
620 MountServiceBinderListener(IMountServiceListener listener) {
621 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700622
San Mehat91c77612010-01-07 10:39:41 -0800623 }
624
San Mehat4270e1e2010-01-29 05:32:19 -0800625 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700626 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700627 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800628 mListeners.remove(this);
629 mListener.asBinder().unlinkToDeath(this, 0);
630 }
631 }
632 }
633
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800634 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800635 // TODO: Add support for multiple share methods
636 if (!method.equals("ums")) {
637 throw new IllegalArgumentException(String.format("Method %s not supported", method));
638 }
639
San Mehat4270e1e2010-01-29 05:32:19 -0800640 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800641 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800642 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700643 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800644 }
San Mehat4270e1e2010-01-29 05:32:19 -0800645 }
646
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700647 private void updatePublicVolumeState(StorageVolume volume, String state) {
648 final String path = volume.getPath();
649 final String oldState;
650 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400651 oldState = mVolumeStates.put(path, state);
652 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700653
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400654 if (state.equals(oldState)) {
655 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
656 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800657 return;
658 }
San Mehatb1043402010-02-05 08:26:50 -0800659
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400660 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700661
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700662 // Tell PackageManager about changes to primary volume state, but only
663 // when not emulated.
664 if (volume.isPrimary() && !volume.isEmulated()) {
665 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
666 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400667
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700668 /*
669 * Some OBBs might have been unmounted when this volume was
670 * unmounted, so send a message to the handler to let it know to
671 * remove those from the list of mounted OBBS.
672 */
673 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
674 OBB_FLUSH_MOUNT_STATE, path));
675 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
676 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400677 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800678 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700679
San Mehat4270e1e2010-01-29 05:32:19 -0800680 synchronized (mListeners) {
681 for (int i = mListeners.size() -1; i >= 0; i--) {
682 MountServiceBinderListener bl = mListeners.get(i);
683 try {
San Mehatb1043402010-02-05 08:26:50 -0800684 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800685 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700686 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800687 mListeners.remove(i);
688 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700689 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800690 }
691 }
692 }
693 }
694
695 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800696 * Callback from NativeDaemonConnector
697 */
698 public void onDaemonConnected() {
699 /*
700 * Since we'll be calling back into the NativeDaemonConnector,
701 * we need to do our work in a new thread.
702 */
Kenny Root51a573c2012-05-17 13:30:28 -0700703 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600704 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800705 public void run() {
706 /**
707 * Determine media state and UMS detection status
708 */
San Mehat4270e1e2010-01-29 05:32:19 -0800709 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800710 final String[] vols = NativeDaemonEvent.filterMessageList(
711 mConnector.executeForList("volume", "list"),
712 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800713 for (String volstr : vols) {
714 String[] tok = volstr.split(" ");
715 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400716 String path = tok[1];
717 String state = Environment.MEDIA_REMOVED;
718
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700719 final StorageVolume volume;
720 synchronized (mVolumesLock) {
721 volume = mVolumesByPath.get(path);
722 }
723
San Mehat4270e1e2010-01-29 05:32:19 -0800724 int st = Integer.parseInt(tok[2]);
725 if (st == VolumeState.NoMedia) {
726 state = Environment.MEDIA_REMOVED;
727 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800728 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800729 } else if (st == VolumeState.Mounted) {
730 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700731 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800732 } else if (st == VolumeState.Shared) {
733 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700734 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800735 } else {
736 throw new Exception(String.format("Unexpected state %d", st));
737 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400738
739 if (state != null) {
740 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700741 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400742 }
San Mehat4270e1e2010-01-29 05:32:19 -0800743 }
744 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700745 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700746 final StorageVolume primary = getPrimaryPhysicalVolume();
747 if (primary != null) {
748 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
749 }
San Mehat4270e1e2010-01-29 05:32:19 -0800750 }
751
San Mehat207e5382010-02-04 20:46:54 -0800752 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600753 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800754 * the hounds!
755 */
Kenny Root51a573c2012-05-17 13:30:28 -0700756 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700757
758 // Let package manager load internal ASECs.
759 mPms.scanAvailableAsecs();
760
761 // Notify people waiting for ASECs to be scanned that it's done.
762 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800763 }
764 }.start();
765 }
766
767 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800768 * Callback from NativeDaemonConnector
769 */
770 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800771 if (DEBUG_EVENTS) {
772 StringBuilder builder = new StringBuilder();
773 builder.append("onEvent::");
774 builder.append(" raw= " + raw);
775 if (cooked != null) {
776 builder.append(" cooked = " );
777 for (String str : cooked) {
778 builder.append(" " + str);
779 }
780 }
San Mehata5078592010-03-25 09:36:54 -0700781 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800782 }
San Mehat4270e1e2010-01-29 05:32:19 -0800783 if (code == VoldResponseCode.VolumeStateChange) {
784 /*
785 * One of the volumes we're managing has changed state.
786 * Format: "NNN Volume <label> <path> state changed
787 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
788 */
789 notifyVolumeStateChange(
790 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
791 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800792 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
793 (code == VoldResponseCode.VolumeDiskRemoved) ||
794 (code == VoldResponseCode.VolumeBadRemoval)) {
795 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
796 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
797 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400798 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800799 final String label = cooked[2];
800 final String path = cooked[3];
801 int major = -1;
802 int minor = -1;
803
804 try {
805 String devComp = cooked[6].substring(1, cooked[6].length() -1);
806 String[] devTok = devComp.split(":");
807 major = Integer.parseInt(devTok[0]);
808 minor = Integer.parseInt(devTok[1]);
809 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700810 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800811 }
812
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700813 final StorageVolume volume;
814 final String state;
815 synchronized (mVolumesLock) {
816 volume = mVolumesByPath.get(path);
817 state = mVolumeStates.get(path);
818 }
819
San Mehat4270e1e2010-01-29 05:32:19 -0800820 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700821 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600822 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800823 public void run() {
824 try {
825 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800826 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700827 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800828 }
829 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700830 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800831 }
832 }
833 }.start();
834 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
835 /*
836 * This event gets trumped if we're already in BAD_REMOVAL state
837 */
838 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
839 return true;
840 }
841 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700842 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700843 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
844 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800845
San Mehata5078592010-03-25 09:36:54 -0700846 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700847 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400848 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800849 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700850 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800851 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700852 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400853 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800854
San Mehata5078592010-03-25 09:36:54 -0700855 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700856 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400857 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
San Mehat4270e1e2010-01-29 05:32:19 -0800858 } else {
San Mehata5078592010-03-25 09:36:54 -0700859 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800860 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400861
862 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700863 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400864 }
San Mehat4270e1e2010-01-29 05:32:19 -0800865 } else {
866 return false;
867 }
868
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400869 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800870 }
871
San Mehat207e5382010-02-04 20:46:54 -0800872 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700873 final StorageVolume volume;
874 final String state;
875 synchronized (mVolumesLock) {
876 volume = mVolumesByPath.get(path);
877 state = getVolumeState(path);
878 }
879
880 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800881
Mike Lockwooda5250c92011-05-23 13:44:04 -0400882 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800883
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500884 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700885 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700886 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500887 }
888
San Mehat4270e1e2010-01-29 05:32:19 -0800889 if (newState == VolumeState.Init) {
890 } else if (newState == VolumeState.NoMedia) {
891 // NoMedia is handled via Disk Remove events
892 } else if (newState == VolumeState.Idle) {
893 /*
894 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
895 * if we're in the process of enabling UMS
896 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700897 if (!state.equals(
898 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
899 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800900 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700901 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700902 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400903 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800904 }
905 } else if (newState == VolumeState.Pending) {
906 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700907 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700908 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400909 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800910 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700911 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700912 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400913 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800914 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400915 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800916 } else if (newState == VolumeState.Formatting) {
917 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700918 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800919 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700920 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
921 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800922
San Mehata5078592010-03-25 09:36:54 -0700923 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700924 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400925 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700926 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800927 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700928 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800929 return;
930 } else {
San Mehata5078592010-03-25 09:36:54 -0700931 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800932 }
933
Mike Lockwooda5250c92011-05-23 13:44:04 -0400934 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700935 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800936 }
937 }
938
San Mehat207e5382010-02-04 20:46:54 -0800939 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800940 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800941
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700942 final StorageVolume volume;
943 synchronized (mVolumesLock) {
944 volume = mVolumesByPath.get(path);
945 }
946
San Mehata5078592010-03-25 09:36:54 -0700947 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800948 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800949 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800950 } catch (NativeDaemonConnectorException e) {
951 /*
952 * Mount failed for some reason
953 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400954 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800955 int code = e.getCode();
956 if (code == VoldResponseCode.OpFailedNoMedia) {
957 /*
958 * Attempt to mount but no media inserted
959 */
San Mehatb1043402010-02-05 08:26:50 -0800960 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800961 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700962 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800963 /*
964 * Media is blank or does not contain a supported filesystem
965 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700966 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400967 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800968 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800969 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700970 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800971 /*
972 * Volume consistency check failed
973 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700974 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400975 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800976 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800977 } else {
San Mehatb1043402010-02-05 08:26:50 -0800978 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800979 }
980
981 /*
982 * Send broadcast intent (if required for the failure)
983 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400984 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700985 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800986 }
987 }
988
989 return rc;
990 }
991
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800992 /*
993 * If force is not set, we do not unmount if there are
994 * processes holding references to the volume about to be unmounted.
995 * If force is set, all the processes holding references need to be
996 * killed via the ActivityManager before actually unmounting the volume.
997 * This might even take a while and might be retried after timed delays
998 * to make sure we dont end up in an instable state and kill some core
999 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001000 * If removeEncryption is set, force is implied, and the system will remove any encryption
1001 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001002 */
Ben Komalo13c71972011-09-07 16:35:56 -07001003 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001004 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001005 return VoldResponseCode.OpFailedVolNotMounted;
1006 }
Kenny Rootaa485402010-09-14 14:49:41 -07001007
1008 /*
1009 * Force a GC to make sure AssetManagers in other threads of the
1010 * system_server are cleaned up. We have to do this since AssetManager
1011 * instances are kept as a WeakReference and it's possible we have files
1012 * open on the external storage.
1013 */
1014 Runtime.getRuntime().gc();
1015
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001016 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001017 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001018 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001019 final Command cmd = new Command("volume", "unmount", path);
1020 if (removeEncryption) {
1021 cmd.appendArg("force_and_revert");
1022 } else if (force) {
1023 cmd.appendArg("force");
1024 }
1025 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001026 // We unmounted the volume. None of the asec containers are available now.
1027 synchronized (mAsecMountSet) {
1028 mAsecMountSet.clear();
1029 }
San Mehatb1043402010-02-05 08:26:50 -08001030 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001031 } catch (NativeDaemonConnectorException e) {
1032 // Don't worry about mismatch in PackageManager since the
1033 // call back will handle the status changes any way.
1034 int code = e.getCode();
1035 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001036 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001037 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1038 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001039 } else {
San Mehatb1043402010-02-05 08:26:50 -08001040 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001041 }
1042 }
1043 }
1044
1045 private int doFormatVolume(String path) {
1046 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001047 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001048 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001049 } catch (NativeDaemonConnectorException e) {
1050 int code = e.getCode();
1051 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001052 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001053 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001054 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001055 } else {
San Mehatb1043402010-02-05 08:26:50 -08001056 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001057 }
1058 }
1059 }
1060
San Mehatb1043402010-02-05 08:26:50 -08001061 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001062 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001063 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001064 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001065 } catch (NativeDaemonConnectorException ex) {
1066 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1067 return false;
1068 }
San Mehatb1043402010-02-05 08:26:50 -08001069
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001070 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1071 return event.getMessage().endsWith("enabled");
1072 } else {
1073 return false;
San Mehatb1043402010-02-05 08:26:50 -08001074 }
San Mehatb1043402010-02-05 08:26:50 -08001075 }
1076
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001077 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001078 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001079 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001080 for (int i = mListeners.size() -1; i >= 0; i--) {
1081 MountServiceBinderListener bl = mListeners.get(i);
1082 try {
San Mehatb1043402010-02-05 08:26:50 -08001083 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001084 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001085 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001086 mListeners.remove(i);
1087 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001088 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001089 }
1090 }
1091 }
1092
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001093 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001094 sendUmsIntent(avail);
1095 } else {
1096 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001097 }
San Mehat2fe718a2010-03-11 12:01:49 -08001098
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001099 final StorageVolume primary = getPrimaryPhysicalVolume();
1100 if (avail == false && primary != null
1101 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1102 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001103 /*
1104 * USB mass storage disconnected while enabled
1105 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001106 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001107 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001108 public void run() {
1109 try {
1110 int rc;
San Mehata5078592010-03-25 09:36:54 -07001111 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001112 doShareUnshareVolume(path, "ums", false);
1113 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001114 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001115 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1116 path, rc));
1117 }
1118 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001119 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001120 }
1121 }
1122 }.start();
1123 }
San Mehat4270e1e2010-01-29 05:32:19 -08001124 }
1125
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001126 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1127 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1128 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1129 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1130 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001131 }
1132
San Mehat6a965af22010-02-24 17:47:30 -08001133 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001134 mContext.sendBroadcastAsUser(
1135 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1136 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001137 }
1138
San Mehat207e5382010-02-04 20:46:54 -08001139 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001140 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1141 throw new SecurityException(String.format("Requires %s permission", perm));
1142 }
1143 }
1144
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001145 // Storage list XML tags
1146 private static final String TAG_STORAGE_LIST = "StorageList";
1147 private static final String TAG_STORAGE = "storage";
1148
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001149 private void readStorageListLocked() {
1150 mVolumes.clear();
1151 mVolumeStates.clear();
1152
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001153 Resources resources = mContext.getResources();
1154
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001155 int id = com.android.internal.R.xml.storage_list;
1156 XmlResourceParser parser = resources.getXml(id);
1157 AttributeSet attrs = Xml.asAttributeSet(parser);
1158
1159 try {
1160 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1161 while (true) {
1162 XmlUtils.nextElement(parser);
1163
1164 String element = parser.getName();
1165 if (element == null) break;
1166
1167 if (TAG_STORAGE.equals(element)) {
1168 TypedArray a = resources.obtainAttributes(attrs,
1169 com.android.internal.R.styleable.Storage);
1170
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001171 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001172 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001173 int descriptionId = a.getResourceId(
1174 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001175 CharSequence description = a.getText(
1176 com.android.internal.R.styleable.Storage_storageDescription);
1177 boolean primary = a.getBoolean(
1178 com.android.internal.R.styleable.Storage_primary, false);
1179 boolean removable = a.getBoolean(
1180 com.android.internal.R.styleable.Storage_removable, false);
1181 boolean emulated = a.getBoolean(
1182 com.android.internal.R.styleable.Storage_emulated, false);
1183 int mtpReserve = a.getInt(
1184 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001185 boolean allowMassStorage = a.getBoolean(
1186 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001187 // resource parser does not support longs, so XML value is in megabytes
1188 long maxFileSize = a.getInt(
1189 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001190
1191 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1192 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001193 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001194 " allowMassStorage: " + allowMassStorage +
1195 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001196
1197 if (emulated) {
1198 // For devices with emulated storage, we create separate
1199 // volumes for each known user.
1200 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1201 true, mtpReserve, false, maxFileSize, null);
1202
1203 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001204 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001205 createEmulatedVolumeForUserLocked(user.getUserHandle());
1206 }
1207
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001208 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001209 if (path == null || description == null) {
1210 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001211 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001212 final StorageVolume volume = new StorageVolume(new File(path),
1213 descriptionId, primary, removable, emulated, mtpReserve,
1214 allowMassStorage, maxFileSize, null);
1215 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001216 }
1217 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001218
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001219 a.recycle();
1220 }
1221 }
1222 } catch (XmlPullParserException e) {
1223 throw new RuntimeException(e);
1224 } catch (IOException e) {
1225 throw new RuntimeException(e);
1226 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001227 // Compute storage ID for each physical volume; emulated storage is
1228 // always 0 when defined.
1229 int index = isExternalStorageEmulated() ? 1 : 0;
1230 for (StorageVolume volume : mVolumes) {
1231 if (!volume.isEmulated()) {
1232 volume.setStorageId(index++);
1233 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001234 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001235 parser.close();
1236 }
1237 }
1238
San Mehat4270e1e2010-01-29 05:32:19 -08001239 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001240 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1241 * using {@link #mEmulatedTemplate} as template.
1242 */
1243 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1244 if (mEmulatedTemplate == null) {
1245 throw new IllegalStateException("Missing emulated volume multi-user template");
1246 }
1247
1248 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1249 final File path = userEnv.getExternalStorageDirectory();
1250 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1251 volume.setStorageId(0);
1252 addVolumeLocked(volume);
1253
1254 if (mSystemReady) {
1255 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1256 } else {
1257 // Place stub status for early callers to find
1258 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1259 }
1260 }
1261
1262 private void addVolumeLocked(StorageVolume volume) {
1263 Slog.d(TAG, "addVolumeLocked() " + volume);
1264 mVolumes.add(volume);
1265 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1266 if (existing != null) {
1267 throw new IllegalStateException(
1268 "Volume at " + volume.getPath() + " already exists: " + existing);
1269 }
1270 }
1271
1272 private void removeVolumeLocked(StorageVolume volume) {
1273 Slog.d(TAG, "removeVolumeLocked() " + volume);
1274 mVolumes.remove(volume);
1275 mVolumesByPath.remove(volume.getPath());
1276 mVolumeStates.remove(volume.getPath());
1277 }
1278
1279 private StorageVolume getPrimaryPhysicalVolume() {
1280 synchronized (mVolumesLock) {
1281 for (StorageVolume volume : mVolumes) {
1282 if (volume.isPrimary() && !volume.isEmulated()) {
1283 return volume;
1284 }
1285 }
1286 }
1287 return null;
1288 }
1289
1290 /**
San Mehat207e5382010-02-04 20:46:54 -08001291 * Constructs a new MountService instance
1292 *
1293 * @param context Binder context for this service
1294 */
1295 public MountService(Context context) {
1296 mContext = context;
1297
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001298 synchronized (mVolumesLock) {
1299 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001300 }
1301
San Mehat207e5382010-02-04 20:46:54 -08001302 // XXX: This will go away soon in favor of IMountServiceObserver
1303 mPms = (PackageManagerService) ServiceManager.getService("package");
1304
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001305 mHandler = new MountServiceHandler(IoThread.get().getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001306
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001307 // Watch for user changes
1308 final IntentFilter userFilter = new IntentFilter();
1309 userFilter.addAction(Intent.ACTION_USER_ADDED);
1310 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1311 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1312
1313 // Watch for USB changes on primary volume
1314 final StorageVolume primary = getPrimaryPhysicalVolume();
1315 if (primary != null && primary.allowMassStorage()) {
1316 mContext.registerReceiver(
1317 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1318 }
1319
Svetoslava7452ee2013-03-20 12:06:59 -07001320 // Watch for idle maintenance changes
1321 IntentFilter idleMaintenanceFilter = new IntentFilter();
1322 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1323 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1324 idleMaintenanceFilter, null, mHandler);
1325
Kenny Roota02b8b02010-08-05 16:14:17 -07001326 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001327 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001328
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001329 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001330 * Create the connection to vold with a maximum queue of twice the
1331 * amount of containers we'd ever expect to have. This keeps an
1332 * "asec list" from blocking a thread repeatedly.
1333 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001334 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001335
Kenny Root305bcbf2010-09-03 07:56:38 -07001336 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001337 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001338
Kenny Root07714d42011-08-17 17:49:28 -07001339 // Add ourself to the Watchdog monitors if enabled.
1340 if (WATCHDOG_ENABLE) {
1341 Watchdog.getInstance().addMonitor(this);
1342 }
San Mehat207e5382010-02-04 20:46:54 -08001343 }
1344
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001345 public void systemReady() {
1346 mSystemReady = true;
1347 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1348 }
1349
San Mehat207e5382010-02-04 20:46:54 -08001350 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001351 * Exposed API calls below here
1352 */
1353
1354 public void registerListener(IMountServiceListener listener) {
1355 synchronized (mListeners) {
1356 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1357 try {
1358 listener.asBinder().linkToDeath(bl, 0);
1359 mListeners.add(bl);
1360 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001361 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001362 }
1363 }
1364 }
1365
1366 public void unregisterListener(IMountServiceListener listener) {
1367 synchronized (mListeners) {
1368 for(MountServiceBinderListener bl : mListeners) {
1369 if (bl.mListener == listener) {
1370 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001371 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001372 return;
1373 }
1374 }
1375 }
1376 }
1377
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001378 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001379 validatePermission(android.Manifest.permission.SHUTDOWN);
1380
San Mehata5078592010-03-25 09:36:54 -07001381 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001382 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001383 for (String path : mVolumeStates.keySet()) {
1384 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001385
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001386 if (state.equals(Environment.MEDIA_SHARED)) {
1387 /*
1388 * If the media is currently shared, unshare it.
1389 * XXX: This is still dangerous!. We should not
1390 * be rebooting at *all* if UMS is enabled, since
1391 * the UMS host could have dirty FAT cache entries
1392 * yet to flush.
1393 */
1394 setUsbMassStorageEnabled(false);
1395 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1396 /*
1397 * If the media is being checked, then we need to wait for
1398 * it to complete before being able to proceed.
1399 */
1400 // XXX: @hackbod - Should we disable the ANR timer here?
1401 int retries = 30;
1402 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1403 try {
1404 Thread.sleep(1000);
1405 } catch (InterruptedException iex) {
1406 Slog.e(TAG, "Interrupted while waiting for media", iex);
1407 break;
1408 }
1409 state = Environment.getExternalStorageState();
1410 }
1411 if (retries == 0) {
1412 Slog.e(TAG, "Timed out waiting for media to check");
1413 }
San Mehat91c77612010-01-07 10:39:41 -08001414 }
San Mehat91c77612010-01-07 10:39:41 -08001415
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001416 if (state.equals(Environment.MEDIA_MOUNTED)) {
1417 // Post a unmount message.
1418 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1419 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1420 } else if (observer != null) {
1421 /*
1422 * Observer is waiting for onShutDownComplete when we are done.
1423 * Since nothing will be done send notification directly so shutdown
1424 * sequence can continue.
1425 */
1426 try {
1427 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1428 } catch (RemoteException e) {
1429 Slog.w(TAG, "RemoteException when shutting down");
1430 }
1431 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001432 }
San Mehat4270e1e2010-01-29 05:32:19 -08001433 }
1434 }
1435
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001436 private boolean getUmsEnabling() {
1437 synchronized (mListeners) {
1438 return mUmsEnabling;
1439 }
1440 }
1441
1442 private void setUmsEnabling(boolean enable) {
1443 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001444 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001445 }
1446 }
1447
San Mehatb1043402010-02-05 08:26:50 -08001448 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001449 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001450
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001451 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001452 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001453 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001454 synchronized (mListeners) {
1455 return mUmsAvailable;
1456 }
San Mehatb1043402010-02-05 08:26:50 -08001457 }
1458
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001459 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001460 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001461 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001462
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001463 final StorageVolume primary = getPrimaryPhysicalVolume();
1464 if (primary == null) return;
1465
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001466 // TODO: Add support for multiple share methods
1467
1468 /*
1469 * If the volume is mounted and we're enabling then unmount it
1470 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001471 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001472 String vs = getVolumeState(path);
1473 String method = "ums";
1474 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1475 // Override for isUsbMassStorageEnabled()
1476 setUmsEnabling(enable);
1477 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1478 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1479 // Clear override
1480 setUmsEnabling(false);
1481 }
1482 /*
1483 * If we disabled UMS then mount the volume
1484 */
1485 if (!enable) {
1486 doShareUnshareVolume(path, method, enable);
1487 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001488 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001489 " after disabling share method " + method);
1490 /*
1491 * Even though the mount failed, the unshare didn't so don't indicate an error.
1492 * The mountVolume() call will have set the storage state and sent the necessary
1493 * broadcasts.
1494 */
1495 }
1496 }
San Mehatb1043402010-02-05 08:26:50 -08001497 }
1498
1499 public boolean isUsbMassStorageEnabled() {
1500 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001501
1502 final StorageVolume primary = getPrimaryPhysicalVolume();
1503 if (primary != null) {
1504 return doGetVolumeShared(primary.getPath(), "ums");
1505 } else {
1506 return false;
1507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001509
San Mehat7fd0fee2009-12-17 07:12:23 -08001510 /**
1511 * @return state of the volume at the specified mount point
1512 */
San Mehat4270e1e2010-01-29 05:32:19 -08001513 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001514 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001515 String state = mVolumeStates.get(mountPoint);
1516 if (state == null) {
1517 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001518 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1519 state = Environment.MEDIA_REMOVED;
1520 } else {
1521 throw new IllegalArgumentException();
1522 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001523 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001524
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001525 return state;
1526 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001527 }
1528
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001529 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001530 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001531 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001532 }
1533
San Mehat4270e1e2010-01-29 05:32:19 -08001534 public int mountVolume(String path) {
1535 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001536
San Mehat207e5382010-02-04 20:46:54 -08001537 waitForReady();
1538 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
Ben Komalo13c71972011-09-07 16:35:56 -07001541 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001542 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001543 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001545 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001546 if (DEBUG_UNMOUNT) {
1547 Slog.i(TAG, "Unmounting " + path
1548 + " force = " + force
1549 + " removeEncryption = " + removeEncryption);
1550 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001551 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1552 Environment.MEDIA_REMOVED.equals(volState) ||
1553 Environment.MEDIA_SHARED.equals(volState) ||
1554 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1555 // Media already unmounted or cannot be unmounted.
1556 // TODO return valid return code when adding observer call back.
1557 return;
1558 }
Ben Komalo13c71972011-09-07 16:35:56 -07001559 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001560 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562
San Mehat4270e1e2010-01-29 05:32:19 -08001563 public int formatVolume(String path) {
1564 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001565 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001566
San Mehat207e5382010-02-04 20:46:54 -08001567 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001570 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001571 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1572 waitForReady();
1573 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001574 final String[] r = NativeDaemonEvent.filterMessageList(
1575 mConnector.executeForList("storage", "users", path),
1576 VoldResponseCode.StorageUsersListResult);
1577
San Mehatc1b4ce92010-02-16 17:13:03 -08001578 // FMT: <pid> <process name>
1579 int[] data = new int[r.length];
1580 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001581 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001582 try {
1583 data[i] = Integer.parseInt(tok[0]);
1584 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001585 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001586 return new int[0];
1587 }
1588 }
1589 return data;
1590 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001591 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001592 return new int[0];
1593 }
1594 }
1595
San Mehatb1043402010-02-05 08:26:50 -08001596 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001597 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001598 if (primary != null) {
1599 boolean mounted = false;
1600 try {
1601 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001602 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001603 }
1604
1605 if (!mounted) {
1606 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1607 }
San Mehatb1043402010-02-05 08:26:50 -08001608 }
1609 }
1610
San Mehat4270e1e2010-01-29 05:32:19 -08001611 public String[] getSecureContainerList() {
1612 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001613 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001614 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001615
San Mehat4270e1e2010-01-29 05:32:19 -08001616 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001617 return NativeDaemonEvent.filterMessageList(
1618 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001619 } catch (NativeDaemonConnectorException e) {
1620 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622 }
San Mehat36972292010-01-06 11:06:32 -08001623
Kenny Root6dceb882012-04-12 14:23:49 -07001624 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1625 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001626 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001627 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001628 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001629
San Mehatb1043402010-02-05 08:26:50 -08001630 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001631 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001632 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1633 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001634 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001635 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001636 }
San Mehata181b212010-02-11 06:50:20 -08001637
1638 if (rc == StorageResultCode.OperationSucceeded) {
1639 synchronized (mAsecMountSet) {
1640 mAsecMountSet.add(id);
1641 }
1642 }
San Mehat4270e1e2010-01-29 05:32:19 -08001643 return rc;
San Mehat36972292010-01-06 11:06:32 -08001644 }
1645
San Mehat4270e1e2010-01-29 05:32:19 -08001646 public int finalizeSecureContainer(String id) {
1647 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001648 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001649
San Mehatb1043402010-02-05 08:26:50 -08001650 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001651 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001652 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001653 /*
1654 * Finalization does a remount, so no need
1655 * to update mAsecMountSet
1656 */
San Mehat4270e1e2010-01-29 05:32:19 -08001657 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001658 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001659 }
San Mehat4270e1e2010-01-29 05:32:19 -08001660 return rc;
San Mehat36972292010-01-06 11:06:32 -08001661 }
1662
Kenny Root6dceb882012-04-12 14:23:49 -07001663 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1664 validatePermission(android.Manifest.permission.ASEC_CREATE);
1665 warnOnNotMounted();
1666
1667 int rc = StorageResultCode.OperationSucceeded;
1668 try {
1669 mConnector.execute("asec", "fixperms", id, gid, filename);
1670 /*
1671 * Fix permissions does a remount, so no need to update
1672 * mAsecMountSet
1673 */
1674 } catch (NativeDaemonConnectorException e) {
1675 rc = StorageResultCode.OperationFailedInternalError;
1676 }
1677 return rc;
1678 }
1679
San Mehatd9709982010-02-18 11:43:03 -08001680 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001681 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001682 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001683 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001684
Kenny Rootaa485402010-09-14 14:49:41 -07001685 /*
1686 * Force a GC to make sure AssetManagers in other threads of the
1687 * system_server are cleaned up. We have to do this since AssetManager
1688 * instances are kept as a WeakReference and it's possible we have files
1689 * open on the external storage.
1690 */
1691 Runtime.getRuntime().gc();
1692
San Mehatb1043402010-02-05 08:26:50 -08001693 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001694 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001695 final Command cmd = new Command("asec", "destroy", id);
1696 if (force) {
1697 cmd.appendArg("force");
1698 }
1699 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001700 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001701 int code = e.getCode();
1702 if (code == VoldResponseCode.OpFailedStorageBusy) {
1703 rc = StorageResultCode.OperationFailedStorageBusy;
1704 } else {
1705 rc = StorageResultCode.OperationFailedInternalError;
1706 }
San Mehat02735bc2010-01-26 15:18:08 -08001707 }
San Mehata181b212010-02-11 06:50:20 -08001708
1709 if (rc == StorageResultCode.OperationSucceeded) {
1710 synchronized (mAsecMountSet) {
1711 if (mAsecMountSet.contains(id)) {
1712 mAsecMountSet.remove(id);
1713 }
1714 }
1715 }
1716
San Mehat4270e1e2010-01-29 05:32:19 -08001717 return rc;
San Mehat36972292010-01-06 11:06:32 -08001718 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001719
San Mehat4270e1e2010-01-29 05:32:19 -08001720 public int mountSecureContainer(String id, String key, int ownerUid) {
1721 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001722 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001723 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001724
San Mehata181b212010-02-11 06:50:20 -08001725 synchronized (mAsecMountSet) {
1726 if (mAsecMountSet.contains(id)) {
1727 return StorageResultCode.OperationFailedStorageMounted;
1728 }
1729 }
1730
San Mehatb1043402010-02-05 08:26:50 -08001731 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001732 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001733 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001734 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001735 int code = e.getCode();
1736 if (code != VoldResponseCode.OpFailedStorageBusy) {
1737 rc = StorageResultCode.OperationFailedInternalError;
1738 }
San Mehat02735bc2010-01-26 15:18:08 -08001739 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001740
1741 if (rc == StorageResultCode.OperationSucceeded) {
1742 synchronized (mAsecMountSet) {
1743 mAsecMountSet.add(id);
1744 }
1745 }
San Mehat4270e1e2010-01-29 05:32:19 -08001746 return rc;
San Mehat36972292010-01-06 11:06:32 -08001747 }
1748
San Mehatd9709982010-02-18 11:43:03 -08001749 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001750 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001751 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001752 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001753
San Mehat6cdd9c02010-02-09 14:45:20 -08001754 synchronized (mAsecMountSet) {
1755 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001756 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001757 }
1758 }
1759
Kenny Rootaa485402010-09-14 14:49:41 -07001760 /*
1761 * Force a GC to make sure AssetManagers in other threads of the
1762 * system_server are cleaned up. We have to do this since AssetManager
1763 * instances are kept as a WeakReference and it's possible we have files
1764 * open on the external storage.
1765 */
1766 Runtime.getRuntime().gc();
1767
San Mehatb1043402010-02-05 08:26:50 -08001768 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001769 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001770 final Command cmd = new Command("asec", "unmount", id);
1771 if (force) {
1772 cmd.appendArg("force");
1773 }
1774 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001775 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001776 int code = e.getCode();
1777 if (code == VoldResponseCode.OpFailedStorageBusy) {
1778 rc = StorageResultCode.OperationFailedStorageBusy;
1779 } else {
1780 rc = StorageResultCode.OperationFailedInternalError;
1781 }
San Mehat02735bc2010-01-26 15:18:08 -08001782 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001783
1784 if (rc == StorageResultCode.OperationSucceeded) {
1785 synchronized (mAsecMountSet) {
1786 mAsecMountSet.remove(id);
1787 }
1788 }
San Mehat4270e1e2010-01-29 05:32:19 -08001789 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001790 }
1791
San Mehat6cdd9c02010-02-09 14:45:20 -08001792 public boolean isSecureContainerMounted(String id) {
1793 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1794 waitForReady();
1795 warnOnNotMounted();
1796
1797 synchronized (mAsecMountSet) {
1798 return mAsecMountSet.contains(id);
1799 }
1800 }
1801
San Mehat4270e1e2010-01-29 05:32:19 -08001802 public int renameSecureContainer(String oldId, String newId) {
1803 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001804 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001805 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001806
San Mehata181b212010-02-11 06:50:20 -08001807 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001808 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001809 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001810 * changed while active, we must ensure both ids are not currently mounted.
1811 */
1812 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001813 return StorageResultCode.OperationFailedStorageMounted;
1814 }
1815 }
1816
San Mehatb1043402010-02-05 08:26:50 -08001817 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001818 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001819 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001820 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001821 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001822 }
San Mehata181b212010-02-11 06:50:20 -08001823
San Mehat4270e1e2010-01-29 05:32:19 -08001824 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001825 }
1826
San Mehat4270e1e2010-01-29 05:32:19 -08001827 public String getSecureContainerPath(String id) {
1828 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001829 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001830 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001831
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001832 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001833 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001834 event = mConnector.execute("asec", "path", id);
1835 event.checkCode(VoldResponseCode.AsecPathResult);
1836 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001837 } catch (NativeDaemonConnectorException e) {
1838 int code = e.getCode();
1839 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001840 Slog.i(TAG, String.format("Container '%s' not found", id));
1841 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001842 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001843 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001844 }
1845 }
San Mehat22dd86e2010-01-12 12:21:18 -08001846 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001847
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001848 public String getSecureContainerFilesystemPath(String id) {
1849 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1850 waitForReady();
1851 warnOnNotMounted();
1852
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001853 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001854 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001855 event = mConnector.execute("asec", "fspath", id);
1856 event.checkCode(VoldResponseCode.AsecPathResult);
1857 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001858 } catch (NativeDaemonConnectorException e) {
1859 int code = e.getCode();
1860 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1861 Slog.i(TAG, String.format("Container '%s' not found", id));
1862 return null;
1863 } else {
1864 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1865 }
1866 }
1867 }
1868
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001869 public void finishMediaUpdate() {
1870 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1871 }
Kenny Root02c87302010-07-01 08:10:18 -07001872
Kenny Roota02b8b02010-08-05 16:14:17 -07001873 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1874 if (callerUid == android.os.Process.SYSTEM_UID) {
1875 return true;
1876 }
1877
Kenny Root02c87302010-07-01 08:10:18 -07001878 if (packageName == null) {
1879 return false;
1880 }
1881
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001882 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001883
1884 if (DEBUG_OBB) {
1885 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1886 packageUid + ", callerUid = " + callerUid);
1887 }
1888
1889 return callerUid == packageUid;
1890 }
1891
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001892 public String getMountedObbPath(String rawPath) {
1893 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001894
Kenny Root02c87302010-07-01 08:10:18 -07001895 waitForReady();
1896 warnOnNotMounted();
1897
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001898 final ObbState state;
1899 synchronized (mObbPathToStateMap) {
1900 state = mObbPathToStateMap.get(rawPath);
1901 }
1902 if (state == null) {
1903 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1904 return null;
1905 }
1906
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001907 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001908 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001909 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001910 event.checkCode(VoldResponseCode.AsecPathResult);
1911 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001912 } catch (NativeDaemonConnectorException e) {
1913 int code = e.getCode();
1914 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001915 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001916 } else {
1917 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1918 }
1919 }
1920 }
1921
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001922 @Override
1923 public boolean isObbMounted(String rawPath) {
1924 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001925 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001926 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001927 }
Kenny Root02c87302010-07-01 08:10:18 -07001928 }
1929
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001930 @Override
1931 public void mountObb(
1932 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1933 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1934 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1935 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001936
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001937 final int callingUid = Binder.getCallingUid();
1938 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1939 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001940 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1941
1942 if (DEBUG_OBB)
1943 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001944 }
1945
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001946 @Override
1947 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1948 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1949
1950 final ObbState existingState;
1951 synchronized (mObbPathToStateMap) {
1952 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001953 }
1954
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001955 if (existingState != null) {
1956 // TODO: separate state object from request data
1957 final int callingUid = Binder.getCallingUid();
1958 final ObbState newState = new ObbState(
1959 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1960 final ObbAction action = new UnmountObbAction(newState, force);
1961 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001962
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001963 if (DEBUG_OBB)
1964 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1965 } else {
1966 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1967 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001968 }
1969
Ben Komalo444eca22011-09-01 15:17:44 -07001970 @Override
1971 public int getEncryptionState() {
1972 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1973 "no permission to access the crypt keeper");
1974
1975 waitForReady();
1976
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001977 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001978 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001979 event = mConnector.execute("cryptfs", "cryptocomplete");
1980 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001981 } catch (NumberFormatException e) {
1982 // Bad result - unexpected.
1983 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1984 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1985 } catch (NativeDaemonConnectorException e) {
1986 // Something bad happened.
1987 Slog.w(TAG, "Error in communicating with cryptfs in validating");
1988 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1989 }
1990 }
1991
1992 @Override
Jason parks5af0b912010-11-29 09:05:25 -06001993 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06001994 if (TextUtils.isEmpty(password)) {
1995 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06001996 }
1997
Jason parks8888c592011-01-20 22:46:41 -06001998 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1999 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002000
2001 waitForReady();
2002
2003 if (DEBUG_EVENTS) {
2004 Slog.i(TAG, "decrypting storage...");
2005 }
2006
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002007 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002008 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002009 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06002010
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002011 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002012 if (code == 0) {
2013 // Decrypt was successful. Post a delayed message before restarting in order
2014 // to let the UI to clear itself
2015 mHandler.postDelayed(new Runnable() {
2016 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002017 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002018 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002019 } catch (NativeDaemonConnectorException e) {
2020 Slog.e(TAG, "problem executing in background", e);
2021 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002022 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002023 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002024 }
2025
2026 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002027 } catch (NativeDaemonConnectorException e) {
2028 // Decryption failed
2029 return e.getCode();
2030 }
Jason parks5af0b912010-11-29 09:05:25 -06002031 }
2032
Jason parks56aa5322011-01-07 09:01:15 -06002033 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002034 if (TextUtils.isEmpty(password)) {
2035 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002036 }
2037
Jason parks8888c592011-01-20 22:46:41 -06002038 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2039 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002040
2041 waitForReady();
2042
2043 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002044 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002045 }
2046
2047 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002048 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002049 } catch (NativeDaemonConnectorException e) {
2050 // Encryption failed
2051 return e.getCode();
2052 }
2053
2054 return 0;
2055 }
2056
Jason parksf7b3cd42011-01-27 09:28:25 -06002057 public int changeEncryptionPassword(String password) {
2058 if (TextUtils.isEmpty(password)) {
2059 throw new IllegalArgumentException("password cannot be empty");
2060 }
2061
2062 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2063 "no permission to access the crypt keeper");
2064
2065 waitForReady();
2066
2067 if (DEBUG_EVENTS) {
2068 Slog.i(TAG, "changing encryption password...");
2069 }
2070
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002071 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002072 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002073 event = mConnector.execute("cryptfs", "changepw", password);
2074 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002075 } catch (NativeDaemonConnectorException e) {
2076 // Encryption failed
2077 return e.getCode();
2078 }
2079 }
2080
Christopher Tate32418be2011-10-10 13:51:12 -07002081 /**
2082 * Validate a user-supplied password string with cryptfs
2083 */
2084 @Override
2085 public int verifyEncryptionPassword(String password) throws RemoteException {
2086 // Only the system process is permitted to validate passwords
2087 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2088 throw new SecurityException("no permission to access the crypt keeper");
2089 }
2090
2091 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2092 "no permission to access the crypt keeper");
2093
2094 if (TextUtils.isEmpty(password)) {
2095 throw new IllegalArgumentException("password cannot be empty");
2096 }
2097
2098 waitForReady();
2099
2100 if (DEBUG_EVENTS) {
2101 Slog.i(TAG, "validating encryption password...");
2102 }
2103
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002104 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002105 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002106 event = mConnector.execute("cryptfs", "verifypw", password);
2107 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2108 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002109 } catch (NativeDaemonConnectorException e) {
2110 // Encryption failed
2111 return e.getCode();
2112 }
2113 }
2114
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002115 @Override
2116 public StorageVolume[] getVolumeList() {
2117 final int callingUserId = UserHandle.getCallingUserId();
2118 final boolean accessAll = (mContext.checkPermission(
2119 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2120 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2121
2122 synchronized (mVolumesLock) {
2123 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2124 for (StorageVolume volume : mVolumes) {
2125 final UserHandle owner = volume.getOwner();
2126 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2127 if (accessAll || ownerMatch) {
2128 filtered.add(volume);
2129 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002130 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002131 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002132 }
2133 }
2134
Kenny Rootaf9d6672010-10-08 09:21:39 -07002135 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2136 final IBinder binder = obbState.getBinder();
2137 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002138
Kenny Rootaf9d6672010-10-08 09:21:39 -07002139 if (obbStates == null) {
2140 obbStates = new ArrayList<ObbState>();
2141 mObbMounts.put(binder, obbStates);
2142 } else {
2143 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002144 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002145 throw new IllegalStateException("Attempt to add ObbState twice. "
2146 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002147 }
2148 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002149 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002150
2151 obbStates.add(obbState);
2152 try {
2153 obbState.link();
2154 } catch (RemoteException e) {
2155 /*
2156 * The binder died before we could link it, so clean up our state
2157 * and return failure.
2158 */
2159 obbStates.remove(obbState);
2160 if (obbStates.isEmpty()) {
2161 mObbMounts.remove(binder);
2162 }
2163
2164 // Rethrow the error so mountObb can get it
2165 throw e;
2166 }
2167
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002168 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002169 }
2170
Kenny Rootaf9d6672010-10-08 09:21:39 -07002171 private void removeObbStateLocked(ObbState obbState) {
2172 final IBinder binder = obbState.getBinder();
2173 final List<ObbState> obbStates = mObbMounts.get(binder);
2174 if (obbStates != null) {
2175 if (obbStates.remove(obbState)) {
2176 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002177 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002178 if (obbStates.isEmpty()) {
2179 mObbMounts.remove(binder);
2180 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002181 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002182
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002183 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002184 }
2185
Kenny Roota02b8b02010-08-05 16:14:17 -07002186 private class ObbActionHandler extends Handler {
2187 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002188 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002189
2190 ObbActionHandler(Looper l) {
2191 super(l);
2192 }
2193
2194 @Override
2195 public void handleMessage(Message msg) {
2196 switch (msg.what) {
2197 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002198 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002199
2200 if (DEBUG_OBB)
2201 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2202
2203 // If a bind was already initiated we don't really
2204 // need to do anything. The pending install
2205 // will be processed later on.
2206 if (!mBound) {
2207 // If this is the only one pending we might
2208 // have to bind to the service again.
2209 if (!connectToService()) {
2210 Slog.e(TAG, "Failed to bind to media container service");
2211 action.handleError();
2212 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002213 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002214 }
Kenny Root735de3b2010-09-30 14:11:39 -07002215
Kenny Root735de3b2010-09-30 14:11:39 -07002216 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002217 break;
2218 }
2219 case OBB_MCS_BOUND: {
2220 if (DEBUG_OBB)
2221 Slog.i(TAG, "OBB_MCS_BOUND");
2222 if (msg.obj != null) {
2223 mContainerService = (IMediaContainerService) msg.obj;
2224 }
2225 if (mContainerService == null) {
2226 // Something seriously wrong. Bail out
2227 Slog.e(TAG, "Cannot bind to media container service");
2228 for (ObbAction action : mActions) {
2229 // Indicate service bind error
2230 action.handleError();
2231 }
2232 mActions.clear();
2233 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002234 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002235 if (action != null) {
2236 action.execute(this);
2237 }
2238 } else {
2239 // Should never happen ideally.
2240 Slog.w(TAG, "Empty queue");
2241 }
2242 break;
2243 }
2244 case OBB_MCS_RECONNECT: {
2245 if (DEBUG_OBB)
2246 Slog.i(TAG, "OBB_MCS_RECONNECT");
2247 if (mActions.size() > 0) {
2248 if (mBound) {
2249 disconnectService();
2250 }
2251 if (!connectToService()) {
2252 Slog.e(TAG, "Failed to bind to media container service");
2253 for (ObbAction action : mActions) {
2254 // Indicate service bind error
2255 action.handleError();
2256 }
2257 mActions.clear();
2258 }
2259 }
2260 break;
2261 }
2262 case OBB_MCS_UNBIND: {
2263 if (DEBUG_OBB)
2264 Slog.i(TAG, "OBB_MCS_UNBIND");
2265
2266 // Delete pending install
2267 if (mActions.size() > 0) {
2268 mActions.remove(0);
2269 }
2270 if (mActions.size() == 0) {
2271 if (mBound) {
2272 disconnectService();
2273 }
2274 } else {
2275 // There are more pending requests in queue.
2276 // Just post MCS_BOUND message to trigger processing
2277 // of next pending install.
2278 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2279 }
2280 break;
2281 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002282 case OBB_FLUSH_MOUNT_STATE: {
2283 final String path = (String) msg.obj;
2284
2285 if (DEBUG_OBB)
2286 Slog.i(TAG, "Flushing all OBB state for path " + path);
2287
2288 synchronized (mObbMounts) {
2289 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2290
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002291 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002292 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002293 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002294
2295 /*
2296 * If this entry's source file is in the volume path
2297 * that got unmounted, remove it because it's no
2298 * longer valid.
2299 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002300 if (state.canonicalPath.startsWith(path)) {
2301 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002302 }
2303 }
2304
2305 for (final ObbState obbState : obbStatesToRemove) {
2306 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002307 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002308
2309 removeObbStateLocked(obbState);
2310
2311 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002312 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002313 OnObbStateChangeListener.UNMOUNTED);
2314 } catch (RemoteException e) {
2315 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002316 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002317 }
2318 }
2319 }
2320 break;
2321 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002322 }
2323 }
2324
2325 private boolean connectToService() {
2326 if (DEBUG_OBB)
2327 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2328
2329 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2330 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2331 mBound = true;
2332 return true;
2333 }
2334 return false;
2335 }
2336
2337 private void disconnectService() {
2338 mContainerService = null;
2339 mBound = false;
2340 mContext.unbindService(mDefContainerConn);
2341 }
2342 }
2343
2344 abstract class ObbAction {
2345 private static final int MAX_RETRIES = 3;
2346 private int mRetries;
2347
2348 ObbState mObbState;
2349
2350 ObbAction(ObbState obbState) {
2351 mObbState = obbState;
2352 }
2353
2354 public void execute(ObbActionHandler handler) {
2355 try {
2356 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002357 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002358 mRetries++;
2359 if (mRetries > MAX_RETRIES) {
2360 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002361 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002362 handleError();
2363 return;
2364 } else {
2365 handleExecute();
2366 if (DEBUG_OBB)
2367 Slog.i(TAG, "Posting install MCS_UNBIND");
2368 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2369 }
2370 } catch (RemoteException e) {
2371 if (DEBUG_OBB)
2372 Slog.i(TAG, "Posting install MCS_RECONNECT");
2373 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2374 } catch (Exception e) {
2375 if (DEBUG_OBB)
2376 Slog.d(TAG, "Error handling OBB action", e);
2377 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002378 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002379 }
2380 }
2381
Kenny Root05105f72010-09-22 17:29:43 -07002382 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002383 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002384
2385 protected ObbInfo getObbInfo() throws IOException {
2386 ObbInfo obbInfo;
2387 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002388 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002389 } catch (RemoteException e) {
2390 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002391 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002392 obbInfo = null;
2393 }
2394 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002396 }
2397 return obbInfo;
2398 }
2399
Kenny Rootaf9d6672010-10-08 09:21:39 -07002400 protected void sendNewStatusOrIgnore(int status) {
2401 if (mObbState == null || mObbState.token == null) {
2402 return;
2403 }
2404
Kenny Root38cf8862010-09-26 14:18:51 -07002405 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002406 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002407 } catch (RemoteException e) {
2408 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2409 }
2410 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002411 }
2412
2413 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002414 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002415 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002416
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002417 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002418 super(obbState);
2419 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002420 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002421 }
2422
Jason parks5af0b912010-11-29 09:05:25 -06002423 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002424 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002425 waitForReady();
2426 warnOnNotMounted();
2427
Kenny Root38cf8862010-09-26 14:18:51 -07002428 final ObbInfo obbInfo = getObbInfo();
2429
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002430 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002431 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2432 + " which is owned by " + obbInfo.packageName);
2433 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2434 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002435 }
2436
Kenny Rootaf9d6672010-10-08 09:21:39 -07002437 final boolean isMounted;
2438 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002439 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002440 }
2441 if (isMounted) {
2442 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2443 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2444 return;
2445 }
2446
Kenny Rootaf9d6672010-10-08 09:21:39 -07002447 final String hashedKey;
2448 if (mKey == null) {
2449 hashedKey = "none";
2450 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002451 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002452 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2453
2454 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2455 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2456 SecretKey key = factory.generateSecret(ks);
2457 BigInteger bi = new BigInteger(key.getEncoded());
2458 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002459 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002460 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2461 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2462 return;
2463 } catch (InvalidKeySpecException e) {
2464 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2465 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002466 return;
2467 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002468 }
Kenny Root38cf8862010-09-26 14:18:51 -07002469
Kenny Rootaf9d6672010-10-08 09:21:39 -07002470 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002471 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002472 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002473 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002474 } catch (NativeDaemonConnectorException e) {
2475 int code = e.getCode();
2476 if (code != VoldResponseCode.OpFailedStorageBusy) {
2477 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002478 }
2479 }
2480
Kenny Rootaf9d6672010-10-08 09:21:39 -07002481 if (rc == StorageResultCode.OperationSucceeded) {
2482 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002483 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002484
2485 synchronized (mObbMounts) {
2486 addObbStateLocked(mObbState);
2487 }
2488
2489 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002490 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002491 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002492
Kenny Rootaf9d6672010-10-08 09:21:39 -07002493 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002494 }
2495 }
2496
Jason parks5af0b912010-11-29 09:05:25 -06002497 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002498 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002499 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002500 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002501
2502 @Override
2503 public String toString() {
2504 StringBuilder sb = new StringBuilder();
2505 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002506 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002507 sb.append('}');
2508 return sb.toString();
2509 }
2510 }
2511
2512 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002513 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002514
2515 UnmountObbAction(ObbState obbState, boolean force) {
2516 super(obbState);
2517 mForceUnmount = force;
2518 }
2519
Jason parks5af0b912010-11-29 09:05:25 -06002520 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002521 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002522 waitForReady();
2523 warnOnNotMounted();
2524
Kenny Root38cf8862010-09-26 14:18:51 -07002525 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002526
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002527 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002528 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002529 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002530 }
Kenny Root38cf8862010-09-26 14:18:51 -07002531
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002532 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002533 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2534 return;
2535 }
2536
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002537 if (existingState.ownerGid != mObbState.ownerGid) {
2538 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2539 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002540 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2541 return;
2542 }
2543
Kenny Rootaf9d6672010-10-08 09:21:39 -07002544 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002545 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002546 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002547 if (mForceUnmount) {
2548 cmd.appendArg("force");
2549 }
2550 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002551 } catch (NativeDaemonConnectorException e) {
2552 int code = e.getCode();
2553 if (code == VoldResponseCode.OpFailedStorageBusy) {
2554 rc = StorageResultCode.OperationFailedStorageBusy;
2555 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2556 // If it's not mounted then we've already won.
2557 rc = StorageResultCode.OperationSucceeded;
2558 } else {
2559 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002560 }
2561 }
2562
Kenny Rootaf9d6672010-10-08 09:21:39 -07002563 if (rc == StorageResultCode.OperationSucceeded) {
2564 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002565 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002566 }
2567
Kenny Rootaf9d6672010-10-08 09:21:39 -07002568 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002569 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002570 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002571 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002572 }
2573 }
2574
Jason parks5af0b912010-11-29 09:05:25 -06002575 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002576 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002577 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002578 }
2579
2580 @Override
2581 public String toString() {
2582 StringBuilder sb = new StringBuilder();
2583 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002584 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002585 sb.append(",force=");
2586 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002587 sb.append('}');
2588 return sb.toString();
2589 }
Kenny Root02c87302010-07-01 08:10:18 -07002590 }
Kenny Root38cf8862010-09-26 14:18:51 -07002591
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002592 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002593 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2594 // TODO: allow caller to provide Environment for full testing
2595
2596 // Only adjust paths when storage is emulated
2597 if (!Environment.isExternalStorageEmulated()) {
2598 return canonicalPath;
2599 }
2600
2601 String path = canonicalPath.toString();
2602
2603 // First trim off any external storage prefix
2604 final UserEnvironment userEnv = new UserEnvironment(userId);
2605
2606 // /storage/emulated/0
2607 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2608 // /storage/emulated_legacy
2609 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2610 .toString();
2611
2612 if (path.startsWith(externalPath)) {
2613 path = path.substring(externalPath.length() + 1);
2614 } else if (path.startsWith(legacyExternalPath)) {
2615 path = path.substring(legacyExternalPath.length() + 1);
2616 } else {
2617 return canonicalPath;
2618 }
2619
2620 // Handle special OBB paths on emulated storage
2621 final String obbPath = "Android/obb";
2622 if (path.startsWith(obbPath)) {
2623 path = path.substring(obbPath.length() + 1);
2624
2625 if (forVold) {
2626 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2627 } else {
2628 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2629 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2630 }
2631 }
2632
2633 // Handle normal external storage paths
2634 if (forVold) {
2635 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2636 } else {
2637 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2638 }
2639 }
2640
Kenny Root38cf8862010-09-26 14:18:51 -07002641 @Override
2642 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2643 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2644 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2645 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2646 + " without permission " + android.Manifest.permission.DUMP);
2647 return;
2648 }
2649
Kenny Root38cf8862010-09-26 14:18:51 -07002650 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002651 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002652
Kenny Rootaf9d6672010-10-08 09:21:39 -07002653 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2654 while (binders.hasNext()) {
2655 Entry<IBinder, List<ObbState>> e = binders.next();
2656 pw.print(" Key="); pw.println(e.getKey().toString());
2657 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002658 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002659 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002660 }
2661 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002662
2663 pw.println("");
2664 pw.println(" mObbPathToStateMap:");
2665 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2666 while (maps.hasNext()) {
2667 final Entry<String, ObbState> e = maps.next();
2668 pw.print(" "); pw.print(e.getKey());
2669 pw.print(" -> "); pw.println(e.getValue().toString());
2670 }
Kenny Root38cf8862010-09-26 14:18:51 -07002671 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002672
2673 pw.println("");
2674
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002675 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002676 pw.println(" mVolumes:");
2677
2678 final int N = mVolumes.size();
2679 for (int i = 0; i < N; i++) {
2680 final StorageVolume v = mVolumes.get(i);
2681 pw.print(" ");
2682 pw.println(v.toString());
2683 }
2684 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002685
2686 pw.println();
2687 pw.println(" mConnection:");
2688 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002691 /** {@inheritDoc} */
2692 public void monitor() {
2693 if (mConnector != null) {
2694 mConnector.monitor();
2695 }
2696 }
2697}