blob: 816ae6967cfd40e637afe843883489f7553c5096 [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 Sharkeyb049e212012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070064import com.android.internal.app.IMediaContainerService;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070065import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070066import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070067import com.android.internal.util.XmlUtils;
68import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070069import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070070import com.android.server.am.ActivityManagerService;
71import com.android.server.pm.PackageManagerService;
72import com.android.server.pm.UserManagerService;
73import com.google.android.collect.Lists;
74import com.google.android.collect.Maps;
75
Mike Lockwood2f6a3882011-05-09 19:08:06 -070076import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070077
Jeff Sharkeyb049e212012-09-07 23:16:01 -070078import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070079import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070080import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070081import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070082import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070083import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070084import java.security.spec.InvalidKeySpecException;
85import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080086import java.util.ArrayList;
Kenny Roota02b8b02010-08-05 16:14:17 -070087import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080088import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070089import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070090import java.util.LinkedList;
91import java.util.List;
92import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070093import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070094import java.util.concurrent.CountDownLatch;
95import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Kenny Root3b1abba2010-10-13 15:00:07 -070097import javax.crypto.SecretKey;
98import javax.crypto.SecretKeyFactory;
99import javax.crypto.spec.PBEKeySpec;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101/**
San Mehatb1043402010-02-05 08:26:50 -0800102 * MountService implements back-end services for platform storage
103 * management.
104 * @hide - Applications should use android.os.storage.StorageManager
105 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700107class MountService extends IMountService.Stub
108 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600109
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700110 // TODO: listen for user creation/deletion
111
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800112 private static final boolean LOCAL_LOGD = false;
113 private static final boolean DEBUG_UNMOUNT = false;
114 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800115 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700116
Kenny Root07714d42011-08-17 17:49:28 -0700117 // Disable this since it messes up long-running cryptfs operations.
118 private static final boolean WATCHDOG_ENABLE = false;
119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private static final String TAG = "MountService";
121
Kenny Root305bcbf2010-09-03 07:56:38 -0700122 private static final String VOLD_TAG = "VoldConnector";
123
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700124 /** Maximum number of ASEC containers allowed to be mounted. */
125 private static final int MAX_CONTAINERS = 250;
126
San Mehat4270e1e2010-01-29 05:32:19 -0800127 /*
128 * Internal vold volume state constants
129 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800130 class VolumeState {
131 public static final int Init = -1;
132 public static final int NoMedia = 0;
133 public static final int Idle = 1;
134 public static final int Pending = 2;
135 public static final int Checking = 3;
136 public static final int Mounted = 4;
137 public static final int Unmounting = 5;
138 public static final int Formatting = 6;
139 public static final int Shared = 7;
140 public static final int SharedMnt = 8;
141 }
142
San Mehat4270e1e2010-01-29 05:32:19 -0800143 /*
144 * Internal vold response code constants
145 */
San Mehat22dd86e2010-01-12 12:21:18 -0800146 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800147 /*
148 * 100 series - Requestion action was initiated; expect another reply
149 * before proceeding with a new command.
150 */
San Mehat22dd86e2010-01-12 12:21:18 -0800151 public static final int VolumeListResult = 110;
152 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800153 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800154
San Mehat4270e1e2010-01-29 05:32:19 -0800155 /*
156 * 200 series - Requestion action has been successfully completed.
157 */
158 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800159 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800160 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800161
San Mehat4270e1e2010-01-29 05:32:19 -0800162 /*
163 * 400 series - Command was accepted, but the requested action
164 * did not take place.
165 */
166 public static final int OpFailedNoMedia = 401;
167 public static final int OpFailedMediaBlank = 402;
168 public static final int OpFailedMediaCorrupt = 403;
169 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800170 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700171 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800172
173 /*
174 * 600 series - Unsolicited broadcasts.
175 */
San Mehat22dd86e2010-01-12 12:21:18 -0800176 public static final int VolumeStateChange = 605;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700177 public static final int VolumeUuidChange = 613;
178 public static final int VolumeUserLabelChange = 614;
San Mehat22dd86e2010-01-12 12:21:18 -0800179 public static final int VolumeDiskInserted = 630;
180 public static final int VolumeDiskRemoved = 631;
181 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700182
183 /*
184 * 700 series - fstrim
185 */
186 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800187 }
188
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700189 private Context mContext;
190 private NativeDaemonConnector mConnector;
191
192 private final Object mVolumesLock = new Object();
193
194 /** When defined, base template for user-specific {@link StorageVolume}. */
195 private StorageVolume mEmulatedTemplate;
196
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700197 // TODO: separate storage volumes on per-user basis
198
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700200 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
201 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800202 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700203 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
204 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800205 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700206 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
207
208 private volatile boolean mSystemReady = false;
209
San Mehat4270e1e2010-01-29 05:32:19 -0800210 private PackageManagerService mPms;
211 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700212 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800213 // Used as a lock for methods that register/unregister listeners.
214 final private ArrayList<MountServiceBinderListener> mListeners =
215 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800216 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
217 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800218 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800219
San Mehat6cdd9c02010-02-09 14:45:20 -0800220 /**
221 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800222 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800223 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800224 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800225
Kenny Root02c87302010-07-01 08:10:18 -0700226 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700227 * The size of the crypto algorithm key in bits for OBB files. Currently
228 * Twofish is used which takes 128-bit keys.
229 */
230 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
231
232 /**
233 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
234 * 1024 is reasonably secure and not too slow.
235 */
236 private static final int PBKDF2_HASH_ROUNDS = 1024;
237
238 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700239 * Mounted OBB tracking information. Used to track the current state of all
240 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700241 */
Kenny Root735de3b2010-09-30 14:11:39 -0700242 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700243
244 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700245 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
246
247 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700248 public ObbState(String rawPath, String canonicalPath, int callingUid,
249 IObbActionListener token, int nonce) {
250 this.rawPath = rawPath;
251 this.canonicalPath = canonicalPath.toString();
252
253 final int userId = UserHandle.getUserId(callingUid);
254 this.ownerPath = buildObbPath(canonicalPath, userId, false);
255 this.voldPath = buildObbPath(canonicalPath, userId, true);
256
257 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700258 this.token = token;
259 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700260 }
261
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700262 final String rawPath;
263 final String canonicalPath;
264 final String ownerPath;
265 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700266
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700267 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
Kenny Rootaf9d6672010-10-08 09:21:39 -0700269 // Token of remote Binder caller
270 final IObbActionListener token;
271
272 // Identifier to pass back to the token
273 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700274
Kenny Root735de3b2010-09-30 14:11:39 -0700275 public IBinder getBinder() {
276 return token.asBinder();
277 }
278
Kenny Roota02b8b02010-08-05 16:14:17 -0700279 @Override
280 public void binderDied() {
281 ObbAction action = new UnmountObbAction(this, true);
282 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700283 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700284
Kenny Root5919ac62010-10-05 09:49:40 -0700285 public void link() throws RemoteException {
286 getBinder().linkToDeath(this, 0);
287 }
288
289 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700290 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700291 }
Kenny Root38cf8862010-09-26 14:18:51 -0700292
293 @Override
294 public String toString() {
295 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700296 sb.append("rawPath=").append(rawPath);
297 sb.append(",canonicalPath=").append(canonicalPath);
298 sb.append(",ownerPath=").append(ownerPath);
299 sb.append(",voldPath=").append(voldPath);
300 sb.append(",ownerGid=").append(ownerGid);
301 sb.append(",token=").append(token);
302 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700303 sb.append('}');
304 return sb.toString();
305 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700306 }
307
308 // OBB Action Handler
309 final private ObbActionHandler mObbActionHandler;
310
311 // OBB action handler messages
312 private static final int OBB_RUN_ACTION = 1;
313 private static final int OBB_MCS_BOUND = 2;
314 private static final int OBB_MCS_UNBIND = 3;
315 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700316 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700317
318 /*
319 * Default Container Service information
320 */
321 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
322 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
323
324 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
325
326 class DefaultContainerConnection implements ServiceConnection {
327 public void onServiceConnected(ComponentName name, IBinder service) {
328 if (DEBUG_OBB)
329 Slog.i(TAG, "onServiceConnected");
330 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
331 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
332 }
333
334 public void onServiceDisconnected(ComponentName name) {
335 if (DEBUG_OBB)
336 Slog.i(TAG, "onServiceDisconnected");
337 }
338 };
339
340 // Used in the ObbActionHandler
341 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700342
343 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800344 private static final int H_UNMOUNT_PM_UPDATE = 1;
345 private static final int H_UNMOUNT_PM_DONE = 2;
346 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700347 private static final int H_SYSTEM_READY = 4;
348
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800349 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
350 private static final int MAX_UNMOUNT_RETRIES = 4;
351
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800352 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700353 final String path;
354 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700355 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800356 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800357
Ben Komalo13c71972011-09-07 16:35:56 -0700358 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359 retries = 0;
360 this.path = path;
361 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700362 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800363 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800364
365 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700366 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700367 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800368 }
369 }
370
371 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700372 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800373
374 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700375 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800376 this.method = method;
377 }
378
379 @Override
380 void handleFinished() {
381 super.handleFinished();
382 doShareUnshareVolume(path, method, true);
383 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800384 }
385
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800386 class ShutdownCallBack extends UnmountCallBack {
387 IMountShutdownObserver observer;
388 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700389 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800390 this.observer = observer;
391 }
392
393 @Override
394 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700395 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800396 if (observer != null) {
397 try {
398 observer.onShutDownComplete(ret);
399 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700400 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800401 }
402 }
403 }
404 }
405
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400406 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800407 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700408 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800409
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400410 MountServiceHandler(Looper l) {
411 super(l);
412 }
413
Jason parks5af0b912010-11-29 09:05:25 -0600414 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800415 public void handleMessage(Message msg) {
416 switch (msg.what) {
417 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700418 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800419 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
420 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700421 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800422 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700423 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700424 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700425 mUpdatingStatus = true;
426 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800427 }
428 break;
429 }
430 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700431 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700432 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700433 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800434 int size = mForceUnmounts.size();
435 int sizeArr[] = new int[size];
436 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700437 // Kill processes holding references first
438 ActivityManagerService ams = (ActivityManagerService)
439 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800440 for (int i = 0; i < size; i++) {
441 UnmountCallBack ucb = mForceUnmounts.get(i);
442 String path = ucb.path;
443 boolean done = false;
444 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800445 done = true;
446 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800447 int pids[] = getStorageUsers(path);
448 if (pids == null || pids.length == 0) {
449 done = true;
450 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800451 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800452 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700453 // Confirm if file references have been freed.
454 pids = getStorageUsers(path);
455 if (pids == null || pids.length == 0) {
456 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800457 }
458 }
459 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700460 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
461 // Retry again
462 Slog.i(TAG, "Retrying to kill storage users again");
463 mHandler.sendMessageDelayed(
464 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
465 ucb.retries++),
466 RETRY_UNMOUNT_DELAY);
467 } else {
468 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
469 Slog.i(TAG, "Failed to unmount media inspite of " +
470 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
471 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800472 sizeArr[sizeArrN++] = i;
473 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
474 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800475 }
476 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800477 // Remove already processed elements from list.
478 for (int i = (sizeArrN-1); i >= 0; i--) {
479 mForceUnmounts.remove(sizeArr[i]);
480 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800481 break;
482 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700483 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700484 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800485 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800486 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800487 break;
488 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700489 case H_SYSTEM_READY: {
490 try {
491 handleSystemReady();
492 } catch (Exception ex) {
493 Slog.e(TAG, "Boot-time mount exception", ex);
494 }
495 break;
496 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800497 }
498 }
499 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700500
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700501 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800502
Kenny Root51a573c2012-05-17 13:30:28 -0700503 void waitForAsecScan() {
504 waitForLatch(mAsecsScanned);
505 }
506
San Mehat207e5382010-02-04 20:46:54 -0800507 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700508 waitForLatch(mConnectedSignal);
509 }
510
511 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700512 for (;;) {
513 try {
514 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800515 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700516 } else {
517 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
518 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800519 }
Kenny Root51a573c2012-05-17 13:30:28 -0700520 } catch (InterruptedException e) {
521 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800522 }
San Mehat207e5382010-02-04 20:46:54 -0800523 }
San Mehat1f6301e2010-01-07 22:40:27 -0800524 }
Kenny Root02c87302010-07-01 08:10:18 -0700525
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700526 private void handleSystemReady() {
527 // Snapshot current volume states since it's not safe to call into vold
528 // while holding locks.
529 final HashMap<String, String> snapshot;
530 synchronized (mVolumesLock) {
531 snapshot = new HashMap<String, String>(mVolumeStates);
532 }
533
534 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
535 final String path = entry.getKey();
536 final String state = entry.getValue();
537
538 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
539 int rc = doMountVolume(path);
540 if (rc != StorageResultCode.OperationSucceeded) {
541 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
542 rc));
543 }
544 } else if (state.equals(Environment.MEDIA_SHARED)) {
545 /*
546 * Bootstrap UMS enabled state since vold indicates
547 * the volume is shared (runtime restart while ums enabled)
548 */
549 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
550 VolumeState.Shared);
551 }
552 }
553
554 // Push mounted state for all emulated storage
555 synchronized (mVolumesLock) {
556 for (StorageVolume volume : mVolumes) {
557 if (volume.isEmulated()) {
558 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
559 }
560 }
561 }
562
563 /*
564 * If UMS was connected on boot, send the connected event
565 * now that we're up.
566 */
567 if (mSendUmsConnectedOnBoot) {
568 sendUmsIntent(true);
569 mSendUmsConnectedOnBoot = false;
570 }
571 }
572
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700573 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
574 @Override
575 public void onReceive(Context context, Intent intent) {
576 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
577 if (userId == -1) return;
578 final UserHandle user = new UserHandle(userId);
579
580 final String action = intent.getAction();
581 if (Intent.ACTION_USER_ADDED.equals(action)) {
582 synchronized (mVolumesLock) {
583 createEmulatedVolumeForUserLocked(user);
584 }
585
586 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
587 synchronized (mVolumesLock) {
588 final List<StorageVolume> toRemove = Lists.newArrayList();
589 for (StorageVolume volume : mVolumes) {
590 if (user.equals(volume.getOwner())) {
591 toRemove.add(volume);
592 }
593 }
594 for (StorageVolume volume : toRemove) {
595 removeVolumeLocked(volume);
596 }
597 }
598 }
599 }
600 };
601
602 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
603 @Override
604 public void onReceive(Context context, Intent intent) {
605 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
606 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
607 notifyShareAvailabilityChange(available);
608 }
609 };
610
Svetoslava7452ee2013-03-20 12:06:59 -0700611 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
612 @Override
613 public void onReceive(Context context, Intent intent) {
614 waitForReady();
615 String action = intent.getAction();
616 // Since fstrim will be run on a daily basis we do not expect
617 // fstrim to be too long, so it is not interruptible. We will
618 // implement interruption only in case we see issues.
619 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
620 try {
621 // This method runs on the handler thread,
622 // so it is safe to directly call into vold.
623 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700624 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700625 } catch (NativeDaemonConnectorException ndce) {
626 Slog.e(TAG, "Failed to run fstrim!");
627 }
628 }
629 }
630 };
631
San Mehat4270e1e2010-01-29 05:32:19 -0800632 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
633 final IMountServiceListener mListener;
634
635 MountServiceBinderListener(IMountServiceListener listener) {
636 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700637
San Mehat91c77612010-01-07 10:39:41 -0800638 }
639
San Mehat4270e1e2010-01-29 05:32:19 -0800640 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700641 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700642 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800643 mListeners.remove(this);
644 mListener.asBinder().unlinkToDeath(this, 0);
645 }
646 }
647 }
648
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800649 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800650 // TODO: Add support for multiple share methods
651 if (!method.equals("ums")) {
652 throw new IllegalArgumentException(String.format("Method %s not supported", method));
653 }
654
San Mehat4270e1e2010-01-29 05:32:19 -0800655 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800656 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800657 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700658 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800659 }
San Mehat4270e1e2010-01-29 05:32:19 -0800660 }
661
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700662 private void updatePublicVolumeState(StorageVolume volume, String state) {
663 final String path = volume.getPath();
664 final String oldState;
665 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400666 oldState = mVolumeStates.put(path, state);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700667 volume.setState(state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400668 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700669
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400670 if (state.equals(oldState)) {
671 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
672 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800673 return;
674 }
San Mehatb1043402010-02-05 08:26:50 -0800675
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400676 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700677
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700678 // Tell PackageManager about changes to primary volume state, but only
679 // when not emulated.
680 if (volume.isPrimary() && !volume.isEmulated()) {
681 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
682 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400683
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700684 /*
685 * Some OBBs might have been unmounted when this volume was
686 * unmounted, so send a message to the handler to let it know to
687 * remove those from the list of mounted OBBS.
688 */
689 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
690 OBB_FLUSH_MOUNT_STATE, path));
691 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
692 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400693 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800694 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700695
San Mehat4270e1e2010-01-29 05:32:19 -0800696 synchronized (mListeners) {
697 for (int i = mListeners.size() -1; i >= 0; i--) {
698 MountServiceBinderListener bl = mListeners.get(i);
699 try {
San Mehatb1043402010-02-05 08:26:50 -0800700 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800701 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700702 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800703 mListeners.remove(i);
704 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700705 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800706 }
707 }
708 }
709 }
710
711 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800712 * Callback from NativeDaemonConnector
713 */
714 public void onDaemonConnected() {
715 /*
716 * Since we'll be calling back into the NativeDaemonConnector,
717 * we need to do our work in a new thread.
718 */
Kenny Root51a573c2012-05-17 13:30:28 -0700719 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600720 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800721 public void run() {
722 /**
723 * Determine media state and UMS detection status
724 */
San Mehat4270e1e2010-01-29 05:32:19 -0800725 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800726 final String[] vols = NativeDaemonEvent.filterMessageList(
727 mConnector.executeForList("volume", "list"),
728 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800729 for (String volstr : vols) {
730 String[] tok = volstr.split(" ");
731 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400732 String path = tok[1];
733 String state = Environment.MEDIA_REMOVED;
734
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700735 final StorageVolume volume;
736 synchronized (mVolumesLock) {
737 volume = mVolumesByPath.get(path);
738 }
739
San Mehat4270e1e2010-01-29 05:32:19 -0800740 int st = Integer.parseInt(tok[2]);
741 if (st == VolumeState.NoMedia) {
742 state = Environment.MEDIA_REMOVED;
743 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800744 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800745 } else if (st == VolumeState.Mounted) {
746 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700747 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800748 } else if (st == VolumeState.Shared) {
749 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700750 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800751 } else {
752 throw new Exception(String.format("Unexpected state %d", st));
753 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400754
755 if (state != null) {
756 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700757 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400758 }
San Mehat4270e1e2010-01-29 05:32:19 -0800759 }
760 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700761 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700762 final StorageVolume primary = getPrimaryPhysicalVolume();
763 if (primary != null) {
764 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
765 }
San Mehat4270e1e2010-01-29 05:32:19 -0800766 }
767
San Mehat207e5382010-02-04 20:46:54 -0800768 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600769 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800770 * the hounds!
771 */
Kenny Root51a573c2012-05-17 13:30:28 -0700772 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700773
774 // Let package manager load internal ASECs.
775 mPms.scanAvailableAsecs();
776
777 // Notify people waiting for ASECs to be scanned that it's done.
778 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800779 }
780 }.start();
781 }
782
783 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800784 * Callback from NativeDaemonConnector
785 */
786 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800787 if (DEBUG_EVENTS) {
788 StringBuilder builder = new StringBuilder();
789 builder.append("onEvent::");
790 builder.append(" raw= " + raw);
791 if (cooked != null) {
792 builder.append(" cooked = " );
793 for (String str : cooked) {
794 builder.append(" " + str);
795 }
796 }
San Mehata5078592010-03-25 09:36:54 -0700797 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800798 }
San Mehat4270e1e2010-01-29 05:32:19 -0800799 if (code == VoldResponseCode.VolumeStateChange) {
800 /*
801 * One of the volumes we're managing has changed state.
802 * Format: "NNN Volume <label> <path> state changed
803 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
804 */
805 notifyVolumeStateChange(
806 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
807 Integer.parseInt(cooked[10]));
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700808 } else if (code == VoldResponseCode.VolumeUuidChange) {
809 // Format: nnn <label> <path> <uuid>
810 final String path = cooked[2];
811 final String uuid = (cooked.length > 3) ? cooked[3] : null;
812
813 final StorageVolume vol = mVolumesByPath.get(path);
814 if (vol != null) {
815 vol.setUuid(uuid);
816 }
817
818 } else if (code == VoldResponseCode.VolumeUserLabelChange) {
819 // Format: nnn <label> <path> <label>
820 final String path = cooked[2];
821 final String userLabel = (cooked.length > 3) ? cooked[3] : null;
822
823 final StorageVolume vol = mVolumesByPath.get(path);
824 if (vol != null) {
825 vol.setUserLabel(userLabel);
826 }
827
San Mehat4270e1e2010-01-29 05:32:19 -0800828 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
829 (code == VoldResponseCode.VolumeDiskRemoved) ||
830 (code == VoldResponseCode.VolumeBadRemoval)) {
831 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
832 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
833 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400834 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800835 final String label = cooked[2];
836 final String path = cooked[3];
837 int major = -1;
838 int minor = -1;
839
840 try {
841 String devComp = cooked[6].substring(1, cooked[6].length() -1);
842 String[] devTok = devComp.split(":");
843 major = Integer.parseInt(devTok[0]);
844 minor = Integer.parseInt(devTok[1]);
845 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700846 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800847 }
848
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700849 final StorageVolume volume;
850 final String state;
851 synchronized (mVolumesLock) {
852 volume = mVolumesByPath.get(path);
853 state = mVolumeStates.get(path);
854 }
855
San Mehat4270e1e2010-01-29 05:32:19 -0800856 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700857 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600858 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800859 public void run() {
860 try {
861 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800862 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700863 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800864 }
865 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700866 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800867 }
868 }
869 }.start();
870 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
871 /*
872 * This event gets trumped if we're already in BAD_REMOVAL state
873 */
874 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
875 return true;
876 }
877 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700878 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700879 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Johan Redestig0464c072014-01-18 22:46:56 +0100880 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800881
San Mehata5078592010-03-25 09:36:54 -0700882 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700883 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400884 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800885 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700886 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800887 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700888 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200889 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800890
San Mehata5078592010-03-25 09:36:54 -0700891 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700892 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400893 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700894 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700895 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800896 } else {
San Mehata5078592010-03-25 09:36:54 -0700897 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800898 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400899
900 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700901 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400902 }
San Mehat4270e1e2010-01-29 05:32:19 -0800903 } else {
904 return false;
905 }
906
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400907 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800908 }
909
San Mehat207e5382010-02-04 20:46:54 -0800910 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700911 final StorageVolume volume;
912 final String state;
913 synchronized (mVolumesLock) {
914 volume = mVolumesByPath.get(path);
915 state = getVolumeState(path);
916 }
917
918 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800919
Mike Lockwooda5250c92011-05-23 13:44:04 -0400920 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800921
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500922 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700923 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700924 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500925 }
926
San Mehat4270e1e2010-01-29 05:32:19 -0800927 if (newState == VolumeState.Init) {
928 } else if (newState == VolumeState.NoMedia) {
929 // NoMedia is handled via Disk Remove events
930 } else if (newState == VolumeState.Idle) {
931 /*
932 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
933 * if we're in the process of enabling UMS
934 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700935 if (!state.equals(
936 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
937 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800938 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700939 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700940 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400941 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800942 }
943 } else if (newState == VolumeState.Pending) {
944 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700945 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700946 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400947 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800948 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700949 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700950 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400951 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800952 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400953 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800954 } else if (newState == VolumeState.Formatting) {
955 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700956 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800957 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700958 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
959 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800960
San Mehata5078592010-03-25 09:36:54 -0700961 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700962 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400963 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700964 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800965 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700966 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800967 return;
968 } else {
San Mehata5078592010-03-25 09:36:54 -0700969 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800970 }
971
Mike Lockwooda5250c92011-05-23 13:44:04 -0400972 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700973 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800974 }
975 }
976
San Mehat207e5382010-02-04 20:46:54 -0800977 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800978 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800979
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700980 final StorageVolume volume;
981 synchronized (mVolumesLock) {
982 volume = mVolumesByPath.get(path);
983 }
984
San Mehata5078592010-03-25 09:36:54 -0700985 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800986 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800987 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800988 } catch (NativeDaemonConnectorException e) {
989 /*
990 * Mount failed for some reason
991 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400992 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800993 int code = e.getCode();
994 if (code == VoldResponseCode.OpFailedNoMedia) {
995 /*
996 * Attempt to mount but no media inserted
997 */
San Mehatb1043402010-02-05 08:26:50 -0800998 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -0800999 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -07001000 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -08001001 /*
1002 * Media is blank or does not contain a supported filesystem
1003 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001004 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001005 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -08001006 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -08001007 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -07001008 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -08001009 /*
1010 * Volume consistency check failed
1011 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001012 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001013 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -08001014 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001015 } else {
San Mehatb1043402010-02-05 08:26:50 -08001016 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001017 }
1018
1019 /*
1020 * Send broadcast intent (if required for the failure)
1021 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001022 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001023 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001024 }
1025 }
1026
1027 return rc;
1028 }
1029
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001030 /*
1031 * If force is not set, we do not unmount if there are
1032 * processes holding references to the volume about to be unmounted.
1033 * If force is set, all the processes holding references need to be
1034 * killed via the ActivityManager before actually unmounting the volume.
1035 * This might even take a while and might be retried after timed delays
1036 * to make sure we dont end up in an instable state and kill some core
1037 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001038 * If removeEncryption is set, force is implied, and the system will remove any encryption
1039 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001040 */
Ben Komalo13c71972011-09-07 16:35:56 -07001041 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001042 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001043 return VoldResponseCode.OpFailedVolNotMounted;
1044 }
Kenny Rootaa485402010-09-14 14:49:41 -07001045
1046 /*
1047 * Force a GC to make sure AssetManagers in other threads of the
1048 * system_server are cleaned up. We have to do this since AssetManager
1049 * instances are kept as a WeakReference and it's possible we have files
1050 * open on the external storage.
1051 */
1052 Runtime.getRuntime().gc();
1053
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001054 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001055 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001056 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001057 final Command cmd = new Command("volume", "unmount", path);
1058 if (removeEncryption) {
1059 cmd.appendArg("force_and_revert");
1060 } else if (force) {
1061 cmd.appendArg("force");
1062 }
1063 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001064 // We unmounted the volume. None of the asec containers are available now.
1065 synchronized (mAsecMountSet) {
1066 mAsecMountSet.clear();
1067 }
San Mehatb1043402010-02-05 08:26:50 -08001068 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001069 } catch (NativeDaemonConnectorException e) {
1070 // Don't worry about mismatch in PackageManager since the
1071 // call back will handle the status changes any way.
1072 int code = e.getCode();
1073 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001074 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001075 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1076 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001077 } else {
San Mehatb1043402010-02-05 08:26:50 -08001078 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001079 }
1080 }
1081 }
1082
1083 private int doFormatVolume(String path) {
1084 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001085 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001086 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001087 } catch (NativeDaemonConnectorException e) {
1088 int code = e.getCode();
1089 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001090 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001091 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001092 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001093 } else {
San Mehatb1043402010-02-05 08:26:50 -08001094 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001095 }
1096 }
1097 }
1098
San Mehatb1043402010-02-05 08:26:50 -08001099 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001100 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001101 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001102 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001103 } catch (NativeDaemonConnectorException ex) {
1104 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1105 return false;
1106 }
San Mehatb1043402010-02-05 08:26:50 -08001107
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001108 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1109 return event.getMessage().endsWith("enabled");
1110 } else {
1111 return false;
San Mehatb1043402010-02-05 08:26:50 -08001112 }
San Mehatb1043402010-02-05 08:26:50 -08001113 }
1114
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001115 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001116 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001117 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001118 for (int i = mListeners.size() -1; i >= 0; i--) {
1119 MountServiceBinderListener bl = mListeners.get(i);
1120 try {
San Mehatb1043402010-02-05 08:26:50 -08001121 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001122 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001123 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001124 mListeners.remove(i);
1125 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001126 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001127 }
1128 }
1129 }
1130
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001131 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001132 sendUmsIntent(avail);
1133 } else {
1134 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001135 }
San Mehat2fe718a2010-03-11 12:01:49 -08001136
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001137 final StorageVolume primary = getPrimaryPhysicalVolume();
1138 if (avail == false && primary != null
1139 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1140 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001141 /*
1142 * USB mass storage disconnected while enabled
1143 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001144 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001145 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001146 public void run() {
1147 try {
1148 int rc;
San Mehata5078592010-03-25 09:36:54 -07001149 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001150 doShareUnshareVolume(path, "ums", false);
1151 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001152 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001153 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1154 path, rc));
1155 }
1156 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001157 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001158 }
1159 }
1160 }.start();
1161 }
San Mehat4270e1e2010-01-29 05:32:19 -08001162 }
1163
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001164 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1165 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1166 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
Johan Redestig0464c072014-01-18 22:46:56 +01001167 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001168 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1169 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001170 }
1171
San Mehat6a965af22010-02-24 17:47:30 -08001172 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001173 mContext.sendBroadcastAsUser(
1174 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1175 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001176 }
1177
San Mehat207e5382010-02-04 20:46:54 -08001178 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001179 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1180 throw new SecurityException(String.format("Requires %s permission", perm));
1181 }
1182 }
1183
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001184 // Storage list XML tags
1185 private static final String TAG_STORAGE_LIST = "StorageList";
1186 private static final String TAG_STORAGE = "storage";
1187
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001188 private void readStorageListLocked() {
1189 mVolumes.clear();
1190 mVolumeStates.clear();
1191
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001192 Resources resources = mContext.getResources();
1193
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001194 int id = com.android.internal.R.xml.storage_list;
1195 XmlResourceParser parser = resources.getXml(id);
1196 AttributeSet attrs = Xml.asAttributeSet(parser);
1197
1198 try {
1199 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1200 while (true) {
1201 XmlUtils.nextElement(parser);
1202
1203 String element = parser.getName();
1204 if (element == null) break;
1205
1206 if (TAG_STORAGE.equals(element)) {
1207 TypedArray a = resources.obtainAttributes(attrs,
1208 com.android.internal.R.styleable.Storage);
1209
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001210 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001211 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001212 int descriptionId = a.getResourceId(
1213 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001214 CharSequence description = a.getText(
1215 com.android.internal.R.styleable.Storage_storageDescription);
1216 boolean primary = a.getBoolean(
1217 com.android.internal.R.styleable.Storage_primary, false);
1218 boolean removable = a.getBoolean(
1219 com.android.internal.R.styleable.Storage_removable, false);
1220 boolean emulated = a.getBoolean(
1221 com.android.internal.R.styleable.Storage_emulated, false);
1222 int mtpReserve = a.getInt(
1223 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001224 boolean allowMassStorage = a.getBoolean(
1225 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001226 // resource parser does not support longs, so XML value is in megabytes
1227 long maxFileSize = a.getInt(
1228 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001229
1230 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1231 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001232 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001233 " allowMassStorage: " + allowMassStorage +
1234 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001235
1236 if (emulated) {
1237 // For devices with emulated storage, we create separate
1238 // volumes for each known user.
1239 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1240 true, mtpReserve, false, maxFileSize, null);
1241
1242 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001243 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001244 createEmulatedVolumeForUserLocked(user.getUserHandle());
1245 }
1246
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001247 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001248 if (path == null || description == null) {
1249 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001250 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001251 final StorageVolume volume = new StorageVolume(new File(path),
1252 descriptionId, primary, removable, emulated, mtpReserve,
1253 allowMassStorage, maxFileSize, null);
1254 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001255
1256 // Until we hear otherwise, treat as unmounted
1257 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001258 volume.setState(Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001259 }
1260 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001261
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001262 a.recycle();
1263 }
1264 }
1265 } catch (XmlPullParserException e) {
1266 throw new RuntimeException(e);
1267 } catch (IOException e) {
1268 throw new RuntimeException(e);
1269 } finally {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001270 // Compute storage ID for each physical volume; emulated storage is
1271 // always 0 when defined.
1272 int index = isExternalStorageEmulated() ? 1 : 0;
1273 for (StorageVolume volume : mVolumes) {
1274 if (!volume.isEmulated()) {
1275 volume.setStorageId(index++);
1276 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001277 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001278 parser.close();
1279 }
1280 }
1281
San Mehat4270e1e2010-01-29 05:32:19 -08001282 /**
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001283 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1284 * using {@link #mEmulatedTemplate} as template.
1285 */
1286 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1287 if (mEmulatedTemplate == null) {
1288 throw new IllegalStateException("Missing emulated volume multi-user template");
1289 }
1290
1291 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1292 final File path = userEnv.getExternalStorageDirectory();
1293 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1294 volume.setStorageId(0);
1295 addVolumeLocked(volume);
1296
1297 if (mSystemReady) {
1298 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1299 } else {
1300 // Place stub status for early callers to find
1301 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001302 volume.setState(Environment.MEDIA_MOUNTED);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001303 }
1304 }
1305
1306 private void addVolumeLocked(StorageVolume volume) {
1307 Slog.d(TAG, "addVolumeLocked() " + volume);
1308 mVolumes.add(volume);
1309 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1310 if (existing != null) {
1311 throw new IllegalStateException(
1312 "Volume at " + volume.getPath() + " already exists: " + existing);
1313 }
1314 }
1315
1316 private void removeVolumeLocked(StorageVolume volume) {
1317 Slog.d(TAG, "removeVolumeLocked() " + volume);
1318 mVolumes.remove(volume);
1319 mVolumesByPath.remove(volume.getPath());
1320 mVolumeStates.remove(volume.getPath());
1321 }
1322
1323 private StorageVolume getPrimaryPhysicalVolume() {
1324 synchronized (mVolumesLock) {
1325 for (StorageVolume volume : mVolumes) {
1326 if (volume.isPrimary() && !volume.isEmulated()) {
1327 return volume;
1328 }
1329 }
1330 }
1331 return null;
1332 }
1333
1334 /**
San Mehat207e5382010-02-04 20:46:54 -08001335 * Constructs a new MountService instance
1336 *
1337 * @param context Binder context for this service
1338 */
1339 public MountService(Context context) {
1340 mContext = context;
1341
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001342 synchronized (mVolumesLock) {
1343 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001344 }
1345
San Mehat207e5382010-02-04 20:46:54 -08001346 // XXX: This will go away soon in favor of IMountServiceObserver
1347 mPms = (PackageManagerService) ServiceManager.getService("package");
1348
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001349 HandlerThread hthread = new HandlerThread(TAG);
1350 hthread.start();
1351 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001352
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001353 // Watch for user changes
1354 final IntentFilter userFilter = new IntentFilter();
1355 userFilter.addAction(Intent.ACTION_USER_ADDED);
1356 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1357 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1358
1359 // Watch for USB changes on primary volume
1360 final StorageVolume primary = getPrimaryPhysicalVolume();
1361 if (primary != null && primary.allowMassStorage()) {
1362 mContext.registerReceiver(
1363 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1364 }
1365
Svetoslava7452ee2013-03-20 12:06:59 -07001366 // Watch for idle maintenance changes
1367 IntentFilter idleMaintenanceFilter = new IntentFilter();
1368 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1369 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1370 idleMaintenanceFilter, null, mHandler);
1371
Kenny Roota02b8b02010-08-05 16:14:17 -07001372 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001373 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001374
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001375 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001376 * Create the connection to vold with a maximum queue of twice the
1377 * amount of containers we'd ever expect to have. This keeps an
1378 * "asec list" from blocking a thread repeatedly.
1379 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001380 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001381
Kenny Root305bcbf2010-09-03 07:56:38 -07001382 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001383 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001384
Kenny Root07714d42011-08-17 17:49:28 -07001385 // Add ourself to the Watchdog monitors if enabled.
1386 if (WATCHDOG_ENABLE) {
1387 Watchdog.getInstance().addMonitor(this);
1388 }
San Mehat207e5382010-02-04 20:46:54 -08001389 }
1390
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001391 public void systemReady() {
1392 mSystemReady = true;
1393 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1394 }
1395
San Mehat207e5382010-02-04 20:46:54 -08001396 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001397 * Exposed API calls below here
1398 */
1399
1400 public void registerListener(IMountServiceListener listener) {
1401 synchronized (mListeners) {
1402 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1403 try {
1404 listener.asBinder().linkToDeath(bl, 0);
1405 mListeners.add(bl);
1406 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001407 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001408 }
1409 }
1410 }
1411
1412 public void unregisterListener(IMountServiceListener listener) {
1413 synchronized (mListeners) {
1414 for(MountServiceBinderListener bl : mListeners) {
Niklas Brunlidd64fe0f2013-07-05 08:54:03 +02001415 if (bl.mListener.asBinder() == listener.asBinder()) {
San Mehat4270e1e2010-01-29 05:32:19 -08001416 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001417 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001418 return;
1419 }
1420 }
1421 }
1422 }
1423
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001424 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001425 validatePermission(android.Manifest.permission.SHUTDOWN);
1426
San Mehata5078592010-03-25 09:36:54 -07001427 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001428 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001429 for (String path : mVolumeStates.keySet()) {
1430 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001431
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001432 if (state.equals(Environment.MEDIA_SHARED)) {
1433 /*
1434 * If the media is currently shared, unshare it.
1435 * XXX: This is still dangerous!. We should not
1436 * be rebooting at *all* if UMS is enabled, since
1437 * the UMS host could have dirty FAT cache entries
1438 * yet to flush.
1439 */
1440 setUsbMassStorageEnabled(false);
1441 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1442 /*
1443 * If the media is being checked, then we need to wait for
1444 * it to complete before being able to proceed.
1445 */
1446 // XXX: @hackbod - Should we disable the ANR timer here?
1447 int retries = 30;
1448 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1449 try {
1450 Thread.sleep(1000);
1451 } catch (InterruptedException iex) {
1452 Slog.e(TAG, "Interrupted while waiting for media", iex);
1453 break;
1454 }
1455 state = Environment.getExternalStorageState();
1456 }
1457 if (retries == 0) {
1458 Slog.e(TAG, "Timed out waiting for media to check");
1459 }
San Mehat91c77612010-01-07 10:39:41 -08001460 }
San Mehat91c77612010-01-07 10:39:41 -08001461
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001462 if (state.equals(Environment.MEDIA_MOUNTED)) {
1463 // Post a unmount message.
1464 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1465 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1466 } else if (observer != null) {
1467 /*
1468 * Observer is waiting for onShutDownComplete when we are done.
1469 * Since nothing will be done send notification directly so shutdown
1470 * sequence can continue.
1471 */
1472 try {
1473 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1474 } catch (RemoteException e) {
1475 Slog.w(TAG, "RemoteException when shutting down");
1476 }
1477 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001478 }
San Mehat4270e1e2010-01-29 05:32:19 -08001479 }
1480 }
1481
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001482 private boolean getUmsEnabling() {
1483 synchronized (mListeners) {
1484 return mUmsEnabling;
1485 }
1486 }
1487
1488 private void setUmsEnabling(boolean enable) {
1489 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001490 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001491 }
1492 }
1493
San Mehatb1043402010-02-05 08:26:50 -08001494 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001495 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001496
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001497 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001498 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001499 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001500 synchronized (mListeners) {
1501 return mUmsAvailable;
1502 }
San Mehatb1043402010-02-05 08:26:50 -08001503 }
1504
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001505 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001506 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001507 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001508
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001509 final StorageVolume primary = getPrimaryPhysicalVolume();
1510 if (primary == null) return;
1511
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001512 // TODO: Add support for multiple share methods
1513
1514 /*
1515 * If the volume is mounted and we're enabling then unmount it
1516 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001517 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001518 String vs = getVolumeState(path);
1519 String method = "ums";
1520 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1521 // Override for isUsbMassStorageEnabled()
1522 setUmsEnabling(enable);
1523 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1524 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1525 // Clear override
1526 setUmsEnabling(false);
1527 }
1528 /*
1529 * If we disabled UMS then mount the volume
1530 */
1531 if (!enable) {
1532 doShareUnshareVolume(path, method, enable);
1533 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001534 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001535 " after disabling share method " + method);
1536 /*
1537 * Even though the mount failed, the unshare didn't so don't indicate an error.
1538 * The mountVolume() call will have set the storage state and sent the necessary
1539 * broadcasts.
1540 */
1541 }
1542 }
San Mehatb1043402010-02-05 08:26:50 -08001543 }
1544
1545 public boolean isUsbMassStorageEnabled() {
1546 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001547
1548 final StorageVolume primary = getPrimaryPhysicalVolume();
1549 if (primary != null) {
1550 return doGetVolumeShared(primary.getPath(), "ums");
1551 } else {
1552 return false;
1553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001555
San Mehat7fd0fee2009-12-17 07:12:23 -08001556 /**
1557 * @return state of the volume at the specified mount point
1558 */
San Mehat4270e1e2010-01-29 05:32:19 -08001559 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001560 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001561 String state = mVolumeStates.get(mountPoint);
1562 if (state == null) {
1563 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001564 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1565 state = Environment.MEDIA_REMOVED;
1566 } else {
1567 throw new IllegalArgumentException();
1568 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001569 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001570
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001571 return state;
1572 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001573 }
1574
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001575 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001576 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001577 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001578 }
1579
San Mehat4270e1e2010-01-29 05:32:19 -08001580 public int mountVolume(String path) {
1581 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001582
San Mehat207e5382010-02-04 20:46:54 -08001583 waitForReady();
1584 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586
Ben Komalo13c71972011-09-07 16:35:56 -07001587 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001588 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001589 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001591 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001592 if (DEBUG_UNMOUNT) {
1593 Slog.i(TAG, "Unmounting " + path
1594 + " force = " + force
1595 + " removeEncryption = " + removeEncryption);
1596 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001597 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1598 Environment.MEDIA_REMOVED.equals(volState) ||
1599 Environment.MEDIA_SHARED.equals(volState) ||
1600 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1601 // Media already unmounted or cannot be unmounted.
1602 // TODO return valid return code when adding observer call back.
1603 return;
1604 }
Ben Komalo13c71972011-09-07 16:35:56 -07001605 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001606 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608
San Mehat4270e1e2010-01-29 05:32:19 -08001609 public int formatVolume(String path) {
1610 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001611 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001612
San Mehat207e5382010-02-04 20:46:54 -08001613 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001616 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001617 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1618 waitForReady();
1619 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001620 final String[] r = NativeDaemonEvent.filterMessageList(
1621 mConnector.executeForList("storage", "users", path),
1622 VoldResponseCode.StorageUsersListResult);
1623
San Mehatc1b4ce92010-02-16 17:13:03 -08001624 // FMT: <pid> <process name>
1625 int[] data = new int[r.length];
1626 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001627 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001628 try {
1629 data[i] = Integer.parseInt(tok[0]);
1630 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001631 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001632 return new int[0];
1633 }
1634 }
1635 return data;
1636 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001637 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001638 return new int[0];
1639 }
1640 }
1641
San Mehatb1043402010-02-05 08:26:50 -08001642 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001643 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001644 if (primary != null) {
1645 boolean mounted = false;
1646 try {
1647 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001648 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001649 }
1650
1651 if (!mounted) {
1652 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1653 }
San Mehatb1043402010-02-05 08:26:50 -08001654 }
1655 }
1656
San Mehat4270e1e2010-01-29 05:32:19 -08001657 public String[] getSecureContainerList() {
1658 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001659 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001660 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001661
San Mehat4270e1e2010-01-29 05:32:19 -08001662 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001663 return NativeDaemonEvent.filterMessageList(
1664 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001665 } catch (NativeDaemonConnectorException e) {
1666 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668 }
San Mehat36972292010-01-06 11:06:32 -08001669
Kenny Root6dceb882012-04-12 14:23:49 -07001670 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1671 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001672 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001673 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001674 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001675
San Mehatb1043402010-02-05 08:26:50 -08001676 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001677 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001678 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1679 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001680 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001681 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001682 }
San Mehata181b212010-02-11 06:50:20 -08001683
1684 if (rc == StorageResultCode.OperationSucceeded) {
1685 synchronized (mAsecMountSet) {
1686 mAsecMountSet.add(id);
1687 }
1688 }
San Mehat4270e1e2010-01-29 05:32:19 -08001689 return rc;
San Mehat36972292010-01-06 11:06:32 -08001690 }
1691
San Mehat4270e1e2010-01-29 05:32:19 -08001692 public int finalizeSecureContainer(String id) {
1693 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001694 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001695
San Mehatb1043402010-02-05 08:26:50 -08001696 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001697 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001698 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001699 /*
1700 * Finalization does a remount, so no need
1701 * to update mAsecMountSet
1702 */
San Mehat4270e1e2010-01-29 05:32:19 -08001703 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001704 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001705 }
San Mehat4270e1e2010-01-29 05:32:19 -08001706 return rc;
San Mehat36972292010-01-06 11:06:32 -08001707 }
1708
Kenny Root6dceb882012-04-12 14:23:49 -07001709 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1710 validatePermission(android.Manifest.permission.ASEC_CREATE);
1711 warnOnNotMounted();
1712
1713 int rc = StorageResultCode.OperationSucceeded;
1714 try {
1715 mConnector.execute("asec", "fixperms", id, gid, filename);
1716 /*
1717 * Fix permissions does a remount, so no need to update
1718 * mAsecMountSet
1719 */
1720 } catch (NativeDaemonConnectorException e) {
1721 rc = StorageResultCode.OperationFailedInternalError;
1722 }
1723 return rc;
1724 }
1725
San Mehatd9709982010-02-18 11:43:03 -08001726 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001727 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001728 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001729 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001730
Kenny Rootaa485402010-09-14 14:49:41 -07001731 /*
1732 * Force a GC to make sure AssetManagers in other threads of the
1733 * system_server are cleaned up. We have to do this since AssetManager
1734 * instances are kept as a WeakReference and it's possible we have files
1735 * open on the external storage.
1736 */
1737 Runtime.getRuntime().gc();
1738
San Mehatb1043402010-02-05 08:26:50 -08001739 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001740 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001741 final Command cmd = new Command("asec", "destroy", id);
1742 if (force) {
1743 cmd.appendArg("force");
1744 }
1745 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001746 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001747 int code = e.getCode();
1748 if (code == VoldResponseCode.OpFailedStorageBusy) {
1749 rc = StorageResultCode.OperationFailedStorageBusy;
1750 } else {
1751 rc = StorageResultCode.OperationFailedInternalError;
1752 }
San Mehat02735bc2010-01-26 15:18:08 -08001753 }
San Mehata181b212010-02-11 06:50:20 -08001754
1755 if (rc == StorageResultCode.OperationSucceeded) {
1756 synchronized (mAsecMountSet) {
1757 if (mAsecMountSet.contains(id)) {
1758 mAsecMountSet.remove(id);
1759 }
1760 }
1761 }
1762
San Mehat4270e1e2010-01-29 05:32:19 -08001763 return rc;
San Mehat36972292010-01-06 11:06:32 -08001764 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001765
San Mehat4270e1e2010-01-29 05:32:19 -08001766 public int mountSecureContainer(String id, String key, int ownerUid) {
1767 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001768 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001769 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001770
San Mehata181b212010-02-11 06:50:20 -08001771 synchronized (mAsecMountSet) {
1772 if (mAsecMountSet.contains(id)) {
1773 return StorageResultCode.OperationFailedStorageMounted;
1774 }
1775 }
1776
San Mehatb1043402010-02-05 08:26:50 -08001777 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001778 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001779 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001780 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001781 int code = e.getCode();
1782 if (code != VoldResponseCode.OpFailedStorageBusy) {
1783 rc = StorageResultCode.OperationFailedInternalError;
1784 }
San Mehat02735bc2010-01-26 15:18:08 -08001785 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001786
1787 if (rc == StorageResultCode.OperationSucceeded) {
1788 synchronized (mAsecMountSet) {
1789 mAsecMountSet.add(id);
1790 }
1791 }
San Mehat4270e1e2010-01-29 05:32:19 -08001792 return rc;
San Mehat36972292010-01-06 11:06:32 -08001793 }
1794
San Mehatd9709982010-02-18 11:43:03 -08001795 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001796 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001797 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001798 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001799
San Mehat6cdd9c02010-02-09 14:45:20 -08001800 synchronized (mAsecMountSet) {
1801 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001802 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001803 }
1804 }
1805
Kenny Rootaa485402010-09-14 14:49:41 -07001806 /*
1807 * Force a GC to make sure AssetManagers in other threads of the
1808 * system_server are cleaned up. We have to do this since AssetManager
1809 * instances are kept as a WeakReference and it's possible we have files
1810 * open on the external storage.
1811 */
1812 Runtime.getRuntime().gc();
1813
San Mehatb1043402010-02-05 08:26:50 -08001814 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001815 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001816 final Command cmd = new Command("asec", "unmount", id);
1817 if (force) {
1818 cmd.appendArg("force");
1819 }
1820 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001821 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001822 int code = e.getCode();
1823 if (code == VoldResponseCode.OpFailedStorageBusy) {
1824 rc = StorageResultCode.OperationFailedStorageBusy;
1825 } else {
1826 rc = StorageResultCode.OperationFailedInternalError;
1827 }
San Mehat02735bc2010-01-26 15:18:08 -08001828 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001829
1830 if (rc == StorageResultCode.OperationSucceeded) {
1831 synchronized (mAsecMountSet) {
1832 mAsecMountSet.remove(id);
1833 }
1834 }
San Mehat4270e1e2010-01-29 05:32:19 -08001835 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001836 }
1837
San Mehat6cdd9c02010-02-09 14:45:20 -08001838 public boolean isSecureContainerMounted(String id) {
1839 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1840 waitForReady();
1841 warnOnNotMounted();
1842
1843 synchronized (mAsecMountSet) {
1844 return mAsecMountSet.contains(id);
1845 }
1846 }
1847
San Mehat4270e1e2010-01-29 05:32:19 -08001848 public int renameSecureContainer(String oldId, String newId) {
1849 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001850 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001851 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001852
San Mehata181b212010-02-11 06:50:20 -08001853 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001854 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001855 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001856 * changed while active, we must ensure both ids are not currently mounted.
1857 */
1858 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001859 return StorageResultCode.OperationFailedStorageMounted;
1860 }
1861 }
1862
San Mehatb1043402010-02-05 08:26:50 -08001863 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001864 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001865 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001866 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001867 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001868 }
San Mehata181b212010-02-11 06:50:20 -08001869
San Mehat4270e1e2010-01-29 05:32:19 -08001870 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001871 }
1872
San Mehat4270e1e2010-01-29 05:32:19 -08001873 public String getSecureContainerPath(String id) {
1874 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001875 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001876 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001877
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001878 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001879 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001880 event = mConnector.execute("asec", "path", id);
1881 event.checkCode(VoldResponseCode.AsecPathResult);
1882 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001883 } catch (NativeDaemonConnectorException e) {
1884 int code = e.getCode();
1885 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001886 Slog.i(TAG, String.format("Container '%s' not found", id));
1887 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001888 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001889 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001890 }
1891 }
San Mehat22dd86e2010-01-12 12:21:18 -08001892 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001893
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001894 public String getSecureContainerFilesystemPath(String id) {
1895 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1896 waitForReady();
1897 warnOnNotMounted();
1898
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001899 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001900 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001901 event = mConnector.execute("asec", "fspath", id);
1902 event.checkCode(VoldResponseCode.AsecPathResult);
1903 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001904 } catch (NativeDaemonConnectorException e) {
1905 int code = e.getCode();
1906 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1907 Slog.i(TAG, String.format("Container '%s' not found", id));
1908 return null;
1909 } else {
1910 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1911 }
1912 }
1913 }
1914
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001915 public void finishMediaUpdate() {
1916 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1917 }
Kenny Root02c87302010-07-01 08:10:18 -07001918
Kenny Roota02b8b02010-08-05 16:14:17 -07001919 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1920 if (callerUid == android.os.Process.SYSTEM_UID) {
1921 return true;
1922 }
1923
Kenny Root02c87302010-07-01 08:10:18 -07001924 if (packageName == null) {
1925 return false;
1926 }
1927
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001928 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001929
1930 if (DEBUG_OBB) {
1931 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1932 packageUid + ", callerUid = " + callerUid);
1933 }
1934
1935 return callerUid == packageUid;
1936 }
1937
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001938 public String getMountedObbPath(String rawPath) {
1939 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001940
Kenny Root02c87302010-07-01 08:10:18 -07001941 waitForReady();
1942 warnOnNotMounted();
1943
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001944 final ObbState state;
1945 synchronized (mObbPathToStateMap) {
1946 state = mObbPathToStateMap.get(rawPath);
1947 }
1948 if (state == null) {
1949 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1950 return null;
1951 }
1952
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001953 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001954 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001955 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001956 event.checkCode(VoldResponseCode.AsecPathResult);
1957 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001958 } catch (NativeDaemonConnectorException e) {
1959 int code = e.getCode();
1960 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001961 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001962 } else {
1963 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1964 }
1965 }
1966 }
1967
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001968 @Override
1969 public boolean isObbMounted(String rawPath) {
1970 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001971 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001972 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001973 }
Kenny Root02c87302010-07-01 08:10:18 -07001974 }
1975
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001976 @Override
1977 public void mountObb(
1978 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1979 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1980 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1981 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001982
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001983 final int callingUid = Binder.getCallingUid();
1984 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1985 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001986 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1987
1988 if (DEBUG_OBB)
1989 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001990 }
1991
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001992 @Override
1993 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1994 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1995
1996 final ObbState existingState;
1997 synchronized (mObbPathToStateMap) {
1998 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001999 }
2000
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002001 if (existingState != null) {
2002 // TODO: separate state object from request data
2003 final int callingUid = Binder.getCallingUid();
2004 final ObbState newState = new ObbState(
2005 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2006 final ObbAction action = new UnmountObbAction(newState, force);
2007 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002008
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002009 if (DEBUG_OBB)
2010 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2011 } else {
2012 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2013 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002014 }
2015
Ben Komalo444eca22011-09-01 15:17:44 -07002016 @Override
2017 public int getEncryptionState() {
2018 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2019 "no permission to access the crypt keeper");
2020
2021 waitForReady();
2022
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002023 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002024 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002025 event = mConnector.execute("cryptfs", "cryptocomplete");
2026 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002027 } catch (NumberFormatException e) {
2028 // Bad result - unexpected.
2029 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2030 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2031 } catch (NativeDaemonConnectorException e) {
2032 // Something bad happened.
2033 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2034 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2035 }
2036 }
2037
2038 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002039 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002040 if (TextUtils.isEmpty(password)) {
2041 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002042 }
2043
Jason parks8888c592011-01-20 22:46:41 -06002044 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2045 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002046
2047 waitForReady();
2048
2049 if (DEBUG_EVENTS) {
2050 Slog.i(TAG, "decrypting storage...");
2051 }
2052
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002053 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002054 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002055 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002056
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002057 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002058 if (code == 0) {
2059 // Decrypt was successful. Post a delayed message before restarting in order
2060 // to let the UI to clear itself
2061 mHandler.postDelayed(new Runnable() {
2062 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002063 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002064 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002065 } catch (NativeDaemonConnectorException e) {
2066 Slog.e(TAG, "problem executing in background", e);
2067 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002068 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002069 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002070 }
2071
2072 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002073 } catch (NativeDaemonConnectorException e) {
2074 // Decryption failed
2075 return e.getCode();
2076 }
Jason parks5af0b912010-11-29 09:05:25 -06002077 }
2078
Jason parks56aa5322011-01-07 09:01:15 -06002079 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002080 if (TextUtils.isEmpty(password)) {
2081 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002082 }
2083
Jason parks8888c592011-01-20 22:46:41 -06002084 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2085 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002086
2087 waitForReady();
2088
2089 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002090 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002091 }
2092
2093 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002094 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002095 } catch (NativeDaemonConnectorException e) {
2096 // Encryption failed
2097 return e.getCode();
2098 }
2099
2100 return 0;
2101 }
2102
Jason parksf7b3cd42011-01-27 09:28:25 -06002103 public int changeEncryptionPassword(String password) {
2104 if (TextUtils.isEmpty(password)) {
2105 throw new IllegalArgumentException("password cannot be empty");
2106 }
2107
2108 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2109 "no permission to access the crypt keeper");
2110
2111 waitForReady();
2112
2113 if (DEBUG_EVENTS) {
2114 Slog.i(TAG, "changing encryption password...");
2115 }
2116
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002117 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002118 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002119 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002120 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002121 } catch (NativeDaemonConnectorException e) {
2122 // Encryption failed
2123 return e.getCode();
2124 }
2125 }
2126
Christopher Tate32418be2011-10-10 13:51:12 -07002127 /**
2128 * Validate a user-supplied password string with cryptfs
2129 */
2130 @Override
2131 public int verifyEncryptionPassword(String password) throws RemoteException {
2132 // Only the system process is permitted to validate passwords
2133 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2134 throw new SecurityException("no permission to access the crypt keeper");
2135 }
2136
2137 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2138 "no permission to access the crypt keeper");
2139
2140 if (TextUtils.isEmpty(password)) {
2141 throw new IllegalArgumentException("password cannot be empty");
2142 }
2143
2144 waitForReady();
2145
2146 if (DEBUG_EVENTS) {
2147 Slog.i(TAG, "validating encryption password...");
2148 }
2149
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002150 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002151 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002152 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002153 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2154 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002155 } catch (NativeDaemonConnectorException e) {
2156 // Encryption failed
2157 return e.getCode();
2158 }
2159 }
2160
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002161 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002162 public int mkdirs(String callingPkg, String appPath) {
2163 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2164 final UserEnvironment userEnv = new UserEnvironment(userId);
2165
2166 // Validate that reported package name belongs to caller
2167 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2168 Context.APP_OPS_SERVICE);
2169 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2170
2171 try {
2172 appPath = new File(appPath).getCanonicalPath();
2173 } catch (IOException e) {
2174 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2175 return -1;
2176 }
2177
Jeff Sharkey5786a272013-10-02 12:50:34 -07002178 if (!appPath.endsWith("/")) {
2179 appPath = appPath + "/";
2180 }
2181
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002182 // Try translating the app path into a vold path, but require that it
2183 // belong to the calling package.
2184 String voldPath = maybeTranslatePathForVold(appPath,
2185 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2186 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2187 if (voldPath != null) {
2188 try {
2189 mConnector.execute("volume", "mkdirs", voldPath);
2190 return 0;
2191 } catch (NativeDaemonConnectorException e) {
2192 return e.getCode();
2193 }
2194 }
2195
2196 voldPath = maybeTranslatePathForVold(appPath,
2197 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2198 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2199 if (voldPath != null) {
2200 try {
2201 mConnector.execute("volume", "mkdirs", voldPath);
2202 return 0;
2203 } catch (NativeDaemonConnectorException e) {
2204 return e.getCode();
2205 }
2206 }
2207
2208 throw new SecurityException("Invalid mkdirs path: " + appPath);
2209 }
2210
2211 /**
2212 * Translate the given path from an app-visible path to a vold-visible path,
2213 * but only if it's under the given whitelisted paths.
2214 *
2215 * @param path a canonicalized app-visible path.
2216 * @param appPaths list of app-visible paths that are allowed.
2217 * @param voldPaths list of vold-visible paths directly corresponding to the
2218 * allowed app-visible paths argument.
2219 * @return a vold-visible path representing the original path, or
2220 * {@code null} if the given path didn't have an app-to-vold
2221 * mapping.
2222 */
2223 @VisibleForTesting
2224 public static String maybeTranslatePathForVold(
2225 String path, File[] appPaths, File[] voldPaths) {
2226 if (appPaths.length != voldPaths.length) {
2227 throw new IllegalStateException("Paths must be 1:1 mapping");
2228 }
2229
2230 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002231 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002232 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002233 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002234 .getAbsolutePath();
2235 if (!path.endsWith("/")) {
2236 path = path + "/";
2237 }
2238 return path;
2239 }
2240 }
2241 return null;
2242 }
2243
2244 @Override
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002245 public StorageVolume[] getVolumeList() {
2246 final int callingUserId = UserHandle.getCallingUserId();
2247 final boolean accessAll = (mContext.checkPermission(
2248 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2249 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2250
2251 synchronized (mVolumesLock) {
2252 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2253 for (StorageVolume volume : mVolumes) {
2254 final UserHandle owner = volume.getOwner();
2255 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2256 if (accessAll || ownerMatch) {
2257 filtered.add(volume);
2258 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002259 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002260 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002261 }
2262 }
2263
Kenny Rootaf9d6672010-10-08 09:21:39 -07002264 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2265 final IBinder binder = obbState.getBinder();
2266 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002267
Kenny Rootaf9d6672010-10-08 09:21:39 -07002268 if (obbStates == null) {
2269 obbStates = new ArrayList<ObbState>();
2270 mObbMounts.put(binder, obbStates);
2271 } else {
2272 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002273 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002274 throw new IllegalStateException("Attempt to add ObbState twice. "
2275 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002276 }
2277 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002278 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002279
2280 obbStates.add(obbState);
2281 try {
2282 obbState.link();
2283 } catch (RemoteException e) {
2284 /*
2285 * The binder died before we could link it, so clean up our state
2286 * and return failure.
2287 */
2288 obbStates.remove(obbState);
2289 if (obbStates.isEmpty()) {
2290 mObbMounts.remove(binder);
2291 }
2292
2293 // Rethrow the error so mountObb can get it
2294 throw e;
2295 }
2296
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002297 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002298 }
2299
Kenny Rootaf9d6672010-10-08 09:21:39 -07002300 private void removeObbStateLocked(ObbState obbState) {
2301 final IBinder binder = obbState.getBinder();
2302 final List<ObbState> obbStates = mObbMounts.get(binder);
2303 if (obbStates != null) {
2304 if (obbStates.remove(obbState)) {
2305 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002306 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002307 if (obbStates.isEmpty()) {
2308 mObbMounts.remove(binder);
2309 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002310 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002311
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002312 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002313 }
2314
Kenny Roota02b8b02010-08-05 16:14:17 -07002315 private class ObbActionHandler extends Handler {
2316 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002317 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002318
2319 ObbActionHandler(Looper l) {
2320 super(l);
2321 }
2322
2323 @Override
2324 public void handleMessage(Message msg) {
2325 switch (msg.what) {
2326 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002327 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002328
2329 if (DEBUG_OBB)
2330 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2331
2332 // If a bind was already initiated we don't really
2333 // need to do anything. The pending install
2334 // will be processed later on.
2335 if (!mBound) {
2336 // If this is the only one pending we might
2337 // have to bind to the service again.
2338 if (!connectToService()) {
2339 Slog.e(TAG, "Failed to bind to media container service");
2340 action.handleError();
2341 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002342 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002343 }
Kenny Root735de3b2010-09-30 14:11:39 -07002344
Kenny Root735de3b2010-09-30 14:11:39 -07002345 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002346 break;
2347 }
2348 case OBB_MCS_BOUND: {
2349 if (DEBUG_OBB)
2350 Slog.i(TAG, "OBB_MCS_BOUND");
2351 if (msg.obj != null) {
2352 mContainerService = (IMediaContainerService) msg.obj;
2353 }
2354 if (mContainerService == null) {
2355 // Something seriously wrong. Bail out
2356 Slog.e(TAG, "Cannot bind to media container service");
2357 for (ObbAction action : mActions) {
2358 // Indicate service bind error
2359 action.handleError();
2360 }
2361 mActions.clear();
2362 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002363 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002364 if (action != null) {
2365 action.execute(this);
2366 }
2367 } else {
2368 // Should never happen ideally.
2369 Slog.w(TAG, "Empty queue");
2370 }
2371 break;
2372 }
2373 case OBB_MCS_RECONNECT: {
2374 if (DEBUG_OBB)
2375 Slog.i(TAG, "OBB_MCS_RECONNECT");
2376 if (mActions.size() > 0) {
2377 if (mBound) {
2378 disconnectService();
2379 }
2380 if (!connectToService()) {
2381 Slog.e(TAG, "Failed to bind to media container service");
2382 for (ObbAction action : mActions) {
2383 // Indicate service bind error
2384 action.handleError();
2385 }
2386 mActions.clear();
2387 }
2388 }
2389 break;
2390 }
2391 case OBB_MCS_UNBIND: {
2392 if (DEBUG_OBB)
2393 Slog.i(TAG, "OBB_MCS_UNBIND");
2394
2395 // Delete pending install
2396 if (mActions.size() > 0) {
2397 mActions.remove(0);
2398 }
2399 if (mActions.size() == 0) {
2400 if (mBound) {
2401 disconnectService();
2402 }
2403 } else {
2404 // There are more pending requests in queue.
2405 // Just post MCS_BOUND message to trigger processing
2406 // of next pending install.
2407 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2408 }
2409 break;
2410 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002411 case OBB_FLUSH_MOUNT_STATE: {
2412 final String path = (String) msg.obj;
2413
2414 if (DEBUG_OBB)
2415 Slog.i(TAG, "Flushing all OBB state for path " + path);
2416
2417 synchronized (mObbMounts) {
2418 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2419
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002420 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002421 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002422 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002423
2424 /*
2425 * If this entry's source file is in the volume path
2426 * that got unmounted, remove it because it's no
2427 * longer valid.
2428 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002429 if (state.canonicalPath.startsWith(path)) {
2430 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002431 }
2432 }
2433
2434 for (final ObbState obbState : obbStatesToRemove) {
2435 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002436 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002437
2438 removeObbStateLocked(obbState);
2439
2440 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002441 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002442 OnObbStateChangeListener.UNMOUNTED);
2443 } catch (RemoteException e) {
2444 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002445 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002446 }
2447 }
2448 }
2449 break;
2450 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002451 }
2452 }
2453
2454 private boolean connectToService() {
2455 if (DEBUG_OBB)
2456 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2457
2458 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2459 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2460 mBound = true;
2461 return true;
2462 }
2463 return false;
2464 }
2465
2466 private void disconnectService() {
2467 mContainerService = null;
2468 mBound = false;
2469 mContext.unbindService(mDefContainerConn);
2470 }
2471 }
2472
2473 abstract class ObbAction {
2474 private static final int MAX_RETRIES = 3;
2475 private int mRetries;
2476
2477 ObbState mObbState;
2478
2479 ObbAction(ObbState obbState) {
2480 mObbState = obbState;
2481 }
2482
2483 public void execute(ObbActionHandler handler) {
2484 try {
2485 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002486 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002487 mRetries++;
2488 if (mRetries > MAX_RETRIES) {
2489 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002490 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002491 handleError();
2492 return;
2493 } else {
2494 handleExecute();
2495 if (DEBUG_OBB)
2496 Slog.i(TAG, "Posting install MCS_UNBIND");
2497 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2498 }
2499 } catch (RemoteException e) {
2500 if (DEBUG_OBB)
2501 Slog.i(TAG, "Posting install MCS_RECONNECT");
2502 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2503 } catch (Exception e) {
2504 if (DEBUG_OBB)
2505 Slog.d(TAG, "Error handling OBB action", e);
2506 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002507 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002508 }
2509 }
2510
Kenny Root05105f72010-09-22 17:29:43 -07002511 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002512 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002513
2514 protected ObbInfo getObbInfo() throws IOException {
2515 ObbInfo obbInfo;
2516 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002517 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002518 } catch (RemoteException e) {
2519 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002520 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002521 obbInfo = null;
2522 }
2523 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002524 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002525 }
2526 return obbInfo;
2527 }
2528
Kenny Rootaf9d6672010-10-08 09:21:39 -07002529 protected void sendNewStatusOrIgnore(int status) {
2530 if (mObbState == null || mObbState.token == null) {
2531 return;
2532 }
2533
Kenny Root38cf8862010-09-26 14:18:51 -07002534 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002535 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002536 } catch (RemoteException e) {
2537 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2538 }
2539 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002540 }
2541
2542 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002543 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002544 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002545
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002546 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002547 super(obbState);
2548 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002549 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002550 }
2551
Jason parks5af0b912010-11-29 09:05:25 -06002552 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002553 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002554 waitForReady();
2555 warnOnNotMounted();
2556
Kenny Root38cf8862010-09-26 14:18:51 -07002557 final ObbInfo obbInfo = getObbInfo();
2558
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002559 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002560 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2561 + " which is owned by " + obbInfo.packageName);
2562 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2563 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002564 }
2565
Kenny Rootaf9d6672010-10-08 09:21:39 -07002566 final boolean isMounted;
2567 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002568 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002569 }
2570 if (isMounted) {
2571 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2572 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2573 return;
2574 }
2575
Kenny Rootaf9d6672010-10-08 09:21:39 -07002576 final String hashedKey;
2577 if (mKey == null) {
2578 hashedKey = "none";
2579 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002580 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002581 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2582
2583 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2584 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2585 SecretKey key = factory.generateSecret(ks);
2586 BigInteger bi = new BigInteger(key.getEncoded());
2587 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002588 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002589 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2590 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2591 return;
2592 } catch (InvalidKeySpecException e) {
2593 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2594 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002595 return;
2596 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002597 }
Kenny Root38cf8862010-09-26 14:18:51 -07002598
Kenny Rootaf9d6672010-10-08 09:21:39 -07002599 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002600 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002601 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2602 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002603 } catch (NativeDaemonConnectorException e) {
2604 int code = e.getCode();
2605 if (code != VoldResponseCode.OpFailedStorageBusy) {
2606 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002607 }
2608 }
2609
Kenny Rootaf9d6672010-10-08 09:21:39 -07002610 if (rc == StorageResultCode.OperationSucceeded) {
2611 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002612 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002613
2614 synchronized (mObbMounts) {
2615 addObbStateLocked(mObbState);
2616 }
2617
2618 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002619 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002620 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002621
Kenny Rootaf9d6672010-10-08 09:21:39 -07002622 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002623 }
2624 }
2625
Jason parks5af0b912010-11-29 09:05:25 -06002626 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002627 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002628 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002629 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002630
2631 @Override
2632 public String toString() {
2633 StringBuilder sb = new StringBuilder();
2634 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002635 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002636 sb.append('}');
2637 return sb.toString();
2638 }
2639 }
2640
2641 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002642 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002643
2644 UnmountObbAction(ObbState obbState, boolean force) {
2645 super(obbState);
2646 mForceUnmount = force;
2647 }
2648
Jason parks5af0b912010-11-29 09:05:25 -06002649 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002650 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002651 waitForReady();
2652 warnOnNotMounted();
2653
Kenny Root38cf8862010-09-26 14:18:51 -07002654 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002655
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002656 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002657 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002658 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002659 }
Kenny Root38cf8862010-09-26 14:18:51 -07002660
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002661 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002662 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2663 return;
2664 }
2665
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002666 if (existingState.ownerGid != mObbState.ownerGid) {
2667 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2668 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002669 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2670 return;
2671 }
2672
Kenny Rootaf9d6672010-10-08 09:21:39 -07002673 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002674 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002675 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002676 if (mForceUnmount) {
2677 cmd.appendArg("force");
2678 }
2679 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002680 } catch (NativeDaemonConnectorException e) {
2681 int code = e.getCode();
2682 if (code == VoldResponseCode.OpFailedStorageBusy) {
2683 rc = StorageResultCode.OperationFailedStorageBusy;
2684 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2685 // If it's not mounted then we've already won.
2686 rc = StorageResultCode.OperationSucceeded;
2687 } else {
2688 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002689 }
2690 }
2691
Kenny Rootaf9d6672010-10-08 09:21:39 -07002692 if (rc == StorageResultCode.OperationSucceeded) {
2693 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002694 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002695 }
2696
Kenny Rootaf9d6672010-10-08 09:21:39 -07002697 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002698 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002699 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002700 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002701 }
2702 }
2703
Jason parks5af0b912010-11-29 09:05:25 -06002704 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002705 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002706 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002707 }
2708
2709 @Override
2710 public String toString() {
2711 StringBuilder sb = new StringBuilder();
2712 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002713 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002714 sb.append(",force=");
2715 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002716 sb.append('}');
2717 return sb.toString();
2718 }
Kenny Root02c87302010-07-01 08:10:18 -07002719 }
Kenny Root38cf8862010-09-26 14:18:51 -07002720
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002721 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002722 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2723 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002724 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002725
2726 // Only adjust paths when storage is emulated
2727 if (!Environment.isExternalStorageEmulated()) {
2728 return canonicalPath;
2729 }
2730
2731 String path = canonicalPath.toString();
2732
2733 // First trim off any external storage prefix
2734 final UserEnvironment userEnv = new UserEnvironment(userId);
2735
2736 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002737 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002738 // /storage/emulated_legacy
2739 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002740 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002741
2742 if (path.startsWith(externalPath)) {
2743 path = path.substring(externalPath.length() + 1);
2744 } else if (path.startsWith(legacyExternalPath)) {
2745 path = path.substring(legacyExternalPath.length() + 1);
2746 } else {
2747 return canonicalPath;
2748 }
2749
2750 // Handle special OBB paths on emulated storage
2751 final String obbPath = "Android/obb";
2752 if (path.startsWith(obbPath)) {
2753 path = path.substring(obbPath.length() + 1);
2754
2755 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002756 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002757 } else {
2758 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002759 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2760 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002761 }
2762 }
2763
2764 // Handle normal external storage paths
2765 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002766 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002767 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002768 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002769 }
2770 }
2771
Kenny Root38cf8862010-09-26 14:18:51 -07002772 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002773 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2775
2776 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07002777
Kenny Root38cf8862010-09-26 14:18:51 -07002778 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002779 pw.println("mObbMounts:");
2780 pw.increaseIndent();
2781 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
2782 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002783 while (binders.hasNext()) {
2784 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002785 pw.println(e.getKey() + ":");
2786 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002787 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002788 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002789 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002790 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002791 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002792 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002793 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002794
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002795 pw.println();
2796 pw.println("mObbPathToStateMap:");
2797 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002798 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2799 while (maps.hasNext()) {
2800 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002801 pw.print(e.getKey());
2802 pw.print(" -> ");
2803 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07002804 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002805 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002806 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002807
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002808 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002809 pw.println();
2810 pw.println("mVolumes:");
2811 pw.increaseIndent();
2812 for (StorageVolume volume : mVolumes) {
2813 pw.println(volume);
2814 pw.increaseIndent();
2815 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
2816 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002817 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002818 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002819 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002820
2821 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002822 pw.println("mConnection:");
2823 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08002824 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002825 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002828 /** {@inheritDoc} */
2829 public void monitor() {
2830 if (mConnector != null) {
2831 mConnector.monitor();
2832 }
2833 }
2834}