blob: e60231a4fd8a69fc9677a778ba3928617671b1d8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
San Mehata5078592010-03-25 09:36:54 -070059import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070060import android.util.Xml;
61
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080062import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e2122012-09-07 23:16:01 -070064import com.android.internal.app.IMediaContainerService;
Jeff 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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-09-07 23:16:01 -0700500
Jeff Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-09-07 23:16:01 -0700879 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
880 sendStorageIntent(Environment.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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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 Sharkeyb049e2122012-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);
1167 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1168 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001169 }
1170
San Mehat6a965af22010-02-24 17:47:30 -08001171 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001172 mContext.sendBroadcastAsUser(
1173 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1174 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001175 }
1176
San Mehat207e5382010-02-04 20:46:54 -08001177 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001178 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1179 throw new SecurityException(String.format("Requires %s permission", perm));
1180 }
1181 }
1182
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001183 // Storage list XML tags
1184 private static final String TAG_STORAGE_LIST = "StorageList";
1185 private static final String TAG_STORAGE = "storage";
1186
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001187 private void readStorageListLocked() {
1188 mVolumes.clear();
1189 mVolumeStates.clear();
1190
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001191 Resources resources = mContext.getResources();
1192
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001193 int id = com.android.internal.R.xml.storage_list;
1194 XmlResourceParser parser = resources.getXml(id);
1195 AttributeSet attrs = Xml.asAttributeSet(parser);
1196
1197 try {
1198 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1199 while (true) {
1200 XmlUtils.nextElement(parser);
1201
1202 String element = parser.getName();
1203 if (element == null) break;
1204
1205 if (TAG_STORAGE.equals(element)) {
1206 TypedArray a = resources.obtainAttributes(attrs,
1207 com.android.internal.R.styleable.Storage);
1208
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001209 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001210 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001211 int descriptionId = a.getResourceId(
1212 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001213 CharSequence description = a.getText(
1214 com.android.internal.R.styleable.Storage_storageDescription);
1215 boolean primary = a.getBoolean(
1216 com.android.internal.R.styleable.Storage_primary, false);
1217 boolean removable = a.getBoolean(
1218 com.android.internal.R.styleable.Storage_removable, false);
1219 boolean emulated = a.getBoolean(
1220 com.android.internal.R.styleable.Storage_emulated, false);
1221 int mtpReserve = a.getInt(
1222 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001223 boolean allowMassStorage = a.getBoolean(
1224 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001225 // resource parser does not support longs, so XML value is in megabytes
1226 long maxFileSize = a.getInt(
1227 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001228
1229 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1230 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001231 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001232 " allowMassStorage: " + allowMassStorage +
1233 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001234
1235 if (emulated) {
1236 // For devices with emulated storage, we create separate
1237 // volumes for each known user.
1238 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1239 true, mtpReserve, false, maxFileSize, null);
1240
1241 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001242 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001243 createEmulatedVolumeForUserLocked(user.getUserHandle());
1244 }
1245
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001246 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001247 if (path == null || description == null) {
1248 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001249 } else {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001250 final StorageVolume volume = new StorageVolume(new File(path),
1251 descriptionId, primary, removable, emulated, mtpReserve,
1252 allowMassStorage, maxFileSize, null);
1253 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001254
1255 // Until we hear otherwise, treat as unmounted
1256 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001257 volume.setState(Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001258 }
1259 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001260
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001261 a.recycle();
1262 }
1263 }
1264 } catch (XmlPullParserException e) {
1265 throw new RuntimeException(e);
1266 } catch (IOException e) {
1267 throw new RuntimeException(e);
1268 } finally {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001269 // Compute storage ID for each physical volume; emulated storage is
1270 // always 0 when defined.
1271 int index = isExternalStorageEmulated() ? 1 : 0;
1272 for (StorageVolume volume : mVolumes) {
1273 if (!volume.isEmulated()) {
1274 volume.setStorageId(index++);
1275 }
Mike Lockwoodfbfe5552011-05-17 17:19:37 -04001276 }
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001277 parser.close();
1278 }
1279 }
1280
San Mehat4270e1e2010-01-29 05:32:19 -08001281 /**
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001282 * Create and add new {@link StorageVolume} for given {@link UserHandle}
1283 * using {@link #mEmulatedTemplate} as template.
1284 */
1285 private void createEmulatedVolumeForUserLocked(UserHandle user) {
1286 if (mEmulatedTemplate == null) {
1287 throw new IllegalStateException("Missing emulated volume multi-user template");
1288 }
1289
1290 final UserEnvironment userEnv = new UserEnvironment(user.getIdentifier());
1291 final File path = userEnv.getExternalStorageDirectory();
1292 final StorageVolume volume = StorageVolume.fromTemplate(mEmulatedTemplate, path, user);
1293 volume.setStorageId(0);
1294 addVolumeLocked(volume);
1295
1296 if (mSystemReady) {
1297 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
1298 } else {
1299 // Place stub status for early callers to find
1300 mVolumeStates.put(volume.getPath(), Environment.MEDIA_MOUNTED);
Jeff Sharkey1f706c62013-10-17 10:52:17 -07001301 volume.setState(Environment.MEDIA_MOUNTED);
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001302 }
1303 }
1304
1305 private void addVolumeLocked(StorageVolume volume) {
1306 Slog.d(TAG, "addVolumeLocked() " + volume);
1307 mVolumes.add(volume);
1308 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1309 if (existing != null) {
1310 throw new IllegalStateException(
1311 "Volume at " + volume.getPath() + " already exists: " + existing);
1312 }
1313 }
1314
1315 private void removeVolumeLocked(StorageVolume volume) {
1316 Slog.d(TAG, "removeVolumeLocked() " + volume);
1317 mVolumes.remove(volume);
1318 mVolumesByPath.remove(volume.getPath());
1319 mVolumeStates.remove(volume.getPath());
1320 }
1321
1322 private StorageVolume getPrimaryPhysicalVolume() {
1323 synchronized (mVolumesLock) {
1324 for (StorageVolume volume : mVolumes) {
1325 if (volume.isPrimary() && !volume.isEmulated()) {
1326 return volume;
1327 }
1328 }
1329 }
1330 return null;
1331 }
1332
1333 /**
San Mehat207e5382010-02-04 20:46:54 -08001334 * Constructs a new MountService instance
1335 *
1336 * @param context Binder context for this service
1337 */
1338 public MountService(Context context) {
1339 mContext = context;
1340
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001341 synchronized (mVolumesLock) {
1342 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001343 }
1344
San Mehat207e5382010-02-04 20:46:54 -08001345 // XXX: This will go away soon in favor of IMountServiceObserver
1346 mPms = (PackageManagerService) ServiceManager.getService("package");
1347
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001348 HandlerThread hthread = new HandlerThread(TAG);
1349 hthread.start();
1350 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001351
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001352 // Watch for user changes
1353 final IntentFilter userFilter = new IntentFilter();
1354 userFilter.addAction(Intent.ACTION_USER_ADDED);
1355 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1356 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1357
1358 // Watch for USB changes on primary volume
1359 final StorageVolume primary = getPrimaryPhysicalVolume();
1360 if (primary != null && primary.allowMassStorage()) {
1361 mContext.registerReceiver(
1362 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1363 }
1364
Svetoslava7452ee2013-03-20 12:06:59 -07001365 // Watch for idle maintenance changes
1366 IntentFilter idleMaintenanceFilter = new IntentFilter();
1367 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1368 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1369 idleMaintenanceFilter, null, mHandler);
1370
Kenny Roota02b8b02010-08-05 16:14:17 -07001371 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001372 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001373
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001374 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001375 * Create the connection to vold with a maximum queue of twice the
1376 * amount of containers we'd ever expect to have. This keeps an
1377 * "asec list" from blocking a thread repeatedly.
1378 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001379 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001380
Kenny Root305bcbf2010-09-03 07:56:38 -07001381 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001382 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001383
Kenny Root07714d42011-08-17 17:49:28 -07001384 // Add ourself to the Watchdog monitors if enabled.
1385 if (WATCHDOG_ENABLE) {
1386 Watchdog.getInstance().addMonitor(this);
1387 }
San Mehat207e5382010-02-04 20:46:54 -08001388 }
1389
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001390 public void systemReady() {
1391 mSystemReady = true;
1392 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1393 }
1394
San Mehat207e5382010-02-04 20:46:54 -08001395 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001396 * Exposed API calls below here
1397 */
1398
1399 public void registerListener(IMountServiceListener listener) {
1400 synchronized (mListeners) {
1401 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1402 try {
1403 listener.asBinder().linkToDeath(bl, 0);
1404 mListeners.add(bl);
1405 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001406 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001407 }
1408 }
1409 }
1410
1411 public void unregisterListener(IMountServiceListener listener) {
1412 synchronized (mListeners) {
1413 for(MountServiceBinderListener bl : mListeners) {
1414 if (bl.mListener == listener) {
1415 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001416 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001417 return;
1418 }
1419 }
1420 }
1421 }
1422
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001423 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001424 validatePermission(android.Manifest.permission.SHUTDOWN);
1425
San Mehata5078592010-03-25 09:36:54 -07001426 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001427 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001428 for (String path : mVolumeStates.keySet()) {
1429 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001430
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001431 if (state.equals(Environment.MEDIA_SHARED)) {
1432 /*
1433 * If the media is currently shared, unshare it.
1434 * XXX: This is still dangerous!. We should not
1435 * be rebooting at *all* if UMS is enabled, since
1436 * the UMS host could have dirty FAT cache entries
1437 * yet to flush.
1438 */
1439 setUsbMassStorageEnabled(false);
1440 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1441 /*
1442 * If the media is being checked, then we need to wait for
1443 * it to complete before being able to proceed.
1444 */
1445 // XXX: @hackbod - Should we disable the ANR timer here?
1446 int retries = 30;
1447 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1448 try {
1449 Thread.sleep(1000);
1450 } catch (InterruptedException iex) {
1451 Slog.e(TAG, "Interrupted while waiting for media", iex);
1452 break;
1453 }
1454 state = Environment.getExternalStorageState();
1455 }
1456 if (retries == 0) {
1457 Slog.e(TAG, "Timed out waiting for media to check");
1458 }
San Mehat91c77612010-01-07 10:39:41 -08001459 }
San Mehat91c77612010-01-07 10:39:41 -08001460
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001461 if (state.equals(Environment.MEDIA_MOUNTED)) {
1462 // Post a unmount message.
1463 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1464 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1465 } else if (observer != null) {
1466 /*
1467 * Observer is waiting for onShutDownComplete when we are done.
1468 * Since nothing will be done send notification directly so shutdown
1469 * sequence can continue.
1470 */
1471 try {
1472 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1473 } catch (RemoteException e) {
1474 Slog.w(TAG, "RemoteException when shutting down");
1475 }
1476 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001477 }
San Mehat4270e1e2010-01-29 05:32:19 -08001478 }
1479 }
1480
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001481 private boolean getUmsEnabling() {
1482 synchronized (mListeners) {
1483 return mUmsEnabling;
1484 }
1485 }
1486
1487 private void setUmsEnabling(boolean enable) {
1488 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001489 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001490 }
1491 }
1492
San Mehatb1043402010-02-05 08:26:50 -08001493 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001494 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001495
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001496 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001497 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001498 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001499 synchronized (mListeners) {
1500 return mUmsAvailable;
1501 }
San Mehatb1043402010-02-05 08:26:50 -08001502 }
1503
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001504 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001505 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001506 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001507
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001508 final StorageVolume primary = getPrimaryPhysicalVolume();
1509 if (primary == null) return;
1510
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001511 // TODO: Add support for multiple share methods
1512
1513 /*
1514 * If the volume is mounted and we're enabling then unmount it
1515 */
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001516 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001517 String vs = getVolumeState(path);
1518 String method = "ums";
1519 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1520 // Override for isUsbMassStorageEnabled()
1521 setUmsEnabling(enable);
1522 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1523 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1524 // Clear override
1525 setUmsEnabling(false);
1526 }
1527 /*
1528 * If we disabled UMS then mount the volume
1529 */
1530 if (!enable) {
1531 doShareUnshareVolume(path, method, enable);
1532 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001533 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001534 " after disabling share method " + method);
1535 /*
1536 * Even though the mount failed, the unshare didn't so don't indicate an error.
1537 * The mountVolume() call will have set the storage state and sent the necessary
1538 * broadcasts.
1539 */
1540 }
1541 }
San Mehatb1043402010-02-05 08:26:50 -08001542 }
1543
1544 public boolean isUsbMassStorageEnabled() {
1545 waitForReady();
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001546
1547 final StorageVolume primary = getPrimaryPhysicalVolume();
1548 if (primary != null) {
1549 return doGetVolumeShared(primary.getPath(), "ums");
1550 } else {
1551 return false;
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001554
San Mehat7fd0fee2009-12-17 07:12:23 -08001555 /**
1556 * @return state of the volume at the specified mount point
1557 */
San Mehat4270e1e2010-01-29 05:32:19 -08001558 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001559 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001560 String state = mVolumeStates.get(mountPoint);
1561 if (state == null) {
1562 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001563 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1564 state = Environment.MEDIA_REMOVED;
1565 } else {
1566 throw new IllegalArgumentException();
1567 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001568 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001569
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001570 return state;
1571 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001572 }
1573
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001574 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001575 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001576 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001577 }
1578
San Mehat4270e1e2010-01-29 05:32:19 -08001579 public int mountVolume(String path) {
1580 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001581
San Mehat207e5382010-02-04 20:46:54 -08001582 waitForReady();
1583 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
Ben Komalo13c71972011-09-07 16:35:56 -07001586 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001587 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001588 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001590 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001591 if (DEBUG_UNMOUNT) {
1592 Slog.i(TAG, "Unmounting " + path
1593 + " force = " + force
1594 + " removeEncryption = " + removeEncryption);
1595 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001596 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1597 Environment.MEDIA_REMOVED.equals(volState) ||
1598 Environment.MEDIA_SHARED.equals(volState) ||
1599 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1600 // Media already unmounted or cannot be unmounted.
1601 // TODO return valid return code when adding observer call back.
1602 return;
1603 }
Ben Komalo13c71972011-09-07 16:35:56 -07001604 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001605 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607
San Mehat4270e1e2010-01-29 05:32:19 -08001608 public int formatVolume(String path) {
1609 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001610 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001611
San Mehat207e5382010-02-04 20:46:54 -08001612 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001615 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001616 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1617 waitForReady();
1618 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001619 final String[] r = NativeDaemonEvent.filterMessageList(
1620 mConnector.executeForList("storage", "users", path),
1621 VoldResponseCode.StorageUsersListResult);
1622
San Mehatc1b4ce92010-02-16 17:13:03 -08001623 // FMT: <pid> <process name>
1624 int[] data = new int[r.length];
1625 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001626 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001627 try {
1628 data[i] = Integer.parseInt(tok[0]);
1629 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001630 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001631 return new int[0];
1632 }
1633 }
1634 return data;
1635 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001636 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001637 return new int[0];
1638 }
1639 }
1640
San Mehatb1043402010-02-05 08:26:50 -08001641 private void warnOnNotMounted() {
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07001642 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001643 if (primary != null) {
1644 boolean mounted = false;
1645 try {
1646 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001647 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001648 }
1649
1650 if (!mounted) {
1651 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1652 }
San Mehatb1043402010-02-05 08:26:50 -08001653 }
1654 }
1655
San Mehat4270e1e2010-01-29 05:32:19 -08001656 public String[] getSecureContainerList() {
1657 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001658 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001659 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001660
San Mehat4270e1e2010-01-29 05:32:19 -08001661 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001662 return NativeDaemonEvent.filterMessageList(
1663 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001664 } catch (NativeDaemonConnectorException e) {
1665 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 }
San Mehat36972292010-01-06 11:06:32 -08001668
Kenny Root6dceb882012-04-12 14:23:49 -07001669 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1670 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001671 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001672 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001673 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001674
San Mehatb1043402010-02-05 08:26:50 -08001675 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001676 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001677 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1678 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001679 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001680 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001681 }
San Mehata181b212010-02-11 06:50:20 -08001682
1683 if (rc == StorageResultCode.OperationSucceeded) {
1684 synchronized (mAsecMountSet) {
1685 mAsecMountSet.add(id);
1686 }
1687 }
San Mehat4270e1e2010-01-29 05:32:19 -08001688 return rc;
San Mehat36972292010-01-06 11:06:32 -08001689 }
1690
San Mehat4270e1e2010-01-29 05:32:19 -08001691 public int finalizeSecureContainer(String id) {
1692 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001693 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001694
San Mehatb1043402010-02-05 08:26:50 -08001695 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001696 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001697 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001698 /*
1699 * Finalization does a remount, so no need
1700 * to update mAsecMountSet
1701 */
San Mehat4270e1e2010-01-29 05:32:19 -08001702 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001703 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001704 }
San Mehat4270e1e2010-01-29 05:32:19 -08001705 return rc;
San Mehat36972292010-01-06 11:06:32 -08001706 }
1707
Kenny Root6dceb882012-04-12 14:23:49 -07001708 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1709 validatePermission(android.Manifest.permission.ASEC_CREATE);
1710 warnOnNotMounted();
1711
1712 int rc = StorageResultCode.OperationSucceeded;
1713 try {
1714 mConnector.execute("asec", "fixperms", id, gid, filename);
1715 /*
1716 * Fix permissions does a remount, so no need to update
1717 * mAsecMountSet
1718 */
1719 } catch (NativeDaemonConnectorException e) {
1720 rc = StorageResultCode.OperationFailedInternalError;
1721 }
1722 return rc;
1723 }
1724
San Mehatd9709982010-02-18 11:43:03 -08001725 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001726 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001727 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001728 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001729
Kenny Rootaa485402010-09-14 14:49:41 -07001730 /*
1731 * Force a GC to make sure AssetManagers in other threads of the
1732 * system_server are cleaned up. We have to do this since AssetManager
1733 * instances are kept as a WeakReference and it's possible we have files
1734 * open on the external storage.
1735 */
1736 Runtime.getRuntime().gc();
1737
San Mehatb1043402010-02-05 08:26:50 -08001738 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001739 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001740 final Command cmd = new Command("asec", "destroy", id);
1741 if (force) {
1742 cmd.appendArg("force");
1743 }
1744 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001745 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001746 int code = e.getCode();
1747 if (code == VoldResponseCode.OpFailedStorageBusy) {
1748 rc = StorageResultCode.OperationFailedStorageBusy;
1749 } else {
1750 rc = StorageResultCode.OperationFailedInternalError;
1751 }
San Mehat02735bc2010-01-26 15:18:08 -08001752 }
San Mehata181b212010-02-11 06:50:20 -08001753
1754 if (rc == StorageResultCode.OperationSucceeded) {
1755 synchronized (mAsecMountSet) {
1756 if (mAsecMountSet.contains(id)) {
1757 mAsecMountSet.remove(id);
1758 }
1759 }
1760 }
1761
San Mehat4270e1e2010-01-29 05:32:19 -08001762 return rc;
San Mehat36972292010-01-06 11:06:32 -08001763 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001764
San Mehat4270e1e2010-01-29 05:32:19 -08001765 public int mountSecureContainer(String id, String key, int ownerUid) {
1766 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001767 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001768 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001769
San Mehata181b212010-02-11 06:50:20 -08001770 synchronized (mAsecMountSet) {
1771 if (mAsecMountSet.contains(id)) {
1772 return StorageResultCode.OperationFailedStorageMounted;
1773 }
1774 }
1775
San Mehatb1043402010-02-05 08:26:50 -08001776 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001777 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001778 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001779 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001780 int code = e.getCode();
1781 if (code != VoldResponseCode.OpFailedStorageBusy) {
1782 rc = StorageResultCode.OperationFailedInternalError;
1783 }
San Mehat02735bc2010-01-26 15:18:08 -08001784 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001785
1786 if (rc == StorageResultCode.OperationSucceeded) {
1787 synchronized (mAsecMountSet) {
1788 mAsecMountSet.add(id);
1789 }
1790 }
San Mehat4270e1e2010-01-29 05:32:19 -08001791 return rc;
San Mehat36972292010-01-06 11:06:32 -08001792 }
1793
San Mehatd9709982010-02-18 11:43:03 -08001794 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001795 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001796 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001797 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001798
San Mehat6cdd9c02010-02-09 14:45:20 -08001799 synchronized (mAsecMountSet) {
1800 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001801 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001802 }
1803 }
1804
Kenny Rootaa485402010-09-14 14:49:41 -07001805 /*
1806 * Force a GC to make sure AssetManagers in other threads of the
1807 * system_server are cleaned up. We have to do this since AssetManager
1808 * instances are kept as a WeakReference and it's possible we have files
1809 * open on the external storage.
1810 */
1811 Runtime.getRuntime().gc();
1812
San Mehatb1043402010-02-05 08:26:50 -08001813 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001814 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001815 final Command cmd = new Command("asec", "unmount", id);
1816 if (force) {
1817 cmd.appendArg("force");
1818 }
1819 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001820 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001821 int code = e.getCode();
1822 if (code == VoldResponseCode.OpFailedStorageBusy) {
1823 rc = StorageResultCode.OperationFailedStorageBusy;
1824 } else {
1825 rc = StorageResultCode.OperationFailedInternalError;
1826 }
San Mehat02735bc2010-01-26 15:18:08 -08001827 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001828
1829 if (rc == StorageResultCode.OperationSucceeded) {
1830 synchronized (mAsecMountSet) {
1831 mAsecMountSet.remove(id);
1832 }
1833 }
San Mehat4270e1e2010-01-29 05:32:19 -08001834 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001835 }
1836
San Mehat6cdd9c02010-02-09 14:45:20 -08001837 public boolean isSecureContainerMounted(String id) {
1838 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1839 waitForReady();
1840 warnOnNotMounted();
1841
1842 synchronized (mAsecMountSet) {
1843 return mAsecMountSet.contains(id);
1844 }
1845 }
1846
San Mehat4270e1e2010-01-29 05:32:19 -08001847 public int renameSecureContainer(String oldId, String newId) {
1848 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001849 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001850 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001851
San Mehata181b212010-02-11 06:50:20 -08001852 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001853 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001854 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001855 * changed while active, we must ensure both ids are not currently mounted.
1856 */
1857 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001858 return StorageResultCode.OperationFailedStorageMounted;
1859 }
1860 }
1861
San Mehatb1043402010-02-05 08:26:50 -08001862 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001863 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001864 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001865 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001866 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001867 }
San Mehata181b212010-02-11 06:50:20 -08001868
San Mehat4270e1e2010-01-29 05:32:19 -08001869 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001870 }
1871
San Mehat4270e1e2010-01-29 05:32:19 -08001872 public String getSecureContainerPath(String id) {
1873 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001874 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001875 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001876
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001877 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001878 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001879 event = mConnector.execute("asec", "path", id);
1880 event.checkCode(VoldResponseCode.AsecPathResult);
1881 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001882 } catch (NativeDaemonConnectorException e) {
1883 int code = e.getCode();
1884 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001885 Slog.i(TAG, String.format("Container '%s' not found", id));
1886 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001887 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001888 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001889 }
1890 }
San Mehat22dd86e2010-01-12 12:21:18 -08001891 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001892
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001893 public String getSecureContainerFilesystemPath(String id) {
1894 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1895 waitForReady();
1896 warnOnNotMounted();
1897
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001898 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001899 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001900 event = mConnector.execute("asec", "fspath", id);
1901 event.checkCode(VoldResponseCode.AsecPathResult);
1902 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001903 } catch (NativeDaemonConnectorException e) {
1904 int code = e.getCode();
1905 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1906 Slog.i(TAG, String.format("Container '%s' not found", id));
1907 return null;
1908 } else {
1909 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1910 }
1911 }
1912 }
1913
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001914 public void finishMediaUpdate() {
1915 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1916 }
Kenny Root02c87302010-07-01 08:10:18 -07001917
Kenny Roota02b8b02010-08-05 16:14:17 -07001918 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1919 if (callerUid == android.os.Process.SYSTEM_UID) {
1920 return true;
1921 }
1922
Kenny Root02c87302010-07-01 08:10:18 -07001923 if (packageName == null) {
1924 return false;
1925 }
1926
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001927 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001928
1929 if (DEBUG_OBB) {
1930 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1931 packageUid + ", callerUid = " + callerUid);
1932 }
1933
1934 return callerUid == packageUid;
1935 }
1936
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001937 public String getMountedObbPath(String rawPath) {
1938 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001939
Kenny Root02c87302010-07-01 08:10:18 -07001940 waitForReady();
1941 warnOnNotMounted();
1942
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001943 final ObbState state;
1944 synchronized (mObbPathToStateMap) {
1945 state = mObbPathToStateMap.get(rawPath);
1946 }
1947 if (state == null) {
1948 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1949 return null;
1950 }
1951
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001952 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001953 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001954 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001955 event.checkCode(VoldResponseCode.AsecPathResult);
1956 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001957 } catch (NativeDaemonConnectorException e) {
1958 int code = e.getCode();
1959 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001960 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001961 } else {
1962 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1963 }
1964 }
1965 }
1966
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001967 @Override
1968 public boolean isObbMounted(String rawPath) {
1969 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001970 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001971 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001972 }
Kenny Root02c87302010-07-01 08:10:18 -07001973 }
1974
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001975 @Override
1976 public void mountObb(
1977 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1978 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1979 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1980 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001981
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001982 final int callingUid = Binder.getCallingUid();
1983 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1984 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001985 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1986
1987 if (DEBUG_OBB)
1988 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001989 }
1990
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001991 @Override
1992 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1993 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1994
1995 final ObbState existingState;
1996 synchronized (mObbPathToStateMap) {
1997 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001998 }
1999
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002000 if (existingState != null) {
2001 // TODO: separate state object from request data
2002 final int callingUid = Binder.getCallingUid();
2003 final ObbState newState = new ObbState(
2004 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2005 final ObbAction action = new UnmountObbAction(newState, force);
2006 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002007
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002008 if (DEBUG_OBB)
2009 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2010 } else {
2011 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2012 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002013 }
2014
Ben Komalo444eca22011-09-01 15:17:44 -07002015 @Override
2016 public int getEncryptionState() {
2017 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2018 "no permission to access the crypt keeper");
2019
2020 waitForReady();
2021
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002022 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002023 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002024 event = mConnector.execute("cryptfs", "cryptocomplete");
2025 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002026 } catch (NumberFormatException e) {
2027 // Bad result - unexpected.
2028 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2029 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2030 } catch (NativeDaemonConnectorException e) {
2031 // Something bad happened.
2032 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2033 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2034 }
2035 }
2036
2037 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002038 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002039 if (TextUtils.isEmpty(password)) {
2040 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002041 }
2042
Jason parks8888c592011-01-20 22:46:41 -06002043 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2044 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002045
2046 waitForReady();
2047
2048 if (DEBUG_EVENTS) {
2049 Slog.i(TAG, "decrypting storage...");
2050 }
2051
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002052 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002053 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002054 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002055
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002056 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002057 if (code == 0) {
2058 // Decrypt was successful. Post a delayed message before restarting in order
2059 // to let the UI to clear itself
2060 mHandler.postDelayed(new Runnable() {
2061 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002062 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002063 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002064 } catch (NativeDaemonConnectorException e) {
2065 Slog.e(TAG, "problem executing in background", e);
2066 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002067 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002068 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002069 }
2070
2071 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002072 } catch (NativeDaemonConnectorException e) {
2073 // Decryption failed
2074 return e.getCode();
2075 }
Jason parks5af0b912010-11-29 09:05:25 -06002076 }
2077
Jason parks56aa5322011-01-07 09:01:15 -06002078 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002079 if (TextUtils.isEmpty(password)) {
2080 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002081 }
2082
Jason parks8888c592011-01-20 22:46:41 -06002083 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2084 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002085
2086 waitForReady();
2087
2088 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002089 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002090 }
2091
2092 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002093 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002094 } catch (NativeDaemonConnectorException e) {
2095 // Encryption failed
2096 return e.getCode();
2097 }
2098
2099 return 0;
2100 }
2101
Jason parksf7b3cd42011-01-27 09:28:25 -06002102 public int changeEncryptionPassword(String password) {
2103 if (TextUtils.isEmpty(password)) {
2104 throw new IllegalArgumentException("password cannot be empty");
2105 }
2106
2107 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2108 "no permission to access the crypt keeper");
2109
2110 waitForReady();
2111
2112 if (DEBUG_EVENTS) {
2113 Slog.i(TAG, "changing encryption password...");
2114 }
2115
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002116 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002117 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002118 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002119 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002120 } catch (NativeDaemonConnectorException e) {
2121 // Encryption failed
2122 return e.getCode();
2123 }
2124 }
2125
Christopher Tate32418be2011-10-10 13:51:12 -07002126 /**
2127 * Validate a user-supplied password string with cryptfs
2128 */
2129 @Override
2130 public int verifyEncryptionPassword(String password) throws RemoteException {
2131 // Only the system process is permitted to validate passwords
2132 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2133 throw new SecurityException("no permission to access the crypt keeper");
2134 }
2135
2136 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2137 "no permission to access the crypt keeper");
2138
2139 if (TextUtils.isEmpty(password)) {
2140 throw new IllegalArgumentException("password cannot be empty");
2141 }
2142
2143 waitForReady();
2144
2145 if (DEBUG_EVENTS) {
2146 Slog.i(TAG, "validating encryption password...");
2147 }
2148
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002149 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002150 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002151 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002152 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2153 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002154 } catch (NativeDaemonConnectorException e) {
2155 // Encryption failed
2156 return e.getCode();
2157 }
2158 }
2159
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002160 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002161 public int mkdirs(String callingPkg, String appPath) {
2162 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2163 final UserEnvironment userEnv = new UserEnvironment(userId);
2164
2165 // Validate that reported package name belongs to caller
2166 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2167 Context.APP_OPS_SERVICE);
2168 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2169
2170 try {
2171 appPath = new File(appPath).getCanonicalPath();
2172 } catch (IOException e) {
2173 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2174 return -1;
2175 }
2176
Jeff Sharkey5786a272013-10-02 12:50:34 -07002177 if (!appPath.endsWith("/")) {
2178 appPath = appPath + "/";
2179 }
2180
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002181 // Try translating the app path into a vold path, but require that it
2182 // belong to the calling package.
2183 String voldPath = maybeTranslatePathForVold(appPath,
2184 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2185 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2186 if (voldPath != null) {
2187 try {
2188 mConnector.execute("volume", "mkdirs", voldPath);
2189 return 0;
2190 } catch (NativeDaemonConnectorException e) {
2191 return e.getCode();
2192 }
2193 }
2194
2195 voldPath = maybeTranslatePathForVold(appPath,
2196 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2197 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2198 if (voldPath != null) {
2199 try {
2200 mConnector.execute("volume", "mkdirs", voldPath);
2201 return 0;
2202 } catch (NativeDaemonConnectorException e) {
2203 return e.getCode();
2204 }
2205 }
2206
2207 throw new SecurityException("Invalid mkdirs path: " + appPath);
2208 }
2209
2210 /**
2211 * Translate the given path from an app-visible path to a vold-visible path,
2212 * but only if it's under the given whitelisted paths.
2213 *
2214 * @param path a canonicalized app-visible path.
2215 * @param appPaths list of app-visible paths that are allowed.
2216 * @param voldPaths list of vold-visible paths directly corresponding to the
2217 * allowed app-visible paths argument.
2218 * @return a vold-visible path representing the original path, or
2219 * {@code null} if the given path didn't have an app-to-vold
2220 * mapping.
2221 */
2222 @VisibleForTesting
2223 public static String maybeTranslatePathForVold(
2224 String path, File[] appPaths, File[] voldPaths) {
2225 if (appPaths.length != voldPaths.length) {
2226 throw new IllegalStateException("Paths must be 1:1 mapping");
2227 }
2228
2229 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002230 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002231 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002232 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002233 .getAbsolutePath();
2234 if (!path.endsWith("/")) {
2235 path = path + "/";
2236 }
2237 return path;
2238 }
2239 }
2240 return null;
2241 }
2242
2243 @Override
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002244 public StorageVolume[] getVolumeList() {
2245 final int callingUserId = UserHandle.getCallingUserId();
2246 final boolean accessAll = (mContext.checkPermission(
2247 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2248 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2249
2250 synchronized (mVolumesLock) {
2251 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2252 for (StorageVolume volume : mVolumes) {
2253 final UserHandle owner = volume.getOwner();
2254 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2255 if (accessAll || ownerMatch) {
2256 filtered.add(volume);
2257 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002258 }
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002259 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002260 }
2261 }
2262
Kenny Rootaf9d6672010-10-08 09:21:39 -07002263 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2264 final IBinder binder = obbState.getBinder();
2265 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002266
Kenny Rootaf9d6672010-10-08 09:21:39 -07002267 if (obbStates == null) {
2268 obbStates = new ArrayList<ObbState>();
2269 mObbMounts.put(binder, obbStates);
2270 } else {
2271 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002272 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002273 throw new IllegalStateException("Attempt to add ObbState twice. "
2274 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002275 }
2276 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002277 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002278
2279 obbStates.add(obbState);
2280 try {
2281 obbState.link();
2282 } catch (RemoteException e) {
2283 /*
2284 * The binder died before we could link it, so clean up our state
2285 * and return failure.
2286 */
2287 obbStates.remove(obbState);
2288 if (obbStates.isEmpty()) {
2289 mObbMounts.remove(binder);
2290 }
2291
2292 // Rethrow the error so mountObb can get it
2293 throw e;
2294 }
2295
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002296 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002297 }
2298
Kenny Rootaf9d6672010-10-08 09:21:39 -07002299 private void removeObbStateLocked(ObbState obbState) {
2300 final IBinder binder = obbState.getBinder();
2301 final List<ObbState> obbStates = mObbMounts.get(binder);
2302 if (obbStates != null) {
2303 if (obbStates.remove(obbState)) {
2304 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002305 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002306 if (obbStates.isEmpty()) {
2307 mObbMounts.remove(binder);
2308 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002309 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002310
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002311 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002312 }
2313
Kenny Roota02b8b02010-08-05 16:14:17 -07002314 private class ObbActionHandler extends Handler {
2315 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002316 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002317
2318 ObbActionHandler(Looper l) {
2319 super(l);
2320 }
2321
2322 @Override
2323 public void handleMessage(Message msg) {
2324 switch (msg.what) {
2325 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002326 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002327
2328 if (DEBUG_OBB)
2329 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2330
2331 // If a bind was already initiated we don't really
2332 // need to do anything. The pending install
2333 // will be processed later on.
2334 if (!mBound) {
2335 // If this is the only one pending we might
2336 // have to bind to the service again.
2337 if (!connectToService()) {
2338 Slog.e(TAG, "Failed to bind to media container service");
2339 action.handleError();
2340 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002341 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002342 }
Kenny Root735de3b2010-09-30 14:11:39 -07002343
Kenny Root735de3b2010-09-30 14:11:39 -07002344 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002345 break;
2346 }
2347 case OBB_MCS_BOUND: {
2348 if (DEBUG_OBB)
2349 Slog.i(TAG, "OBB_MCS_BOUND");
2350 if (msg.obj != null) {
2351 mContainerService = (IMediaContainerService) msg.obj;
2352 }
2353 if (mContainerService == null) {
2354 // Something seriously wrong. Bail out
2355 Slog.e(TAG, "Cannot bind to media container service");
2356 for (ObbAction action : mActions) {
2357 // Indicate service bind error
2358 action.handleError();
2359 }
2360 mActions.clear();
2361 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002362 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002363 if (action != null) {
2364 action.execute(this);
2365 }
2366 } else {
2367 // Should never happen ideally.
2368 Slog.w(TAG, "Empty queue");
2369 }
2370 break;
2371 }
2372 case OBB_MCS_RECONNECT: {
2373 if (DEBUG_OBB)
2374 Slog.i(TAG, "OBB_MCS_RECONNECT");
2375 if (mActions.size() > 0) {
2376 if (mBound) {
2377 disconnectService();
2378 }
2379 if (!connectToService()) {
2380 Slog.e(TAG, "Failed to bind to media container service");
2381 for (ObbAction action : mActions) {
2382 // Indicate service bind error
2383 action.handleError();
2384 }
2385 mActions.clear();
2386 }
2387 }
2388 break;
2389 }
2390 case OBB_MCS_UNBIND: {
2391 if (DEBUG_OBB)
2392 Slog.i(TAG, "OBB_MCS_UNBIND");
2393
2394 // Delete pending install
2395 if (mActions.size() > 0) {
2396 mActions.remove(0);
2397 }
2398 if (mActions.size() == 0) {
2399 if (mBound) {
2400 disconnectService();
2401 }
2402 } else {
2403 // There are more pending requests in queue.
2404 // Just post MCS_BOUND message to trigger processing
2405 // of next pending install.
2406 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2407 }
2408 break;
2409 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002410 case OBB_FLUSH_MOUNT_STATE: {
2411 final String path = (String) msg.obj;
2412
2413 if (DEBUG_OBB)
2414 Slog.i(TAG, "Flushing all OBB state for path " + path);
2415
2416 synchronized (mObbMounts) {
2417 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2418
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002419 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002420 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002422
2423 /*
2424 * If this entry's source file is in the volume path
2425 * that got unmounted, remove it because it's no
2426 * longer valid.
2427 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002428 if (state.canonicalPath.startsWith(path)) {
2429 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002430 }
2431 }
2432
2433 for (final ObbState obbState : obbStatesToRemove) {
2434 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002435 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002436
2437 removeObbStateLocked(obbState);
2438
2439 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002440 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002441 OnObbStateChangeListener.UNMOUNTED);
2442 } catch (RemoteException e) {
2443 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002444 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002445 }
2446 }
2447 }
2448 break;
2449 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002450 }
2451 }
2452
2453 private boolean connectToService() {
2454 if (DEBUG_OBB)
2455 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2456
2457 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2458 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2459 mBound = true;
2460 return true;
2461 }
2462 return false;
2463 }
2464
2465 private void disconnectService() {
2466 mContainerService = null;
2467 mBound = false;
2468 mContext.unbindService(mDefContainerConn);
2469 }
2470 }
2471
2472 abstract class ObbAction {
2473 private static final int MAX_RETRIES = 3;
2474 private int mRetries;
2475
2476 ObbState mObbState;
2477
2478 ObbAction(ObbState obbState) {
2479 mObbState = obbState;
2480 }
2481
2482 public void execute(ObbActionHandler handler) {
2483 try {
2484 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002485 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002486 mRetries++;
2487 if (mRetries > MAX_RETRIES) {
2488 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002489 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002490 handleError();
2491 return;
2492 } else {
2493 handleExecute();
2494 if (DEBUG_OBB)
2495 Slog.i(TAG, "Posting install MCS_UNBIND");
2496 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2497 }
2498 } catch (RemoteException e) {
2499 if (DEBUG_OBB)
2500 Slog.i(TAG, "Posting install MCS_RECONNECT");
2501 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2502 } catch (Exception e) {
2503 if (DEBUG_OBB)
2504 Slog.d(TAG, "Error handling OBB action", e);
2505 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002506 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002507 }
2508 }
2509
Kenny Root05105f72010-09-22 17:29:43 -07002510 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002511 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002512
2513 protected ObbInfo getObbInfo() throws IOException {
2514 ObbInfo obbInfo;
2515 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002516 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002517 } catch (RemoteException e) {
2518 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002519 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002520 obbInfo = null;
2521 }
2522 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002523 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002524 }
2525 return obbInfo;
2526 }
2527
Kenny Rootaf9d6672010-10-08 09:21:39 -07002528 protected void sendNewStatusOrIgnore(int status) {
2529 if (mObbState == null || mObbState.token == null) {
2530 return;
2531 }
2532
Kenny Root38cf8862010-09-26 14:18:51 -07002533 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002534 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002535 } catch (RemoteException e) {
2536 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2537 }
2538 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002539 }
2540
2541 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002542 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002543 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002544
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002545 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002546 super(obbState);
2547 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002548 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002549 }
2550
Jason parks5af0b912010-11-29 09:05:25 -06002551 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002552 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002553 waitForReady();
2554 warnOnNotMounted();
2555
Kenny Root38cf8862010-09-26 14:18:51 -07002556 final ObbInfo obbInfo = getObbInfo();
2557
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002558 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002559 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2560 + " which is owned by " + obbInfo.packageName);
2561 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2562 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002563 }
2564
Kenny Rootaf9d6672010-10-08 09:21:39 -07002565 final boolean isMounted;
2566 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002567 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002568 }
2569 if (isMounted) {
2570 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2571 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2572 return;
2573 }
2574
Kenny Rootaf9d6672010-10-08 09:21:39 -07002575 final String hashedKey;
2576 if (mKey == null) {
2577 hashedKey = "none";
2578 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002579 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002580 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2581
2582 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2583 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2584 SecretKey key = factory.generateSecret(ks);
2585 BigInteger bi = new BigInteger(key.getEncoded());
2586 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002587 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002588 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2589 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2590 return;
2591 } catch (InvalidKeySpecException e) {
2592 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2593 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002594 return;
2595 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002596 }
Kenny Root38cf8862010-09-26 14:18:51 -07002597
Kenny Rootaf9d6672010-10-08 09:21:39 -07002598 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002599 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002600 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2601 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002602 } catch (NativeDaemonConnectorException e) {
2603 int code = e.getCode();
2604 if (code != VoldResponseCode.OpFailedStorageBusy) {
2605 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002606 }
2607 }
2608
Kenny Rootaf9d6672010-10-08 09:21:39 -07002609 if (rc == StorageResultCode.OperationSucceeded) {
2610 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002611 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002612
2613 synchronized (mObbMounts) {
2614 addObbStateLocked(mObbState);
2615 }
2616
2617 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002618 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002619 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002620
Kenny Rootaf9d6672010-10-08 09:21:39 -07002621 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002622 }
2623 }
2624
Jason parks5af0b912010-11-29 09:05:25 -06002625 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002626 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002627 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002628 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002629
2630 @Override
2631 public String toString() {
2632 StringBuilder sb = new StringBuilder();
2633 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002634 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002635 sb.append('}');
2636 return sb.toString();
2637 }
2638 }
2639
2640 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002641 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002642
2643 UnmountObbAction(ObbState obbState, boolean force) {
2644 super(obbState);
2645 mForceUnmount = force;
2646 }
2647
Jason parks5af0b912010-11-29 09:05:25 -06002648 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002649 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002650 waitForReady();
2651 warnOnNotMounted();
2652
Kenny Root38cf8862010-09-26 14:18:51 -07002653 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002654
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002655 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002656 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002657 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002658 }
Kenny Root38cf8862010-09-26 14:18:51 -07002659
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002660 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002661 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2662 return;
2663 }
2664
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002665 if (existingState.ownerGid != mObbState.ownerGid) {
2666 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2667 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002668 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2669 return;
2670 }
2671
Kenny Rootaf9d6672010-10-08 09:21:39 -07002672 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002673 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002674 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002675 if (mForceUnmount) {
2676 cmd.appendArg("force");
2677 }
2678 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002679 } catch (NativeDaemonConnectorException e) {
2680 int code = e.getCode();
2681 if (code == VoldResponseCode.OpFailedStorageBusy) {
2682 rc = StorageResultCode.OperationFailedStorageBusy;
2683 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2684 // If it's not mounted then we've already won.
2685 rc = StorageResultCode.OperationSucceeded;
2686 } else {
2687 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002688 }
2689 }
2690
Kenny Rootaf9d6672010-10-08 09:21:39 -07002691 if (rc == StorageResultCode.OperationSucceeded) {
2692 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002693 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002694 }
2695
Kenny Rootaf9d6672010-10-08 09:21:39 -07002696 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002697 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002698 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002699 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002700 }
2701 }
2702
Jason parks5af0b912010-11-29 09:05:25 -06002703 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002704 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002705 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002706 }
2707
2708 @Override
2709 public String toString() {
2710 StringBuilder sb = new StringBuilder();
2711 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002712 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002713 sb.append(",force=");
2714 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002715 sb.append('}');
2716 return sb.toString();
2717 }
Kenny Root02c87302010-07-01 08:10:18 -07002718 }
Kenny Root38cf8862010-09-26 14:18:51 -07002719
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002720 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002721 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2722 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002723 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002724
2725 // Only adjust paths when storage is emulated
2726 if (!Environment.isExternalStorageEmulated()) {
2727 return canonicalPath;
2728 }
2729
2730 String path = canonicalPath.toString();
2731
2732 // First trim off any external storage prefix
2733 final UserEnvironment userEnv = new UserEnvironment(userId);
2734
2735 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002736 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002737 // /storage/emulated_legacy
2738 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002739 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002740
2741 if (path.startsWith(externalPath)) {
2742 path = path.substring(externalPath.length() + 1);
2743 } else if (path.startsWith(legacyExternalPath)) {
2744 path = path.substring(legacyExternalPath.length() + 1);
2745 } else {
2746 return canonicalPath;
2747 }
2748
2749 // Handle special OBB paths on emulated storage
2750 final String obbPath = "Android/obb";
2751 if (path.startsWith(obbPath)) {
2752 path = path.substring(obbPath.length() + 1);
2753
2754 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002755 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002756 } else {
2757 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002758 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2759 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002760 }
2761 }
2762
2763 // Handle normal external storage paths
2764 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002765 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002766 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002767 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002768 }
2769 }
2770
Kenny Root38cf8862010-09-26 14:18:51 -07002771 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002772 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2774
2775 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07002776
Kenny Root38cf8862010-09-26 14:18:51 -07002777 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002778 pw.println("mObbMounts:");
2779 pw.increaseIndent();
2780 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
2781 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002782 while (binders.hasNext()) {
2783 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002784 pw.println(e.getKey() + ":");
2785 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002786 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002787 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002788 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002789 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002790 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002791 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002792 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002793
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002794 pw.println();
2795 pw.println("mObbPathToStateMap:");
2796 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002797 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2798 while (maps.hasNext()) {
2799 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002800 pw.print(e.getKey());
2801 pw.print(" -> ");
2802 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07002803 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002804 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002805 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002806
Jeff Sharkeyb049e2122012-09-07 23:16:01 -07002807 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002808 pw.println();
2809 pw.println("mVolumes:");
2810 pw.increaseIndent();
2811 for (StorageVolume volume : mVolumes) {
2812 pw.println(volume);
2813 pw.increaseIndent();
2814 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
2815 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002816 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002817 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002818 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002819
2820 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002821 pw.println("mConnection:");
2822 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08002823 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002824 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002827 /** {@inheritDoc} */
2828 public void monitor() {
2829 if (mConnector != null) {
2830 mConnector.monitor();
2831 }
2832 }
2833}