blob: 7857d6c236848be34acf80bd45e7f98a489f1b49 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070023import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070027import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070029import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070030import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070034import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070036import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070037import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070038import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080039import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070040import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070041import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040042import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080043import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080044import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080045import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070046import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070048import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070049import android.os.storage.IMountService;
50import android.os.storage.IMountServiceListener;
51import android.os.storage.IMountShutdownObserver;
52import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070053import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070054import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070055import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060056import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070057import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070058import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070059import android.util.Xml;
60
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080061import com.android.internal.annotations.GuardedBy;
62import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070063import com.android.internal.app.IMediaContainerService;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070064import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070065import com.android.internal.util.XmlUtils;
66import com.android.server.NativeDaemonConnector.Command;
67import com.android.server.am.ActivityManagerService;
68import com.android.server.pm.PackageManagerService;
69import com.android.server.pm.UserManagerService;
70import com.google.android.collect.Lists;
71import com.google.android.collect.Maps;
72
Mike Lockwood2f6a3882011-05-09 19:08:06 -070073import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070074
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070075import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070076import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070077import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070078import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070079import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070080import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070081import java.security.spec.InvalidKeySpecException;
82import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080083import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070084import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080085import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070086import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070087import java.util.LinkedList;
88import java.util.List;
89import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070090import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070091import java.util.concurrent.CountDownLatch;
92import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Kenny Root3b1abba2010-10-13 15:00:07 -070094import javax.crypto.SecretKey;
95import javax.crypto.SecretKeyFactory;
96import javax.crypto.spec.PBEKeySpec;
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098/**
San Mehatb1043402010-02-05 08:26:50 -080099 * MountService implements back-end services for platform storage
100 * management.
101 * @hide - Applications should use android.os.storage.StorageManager
102 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700104class MountService extends IMountService.Stub
105 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600106
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700107 // TODO: listen for user creation/deletion
108
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800109 private static final boolean LOCAL_LOGD = false;
110 private static final boolean DEBUG_UNMOUNT = false;
111 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800112 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700113
Kenny Root07714d42011-08-17 17:49:28 -0700114 // Disable this since it messes up long-running cryptfs operations.
115 private static final boolean WATCHDOG_ENABLE = false;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private static final String TAG = "MountService";
118
Kenny Root305bcbf2010-09-03 07:56:38 -0700119 private static final String VOLD_TAG = "VoldConnector";
120
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700121 /** Maximum number of ASEC containers allowed to be mounted. */
122 private static final int MAX_CONTAINERS = 250;
123
San Mehat4270e1e2010-01-29 05:32:19 -0800124 /*
125 * Internal vold volume state constants
126 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800127 class VolumeState {
128 public static final int Init = -1;
129 public static final int NoMedia = 0;
130 public static final int Idle = 1;
131 public static final int Pending = 2;
132 public static final int Checking = 3;
133 public static final int Mounted = 4;
134 public static final int Unmounting = 5;
135 public static final int Formatting = 6;
136 public static final int Shared = 7;
137 public static final int SharedMnt = 8;
138 }
139
San Mehat4270e1e2010-01-29 05:32:19 -0800140 /*
141 * Internal vold response code constants
142 */
San Mehat22dd86e2010-01-12 12:21:18 -0800143 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800144 /*
145 * 100 series - Requestion action was initiated; expect another reply
146 * before proceeding with a new command.
147 */
San Mehat22dd86e2010-01-12 12:21:18 -0800148 public static final int VolumeListResult = 110;
149 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800150 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800151
San Mehat4270e1e2010-01-29 05:32:19 -0800152 /*
153 * 200 series - Requestion action has been successfully completed.
154 */
155 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800156 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800157 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800158
San Mehat4270e1e2010-01-29 05:32:19 -0800159 /*
160 * 400 series - Command was accepted, but the requested action
161 * did not take place.
162 */
163 public static final int OpFailedNoMedia = 401;
164 public static final int OpFailedMediaBlank = 402;
165 public static final int OpFailedMediaCorrupt = 403;
166 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800167 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700168 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800169
170 /*
171 * 600 series - Unsolicited broadcasts.
172 */
San Mehat22dd86e2010-01-12 12:21:18 -0800173 public static final int VolumeStateChange = 605;
San Mehat22dd86e2010-01-12 12:21:18 -0800174 public static final int VolumeDiskInserted = 630;
175 public static final int VolumeDiskRemoved = 631;
176 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700177
178 /*
179 * 700 series - fstrim
180 */
181 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800182 }
183
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700184 private Context mContext;
185 private NativeDaemonConnector mConnector;
186
187 private final Object mVolumesLock = new Object();
188
189 /** When defined, base template for user-specific {@link StorageVolume}. */
190 private StorageVolume mEmulatedTemplate;
191
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700193 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
194 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800195 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700196 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
197 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800198 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700199 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
200
201 private volatile boolean mSystemReady = false;
202
San Mehat4270e1e2010-01-29 05:32:19 -0800203 private PackageManagerService mPms;
204 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700205 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800206 // Used as a lock for methods that register/unregister listeners.
207 final private ArrayList<MountServiceBinderListener> mListeners =
208 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800209 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
210 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800211 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800212
San Mehat6cdd9c02010-02-09 14:45:20 -0800213 /**
214 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800215 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800216 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800217 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800218
Kenny Root02c87302010-07-01 08:10:18 -0700219 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700220 * The size of the crypto algorithm key in bits for OBB files. Currently
221 * Twofish is used which takes 128-bit keys.
222 */
223 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
224
225 /**
226 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
227 * 1024 is reasonably secure and not too slow.
228 */
229 private static final int PBKDF2_HASH_ROUNDS = 1024;
230
231 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700232 * Mounted OBB tracking information. Used to track the current state of all
233 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700234 */
Kenny Root735de3b2010-09-30 14:11:39 -0700235 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700236
237 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700238 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
239
240 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700241 public ObbState(String rawPath, String canonicalPath, int callingUid,
242 IObbActionListener token, int nonce) {
243 this.rawPath = rawPath;
244 this.canonicalPath = canonicalPath.toString();
245
246 final int userId = UserHandle.getUserId(callingUid);
247 this.ownerPath = buildObbPath(canonicalPath, userId, false);
248 this.voldPath = buildObbPath(canonicalPath, userId, true);
249
250 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700251 this.token = token;
252 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700253 }
254
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700255 final String rawPath;
256 final String canonicalPath;
257 final String ownerPath;
258 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700259
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700260 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700261
Kenny Rootaf9d6672010-10-08 09:21:39 -0700262 // Token of remote Binder caller
263 final IObbActionListener token;
264
265 // Identifier to pass back to the token
266 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700267
Kenny Root735de3b2010-09-30 14:11:39 -0700268 public IBinder getBinder() {
269 return token.asBinder();
270 }
271
Kenny Roota02b8b02010-08-05 16:14:17 -0700272 @Override
273 public void binderDied() {
274 ObbAction action = new UnmountObbAction(this, true);
275 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700276 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700277
Kenny Root5919ac62010-10-05 09:49:40 -0700278 public void link() throws RemoteException {
279 getBinder().linkToDeath(this, 0);
280 }
281
282 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700283 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700284 }
Kenny Root38cf8862010-09-26 14:18:51 -0700285
286 @Override
287 public String toString() {
288 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700289 sb.append("rawPath=").append(rawPath);
290 sb.append(",canonicalPath=").append(canonicalPath);
291 sb.append(",ownerPath=").append(ownerPath);
292 sb.append(",voldPath=").append(voldPath);
293 sb.append(",ownerGid=").append(ownerGid);
294 sb.append(",token=").append(token);
295 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700296 sb.append('}');
297 return sb.toString();
298 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700299 }
300
301 // OBB Action Handler
302 final private ObbActionHandler mObbActionHandler;
303
304 // OBB action handler messages
305 private static final int OBB_RUN_ACTION = 1;
306 private static final int OBB_MCS_BOUND = 2;
307 private static final int OBB_MCS_UNBIND = 3;
308 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700309 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700310
311 /*
312 * Default Container Service information
313 */
314 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
315 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
316
317 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
318
319 class DefaultContainerConnection implements ServiceConnection {
320 public void onServiceConnected(ComponentName name, IBinder service) {
321 if (DEBUG_OBB)
322 Slog.i(TAG, "onServiceConnected");
323 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
324 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
325 }
326
327 public void onServiceDisconnected(ComponentName name) {
328 if (DEBUG_OBB)
329 Slog.i(TAG, "onServiceDisconnected");
330 }
331 };
332
333 // Used in the ObbActionHandler
334 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700335
336 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800337 private static final int H_UNMOUNT_PM_UPDATE = 1;
338 private static final int H_UNMOUNT_PM_DONE = 2;
339 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700340 private static final int H_SYSTEM_READY = 4;
341
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800342 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
343 private static final int MAX_UNMOUNT_RETRIES = 4;
344
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800345 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700346 final String path;
347 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700348 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800350
Ben Komalo13c71972011-09-07 16:35:56 -0700351 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800352 retries = 0;
353 this.path = path;
354 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700355 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800356 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800357
358 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700359 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700360 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800361 }
362 }
363
364 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700365 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800366
367 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700368 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800369 this.method = method;
370 }
371
372 @Override
373 void handleFinished() {
374 super.handleFinished();
375 doShareUnshareVolume(path, method, true);
376 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800377 }
378
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800379 class ShutdownCallBack extends UnmountCallBack {
380 IMountShutdownObserver observer;
381 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700382 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800383 this.observer = observer;
384 }
385
386 @Override
387 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700388 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800389 if (observer != null) {
390 try {
391 observer.onShutDownComplete(ret);
392 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700393 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800394 }
395 }
396 }
397 }
398
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400399 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800400 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700401 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800402
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400403 MountServiceHandler(Looper l) {
404 super(l);
405 }
406
Jason parks5af0b912010-11-29 09:05:25 -0600407 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800408 public void handleMessage(Message msg) {
409 switch (msg.what) {
410 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700411 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800412 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
413 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700414 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800415 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700416 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700417 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700418 mUpdatingStatus = true;
419 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800420 }
421 break;
422 }
423 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700424 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700425 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700426 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800427 int size = mForceUnmounts.size();
428 int sizeArr[] = new int[size];
429 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700430 // Kill processes holding references first
431 ActivityManagerService ams = (ActivityManagerService)
432 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800433 for (int i = 0; i < size; i++) {
434 UnmountCallBack ucb = mForceUnmounts.get(i);
435 String path = ucb.path;
436 boolean done = false;
437 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800438 done = true;
439 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800440 int pids[] = getStorageUsers(path);
441 if (pids == null || pids.length == 0) {
442 done = true;
443 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800444 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800445 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700446 // Confirm if file references have been freed.
447 pids = getStorageUsers(path);
448 if (pids == null || pids.length == 0) {
449 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800450 }
451 }
452 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700453 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
454 // Retry again
455 Slog.i(TAG, "Retrying to kill storage users again");
456 mHandler.sendMessageDelayed(
457 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
458 ucb.retries++),
459 RETRY_UNMOUNT_DELAY);
460 } else {
461 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
462 Slog.i(TAG, "Failed to unmount media inspite of " +
463 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
464 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800465 sizeArr[sizeArrN++] = i;
466 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
467 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800468 }
469 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800470 // Remove already processed elements from list.
471 for (int i = (sizeArrN-1); i >= 0; i--) {
472 mForceUnmounts.remove(sizeArr[i]);
473 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800474 break;
475 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700476 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700477 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800478 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800479 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800480 break;
481 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700482 case H_SYSTEM_READY: {
483 try {
484 handleSystemReady();
485 } catch (Exception ex) {
486 Slog.e(TAG, "Boot-time mount exception", ex);
487 }
488 break;
489 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800490 }
491 }
492 };
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700493
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700494 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800495
Kenny Root51a573c2012-05-17 13:30:28 -0700496 void waitForAsecScan() {
497 waitForLatch(mAsecsScanned);
498 }
499
San Mehat207e5382010-02-04 20:46:54 -0800500 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700501 waitForLatch(mConnectedSignal);
502 }
503
504 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700505 for (;;) {
506 try {
507 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800508 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700509 } else {
510 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
511 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800512 }
Kenny Root51a573c2012-05-17 13:30:28 -0700513 } catch (InterruptedException e) {
514 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800515 }
San Mehat207e5382010-02-04 20:46:54 -0800516 }
San Mehat1f6301e2010-01-07 22:40:27 -0800517 }
Kenny Root02c87302010-07-01 08:10:18 -0700518
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700519 private void handleSystemReady() {
520 // Snapshot current volume states since it's not safe to call into vold
521 // while holding locks.
522 final HashMap<String, String> snapshot;
523 synchronized (mVolumesLock) {
524 snapshot = new HashMap<String, String>(mVolumeStates);
525 }
526
527 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
528 final String path = entry.getKey();
529 final String state = entry.getValue();
530
531 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
532 int rc = doMountVolume(path);
533 if (rc != StorageResultCode.OperationSucceeded) {
534 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
535 rc));
536 }
537 } else if (state.equals(Environment.MEDIA_SHARED)) {
538 /*
539 * Bootstrap UMS enabled state since vold indicates
540 * the volume is shared (runtime restart while ums enabled)
541 */
542 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
543 VolumeState.Shared);
544 }
545 }
546
547 // Push mounted state for all emulated storage
548 synchronized (mVolumesLock) {
549 for (StorageVolume volume : mVolumes) {
550 if (volume.isEmulated()) {
551 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
552 }
553 }
554 }
555
556 /*
557 * If UMS was connected on boot, send the connected event
558 * now that we're up.
559 */
560 if (mSendUmsConnectedOnBoot) {
561 sendUmsIntent(true);
562 mSendUmsConnectedOnBoot = false;
563 }
564 }
565
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700566 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
567 @Override
568 public void onReceive(Context context, Intent intent) {
569 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
570 if (userId == -1) return;
571 final UserHandle user = new UserHandle(userId);
572
573 final String action = intent.getAction();
574 if (Intent.ACTION_USER_ADDED.equals(action)) {
575 synchronized (mVolumesLock) {
576 createEmulatedVolumeForUserLocked(user);
577 }
578
579 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
580 synchronized (mVolumesLock) {
581 final List<StorageVolume> toRemove = Lists.newArrayList();
582 for (StorageVolume volume : mVolumes) {
583 if (user.equals(volume.getOwner())) {
584 toRemove.add(volume);
585 }
586 }
587 for (StorageVolume volume : toRemove) {
588 removeVolumeLocked(volume);
589 }
590 }
591 }
592 }
593 };
594
595 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
596 @Override
597 public void onReceive(Context context, Intent intent) {
598 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
599 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
600 notifyShareAvailabilityChange(available);
601 }
602 };
603
Svetoslava7452ee2013-03-20 12:06:59 -0700604 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
605 @Override
606 public void onReceive(Context context, Intent intent) {
607 waitForReady();
608 String action = intent.getAction();
609 // Since fstrim will be run on a daily basis we do not expect
610 // fstrim to be too long, so it is not interruptible. We will
611 // implement interruption only in case we see issues.
612 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
613 try {
614 // This method runs on the handler thread,
615 // so it is safe to directly call into vold.
616 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700617 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700618 } catch (NativeDaemonConnectorException ndce) {
619 Slog.e(TAG, "Failed to run fstrim!");
620 }
621 }
622 }
623 };
624
San Mehat4270e1e2010-01-29 05:32:19 -0800625 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
626 final IMountServiceListener mListener;
627
628 MountServiceBinderListener(IMountServiceListener listener) {
629 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700630
San Mehat91c77612010-01-07 10:39:41 -0800631 }
632
San Mehat4270e1e2010-01-29 05:32:19 -0800633 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700634 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700635 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800636 mListeners.remove(this);
637 mListener.asBinder().unlinkToDeath(this, 0);
638 }
639 }
640 }
641
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800642 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800643 // TODO: Add support for multiple share methods
644 if (!method.equals("ums")) {
645 throw new IllegalArgumentException(String.format("Method %s not supported", method));
646 }
647
San Mehat4270e1e2010-01-29 05:32:19 -0800648 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800649 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800650 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700651 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800652 }
San Mehat4270e1e2010-01-29 05:32:19 -0800653 }
654
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700655 private void updatePublicVolumeState(StorageVolume volume, String state) {
656 final String path = volume.getPath();
657 final String oldState;
658 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400659 oldState = mVolumeStates.put(path, state);
660 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700661
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400662 if (state.equals(oldState)) {
663 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
664 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800665 return;
666 }
San Mehatb1043402010-02-05 08:26:50 -0800667
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400668 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700669
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700670 // Tell PackageManager about changes to primary volume state, but only
671 // when not emulated.
672 if (volume.isPrimary() && !volume.isEmulated()) {
673 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
674 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400675
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700676 /*
677 * Some OBBs might have been unmounted when this volume was
678 * unmounted, so send a message to the handler to let it know to
679 * remove those from the list of mounted OBBS.
680 */
681 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
682 OBB_FLUSH_MOUNT_STATE, path));
683 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
684 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400685 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800686 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700687
San Mehat4270e1e2010-01-29 05:32:19 -0800688 synchronized (mListeners) {
689 for (int i = mListeners.size() -1; i >= 0; i--) {
690 MountServiceBinderListener bl = mListeners.get(i);
691 try {
San Mehatb1043402010-02-05 08:26:50 -0800692 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800693 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700694 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800695 mListeners.remove(i);
696 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700697 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800698 }
699 }
700 }
701 }
702
703 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800704 * Callback from NativeDaemonConnector
705 */
706 public void onDaemonConnected() {
707 /*
708 * Since we'll be calling back into the NativeDaemonConnector,
709 * we need to do our work in a new thread.
710 */
Kenny Root51a573c2012-05-17 13:30:28 -0700711 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600712 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800713 public void run() {
714 /**
715 * Determine media state and UMS detection status
716 */
San Mehat4270e1e2010-01-29 05:32:19 -0800717 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800718 final String[] vols = NativeDaemonEvent.filterMessageList(
719 mConnector.executeForList("volume", "list"),
720 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800721 for (String volstr : vols) {
722 String[] tok = volstr.split(" ");
723 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400724 String path = tok[1];
725 String state = Environment.MEDIA_REMOVED;
726
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700727 final StorageVolume volume;
728 synchronized (mVolumesLock) {
729 volume = mVolumesByPath.get(path);
730 }
731
San Mehat4270e1e2010-01-29 05:32:19 -0800732 int st = Integer.parseInt(tok[2]);
733 if (st == VolumeState.NoMedia) {
734 state = Environment.MEDIA_REMOVED;
735 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800736 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800737 } else if (st == VolumeState.Mounted) {
738 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700739 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800740 } else if (st == VolumeState.Shared) {
741 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700742 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800743 } else {
744 throw new Exception(String.format("Unexpected state %d", st));
745 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400746
747 if (state != null) {
748 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700749 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400750 }
San Mehat4270e1e2010-01-29 05:32:19 -0800751 }
752 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700753 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700754 final StorageVolume primary = getPrimaryPhysicalVolume();
755 if (primary != null) {
756 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
757 }
San Mehat4270e1e2010-01-29 05:32:19 -0800758 }
759
San Mehat207e5382010-02-04 20:46:54 -0800760 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600761 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800762 * the hounds!
763 */
Kenny Root51a573c2012-05-17 13:30:28 -0700764 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700765
766 // Let package manager load internal ASECs.
767 mPms.scanAvailableAsecs();
768
769 // Notify people waiting for ASECs to be scanned that it's done.
770 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800771 }
772 }.start();
773 }
774
775 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800776 * Callback from NativeDaemonConnector
777 */
778 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800779 if (DEBUG_EVENTS) {
780 StringBuilder builder = new StringBuilder();
781 builder.append("onEvent::");
782 builder.append(" raw= " + raw);
783 if (cooked != null) {
784 builder.append(" cooked = " );
785 for (String str : cooked) {
786 builder.append(" " + str);
787 }
788 }
San Mehata5078592010-03-25 09:36:54 -0700789 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800790 }
San Mehat4270e1e2010-01-29 05:32:19 -0800791 if (code == VoldResponseCode.VolumeStateChange) {
792 /*
793 * One of the volumes we're managing has changed state.
794 * Format: "NNN Volume <label> <path> state changed
795 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
796 */
797 notifyVolumeStateChange(
798 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
799 Integer.parseInt(cooked[10]));
San Mehat4270e1e2010-01-29 05:32:19 -0800800 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
801 (code == VoldResponseCode.VolumeDiskRemoved) ||
802 (code == VoldResponseCode.VolumeBadRemoval)) {
803 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
804 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
805 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400806 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800807 final String label = cooked[2];
808 final String path = cooked[3];
809 int major = -1;
810 int minor = -1;
811
812 try {
813 String devComp = cooked[6].substring(1, cooked[6].length() -1);
814 String[] devTok = devComp.split(":");
815 major = Integer.parseInt(devTok[0]);
816 minor = Integer.parseInt(devTok[1]);
817 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700818 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800819 }
820
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700821 final StorageVolume volume;
822 final String state;
823 synchronized (mVolumesLock) {
824 volume = mVolumesByPath.get(path);
825 state = mVolumeStates.get(path);
826 }
827
San Mehat4270e1e2010-01-29 05:32:19 -0800828 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700829 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600830 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800831 public void run() {
832 try {
833 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800834 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700835 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800836 }
837 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700838 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800839 }
840 }
841 }.start();
842 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
843 /*
844 * This event gets trumped if we're already in BAD_REMOVAL state
845 */
846 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
847 return true;
848 }
849 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700850 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700851 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
852 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800853
San Mehata5078592010-03-25 09:36:54 -0700854 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700855 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400856 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800857 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700858 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800859 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700860 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400861 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800862
San Mehata5078592010-03-25 09:36:54 -0700863 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700864 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400865 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700866 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700867 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800868 } else {
San Mehata5078592010-03-25 09:36:54 -0700869 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800870 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400871
872 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700873 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400874 }
San Mehat4270e1e2010-01-29 05:32:19 -0800875 } else {
876 return false;
877 }
878
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400879 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800880 }
881
San Mehat207e5382010-02-04 20:46:54 -0800882 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700883 final StorageVolume volume;
884 final String state;
885 synchronized (mVolumesLock) {
886 volume = mVolumesByPath.get(path);
887 state = getVolumeState(path);
888 }
889
890 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800891
Mike Lockwooda5250c92011-05-23 13:44:04 -0400892 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800893
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500894 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700895 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700896 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500897 }
898
San Mehat4270e1e2010-01-29 05:32:19 -0800899 if (newState == VolumeState.Init) {
900 } else if (newState == VolumeState.NoMedia) {
901 // NoMedia is handled via Disk Remove events
902 } else if (newState == VolumeState.Idle) {
903 /*
904 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
905 * if we're in the process of enabling UMS
906 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700907 if (!state.equals(
908 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
909 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800910 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700911 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700912 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400913 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800914 }
915 } else if (newState == VolumeState.Pending) {
916 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700917 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700918 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400919 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800920 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700921 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700922 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400923 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800924 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400925 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800926 } else if (newState == VolumeState.Formatting) {
927 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700928 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800929 /* Send the media unmounted event first */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700930 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
931 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800932
San Mehata5078592010-03-25 09:36:54 -0700933 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700934 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400935 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700936 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800937 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700938 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800939 return;
940 } else {
San Mehata5078592010-03-25 09:36:54 -0700941 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800942 }
943
Mike Lockwooda5250c92011-05-23 13:44:04 -0400944 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700945 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800946 }
947 }
948
San Mehat207e5382010-02-04 20:46:54 -0800949 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800950 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800951
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700952 final StorageVolume volume;
953 synchronized (mVolumesLock) {
954 volume = mVolumesByPath.get(path);
955 }
956
San Mehata5078592010-03-25 09:36:54 -0700957 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800958 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800959 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800960 } catch (NativeDaemonConnectorException e) {
961 /*
962 * Mount failed for some reason
963 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400964 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800965 int code = e.getCode();
966 if (code == VoldResponseCode.OpFailedNoMedia) {
967 /*
968 * Attempt to mount but no media inserted
969 */
San Mehatb1043402010-02-05 08:26:50 -0800970 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800971 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -0700972 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -0800973 /*
974 * Media is blank or does not contain a supported filesystem
975 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700976 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400977 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -0800978 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -0800979 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -0700980 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -0800981 /*
982 * Volume consistency check failed
983 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700984 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400985 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -0800986 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -0800987 } else {
San Mehatb1043402010-02-05 08:26:50 -0800988 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -0800989 }
990
991 /*
992 * Send broadcast intent (if required for the failure)
993 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400994 if (action != null) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -0700995 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -0800996 }
997 }
998
999 return rc;
1000 }
1001
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001002 /*
1003 * If force is not set, we do not unmount if there are
1004 * processes holding references to the volume about to be unmounted.
1005 * If force is set, all the processes holding references need to be
1006 * killed via the ActivityManager before actually unmounting the volume.
1007 * This might even take a while and might be retried after timed delays
1008 * to make sure we dont end up in an instable state and kill some core
1009 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001010 * If removeEncryption is set, force is implied, and the system will remove any encryption
1011 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001012 */
Ben Komalo13c71972011-09-07 16:35:56 -07001013 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001014 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001015 return VoldResponseCode.OpFailedVolNotMounted;
1016 }
Kenny Rootaa485402010-09-14 14:49:41 -07001017
1018 /*
1019 * Force a GC to make sure AssetManagers in other threads of the
1020 * system_server are cleaned up. We have to do this since AssetManager
1021 * instances are kept as a WeakReference and it's possible we have files
1022 * open on the external storage.
1023 */
1024 Runtime.getRuntime().gc();
1025
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001026 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001027 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001028 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001029 final Command cmd = new Command("volume", "unmount", path);
1030 if (removeEncryption) {
1031 cmd.appendArg("force_and_revert");
1032 } else if (force) {
1033 cmd.appendArg("force");
1034 }
1035 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001036 // We unmounted the volume. None of the asec containers are available now.
1037 synchronized (mAsecMountSet) {
1038 mAsecMountSet.clear();
1039 }
San Mehatb1043402010-02-05 08:26:50 -08001040 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001041 } catch (NativeDaemonConnectorException e) {
1042 // Don't worry about mismatch in PackageManager since the
1043 // call back will handle the status changes any way.
1044 int code = e.getCode();
1045 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001046 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001047 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1048 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001049 } else {
San Mehatb1043402010-02-05 08:26:50 -08001050 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001051 }
1052 }
1053 }
1054
1055 private int doFormatVolume(String path) {
1056 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001057 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001058 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001059 } catch (NativeDaemonConnectorException e) {
1060 int code = e.getCode();
1061 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001062 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001063 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001064 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001065 } else {
San Mehatb1043402010-02-05 08:26:50 -08001066 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001067 }
1068 }
1069 }
1070
San Mehatb1043402010-02-05 08:26:50 -08001071 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001072 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001073 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001074 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001075 } catch (NativeDaemonConnectorException ex) {
1076 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1077 return false;
1078 }
San Mehatb1043402010-02-05 08:26:50 -08001079
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001080 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1081 return event.getMessage().endsWith("enabled");
1082 } else {
1083 return false;
San Mehatb1043402010-02-05 08:26:50 -08001084 }
San Mehatb1043402010-02-05 08:26:50 -08001085 }
1086
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001087 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001088 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001089 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001090 for (int i = mListeners.size() -1; i >= 0; i--) {
1091 MountServiceBinderListener bl = mListeners.get(i);
1092 try {
San Mehatb1043402010-02-05 08:26:50 -08001093 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001094 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001095 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001096 mListeners.remove(i);
1097 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001098 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001099 }
1100 }
1101 }
1102
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001103 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001104 sendUmsIntent(avail);
1105 } else {
1106 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001107 }
San Mehat2fe718a2010-03-11 12:01:49 -08001108
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001109 final StorageVolume primary = getPrimaryPhysicalVolume();
1110 if (avail == false && primary != null
1111 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1112 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001113 /*
1114 * USB mass storage disconnected while enabled
1115 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001116 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001117 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001118 public void run() {
1119 try {
1120 int rc;
San Mehata5078592010-03-25 09:36:54 -07001121 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001122 doShareUnshareVolume(path, "ums", false);
1123 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001124 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001125 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1126 path, rc));
1127 }
1128 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001129 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001130 }
1131 }
1132 }.start();
1133 }
San Mehat4270e1e2010-01-29 05:32:19 -08001134 }
1135
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001136 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1137 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1138 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1139 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1140 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001141 }
1142
San Mehat6a965af22010-02-24 17:47:30 -08001143 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001144 mContext.sendBroadcastAsUser(
1145 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1146 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001147 }
1148
San Mehat207e5382010-02-04 20:46:54 -08001149 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001150 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1151 throw new SecurityException(String.format("Requires %s permission", perm));
1152 }
1153 }
1154
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001155 // Storage list XML tags
1156 private static final String TAG_STORAGE_LIST = "StorageList";
1157 private static final String TAG_STORAGE = "storage";
1158
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001159 private void readStorageListLocked() {
1160 mVolumes.clear();
1161 mVolumeStates.clear();
1162
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001163 Resources resources = mContext.getResources();
1164
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001165 int id = com.android.internal.R.xml.storage_list;
1166 XmlResourceParser parser = resources.getXml(id);
1167 AttributeSet attrs = Xml.asAttributeSet(parser);
1168
1169 try {
1170 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1171 while (true) {
1172 XmlUtils.nextElement(parser);
1173
1174 String element = parser.getName();
1175 if (element == null) break;
1176
1177 if (TAG_STORAGE.equals(element)) {
1178 TypedArray a = resources.obtainAttributes(attrs,
1179 com.android.internal.R.styleable.Storage);
1180
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001181 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001182 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001183 int descriptionId = a.getResourceId(
1184 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001185 CharSequence description = a.getText(
1186 com.android.internal.R.styleable.Storage_storageDescription);
1187 boolean primary = a.getBoolean(
1188 com.android.internal.R.styleable.Storage_primary, false);
1189 boolean removable = a.getBoolean(
1190 com.android.internal.R.styleable.Storage_removable, false);
1191 boolean emulated = a.getBoolean(
1192 com.android.internal.R.styleable.Storage_emulated, false);
1193 int mtpReserve = a.getInt(
1194 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001195 boolean allowMassStorage = a.getBoolean(
1196 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001197 // resource parser does not support longs, so XML value is in megabytes
1198 long maxFileSize = a.getInt(
1199 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001200
1201 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1202 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001203 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001204 " allowMassStorage: " + allowMassStorage +
1205 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001206
1207 if (emulated) {
1208 // For devices with emulated storage, we create separate
1209 // volumes for each known user.
1210 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1211 true, mtpReserve, false, maxFileSize, null);
1212
1213 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001214 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001215 createEmulatedVolumeForUserLocked(user.getUserHandle());
1216 }
1217
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001218 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001219 if (path == null || description == null) {
1220 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001221 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001222 final StorageVolume volume = new StorageVolume(new File(path),
1223 descriptionId, primary, removable, emulated, mtpReserve,
1224 allowMassStorage, maxFileSize, null);
1225 addVolumeLocked(volume);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001226 }
1227 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001228
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001229 a.recycle();
1230 }
1231 }
1232 } catch (XmlPullParserException e) {
1233 throw new RuntimeException(e);
1234 } catch (IOException e) {
1235 throw new RuntimeException(e);
1236 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001237 // Compute storage ID for each physical volume; emulated storage is
1238 // always 0 when defined.
1239 int index = isExternalStorageEmulated() ? 1 : 0;
1240 for (StorageVolume volume : mVolumes) {
1241 if (!volume.isEmulated()) {
1242 volume.setStorageId(index++);
1243 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001244 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001245 parser.close();
1246 }
1247 }
1248
San Mehat4270e1e2010-01-29 05:32:19 -08001249 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001250 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1251 * using {@link #mEmulatedTemplate} as template.
1252 */
1253 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1254 if (mEmulatedTemplate == null) {
1255 throw new IllegalStateException("Missing emulated volume multi-user template");
1256 }
1257
1258 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1259 final File path = userEnv.getExternalStorageDirectory();
1260 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1261 volume.setStorageId(0);
1262 addVolumeLocked(volume);
1263
1264 if (mSystemReady) {
1265 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1266 } else {
1267 // Place stub status for early callers to find
1268 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
1269 }
1270 }
1271
1272 private void addVolumeLocked(StorageVolume volume) {
1273 Slog.d(TAG, "addVolumeLocked() " + volume);
1274 mVolumes.add(volume);
1275 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1276 if (existing != null) {
1277 throw new IllegalStateException(
1278 "Volume at " + volume.getPath() + " already exists: " + existing);
1279 }
1280 }
1281
1282 private void removeVolumeLocked(StorageVolume volume) {
1283 Slog.d(TAG, "removeVolumeLocked() " + volume);
1284 mVolumes.remove(volume);
1285 mVolumesByPath.remove(volume.getPath());
1286 mVolumeStates.remove(volume.getPath());
1287 }
1288
1289 private StorageVolume getPrimaryPhysicalVolume() {
1290 synchronized (mVolumesLock) {
1291 for (StorageVolume volume : mVolumes) {
1292 if (volume.isPrimary() && !volume.isEmulated()) {
1293 return volume;
1294 }
1295 }
1296 }
1297 return null;
1298 }
1299
1300 /**
San Mehat207e5382010-02-04 20:46:54 -08001301 * Constructs a new MountService instance
1302 *
1303 * @param context Binder context for this service
1304 */
1305 public MountService(Context context) {
1306 mContext = context;
1307
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001308 synchronized (mVolumesLock) {
1309 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001310 }
1311
San Mehat207e5382010-02-04 20:46:54 -08001312 // XXX: This will go away soon in favor of IMountServiceObserver
1313 mPms = (PackageManagerService) ServiceManager.getService("package");
1314
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001315 HandlerThread hthread = new HandlerThread(TAG);
1316 hthread.start();
1317 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001318
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001319 // Watch for user changes
1320 final IntentFilter userFilter = new IntentFilter();
1321 userFilter.addAction(Intent.ACTION_USER_ADDED);
1322 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1323 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1324
1325 // Watch for USB changes on primary volume
1326 final StorageVolume primary = getPrimaryPhysicalVolume();
1327 if (primary != null && primary.allowMassStorage()) {
1328 mContext.registerReceiver(
1329 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1330 }
1331
Svetoslava7452ee2013-03-20 12:06:59 -07001332 // Watch for idle maintenance changes
1333 IntentFilter idleMaintenanceFilter = new IntentFilter();
1334 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1335 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1336 idleMaintenanceFilter, null, mHandler);
1337
Kenny Roota02b8b02010-08-05 16:14:17 -07001338 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001339 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001340
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001341 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001342 * Create the connection to vold with a maximum queue of twice the
1343 * amount of containers we'd ever expect to have. This keeps an
1344 * "asec list" from blocking a thread repeatedly.
1345 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001346 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001347
Kenny Root305bcbf2010-09-03 07:56:38 -07001348 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001349 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001350
Kenny Root07714d42011-08-17 17:49:28 -07001351 // Add ourself to the Watchdog monitors if enabled.
1352 if (WATCHDOG_ENABLE) {
1353 Watchdog.getInstance().addMonitor(this);
1354 }
San Mehat207e5382010-02-04 20:46:54 -08001355 }
1356
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001357 public void systemReady() {
1358 mSystemReady = true;
1359 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1360 }
1361
San Mehat207e5382010-02-04 20:46:54 -08001362 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001363 * Exposed API calls below here
1364 */
1365
1366 public void registerListener(IMountServiceListener listener) {
1367 synchronized (mListeners) {
1368 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1369 try {
1370 listener.asBinder().linkToDeath(bl, 0);
1371 mListeners.add(bl);
1372 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001373 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001374 }
1375 }
1376 }
1377
1378 public void unregisterListener(IMountServiceListener listener) {
1379 synchronized (mListeners) {
1380 for(MountServiceBinderListener bl : mListeners) {
1381 if (bl.mListener == listener) {
1382 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001383 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001384 return;
1385 }
1386 }
1387 }
1388 }
1389
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001390 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001391 validatePermission(android.Manifest.permission.SHUTDOWN);
1392
San Mehata5078592010-03-25 09:36:54 -07001393 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001394 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001395 for (String path : mVolumeStates.keySet()) {
1396 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001397
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001398 if (state.equals(Environment.MEDIA_SHARED)) {
1399 /*
1400 * If the media is currently shared, unshare it.
1401 * XXX: This is still dangerous!. We should not
1402 * be rebooting at *all* if UMS is enabled, since
1403 * the UMS host could have dirty FAT cache entries
1404 * yet to flush.
1405 */
1406 setUsbMassStorageEnabled(false);
1407 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1408 /*
1409 * If the media is being checked, then we need to wait for
1410 * it to complete before being able to proceed.
1411 */
1412 // XXX: @hackbod - Should we disable the ANR timer here?
1413 int retries = 30;
1414 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1415 try {
1416 Thread.sleep(1000);
1417 } catch (InterruptedException iex) {
1418 Slog.e(TAG, "Interrupted while waiting for media", iex);
1419 break;
1420 }
1421 state = Environment.getExternalStorageState();
1422 }
1423 if (retries == 0) {
1424 Slog.e(TAG, "Timed out waiting for media to check");
1425 }
San Mehat91c77612010-01-07 10:39:41 -08001426 }
San Mehat91c77612010-01-07 10:39:41 -08001427
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001428 if (state.equals(Environment.MEDIA_MOUNTED)) {
1429 // Post a unmount message.
1430 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1431 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1432 } else if (observer != null) {
1433 /*
1434 * Observer is waiting for onShutDownComplete when we are done.
1435 * Since nothing will be done send notification directly so shutdown
1436 * sequence can continue.
1437 */
1438 try {
1439 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1440 } catch (RemoteException e) {
1441 Slog.w(TAG, "RemoteException when shutting down");
1442 }
1443 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001444 }
San Mehat4270e1e2010-01-29 05:32:19 -08001445 }
1446 }
1447
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001448 private boolean getUmsEnabling() {
1449 synchronized (mListeners) {
1450 return mUmsEnabling;
1451 }
1452 }
1453
1454 private void setUmsEnabling(boolean enable) {
1455 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001456 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001457 }
1458 }
1459
San Mehatb1043402010-02-05 08:26:50 -08001460 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001461 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001462
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001463 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001464 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001465 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001466 synchronized (mListeners) {
1467 return mUmsAvailable;
1468 }
San Mehatb1043402010-02-05 08:26:50 -08001469 }
1470
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001471 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001472 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001473 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001474
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001475 final StorageVolume primary = getPrimaryPhysicalVolume();
1476 if (primary == null) return;
1477
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001478 // TODO: Add support for multiple share methods
1479
1480 /*
1481 * If the volume is mounted and we're enabling then unmount it
1482 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001483 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001484 String vs = getVolumeState(path);
1485 String method = "ums";
1486 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1487 // Override for isUsbMassStorageEnabled()
1488 setUmsEnabling(enable);
1489 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1490 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1491 // Clear override
1492 setUmsEnabling(false);
1493 }
1494 /*
1495 * If we disabled UMS then mount the volume
1496 */
1497 if (!enable) {
1498 doShareUnshareVolume(path, method, enable);
1499 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001500 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001501 " after disabling share method " + method);
1502 /*
1503 * Even though the mount failed, the unshare didn't so don't indicate an error.
1504 * The mountVolume() call will have set the storage state and sent the necessary
1505 * broadcasts.
1506 */
1507 }
1508 }
San Mehatb1043402010-02-05 08:26:50 -08001509 }
1510
1511 public boolean isUsbMassStorageEnabled() {
1512 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001513
1514 final StorageVolume primary = getPrimaryPhysicalVolume();
1515 if (primary != null) {
1516 return doGetVolumeShared(primary.getPath(), "ums");
1517 } else {
1518 return false;
1519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001521
San Mehat7fd0fee2009-12-17 07:12:23 -08001522 /**
1523 * @return state of the volume at the specified mount point
1524 */
San Mehat4270e1e2010-01-29 05:32:19 -08001525 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001526 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001527 String state = mVolumeStates.get(mountPoint);
1528 if (state == null) {
1529 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001530 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1531 state = Environment.MEDIA_REMOVED;
1532 } else {
1533 throw new IllegalArgumentException();
1534 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001535 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001536
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001537 return state;
1538 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001539 }
1540
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001541 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001542 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001543 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001544 }
1545
San Mehat4270e1e2010-01-29 05:32:19 -08001546 public int mountVolume(String path) {
1547 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001548
San Mehat207e5382010-02-04 20:46:54 -08001549 waitForReady();
1550 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552
Ben Komalo13c71972011-09-07 16:35:56 -07001553 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001554 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001555 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001557 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001558 if (DEBUG_UNMOUNT) {
1559 Slog.i(TAG, "Unmounting " + path
1560 + " force = " + force
1561 + " removeEncryption = " + removeEncryption);
1562 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001563 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1564 Environment.MEDIA_REMOVED.equals(volState) ||
1565 Environment.MEDIA_SHARED.equals(volState) ||
1566 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1567 // Media already unmounted or cannot be unmounted.
1568 // TODO return valid return code when adding observer call back.
1569 return;
1570 }
Ben Komalo13c71972011-09-07 16:35:56 -07001571 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001572 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
San Mehat4270e1e2010-01-29 05:32:19 -08001575 public int formatVolume(String path) {
1576 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001577 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001578
San Mehat207e5382010-02-04 20:46:54 -08001579 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001582 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001583 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1584 waitForReady();
1585 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001586 final String[] r = NativeDaemonEvent.filterMessageList(
1587 mConnector.executeForList("storage", "users", path),
1588 VoldResponseCode.StorageUsersListResult);
1589
San Mehatc1b4ce92010-02-16 17:13:03 -08001590 // FMT: <pid> <process name>
1591 int[] data = new int[r.length];
1592 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001593 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001594 try {
1595 data[i] = Integer.parseInt(tok[0]);
1596 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001597 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001598 return new int[0];
1599 }
1600 }
1601 return data;
1602 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001603 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001604 return new int[0];
1605 }
1606 }
1607
San Mehatb1043402010-02-05 08:26:50 -08001608 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001609 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001610 if (primary != null) {
1611 boolean mounted = false;
1612 try {
1613 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001614 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001615 }
1616
1617 if (!mounted) {
1618 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1619 }
San Mehatb1043402010-02-05 08:26:50 -08001620 }
1621 }
1622
San Mehat4270e1e2010-01-29 05:32:19 -08001623 public String[] getSecureContainerList() {
1624 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001625 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001626 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001627
San Mehat4270e1e2010-01-29 05:32:19 -08001628 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001629 return NativeDaemonEvent.filterMessageList(
1630 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001631 } catch (NativeDaemonConnectorException e) {
1632 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 }
San Mehat36972292010-01-06 11:06:32 -08001635
Kenny Root6dceb882012-04-12 14:23:49 -07001636 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1637 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001638 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001639 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001640 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001641
San Mehatb1043402010-02-05 08:26:50 -08001642 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001643 try {
Kenny Root6dceb882012-04-12 14:23:49 -07001644 mConnector.execute("asec", "create", id, sizeMb, fstype, key, ownerUid,
1645 external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001646 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001647 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001648 }
San Mehata181b212010-02-11 06:50:20 -08001649
1650 if (rc == StorageResultCode.OperationSucceeded) {
1651 synchronized (mAsecMountSet) {
1652 mAsecMountSet.add(id);
1653 }
1654 }
San Mehat4270e1e2010-01-29 05:32:19 -08001655 return rc;
San Mehat36972292010-01-06 11:06:32 -08001656 }
1657
San Mehat4270e1e2010-01-29 05:32:19 -08001658 public int finalizeSecureContainer(String id) {
1659 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001660 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001661
San Mehatb1043402010-02-05 08:26:50 -08001662 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001663 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001664 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001665 /*
1666 * Finalization does a remount, so no need
1667 * to update mAsecMountSet
1668 */
San Mehat4270e1e2010-01-29 05:32:19 -08001669 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001670 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001671 }
San Mehat4270e1e2010-01-29 05:32:19 -08001672 return rc;
San Mehat36972292010-01-06 11:06:32 -08001673 }
1674
Kenny Root6dceb882012-04-12 14:23:49 -07001675 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1676 validatePermission(android.Manifest.permission.ASEC_CREATE);
1677 warnOnNotMounted();
1678
1679 int rc = StorageResultCode.OperationSucceeded;
1680 try {
1681 mConnector.execute("asec", "fixperms", id, gid, filename);
1682 /*
1683 * Fix permissions does a remount, so no need to update
1684 * mAsecMountSet
1685 */
1686 } catch (NativeDaemonConnectorException e) {
1687 rc = StorageResultCode.OperationFailedInternalError;
1688 }
1689 return rc;
1690 }
1691
San Mehatd9709982010-02-18 11:43:03 -08001692 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001693 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001694 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001695 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001696
Kenny Rootaa485402010-09-14 14:49:41 -07001697 /*
1698 * Force a GC to make sure AssetManagers in other threads of the
1699 * system_server are cleaned up. We have to do this since AssetManager
1700 * instances are kept as a WeakReference and it's possible we have files
1701 * open on the external storage.
1702 */
1703 Runtime.getRuntime().gc();
1704
San Mehatb1043402010-02-05 08:26:50 -08001705 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001706 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001707 final Command cmd = new Command("asec", "destroy", id);
1708 if (force) {
1709 cmd.appendArg("force");
1710 }
1711 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001712 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001713 int code = e.getCode();
1714 if (code == VoldResponseCode.OpFailedStorageBusy) {
1715 rc = StorageResultCode.OperationFailedStorageBusy;
1716 } else {
1717 rc = StorageResultCode.OperationFailedInternalError;
1718 }
San Mehat02735bc2010-01-26 15:18:08 -08001719 }
San Mehata181b212010-02-11 06:50:20 -08001720
1721 if (rc == StorageResultCode.OperationSucceeded) {
1722 synchronized (mAsecMountSet) {
1723 if (mAsecMountSet.contains(id)) {
1724 mAsecMountSet.remove(id);
1725 }
1726 }
1727 }
1728
San Mehat4270e1e2010-01-29 05:32:19 -08001729 return rc;
San Mehat36972292010-01-06 11:06:32 -08001730 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001731
San Mehat4270e1e2010-01-29 05:32:19 -08001732 public int mountSecureContainer(String id, String key, int ownerUid) {
1733 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001734 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001735 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001736
San Mehata181b212010-02-11 06:50:20 -08001737 synchronized (mAsecMountSet) {
1738 if (mAsecMountSet.contains(id)) {
1739 return StorageResultCode.OperationFailedStorageMounted;
1740 }
1741 }
1742
San Mehatb1043402010-02-05 08:26:50 -08001743 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001744 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001745 mConnector.execute("asec", "mount", id, key, ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001746 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001747 int code = e.getCode();
1748 if (code != VoldResponseCode.OpFailedStorageBusy) {
1749 rc = StorageResultCode.OperationFailedInternalError;
1750 }
San Mehat02735bc2010-01-26 15:18:08 -08001751 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001752
1753 if (rc == StorageResultCode.OperationSucceeded) {
1754 synchronized (mAsecMountSet) {
1755 mAsecMountSet.add(id);
1756 }
1757 }
San Mehat4270e1e2010-01-29 05:32:19 -08001758 return rc;
San Mehat36972292010-01-06 11:06:32 -08001759 }
1760
San Mehatd9709982010-02-18 11:43:03 -08001761 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001762 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001763 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001764 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001765
San Mehat6cdd9c02010-02-09 14:45:20 -08001766 synchronized (mAsecMountSet) {
1767 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001768 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001769 }
1770 }
1771
Kenny Rootaa485402010-09-14 14:49:41 -07001772 /*
1773 * Force a GC to make sure AssetManagers in other threads of the
1774 * system_server are cleaned up. We have to do this since AssetManager
1775 * instances are kept as a WeakReference and it's possible we have files
1776 * open on the external storage.
1777 */
1778 Runtime.getRuntime().gc();
1779
San Mehatb1043402010-02-05 08:26:50 -08001780 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001781 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001782 final Command cmd = new Command("asec", "unmount", id);
1783 if (force) {
1784 cmd.appendArg("force");
1785 }
1786 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001787 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001788 int code = e.getCode();
1789 if (code == VoldResponseCode.OpFailedStorageBusy) {
1790 rc = StorageResultCode.OperationFailedStorageBusy;
1791 } else {
1792 rc = StorageResultCode.OperationFailedInternalError;
1793 }
San Mehat02735bc2010-01-26 15:18:08 -08001794 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001795
1796 if (rc == StorageResultCode.OperationSucceeded) {
1797 synchronized (mAsecMountSet) {
1798 mAsecMountSet.remove(id);
1799 }
1800 }
San Mehat4270e1e2010-01-29 05:32:19 -08001801 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001802 }
1803
San Mehat6cdd9c02010-02-09 14:45:20 -08001804 public boolean isSecureContainerMounted(String id) {
1805 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1806 waitForReady();
1807 warnOnNotMounted();
1808
1809 synchronized (mAsecMountSet) {
1810 return mAsecMountSet.contains(id);
1811 }
1812 }
1813
San Mehat4270e1e2010-01-29 05:32:19 -08001814 public int renameSecureContainer(String oldId, String newId) {
1815 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001816 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001817 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001818
San Mehata181b212010-02-11 06:50:20 -08001819 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001820 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001821 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001822 * changed while active, we must ensure both ids are not currently mounted.
1823 */
1824 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001825 return StorageResultCode.OperationFailedStorageMounted;
1826 }
1827 }
1828
San Mehatb1043402010-02-05 08:26:50 -08001829 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001830 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001831 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001832 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001833 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001834 }
San Mehata181b212010-02-11 06:50:20 -08001835
San Mehat4270e1e2010-01-29 05:32:19 -08001836 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001837 }
1838
San Mehat4270e1e2010-01-29 05:32:19 -08001839 public String getSecureContainerPath(String id) {
1840 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001841 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001842 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001843
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001844 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001845 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001846 event = mConnector.execute("asec", "path", id);
1847 event.checkCode(VoldResponseCode.AsecPathResult);
1848 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001849 } catch (NativeDaemonConnectorException e) {
1850 int code = e.getCode();
1851 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001852 Slog.i(TAG, String.format("Container '%s' not found", id));
1853 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001854 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001855 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001856 }
1857 }
San Mehat22dd86e2010-01-12 12:21:18 -08001858 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001859
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001860 public String getSecureContainerFilesystemPath(String id) {
1861 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1862 waitForReady();
1863 warnOnNotMounted();
1864
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001865 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001866 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001867 event = mConnector.execute("asec", "fspath", id);
1868 event.checkCode(VoldResponseCode.AsecPathResult);
1869 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001870 } catch (NativeDaemonConnectorException e) {
1871 int code = e.getCode();
1872 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1873 Slog.i(TAG, String.format("Container '%s' not found", id));
1874 return null;
1875 } else {
1876 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1877 }
1878 }
1879 }
1880
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001881 public void finishMediaUpdate() {
1882 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1883 }
Kenny Root02c87302010-07-01 08:10:18 -07001884
Kenny Roota02b8b02010-08-05 16:14:17 -07001885 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1886 if (callerUid == android.os.Process.SYSTEM_UID) {
1887 return true;
1888 }
1889
Kenny Root02c87302010-07-01 08:10:18 -07001890 if (packageName == null) {
1891 return false;
1892 }
1893
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001894 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001895
1896 if (DEBUG_OBB) {
1897 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1898 packageUid + ", callerUid = " + callerUid);
1899 }
1900
1901 return callerUid == packageUid;
1902 }
1903
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001904 public String getMountedObbPath(String rawPath) {
1905 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001906
Kenny Root02c87302010-07-01 08:10:18 -07001907 waitForReady();
1908 warnOnNotMounted();
1909
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001910 final ObbState state;
1911 synchronized (mObbPathToStateMap) {
1912 state = mObbPathToStateMap.get(rawPath);
1913 }
1914 if (state == null) {
1915 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1916 return null;
1917 }
1918
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001919 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001920 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001921 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001922 event.checkCode(VoldResponseCode.AsecPathResult);
1923 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001924 } catch (NativeDaemonConnectorException e) {
1925 int code = e.getCode();
1926 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001927 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001928 } else {
1929 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1930 }
1931 }
1932 }
1933
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001934 @Override
1935 public boolean isObbMounted(String rawPath) {
1936 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001937 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001938 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001939 }
Kenny Root02c87302010-07-01 08:10:18 -07001940 }
1941
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001942 @Override
1943 public void mountObb(
1944 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1945 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1946 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1947 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001948
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001949 final int callingUid = Binder.getCallingUid();
1950 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1951 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001952 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1953
1954 if (DEBUG_OBB)
1955 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001956 }
1957
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001958 @Override
1959 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1960 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1961
1962 final ObbState existingState;
1963 synchronized (mObbPathToStateMap) {
1964 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001965 }
1966
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001967 if (existingState != null) {
1968 // TODO: separate state object from request data
1969 final int callingUid = Binder.getCallingUid();
1970 final ObbState newState = new ObbState(
1971 rawPath, existingState.canonicalPath, callingUid, token, nonce);
1972 final ObbAction action = new UnmountObbAction(newState, force);
1973 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07001974
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001975 if (DEBUG_OBB)
1976 Slog.i(TAG, "Send to OBB handler: " + action.toString());
1977 } else {
1978 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
1979 }
Kenny Roota02b8b02010-08-05 16:14:17 -07001980 }
1981
Ben Komalo444eca22011-09-01 15:17:44 -07001982 @Override
1983 public int getEncryptionState() {
1984 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
1985 "no permission to access the crypt keeper");
1986
1987 waitForReady();
1988
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001989 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07001990 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001991 event = mConnector.execute("cryptfs", "cryptocomplete");
1992 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07001993 } catch (NumberFormatException e) {
1994 // Bad result - unexpected.
1995 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
1996 return ENCRYPTION_STATE_ERROR_UNKNOWN;
1997 } catch (NativeDaemonConnectorException e) {
1998 // Something bad happened.
1999 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2000 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2001 }
2002 }
2003
2004 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002005 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002006 if (TextUtils.isEmpty(password)) {
2007 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002008 }
2009
Jason parks8888c592011-01-20 22:46:41 -06002010 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2011 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002012
2013 waitForReady();
2014
2015 if (DEBUG_EVENTS) {
2016 Slog.i(TAG, "decrypting storage...");
2017 }
2018
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002019 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002020 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002021 event = mConnector.execute("cryptfs", "checkpw", password);
Jason parks9ed98bc2011-01-17 09:58:35 -06002022
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002023 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002024 if (code == 0) {
2025 // Decrypt was successful. Post a delayed message before restarting in order
2026 // to let the UI to clear itself
2027 mHandler.postDelayed(new Runnable() {
2028 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002029 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002030 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002031 } catch (NativeDaemonConnectorException e) {
2032 Slog.e(TAG, "problem executing in background", e);
2033 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002034 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002035 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002036 }
2037
2038 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002039 } catch (NativeDaemonConnectorException e) {
2040 // Decryption failed
2041 return e.getCode();
2042 }
Jason parks5af0b912010-11-29 09:05:25 -06002043 }
2044
Jason parks56aa5322011-01-07 09:01:15 -06002045 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002046 if (TextUtils.isEmpty(password)) {
2047 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002048 }
2049
Jason parks8888c592011-01-20 22:46:41 -06002050 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2051 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002052
2053 waitForReady();
2054
2055 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002056 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002057 }
2058
2059 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002060 mConnector.execute("cryptfs", "enablecrypto", "inplace", password);
Jason parks56aa5322011-01-07 09:01:15 -06002061 } catch (NativeDaemonConnectorException e) {
2062 // Encryption failed
2063 return e.getCode();
2064 }
2065
2066 return 0;
2067 }
2068
Jason parksf7b3cd42011-01-27 09:28:25 -06002069 public int changeEncryptionPassword(String password) {
2070 if (TextUtils.isEmpty(password)) {
2071 throw new IllegalArgumentException("password cannot be empty");
2072 }
2073
2074 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2075 "no permission to access the crypt keeper");
2076
2077 waitForReady();
2078
2079 if (DEBUG_EVENTS) {
2080 Slog.i(TAG, "changing encryption password...");
2081 }
2082
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002083 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002084 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002085 event = mConnector.execute("cryptfs", "changepw", password);
2086 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002087 } catch (NativeDaemonConnectorException e) {
2088 // Encryption failed
2089 return e.getCode();
2090 }
2091 }
2092
Christopher Tate32418be2011-10-10 13:51:12 -07002093 /**
2094 * Validate a user-supplied password string with cryptfs
2095 */
2096 @Override
2097 public int verifyEncryptionPassword(String password) throws RemoteException {
2098 // Only the system process is permitted to validate passwords
2099 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2100 throw new SecurityException("no permission to access the crypt keeper");
2101 }
2102
2103 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2104 "no permission to access the crypt keeper");
2105
2106 if (TextUtils.isEmpty(password)) {
2107 throw new IllegalArgumentException("password cannot be empty");
2108 }
2109
2110 waitForReady();
2111
2112 if (DEBUG_EVENTS) {
2113 Slog.i(TAG, "validating encryption password...");
2114 }
2115
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002116 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002117 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002118 event = mConnector.execute("cryptfs", "verifypw", password);
2119 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2120 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002121 } catch (NativeDaemonConnectorException e) {
2122 // Encryption failed
2123 return e.getCode();
2124 }
2125 }
2126
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002127 @Override
2128 public StorageVolume[] getVolumeList() {
2129 final int callingUserId = UserHandle.getCallingUserId();
2130 final boolean accessAll = (mContext.checkPermission(
2131 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2132 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2133
2134 synchronized (mVolumesLock) {
2135 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2136 for (StorageVolume volume : mVolumes) {
2137 final UserHandle owner = volume.getOwner();
2138 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2139 if (accessAll || ownerMatch) {
2140 filtered.add(volume);
2141 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002142 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002143 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002144 }
2145 }
2146
Kenny Rootaf9d6672010-10-08 09:21:39 -07002147 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2148 final IBinder binder = obbState.getBinder();
2149 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002150
Kenny Rootaf9d6672010-10-08 09:21:39 -07002151 if (obbStates == null) {
2152 obbStates = new ArrayList<ObbState>();
2153 mObbMounts.put(binder, obbStates);
2154 } else {
2155 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002156 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002157 throw new IllegalStateException("Attempt to add ObbState twice. "
2158 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002159 }
2160 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002161 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002162
2163 obbStates.add(obbState);
2164 try {
2165 obbState.link();
2166 } catch (RemoteException e) {
2167 /*
2168 * The binder died before we could link it, so clean up our state
2169 * and return failure.
2170 */
2171 obbStates.remove(obbState);
2172 if (obbStates.isEmpty()) {
2173 mObbMounts.remove(binder);
2174 }
2175
2176 // Rethrow the error so mountObb can get it
2177 throw e;
2178 }
2179
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002180 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002181 }
2182
Kenny Rootaf9d6672010-10-08 09:21:39 -07002183 private void removeObbStateLocked(ObbState obbState) {
2184 final IBinder binder = obbState.getBinder();
2185 final List<ObbState> obbStates = mObbMounts.get(binder);
2186 if (obbStates != null) {
2187 if (obbStates.remove(obbState)) {
2188 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002189 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002190 if (obbStates.isEmpty()) {
2191 mObbMounts.remove(binder);
2192 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002193 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002194
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002195 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002196 }
2197
Kenny Roota02b8b02010-08-05 16:14:17 -07002198 private class ObbActionHandler extends Handler {
2199 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002200 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002201
2202 ObbActionHandler(Looper l) {
2203 super(l);
2204 }
2205
2206 @Override
2207 public void handleMessage(Message msg) {
2208 switch (msg.what) {
2209 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002210 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002211
2212 if (DEBUG_OBB)
2213 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2214
2215 // If a bind was already initiated we don't really
2216 // need to do anything. The pending install
2217 // will be processed later on.
2218 if (!mBound) {
2219 // If this is the only one pending we might
2220 // have to bind to the service again.
2221 if (!connectToService()) {
2222 Slog.e(TAG, "Failed to bind to media container service");
2223 action.handleError();
2224 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002225 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002226 }
Kenny Root735de3b2010-09-30 14:11:39 -07002227
Kenny Root735de3b2010-09-30 14:11:39 -07002228 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002229 break;
2230 }
2231 case OBB_MCS_BOUND: {
2232 if (DEBUG_OBB)
2233 Slog.i(TAG, "OBB_MCS_BOUND");
2234 if (msg.obj != null) {
2235 mContainerService = (IMediaContainerService) msg.obj;
2236 }
2237 if (mContainerService == null) {
2238 // Something seriously wrong. Bail out
2239 Slog.e(TAG, "Cannot bind to media container service");
2240 for (ObbAction action : mActions) {
2241 // Indicate service bind error
2242 action.handleError();
2243 }
2244 mActions.clear();
2245 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002246 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002247 if (action != null) {
2248 action.execute(this);
2249 }
2250 } else {
2251 // Should never happen ideally.
2252 Slog.w(TAG, "Empty queue");
2253 }
2254 break;
2255 }
2256 case OBB_MCS_RECONNECT: {
2257 if (DEBUG_OBB)
2258 Slog.i(TAG, "OBB_MCS_RECONNECT");
2259 if (mActions.size() > 0) {
2260 if (mBound) {
2261 disconnectService();
2262 }
2263 if (!connectToService()) {
2264 Slog.e(TAG, "Failed to bind to media container service");
2265 for (ObbAction action : mActions) {
2266 // Indicate service bind error
2267 action.handleError();
2268 }
2269 mActions.clear();
2270 }
2271 }
2272 break;
2273 }
2274 case OBB_MCS_UNBIND: {
2275 if (DEBUG_OBB)
2276 Slog.i(TAG, "OBB_MCS_UNBIND");
2277
2278 // Delete pending install
2279 if (mActions.size() > 0) {
2280 mActions.remove(0);
2281 }
2282 if (mActions.size() == 0) {
2283 if (mBound) {
2284 disconnectService();
2285 }
2286 } else {
2287 // There are more pending requests in queue.
2288 // Just post MCS_BOUND message to trigger processing
2289 // of next pending install.
2290 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2291 }
2292 break;
2293 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002294 case OBB_FLUSH_MOUNT_STATE: {
2295 final String path = (String) msg.obj;
2296
2297 if (DEBUG_OBB)
2298 Slog.i(TAG, "Flushing all OBB state for path " + path);
2299
2300 synchronized (mObbMounts) {
2301 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2302
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002303 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002304 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002305 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306
2307 /*
2308 * If this entry's source file is in the volume path
2309 * that got unmounted, remove it because it's no
2310 * longer valid.
2311 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002312 if (state.canonicalPath.startsWith(path)) {
2313 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002314 }
2315 }
2316
2317 for (final ObbState obbState : obbStatesToRemove) {
2318 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002319 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002320
2321 removeObbStateLocked(obbState);
2322
2323 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002324 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002325 OnObbStateChangeListener.UNMOUNTED);
2326 } catch (RemoteException e) {
2327 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002328 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002329 }
2330 }
2331 }
2332 break;
2333 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002334 }
2335 }
2336
2337 private boolean connectToService() {
2338 if (DEBUG_OBB)
2339 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2340
2341 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2342 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2343 mBound = true;
2344 return true;
2345 }
2346 return false;
2347 }
2348
2349 private void disconnectService() {
2350 mContainerService = null;
2351 mBound = false;
2352 mContext.unbindService(mDefContainerConn);
2353 }
2354 }
2355
2356 abstract class ObbAction {
2357 private static final int MAX_RETRIES = 3;
2358 private int mRetries;
2359
2360 ObbState mObbState;
2361
2362 ObbAction(ObbState obbState) {
2363 mObbState = obbState;
2364 }
2365
2366 public void execute(ObbActionHandler handler) {
2367 try {
2368 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002369 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002370 mRetries++;
2371 if (mRetries > MAX_RETRIES) {
2372 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002373 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002374 handleError();
2375 return;
2376 } else {
2377 handleExecute();
2378 if (DEBUG_OBB)
2379 Slog.i(TAG, "Posting install MCS_UNBIND");
2380 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2381 }
2382 } catch (RemoteException e) {
2383 if (DEBUG_OBB)
2384 Slog.i(TAG, "Posting install MCS_RECONNECT");
2385 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2386 } catch (Exception e) {
2387 if (DEBUG_OBB)
2388 Slog.d(TAG, "Error handling OBB action", e);
2389 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002390 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002391 }
2392 }
2393
Kenny Root05105f72010-09-22 17:29:43 -07002394 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002395 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002396
2397 protected ObbInfo getObbInfo() throws IOException {
2398 ObbInfo obbInfo;
2399 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002400 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002401 } catch (RemoteException e) {
2402 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002403 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002404 obbInfo = null;
2405 }
2406 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002407 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002408 }
2409 return obbInfo;
2410 }
2411
Kenny Rootaf9d6672010-10-08 09:21:39 -07002412 protected void sendNewStatusOrIgnore(int status) {
2413 if (mObbState == null || mObbState.token == null) {
2414 return;
2415 }
2416
Kenny Root38cf8862010-09-26 14:18:51 -07002417 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002418 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002419 } catch (RemoteException e) {
2420 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2421 }
2422 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002423 }
2424
2425 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002426 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002427 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002428
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002429 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002430 super(obbState);
2431 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002432 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002433 }
2434
Jason parks5af0b912010-11-29 09:05:25 -06002435 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002436 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002437 waitForReady();
2438 warnOnNotMounted();
2439
Kenny Root38cf8862010-09-26 14:18:51 -07002440 final ObbInfo obbInfo = getObbInfo();
2441
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002442 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002443 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2444 + " which is owned by " + obbInfo.packageName);
2445 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2446 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002447 }
2448
Kenny Rootaf9d6672010-10-08 09:21:39 -07002449 final boolean isMounted;
2450 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002451 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002452 }
2453 if (isMounted) {
2454 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2455 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2456 return;
2457 }
2458
Kenny Rootaf9d6672010-10-08 09:21:39 -07002459 final String hashedKey;
2460 if (mKey == null) {
2461 hashedKey = "none";
2462 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002463 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002464 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2465
2466 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2467 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2468 SecretKey key = factory.generateSecret(ks);
2469 BigInteger bi = new BigInteger(key.getEncoded());
2470 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002471 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002472 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2473 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2474 return;
2475 } catch (InvalidKeySpecException e) {
2476 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2477 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002478 return;
2479 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002480 }
Kenny Root38cf8862010-09-26 14:18:51 -07002481
Kenny Rootaf9d6672010-10-08 09:21:39 -07002482 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002483 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002484 mConnector.execute(
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002485 "obb", "mount", mObbState.voldPath, hashedKey, mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002486 } catch (NativeDaemonConnectorException e) {
2487 int code = e.getCode();
2488 if (code != VoldResponseCode.OpFailedStorageBusy) {
2489 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002490 }
2491 }
2492
Kenny Rootaf9d6672010-10-08 09:21:39 -07002493 if (rc == StorageResultCode.OperationSucceeded) {
2494 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002495 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002496
2497 synchronized (mObbMounts) {
2498 addObbStateLocked(mObbState);
2499 }
2500
2501 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002502 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002503 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002504
Kenny Rootaf9d6672010-10-08 09:21:39 -07002505 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002506 }
2507 }
2508
Jason parks5af0b912010-11-29 09:05:25 -06002509 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002510 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002511 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002512 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002513
2514 @Override
2515 public String toString() {
2516 StringBuilder sb = new StringBuilder();
2517 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002518 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002519 sb.append('}');
2520 return sb.toString();
2521 }
2522 }
2523
2524 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002525 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002526
2527 UnmountObbAction(ObbState obbState, boolean force) {
2528 super(obbState);
2529 mForceUnmount = force;
2530 }
2531
Jason parks5af0b912010-11-29 09:05:25 -06002532 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002533 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002534 waitForReady();
2535 warnOnNotMounted();
2536
Kenny Root38cf8862010-09-26 14:18:51 -07002537 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002538
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002539 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002540 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002541 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002542 }
Kenny Root38cf8862010-09-26 14:18:51 -07002543
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002544 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002545 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2546 return;
2547 }
2548
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002549 if (existingState.ownerGid != mObbState.ownerGid) {
2550 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2551 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002552 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2553 return;
2554 }
2555
Kenny Rootaf9d6672010-10-08 09:21:39 -07002556 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002557 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002558 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002559 if (mForceUnmount) {
2560 cmd.appendArg("force");
2561 }
2562 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002563 } catch (NativeDaemonConnectorException e) {
2564 int code = e.getCode();
2565 if (code == VoldResponseCode.OpFailedStorageBusy) {
2566 rc = StorageResultCode.OperationFailedStorageBusy;
2567 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2568 // If it's not mounted then we've already won.
2569 rc = StorageResultCode.OperationSucceeded;
2570 } else {
2571 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002572 }
2573 }
2574
Kenny Rootaf9d6672010-10-08 09:21:39 -07002575 if (rc == StorageResultCode.OperationSucceeded) {
2576 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002577 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002578 }
2579
Kenny Rootaf9d6672010-10-08 09:21:39 -07002580 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002581 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002582 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002583 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002584 }
2585 }
2586
Jason parks5af0b912010-11-29 09:05:25 -06002587 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002588 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002589 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002590 }
2591
2592 @Override
2593 public String toString() {
2594 StringBuilder sb = new StringBuilder();
2595 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002596 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002597 sb.append(",force=");
2598 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002599 sb.append('}');
2600 return sb.toString();
2601 }
Kenny Root02c87302010-07-01 08:10:18 -07002602 }
Kenny Root38cf8862010-09-26 14:18:51 -07002603
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002604 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002605 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2606 // TODO: allow caller to provide Environment for full testing
2607
2608 // Only adjust paths when storage is emulated
2609 if (!Environment.isExternalStorageEmulated()) {
2610 return canonicalPath;
2611 }
2612
2613 String path = canonicalPath.toString();
2614
2615 // First trim off any external storage prefix
2616 final UserEnvironment userEnv = new UserEnvironment(userId);
2617
2618 // /storage/emulated/0
2619 final String externalPath = userEnv.getExternalStorageDirectory().toString();
2620 // /storage/emulated_legacy
2621 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
2622 .toString();
2623
2624 if (path.startsWith(externalPath)) {
2625 path = path.substring(externalPath.length() + 1);
2626 } else if (path.startsWith(legacyExternalPath)) {
2627 path = path.substring(legacyExternalPath.length() + 1);
2628 } else {
2629 return canonicalPath;
2630 }
2631
2632 // Handle special OBB paths on emulated storage
2633 final String obbPath = "Android/obb";
2634 if (path.startsWith(obbPath)) {
2635 path = path.substring(obbPath.length() + 1);
2636
2637 if (forVold) {
2638 return new File(Environment.getEmulatedStorageObbSource(), path).toString();
2639 } else {
2640 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
2641 return new File(ownerEnv.getExternalStorageObbDirectory(), path).toString();
2642 }
2643 }
2644
2645 // Handle normal external storage paths
2646 if (forVold) {
2647 return new File(Environment.getEmulatedStorageSource(userId), path).toString();
2648 } else {
2649 return new File(userEnv.getExternalStorageDirectory(), path).toString();
2650 }
2651 }
2652
Kenny Root38cf8862010-09-26 14:18:51 -07002653 @Override
2654 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2655 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) {
2656 pw.println("Permission Denial: can't dump ActivityManager from from pid="
2657 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2658 + " without permission " + android.Manifest.permission.DUMP);
2659 return;
2660 }
2661
Kenny Root38cf8862010-09-26 14:18:51 -07002662 synchronized (mObbMounts) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002663 pw.println(" mObbMounts:");
Kenny Root38cf8862010-09-26 14:18:51 -07002664
Kenny Rootaf9d6672010-10-08 09:21:39 -07002665 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet().iterator();
2666 while (binders.hasNext()) {
2667 Entry<IBinder, List<ObbState>> e = binders.next();
2668 pw.print(" Key="); pw.println(e.getKey().toString());
2669 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002670 for (final ObbState obbState : obbStates) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002671 pw.print(" "); pw.println(obbState.toString());
Kenny Root38cf8862010-09-26 14:18:51 -07002672 }
2673 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002674
2675 pw.println("");
2676 pw.println(" mObbPathToStateMap:");
2677 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2678 while (maps.hasNext()) {
2679 final Entry<String, ObbState> e = maps.next();
2680 pw.print(" "); pw.print(e.getKey());
2681 pw.print(" -> "); pw.println(e.getValue().toString());
2682 }
Kenny Root38cf8862010-09-26 14:18:51 -07002683 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002684
2685 pw.println("");
2686
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002687 synchronized (mVolumesLock) {
Kenny Root4161f9b2011-07-13 09:48:33 -07002688 pw.println(" mVolumes:");
2689
2690 final int N = mVolumes.size();
2691 for (int i = 0; i < N; i++) {
2692 final StorageVolume v = mVolumes.get(i);
2693 pw.print(" ");
2694 pw.println(v.toString());
2695 }
2696 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002697
2698 pw.println();
2699 pw.println(" mConnection:");
2700 mConnector.dump(fd, pw, args);
Kenny Root38cf8862010-09-26 14:18:51 -07002701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002703 /** {@inheritDoc} */
2704 public void monitor() {
2705 if (mConnector != null) {
2706 mConnector.monitor();
2707 }
2708 }
2709}