blob: 7308b7d7bb3ecb09f6fd713c5f4e77f6ed374fc0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkeyb049e212012-09-07 23:16:01 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080020
Jason parks8888c592011-01-20 22:46:41 -060021import android.Manifest;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070022import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070028import android.content.ServiceConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.PackageManager;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070030import android.content.pm.UserInfo;
Kenny Root02c87302010-07-01 08:10:18 -070031import android.content.res.ObbInfo;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070032import android.content.res.Resources;
33import android.content.res.TypedArray;
34import android.content.res.XmlResourceParser;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -070035import android.hardware.usb.UsbManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070037import android.os.Binder;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070039import android.os.Environment.UserEnvironment;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080040import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070041import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040043import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080044import android.os.Message;
San Mehat4270e1e2010-01-29 05:32:19 -080045import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080046import android.os.ServiceManager;
Svetoslavf23b64d2013-04-25 14:45:54 -070047import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070049import android.os.UserHandle;
Kenny Roota02b8b02010-08-05 16:14:17 -070050import android.os.storage.IMountService;
51import android.os.storage.IMountServiceListener;
52import android.os.storage.IMountShutdownObserver;
53import android.os.storage.IObbActionListener;
Kenny Rootaf9d6672010-10-08 09:21:39 -070054import android.os.storage.OnObbStateChangeListener;
Kenny Roota02b8b02010-08-05 16:14:17 -070055import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070056import android.os.storage.StorageVolume;
Jason parksf7b3cd42011-01-27 09:28:25 -060057import android.text.TextUtils;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070058import android.util.AttributeSet;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070059import android.util.Log;
San Mehata5078592010-03-25 09:36:54 -070060import android.util.Slog;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070061import android.util.Xml;
62
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080063import com.android.internal.annotations.GuardedBy;
64import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070065import com.android.internal.app.IMediaContainerService;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070066import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -070067import com.android.internal.util.Preconditions;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070068import com.android.internal.util.XmlUtils;
69import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -070070import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070071import com.android.server.am.ActivityManagerService;
72import com.android.server.pm.PackageManagerService;
73import com.android.server.pm.UserManagerService;
74import com.google.android.collect.Lists;
75import com.google.android.collect.Maps;
76
Mike Lockwood2f6a3882011-05-09 19:08:06 -070077import org.xmlpull.v1.XmlPullParserException;
Kenny Roota02b8b02010-08-05 16:14:17 -070078
Jeff Sharkeyb049e212012-09-07 23:16:01 -070079import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -070080import java.io.FileDescriptor;
Kenny Root05105f72010-09-22 17:29:43 -070081import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -070082import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -070083import java.math.BigInteger;
Kenny Root735de3b2010-09-30 14:11:39 -070084import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -070085import java.security.spec.InvalidKeySpecException;
86import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -080087import java.util.ArrayList;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -070088import java.util.Arrays;
Kenny Roota02b8b02010-08-05 16:14:17 -070089import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -080090import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -070091import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -070092import java.util.LinkedList;
93import java.util.List;
94import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -070095import java.util.Map.Entry;
Kenny Root51a573c2012-05-17 13:30:28 -070096import java.util.concurrent.CountDownLatch;
97import java.util.concurrent.TimeUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098
Kenny Root3b1abba2010-10-13 15:00:07 -070099import javax.crypto.SecretKey;
100import javax.crypto.SecretKeyFactory;
101import javax.crypto.spec.PBEKeySpec;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103/**
San Mehatb1043402010-02-05 08:26:50 -0800104 * MountService implements back-end services for platform storage
105 * management.
106 * @hide - Applications should use android.os.storage.StorageManager
107 * to access the MountService.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700109class MountService extends IMountService.Stub
110 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600111
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700112 // TODO: listen for user creation/deletion
113
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800114 private static final boolean LOCAL_LOGD = false;
115 private static final boolean DEBUG_UNMOUNT = false;
116 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800117 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700118
Kenny Root07714d42011-08-17 17:49:28 -0700119 // Disable this since it messes up long-running cryptfs operations.
120 private static final boolean WATCHDOG_ENABLE = false;
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final String TAG = "MountService";
123
Kenny Root305bcbf2010-09-03 07:56:38 -0700124 private static final String VOLD_TAG = "VoldConnector";
125
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700126 /** Maximum number of ASEC containers allowed to be mounted. */
127 private static final int MAX_CONTAINERS = 250;
128
San Mehat4270e1e2010-01-29 05:32:19 -0800129 /*
130 * Internal vold volume state constants
131 */
San Mehat7fd0fee2009-12-17 07:12:23 -0800132 class VolumeState {
133 public static final int Init = -1;
134 public static final int NoMedia = 0;
135 public static final int Idle = 1;
136 public static final int Pending = 2;
137 public static final int Checking = 3;
138 public static final int Mounted = 4;
139 public static final int Unmounting = 5;
140 public static final int Formatting = 6;
141 public static final int Shared = 7;
142 public static final int SharedMnt = 8;
143 }
144
San Mehat4270e1e2010-01-29 05:32:19 -0800145 /*
146 * Internal vold response code constants
147 */
San Mehat22dd86e2010-01-12 12:21:18 -0800148 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800149 /*
150 * 100 series - Requestion action was initiated; expect another reply
151 * before proceeding with a new command.
152 */
San Mehat22dd86e2010-01-12 12:21:18 -0800153 public static final int VolumeListResult = 110;
154 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800155 public static final int StorageUsersListResult = 112;
San Mehat22dd86e2010-01-12 12:21:18 -0800156
San Mehat4270e1e2010-01-29 05:32:19 -0800157 /*
158 * 200 series - Requestion action has been successfully completed.
159 */
160 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800161 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800162 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800163
San Mehat4270e1e2010-01-29 05:32:19 -0800164 /*
165 * 400 series - Command was accepted, but the requested action
166 * did not take place.
167 */
168 public static final int OpFailedNoMedia = 401;
169 public static final int OpFailedMediaBlank = 402;
170 public static final int OpFailedMediaCorrupt = 403;
171 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800172 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700173 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800174
175 /*
176 * 600 series - Unsolicited broadcasts.
177 */
San Mehat22dd86e2010-01-12 12:21:18 -0800178 public static final int VolumeStateChange = 605;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700179 public static final int VolumeUuidChange = 613;
180 public static final int VolumeUserLabelChange = 614;
San Mehat22dd86e2010-01-12 12:21:18 -0800181 public static final int VolumeDiskInserted = 630;
182 public static final int VolumeDiskRemoved = 631;
183 public static final int VolumeBadRemoval = 632;
Svetoslavf23b64d2013-04-25 14:45:54 -0700184
185 /*
186 * 700 series - fstrim
187 */
188 public static final int FstrimCompleted = 700;
San Mehat22dd86e2010-01-12 12:21:18 -0800189 }
190
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700191 private Context mContext;
192 private NativeDaemonConnector mConnector;
193
194 private final Object mVolumesLock = new Object();
195
196 /** When defined, base template for user-specific {@link StorageVolume}. */
197 private StorageVolume mEmulatedTemplate;
198
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700199 // TODO: separate storage volumes on per-user basis
200
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800201 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700202 private final ArrayList<StorageVolume> mVolumes = Lists.newArrayList();
203 /** Map from path to {@link StorageVolume} */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800204 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700205 private final HashMap<String, StorageVolume> mVolumesByPath = Maps.newHashMap();
206 /** Map from path to state */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800207 @GuardedBy("mVolumesLock")
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700208 private final HashMap<String, String> mVolumeStates = Maps.newHashMap();
209
210 private volatile boolean mSystemReady = false;
211
San Mehat4270e1e2010-01-29 05:32:19 -0800212 private PackageManagerService mPms;
213 private boolean mUmsEnabling;
Mike Lockwoodecedfdc2011-06-08 15:11:59 -0700214 private boolean mUmsAvailable = false;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800215 // Used as a lock for methods that register/unregister listeners.
216 final private ArrayList<MountServiceBinderListener> mListeners =
217 new ArrayList<MountServiceBinderListener>();
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800218 private final CountDownLatch mConnectedSignal = new CountDownLatch(1);
219 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
San Mehat6a965af22010-02-24 17:47:30 -0800220 private boolean mSendUmsConnectedOnBoot = false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800221
San Mehat6cdd9c02010-02-09 14:45:20 -0800222 /**
223 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800224 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800225 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800226 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800227
Kenny Root02c87302010-07-01 08:10:18 -0700228 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700229 * The size of the crypto algorithm key in bits for OBB files. Currently
230 * Twofish is used which takes 128-bit keys.
231 */
232 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
233
234 /**
235 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
236 * 1024 is reasonably secure and not too slow.
237 */
238 private static final int PBKDF2_HASH_ROUNDS = 1024;
239
240 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700241 * Mounted OBB tracking information. Used to track the current state of all
242 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700243 */
Kenny Root735de3b2010-09-30 14:11:39 -0700244 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700245
246 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700247 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
248
249 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700250 public ObbState(String rawPath, String canonicalPath, int callingUid,
251 IObbActionListener token, int nonce) {
252 this.rawPath = rawPath;
253 this.canonicalPath = canonicalPath.toString();
254
255 final int userId = UserHandle.getUserId(callingUid);
256 this.ownerPath = buildObbPath(canonicalPath, userId, false);
257 this.voldPath = buildObbPath(canonicalPath, userId, true);
258
259 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700260 this.token = token;
261 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700262 }
263
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700264 final String rawPath;
265 final String canonicalPath;
266 final String ownerPath;
267 final String voldPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700268
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700269 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700270
Kenny Rootaf9d6672010-10-08 09:21:39 -0700271 // Token of remote Binder caller
272 final IObbActionListener token;
273
274 // Identifier to pass back to the token
275 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700276
Kenny Root735de3b2010-09-30 14:11:39 -0700277 public IBinder getBinder() {
278 return token.asBinder();
279 }
280
Kenny Roota02b8b02010-08-05 16:14:17 -0700281 @Override
282 public void binderDied() {
283 ObbAction action = new UnmountObbAction(this, true);
284 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700285 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700286
Kenny Root5919ac62010-10-05 09:49:40 -0700287 public void link() throws RemoteException {
288 getBinder().linkToDeath(this, 0);
289 }
290
291 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700292 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700293 }
Kenny Root38cf8862010-09-26 14:18:51 -0700294
295 @Override
296 public String toString() {
297 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700298 sb.append("rawPath=").append(rawPath);
299 sb.append(",canonicalPath=").append(canonicalPath);
300 sb.append(",ownerPath=").append(ownerPath);
301 sb.append(",voldPath=").append(voldPath);
302 sb.append(",ownerGid=").append(ownerGid);
303 sb.append(",token=").append(token);
304 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700305 sb.append('}');
306 return sb.toString();
307 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700308 }
309
310 // OBB Action Handler
311 final private ObbActionHandler mObbActionHandler;
312
313 // OBB action handler messages
314 private static final int OBB_RUN_ACTION = 1;
315 private static final int OBB_MCS_BOUND = 2;
316 private static final int OBB_MCS_UNBIND = 3;
317 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700318 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700319
320 /*
321 * Default Container Service information
322 */
323 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
324 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
325
326 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
327
328 class DefaultContainerConnection implements ServiceConnection {
329 public void onServiceConnected(ComponentName name, IBinder service) {
330 if (DEBUG_OBB)
331 Slog.i(TAG, "onServiceConnected");
332 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
333 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
334 }
335
336 public void onServiceDisconnected(ComponentName name) {
337 if (DEBUG_OBB)
338 Slog.i(TAG, "onServiceDisconnected");
339 }
340 };
341
342 // Used in the ObbActionHandler
343 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700344
345 // Handler messages
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800346 private static final int H_UNMOUNT_PM_UPDATE = 1;
347 private static final int H_UNMOUNT_PM_DONE = 2;
348 private static final int H_UNMOUNT_MS = 3;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700349 private static final int H_SYSTEM_READY = 4;
350
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800351 private static final int RETRY_UNMOUNT_DELAY = 30; // in ms
352 private static final int MAX_UNMOUNT_RETRIES = 4;
353
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800354 class UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700355 final String path;
356 final boolean force;
Ben Komalo13c71972011-09-07 16:35:56 -0700357 final boolean removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800358 int retries;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800359
Ben Komalo13c71972011-09-07 16:35:56 -0700360 UnmountCallBack(String path, boolean force, boolean removeEncryption) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800361 retries = 0;
362 this.path = path;
363 this.force = force;
Ben Komalo13c71972011-09-07 16:35:56 -0700364 this.removeEncryption = removeEncryption;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800365 }
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800366
367 void handleFinished() {
San Mehata5078592010-03-25 09:36:54 -0700368 if (DEBUG_UNMOUNT) Slog.i(TAG, "Unmounting " + path);
Ben Komalo13c71972011-09-07 16:35:56 -0700369 doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800370 }
371 }
372
373 class UmsEnableCallBack extends UnmountCallBack {
Kenny Root05105f72010-09-22 17:29:43 -0700374 final String method;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800375
376 UmsEnableCallBack(String path, String method, boolean force) {
Ben Komalo13c71972011-09-07 16:35:56 -0700377 super(path, force, false);
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800378 this.method = method;
379 }
380
381 @Override
382 void handleFinished() {
383 super.handleFinished();
384 doShareUnshareVolume(path, method, true);
385 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800386 }
387
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800388 class ShutdownCallBack extends UnmountCallBack {
389 IMountShutdownObserver observer;
390 ShutdownCallBack(String path, IMountShutdownObserver observer) {
Ben Komalo13c71972011-09-07 16:35:56 -0700391 super(path, true, false);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800392 this.observer = observer;
393 }
394
395 @Override
396 void handleFinished() {
Ben Komalo13c71972011-09-07 16:35:56 -0700397 int ret = doUnmountVolume(path, true, removeEncryption);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800398 if (observer != null) {
399 try {
400 observer.onShutDownComplete(ret);
401 } catch (RemoteException e) {
San Mehata5078592010-03-25 09:36:54 -0700402 Slog.w(TAG, "RemoteException when shutting down");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800403 }
404 }
405 }
406 }
407
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400408 class MountServiceHandler extends Handler {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800409 ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700410 boolean mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800411
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400412 MountServiceHandler(Looper l) {
413 super(l);
414 }
415
Jason parks5af0b912010-11-29 09:05:25 -0600416 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800417 public void handleMessage(Message msg) {
418 switch (msg.what) {
419 case H_UNMOUNT_PM_UPDATE: {
San Mehata5078592010-03-25 09:36:54 -0700420 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_UPDATE");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800421 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
422 mForceUnmounts.add(ucb);
San Mehata5078592010-03-25 09:36:54 -0700423 if (DEBUG_UNMOUNT) Slog.i(TAG, " registered = " + mUpdatingStatus);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800424 // Register only if needed.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700425 if (!mUpdatingStatus) {
San Mehata5078592010-03-25 09:36:54 -0700426 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updating external media status on PackageManager");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700427 mUpdatingStatus = true;
428 mPms.updateExternalMediaStatus(false, true);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800429 }
430 break;
431 }
432 case H_UNMOUNT_PM_DONE: {
San Mehata5078592010-03-25 09:36:54 -0700433 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_PM_DONE");
San Mehata5078592010-03-25 09:36:54 -0700434 if (DEBUG_UNMOUNT) Slog.i(TAG, "Updated status. Processing requests");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700435 mUpdatingStatus = false;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800436 int size = mForceUnmounts.size();
437 int sizeArr[] = new int[size];
438 int sizeArrN = 0;
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700439 // Kill processes holding references first
440 ActivityManagerService ams = (ActivityManagerService)
441 ServiceManager.getService("activity");
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800442 for (int i = 0; i < size; i++) {
443 UnmountCallBack ucb = mForceUnmounts.get(i);
444 String path = ucb.path;
445 boolean done = false;
446 if (!ucb.force) {
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800447 done = true;
448 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800449 int pids[] = getStorageUsers(path);
450 if (pids == null || pids.length == 0) {
451 done = true;
452 } else {
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800453 // Eliminate system process here?
Dianne Hackborn64825172011-03-02 21:32:58 -0800454 ams.killPids(pids, "unmount media", true);
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700455 // Confirm if file references have been freed.
456 pids = getStorageUsers(path);
457 if (pids == null || pids.length == 0) {
458 done = true;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800459 }
460 }
461 }
Suchi Amalapurapu7af074a2010-04-05 16:46:32 -0700462 if (!done && (ucb.retries < MAX_UNMOUNT_RETRIES)) {
463 // Retry again
464 Slog.i(TAG, "Retrying to kill storage users again");
465 mHandler.sendMessageDelayed(
466 mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
467 ucb.retries++),
468 RETRY_UNMOUNT_DELAY);
469 } else {
470 if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
471 Slog.i(TAG, "Failed to unmount media inspite of " +
472 MAX_UNMOUNT_RETRIES + " retries. Forcibly killing processes now");
473 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800474 sizeArr[sizeArrN++] = i;
475 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
476 ucb));
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800477 }
478 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800479 // Remove already processed elements from list.
480 for (int i = (sizeArrN-1); i >= 0; i--) {
481 mForceUnmounts.remove(sizeArr[i]);
482 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800483 break;
484 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700485 case H_UNMOUNT_MS: {
San Mehata5078592010-03-25 09:36:54 -0700486 if (DEBUG_UNMOUNT) Slog.i(TAG, "H_UNMOUNT_MS");
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800487 UnmountCallBack ucb = (UnmountCallBack) msg.obj;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800488 ucb.handleFinished();
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800489 break;
490 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700491 case H_SYSTEM_READY: {
492 try {
493 handleSystemReady();
494 } catch (Exception ex) {
495 Slog.e(TAG, "Boot-time mount exception", ex);
496 }
497 break;
498 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800499 }
500 }
501 };
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700502
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700503 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800504
Kenny Root51a573c2012-05-17 13:30:28 -0700505 void waitForAsecScan() {
506 waitForLatch(mAsecsScanned);
507 }
508
San Mehat207e5382010-02-04 20:46:54 -0800509 private void waitForReady() {
Kenny Root51a573c2012-05-17 13:30:28 -0700510 waitForLatch(mConnectedSignal);
511 }
512
513 private void waitForLatch(CountDownLatch latch) {
Kenny Root51a573c2012-05-17 13:30:28 -0700514 for (;;) {
515 try {
516 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800517 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700518 } else {
519 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
520 + " still waiting for MountService ready...");
San Mehat207e5382010-02-04 20:46:54 -0800521 }
Kenny Root51a573c2012-05-17 13:30:28 -0700522 } catch (InterruptedException e) {
523 Slog.w(TAG, "Interrupt while waiting for MountService to be ready.");
San Mehat207e5382010-02-04 20:46:54 -0800524 }
San Mehat207e5382010-02-04 20:46:54 -0800525 }
San Mehat1f6301e2010-01-07 22:40:27 -0800526 }
Kenny Root02c87302010-07-01 08:10:18 -0700527
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700528 private void handleSystemReady() {
529 // Snapshot current volume states since it's not safe to call into vold
530 // while holding locks.
531 final HashMap<String, String> snapshot;
532 synchronized (mVolumesLock) {
533 snapshot = new HashMap<String, String>(mVolumeStates);
534 }
535
536 for (Map.Entry<String, String> entry : snapshot.entrySet()) {
537 final String path = entry.getKey();
538 final String state = entry.getValue();
539
540 if (state.equals(Environment.MEDIA_UNMOUNTED)) {
541 int rc = doMountVolume(path);
542 if (rc != StorageResultCode.OperationSucceeded) {
543 Slog.e(TAG, String.format("Boot-time mount failed (%d)",
544 rc));
545 }
546 } else if (state.equals(Environment.MEDIA_SHARED)) {
547 /*
548 * Bootstrap UMS enabled state since vold indicates
549 * the volume is shared (runtime restart while ums enabled)
550 */
551 notifyVolumeStateChange(null, path, VolumeState.NoMedia,
552 VolumeState.Shared);
553 }
554 }
555
556 // Push mounted state for all emulated storage
557 synchronized (mVolumesLock) {
558 for (StorageVolume volume : mVolumes) {
559 if (volume.isEmulated()) {
560 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
561 }
562 }
563 }
564
565 /*
566 * If UMS was connected on boot, send the connected event
567 * now that we're up.
568 */
569 if (mSendUmsConnectedOnBoot) {
570 sendUmsIntent(true);
571 mSendUmsConnectedOnBoot = false;
572 }
573 }
574
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700575 private final BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
576 @Override
577 public void onReceive(Context context, Intent intent) {
578 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
579 if (userId == -1) return;
580 final UserHandle user = new UserHandle(userId);
581
582 final String action = intent.getAction();
583 if (Intent.ACTION_USER_ADDED.equals(action)) {
584 synchronized (mVolumesLock) {
585 createEmulatedVolumeForUserLocked(user);
586 }
587
588 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
589 synchronized (mVolumesLock) {
590 final List<StorageVolume> toRemove = Lists.newArrayList();
591 for (StorageVolume volume : mVolumes) {
592 if (user.equals(volume.getOwner())) {
593 toRemove.add(volume);
594 }
595 }
596 for (StorageVolume volume : toRemove) {
597 removeVolumeLocked(volume);
598 }
599 }
600 }
601 }
602 };
603
604 private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
605 @Override
606 public void onReceive(Context context, Intent intent) {
607 boolean available = (intent.getBooleanExtra(UsbManager.USB_CONNECTED, false) &&
608 intent.getBooleanExtra(UsbManager.USB_FUNCTION_MASS_STORAGE, false));
609 notifyShareAvailabilityChange(available);
610 }
611 };
612
Svetoslava7452ee2013-03-20 12:06:59 -0700613 private final BroadcastReceiver mIdleMaintenanceReceiver = new BroadcastReceiver() {
614 @Override
615 public void onReceive(Context context, Intent intent) {
616 waitForReady();
617 String action = intent.getAction();
618 // Since fstrim will be run on a daily basis we do not expect
619 // fstrim to be too long, so it is not interruptible. We will
620 // implement interruption only in case we see issues.
621 if (Intent.ACTION_IDLE_MAINTENANCE_START.equals(action)) {
622 try {
623 // This method runs on the handler thread,
624 // so it is safe to directly call into vold.
625 mConnector.execute("fstrim", "dotrim");
Svetoslavf23b64d2013-04-25 14:45:54 -0700626 EventLogTags.writeFstrimStart(SystemClock.elapsedRealtime());
Svetoslava7452ee2013-03-20 12:06:59 -0700627 } catch (NativeDaemonConnectorException ndce) {
628 Slog.e(TAG, "Failed to run fstrim!");
629 }
630 }
631 }
632 };
633
San Mehat4270e1e2010-01-29 05:32:19 -0800634 private final class MountServiceBinderListener implements IBinder.DeathRecipient {
635 final IMountServiceListener mListener;
636
637 MountServiceBinderListener(IMountServiceListener listener) {
638 mListener = listener;
Kenny Root02c87302010-07-01 08:10:18 -0700639
San Mehat91c77612010-01-07 10:39:41 -0800640 }
641
San Mehat4270e1e2010-01-29 05:32:19 -0800642 public void binderDied() {
San Mehata5078592010-03-25 09:36:54 -0700643 if (LOCAL_LOGD) Slog.d(TAG, "An IMountServiceListener has died!");
Kenny Roota02b8b02010-08-05 16:14:17 -0700644 synchronized (mListeners) {
San Mehat4270e1e2010-01-29 05:32:19 -0800645 mListeners.remove(this);
646 mListener.asBinder().unlinkToDeath(this, 0);
647 }
648 }
649 }
650
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800651 private void doShareUnshareVolume(String path, String method, boolean enable) {
San Mehat4270e1e2010-01-29 05:32:19 -0800652 // TODO: Add support for multiple share methods
653 if (!method.equals("ums")) {
654 throw new IllegalArgumentException(String.format("Method %s not supported", method));
655 }
656
San Mehat4270e1e2010-01-29 05:32:19 -0800657 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800658 mConnector.execute("volume", enable ? "share" : "unshare", path, method);
San Mehat4270e1e2010-01-29 05:32:19 -0800659 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -0700660 Slog.e(TAG, "Failed to share/unshare", e);
San Mehat4270e1e2010-01-29 05:32:19 -0800661 }
San Mehat4270e1e2010-01-29 05:32:19 -0800662 }
663
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700664 private void updatePublicVolumeState(StorageVolume volume, String state) {
665 final String path = volume.getPath();
666 final String oldState;
667 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400668 oldState = mVolumeStates.put(path, state);
669 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700670
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400671 if (state.equals(oldState)) {
672 Slog.w(TAG, String.format("Duplicate state transition (%s -> %s) for %s",
673 state, state, path));
San Mehat4270e1e2010-01-29 05:32:19 -0800674 return;
675 }
San Mehatb1043402010-02-05 08:26:50 -0800676
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400677 Slog.d(TAG, "volume state changed for " + path + " (" + oldState + " -> " + state + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -0700678
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700679 // Tell PackageManager about changes to primary volume state, but only
680 // when not emulated.
681 if (volume.isPrimary() && !volume.isEmulated()) {
682 if (Environment.MEDIA_UNMOUNTED.equals(state)) {
683 mPms.updateExternalMediaStatus(false, false);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400684
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700685 /*
686 * Some OBBs might have been unmounted when this volume was
687 * unmounted, so send a message to the handler to let it know to
688 * remove those from the list of mounted OBBS.
689 */
690 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
691 OBB_FLUSH_MOUNT_STATE, path));
692 } else if (Environment.MEDIA_MOUNTED.equals(state)) {
693 mPms.updateExternalMediaStatus(true, false);
Mike Lockwood03559752010-07-19 18:25:03 -0400694 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800695 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700696
San Mehat4270e1e2010-01-29 05:32:19 -0800697 synchronized (mListeners) {
698 for (int i = mListeners.size() -1; i >= 0; i--) {
699 MountServiceBinderListener bl = mListeners.get(i);
700 try {
San Mehatb1043402010-02-05 08:26:50 -0800701 bl.mListener.onStorageStateChanged(path, oldState, state);
San Mehat4270e1e2010-01-29 05:32:19 -0800702 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -0700703 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -0800704 mListeners.remove(i);
705 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700706 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800707 }
708 }
709 }
710 }
711
712 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800713 * Callback from NativeDaemonConnector
714 */
715 public void onDaemonConnected() {
716 /*
717 * Since we'll be calling back into the NativeDaemonConnector,
718 * we need to do our work in a new thread.
719 */
Kenny Root51a573c2012-05-17 13:30:28 -0700720 new Thread("MountService#onDaemonConnected") {
Jason parks5af0b912010-11-29 09:05:25 -0600721 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800722 public void run() {
723 /**
724 * Determine media state and UMS detection status
725 */
San Mehat4270e1e2010-01-29 05:32:19 -0800726 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800727 final String[] vols = NativeDaemonEvent.filterMessageList(
728 mConnector.executeForList("volume", "list"),
729 VoldResponseCode.VolumeListResult);
San Mehat4270e1e2010-01-29 05:32:19 -0800730 for (String volstr : vols) {
731 String[] tok = volstr.split(" ");
732 // FMT: <label> <mountpoint> <state>
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400733 String path = tok[1];
734 String state = Environment.MEDIA_REMOVED;
735
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700736 final StorageVolume volume;
737 synchronized (mVolumesLock) {
738 volume = mVolumesByPath.get(path);
739 }
740
San Mehat4270e1e2010-01-29 05:32:19 -0800741 int st = Integer.parseInt(tok[2]);
742 if (st == VolumeState.NoMedia) {
743 state = Environment.MEDIA_REMOVED;
744 } else if (st == VolumeState.Idle) {
San Mehat207e5382010-02-04 20:46:54 -0800745 state = Environment.MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800746 } else if (st == VolumeState.Mounted) {
747 state = Environment.MEDIA_MOUNTED;
San Mehata5078592010-03-25 09:36:54 -0700748 Slog.i(TAG, "Media already mounted on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800749 } else if (st == VolumeState.Shared) {
750 state = Environment.MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700751 Slog.i(TAG, "Media shared on daemon connection");
San Mehat4270e1e2010-01-29 05:32:19 -0800752 } else {
753 throw new Exception(String.format("Unexpected state %d", st));
754 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400755
756 if (state != null) {
757 if (DEBUG_EVENTS) Slog.i(TAG, "Updating valid state " + state);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700758 updatePublicVolumeState(volume, state);
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400759 }
San Mehat4270e1e2010-01-29 05:32:19 -0800760 }
761 } catch (Exception e) {
San Mehata5078592010-03-25 09:36:54 -0700762 Slog.e(TAG, "Error processing initial volume state", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700763 final StorageVolume primary = getPrimaryPhysicalVolume();
764 if (primary != null) {
765 updatePublicVolumeState(primary, Environment.MEDIA_REMOVED);
766 }
San Mehat4270e1e2010-01-29 05:32:19 -0800767 }
768
San Mehat207e5382010-02-04 20:46:54 -0800769 /*
Jason parks9ed98bc2011-01-17 09:58:35 -0600770 * Now that we've done our initialization, release
San Mehat207e5382010-02-04 20:46:54 -0800771 * the hounds!
772 */
Kenny Root51a573c2012-05-17 13:30:28 -0700773 mConnectedSignal.countDown();
Kenny Root51a573c2012-05-17 13:30:28 -0700774
775 // Let package manager load internal ASECs.
776 mPms.scanAvailableAsecs();
777
778 // Notify people waiting for ASECs to be scanned that it's done.
779 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800780 }
781 }.start();
782 }
783
784 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800785 * Callback from NativeDaemonConnector
786 */
787 public boolean onEvent(int code, String raw, String[] cooked) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800788 if (DEBUG_EVENTS) {
789 StringBuilder builder = new StringBuilder();
790 builder.append("onEvent::");
791 builder.append(" raw= " + raw);
792 if (cooked != null) {
793 builder.append(" cooked = " );
794 for (String str : cooked) {
795 builder.append(" " + str);
796 }
797 }
San Mehata5078592010-03-25 09:36:54 -0700798 Slog.i(TAG, builder.toString());
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -0800799 }
San Mehat4270e1e2010-01-29 05:32:19 -0800800 if (code == VoldResponseCode.VolumeStateChange) {
801 /*
802 * One of the volumes we're managing has changed state.
803 * Format: "NNN Volume <label> <path> state changed
804 * from <old_#> (<old_str>) to <new_#> (<new_str>)"
805 */
806 notifyVolumeStateChange(
807 cooked[2], cooked[3], Integer.parseInt(cooked[7]),
808 Integer.parseInt(cooked[10]));
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700809 } else if (code == VoldResponseCode.VolumeUuidChange) {
810 // Format: nnn <label> <path> <uuid>
811 final String path = cooked[2];
812 final String uuid = (cooked.length > 3) ? cooked[3] : null;
813
814 final StorageVolume vol = mVolumesByPath.get(path);
815 if (vol != null) {
816 vol.setUuid(uuid);
817 }
818
819 } else if (code == VoldResponseCode.VolumeUserLabelChange) {
820 // Format: nnn <label> <path> <label>
821 final String path = cooked[2];
822 final String userLabel = (cooked.length > 3) ? cooked[3] : null;
823
824 final StorageVolume vol = mVolumesByPath.get(path);
825 if (vol != null) {
826 vol.setUserLabel(userLabel);
827 }
828
San Mehat4270e1e2010-01-29 05:32:19 -0800829 } else if ((code == VoldResponseCode.VolumeDiskInserted) ||
830 (code == VoldResponseCode.VolumeDiskRemoved) ||
831 (code == VoldResponseCode.VolumeBadRemoval)) {
832 // FMT: NNN Volume <label> <mountpoint> disk inserted (<major>:<minor>)
833 // FMT: NNN Volume <label> <mountpoint> disk removed (<major>:<minor>)
834 // FMT: NNN Volume <label> <mountpoint> bad removal (<major>:<minor>)
Mike Lockwooda5250c92011-05-23 13:44:04 -0400835 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800836 final String label = cooked[2];
837 final String path = cooked[3];
838 int major = -1;
839 int minor = -1;
840
841 try {
842 String devComp = cooked[6].substring(1, cooked[6].length() -1);
843 String[] devTok = devComp.split(":");
844 major = Integer.parseInt(devTok[0]);
845 minor = Integer.parseInt(devTok[1]);
846 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700847 Slog.e(TAG, "Failed to parse major/minor", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800848 }
849
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700850 final StorageVolume volume;
851 final String state;
852 synchronized (mVolumesLock) {
853 volume = mVolumesByPath.get(path);
854 state = mVolumeStates.get(path);
855 }
856
San Mehat4270e1e2010-01-29 05:32:19 -0800857 if (code == VoldResponseCode.VolumeDiskInserted) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700858 new Thread("MountService#VolumeDiskInserted") {
Jason parks5af0b912010-11-29 09:05:25 -0600859 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800860 public void run() {
861 try {
862 int rc;
San Mehatb1043402010-02-05 08:26:50 -0800863 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -0700864 Slog.w(TAG, String.format("Insertion mount failed (%d)", rc));
San Mehat4270e1e2010-01-29 05:32:19 -0800865 }
866 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -0700867 Slog.w(TAG, "Failed to mount media on insertion", ex);
San Mehat4270e1e2010-01-29 05:32:19 -0800868 }
869 }
870 }.start();
871 } else if (code == VoldResponseCode.VolumeDiskRemoved) {
872 /*
873 * This event gets trumped if we're already in BAD_REMOVAL state
874 */
875 if (getVolumeState(path).equals(Environment.MEDIA_BAD_REMOVAL)) {
876 return true;
877 }
878 /* Send the media unmounted event first */
San Mehata5078592010-03-25 09:36:54 -0700879 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700880 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
881 sendStorageIntent(Environment.MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800882
San Mehata5078592010-03-25 09:36:54 -0700883 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media removed");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700884 updatePublicVolumeState(volume, Environment.MEDIA_REMOVED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400885 action = Intent.ACTION_MEDIA_REMOVED;
San Mehat4270e1e2010-01-29 05:32:19 -0800886 } else if (code == VoldResponseCode.VolumeBadRemoval) {
San Mehata5078592010-03-25 09:36:54 -0700887 if (DEBUG_EVENTS) Slog.i(TAG, "Sending unmounted event first");
San Mehat4270e1e2010-01-29 05:32:19 -0800888 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700889 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Christian Beckf503c8f2013-05-20 08:42:45 +0200890 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800891
San Mehata5078592010-03-25 09:36:54 -0700892 if (DEBUG_EVENTS) Slog.i(TAG, "Sending media bad removal");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700893 updatePublicVolumeState(volume, Environment.MEDIA_BAD_REMOVAL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400894 action = Intent.ACTION_MEDIA_BAD_REMOVAL;
Svetoslavf23b64d2013-04-25 14:45:54 -0700895 } else if (code == VoldResponseCode.FstrimCompleted) {
Svetoslav9e814a82013-04-30 10:43:56 -0700896 EventLogTags.writeFstrimFinish(SystemClock.elapsedRealtime());
San Mehat4270e1e2010-01-29 05:32:19 -0800897 } else {
San Mehata5078592010-03-25 09:36:54 -0700898 Slog.e(TAG, String.format("Unknown code {%d}", code));
San Mehat4270e1e2010-01-29 05:32:19 -0800899 }
Mike Lockwooda5250c92011-05-23 13:44:04 -0400900
901 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700902 sendStorageIntent(action, volume, UserHandle.ALL);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400903 }
San Mehat4270e1e2010-01-29 05:32:19 -0800904 } else {
905 return false;
906 }
907
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400908 return true;
San Mehat4270e1e2010-01-29 05:32:19 -0800909 }
910
San Mehat207e5382010-02-04 20:46:54 -0800911 private void notifyVolumeStateChange(String label, String path, int oldState, int newState) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700912 final StorageVolume volume;
913 final String state;
914 synchronized (mVolumesLock) {
915 volume = mVolumesByPath.get(path);
916 state = getVolumeState(path);
917 }
918
919 if (DEBUG_EVENTS) Slog.i(TAG, "notifyVolumeStateChange::" + state);
San Mehat4270e1e2010-01-29 05:32:19 -0800920
Mike Lockwooda5250c92011-05-23 13:44:04 -0400921 String action = null;
San Mehat4270e1e2010-01-29 05:32:19 -0800922
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500923 if (oldState == VolumeState.Shared && newState != oldState) {
San Mehata5078592010-03-25 09:36:54 -0700924 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_UNSHARED intent");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700925 sendStorageIntent(Intent.ACTION_MEDIA_UNSHARED, volume, UserHandle.ALL);
Mike Lockwoodbf2dd442010-03-03 06:16:52 -0500926 }
927
San Mehat4270e1e2010-01-29 05:32:19 -0800928 if (newState == VolumeState.Init) {
929 } else if (newState == VolumeState.NoMedia) {
930 // NoMedia is handled via Disk Remove events
931 } else if (newState == VolumeState.Idle) {
932 /*
933 * Don't notify if we're in BAD_REMOVAL, NOFS, UNMOUNTABLE, or
934 * if we're in the process of enabling UMS
935 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700936 if (!state.equals(
937 Environment.MEDIA_BAD_REMOVAL) && !state.equals(
938 Environment.MEDIA_NOFS) && !state.equals(
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800939 Environment.MEDIA_UNMOUNTABLE) && !getUmsEnabling()) {
San Mehata5078592010-03-25 09:36:54 -0700940 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state for media bad removal nofs and unmountable");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700941 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400942 action = Intent.ACTION_MEDIA_UNMOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800943 }
944 } else if (newState == VolumeState.Pending) {
945 } else if (newState == VolumeState.Checking) {
San Mehata5078592010-03-25 09:36:54 -0700946 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state checking");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700947 updatePublicVolumeState(volume, Environment.MEDIA_CHECKING);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400948 action = Intent.ACTION_MEDIA_CHECKING;
San Mehat4270e1e2010-01-29 05:32:19 -0800949 } else if (newState == VolumeState.Mounted) {
San Mehata5078592010-03-25 09:36:54 -0700950 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state mounted");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700951 updatePublicVolumeState(volume, Environment.MEDIA_MOUNTED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400952 action = Intent.ACTION_MEDIA_MOUNTED;
San Mehat4270e1e2010-01-29 05:32:19 -0800953 } else if (newState == VolumeState.Unmounting) {
Mike Lockwooda5250c92011-05-23 13:44:04 -0400954 action = Intent.ACTION_MEDIA_EJECT;
San Mehat4270e1e2010-01-29 05:32:19 -0800955 } else if (newState == VolumeState.Formatting) {
956 } else if (newState == VolumeState.Shared) {
San Mehata5078592010-03-25 09:36:54 -0700957 if (DEBUG_EVENTS) Slog.i(TAG, "Updating volume state media mounted");
San Mehat4270e1e2010-01-29 05:32:19 -0800958 /* Send the media unmounted event first */
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700959 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTED);
960 sendStorageIntent(Intent.ACTION_MEDIA_UNMOUNTED, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800961
San Mehata5078592010-03-25 09:36:54 -0700962 if (DEBUG_EVENTS) Slog.i(TAG, "Updating media shared");
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700963 updatePublicVolumeState(volume, Environment.MEDIA_SHARED);
Mike Lockwooda5250c92011-05-23 13:44:04 -0400964 action = Intent.ACTION_MEDIA_SHARED;
San Mehata5078592010-03-25 09:36:54 -0700965 if (LOCAL_LOGD) Slog.d(TAG, "Sending ACTION_MEDIA_SHARED intent");
San Mehat4270e1e2010-01-29 05:32:19 -0800966 } else if (newState == VolumeState.SharedMnt) {
San Mehata5078592010-03-25 09:36:54 -0700967 Slog.e(TAG, "Live shared mounts not supported yet!");
San Mehat4270e1e2010-01-29 05:32:19 -0800968 return;
969 } else {
San Mehata5078592010-03-25 09:36:54 -0700970 Slog.e(TAG, "Unhandled VolumeState {" + newState + "}");
San Mehat4270e1e2010-01-29 05:32:19 -0800971 }
972
Mike Lockwooda5250c92011-05-23 13:44:04 -0400973 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700974 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat4270e1e2010-01-29 05:32:19 -0800975 }
976 }
977
San Mehat207e5382010-02-04 20:46:54 -0800978 private int doMountVolume(String path) {
San Mehatb1043402010-02-05 08:26:50 -0800979 int rc = StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -0800980
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700981 final StorageVolume volume;
982 synchronized (mVolumesLock) {
983 volume = mVolumesByPath.get(path);
984 }
985
San Mehata5078592010-03-25 09:36:54 -0700986 if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
San Mehat207e5382010-02-04 20:46:54 -0800987 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -0800988 mConnector.execute("volume", "mount", path);
San Mehat207e5382010-02-04 20:46:54 -0800989 } catch (NativeDaemonConnectorException e) {
990 /*
991 * Mount failed for some reason
992 */
Mike Lockwooda5250c92011-05-23 13:44:04 -0400993 String action = null;
San Mehat207e5382010-02-04 20:46:54 -0800994 int code = e.getCode();
995 if (code == VoldResponseCode.OpFailedNoMedia) {
996 /*
997 * Attempt to mount but no media inserted
998 */
San Mehatb1043402010-02-05 08:26:50 -0800999 rc = StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001000 } else if (code == VoldResponseCode.OpFailedMediaBlank) {
San Mehata5078592010-03-25 09:36:54 -07001001 if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
San Mehat207e5382010-02-04 20:46:54 -08001002 /*
1003 * Media is blank or does not contain a supported filesystem
1004 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001005 updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001006 action = Intent.ACTION_MEDIA_NOFS;
San Mehatb1043402010-02-05 08:26:50 -08001007 rc = StorageResultCode.OperationFailedMediaBlank;
San Mehat207e5382010-02-04 20:46:54 -08001008 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehata5078592010-03-25 09:36:54 -07001009 if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
San Mehat207e5382010-02-04 20:46:54 -08001010 /*
1011 * Volume consistency check failed
1012 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001013 updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001014 action = Intent.ACTION_MEDIA_UNMOUNTABLE;
San Mehatb1043402010-02-05 08:26:50 -08001015 rc = StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001016 } else {
San Mehatb1043402010-02-05 08:26:50 -08001017 rc = StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001018 }
1019
1020 /*
1021 * Send broadcast intent (if required for the failure)
1022 */
Mike Lockwooda5250c92011-05-23 13:44:04 -04001023 if (action != null) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001024 sendStorageIntent(action, volume, UserHandle.ALL);
San Mehat207e5382010-02-04 20:46:54 -08001025 }
1026 }
1027
1028 return rc;
1029 }
1030
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001031 /*
1032 * If force is not set, we do not unmount if there are
1033 * processes holding references to the volume about to be unmounted.
1034 * If force is set, all the processes holding references need to be
1035 * killed via the ActivityManager before actually unmounting the volume.
1036 * This might even take a while and might be retried after timed delays
1037 * to make sure we dont end up in an instable state and kill some core
1038 * processes.
Ben Komalo13c71972011-09-07 16:35:56 -07001039 * If removeEncryption is set, force is implied, and the system will remove any encryption
1040 * mapping set on the volume when unmounting.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001041 */
Ben Komalo13c71972011-09-07 16:35:56 -07001042 private int doUnmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat59443a62010-02-09 13:28:45 -08001043 if (!getVolumeState(path).equals(Environment.MEDIA_MOUNTED)) {
San Mehat207e5382010-02-04 20:46:54 -08001044 return VoldResponseCode.OpFailedVolNotMounted;
1045 }
Kenny Rootaa485402010-09-14 14:49:41 -07001046
1047 /*
1048 * Force a GC to make sure AssetManagers in other threads of the
1049 * system_server are cleaned up. We have to do this since AssetManager
1050 * instances are kept as a WeakReference and it's possible we have files
1051 * open on the external storage.
1052 */
1053 Runtime.getRuntime().gc();
1054
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001055 // Redundant probably. But no harm in updating state again.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001056 mPms.updateExternalMediaStatus(false, false);
San Mehat207e5382010-02-04 20:46:54 -08001057 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001058 final Command cmd = new Command("volume", "unmount", path);
1059 if (removeEncryption) {
1060 cmd.appendArg("force_and_revert");
1061 } else if (force) {
1062 cmd.appendArg("force");
1063 }
1064 mConnector.execute(cmd);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001065 // We unmounted the volume. None of the asec containers are available now.
1066 synchronized (mAsecMountSet) {
1067 mAsecMountSet.clear();
1068 }
San Mehatb1043402010-02-05 08:26:50 -08001069 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001070 } catch (NativeDaemonConnectorException e) {
1071 // Don't worry about mismatch in PackageManager since the
1072 // call back will handle the status changes any way.
1073 int code = e.getCode();
1074 if (code == VoldResponseCode.OpFailedVolNotMounted) {
San Mehata181b212010-02-11 06:50:20 -08001075 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehatd9709982010-02-18 11:43:03 -08001076 } else if (code == VoldResponseCode.OpFailedStorageBusy) {
1077 return StorageResultCode.OperationFailedStorageBusy;
San Mehat207e5382010-02-04 20:46:54 -08001078 } else {
San Mehatb1043402010-02-05 08:26:50 -08001079 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001080 }
1081 }
1082 }
1083
1084 private int doFormatVolume(String path) {
1085 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001086 mConnector.execute("volume", "format", path);
San Mehatb1043402010-02-05 08:26:50 -08001087 return StorageResultCode.OperationSucceeded;
San Mehat207e5382010-02-04 20:46:54 -08001088 } catch (NativeDaemonConnectorException e) {
1089 int code = e.getCode();
1090 if (code == VoldResponseCode.OpFailedNoMedia) {
San Mehatb1043402010-02-05 08:26:50 -08001091 return StorageResultCode.OperationFailedNoMedia;
San Mehat207e5382010-02-04 20:46:54 -08001092 } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
San Mehatb1043402010-02-05 08:26:50 -08001093 return StorageResultCode.OperationFailedMediaCorrupt;
San Mehat207e5382010-02-04 20:46:54 -08001094 } else {
San Mehatb1043402010-02-05 08:26:50 -08001095 return StorageResultCode.OperationFailedInternalError;
San Mehat207e5382010-02-04 20:46:54 -08001096 }
1097 }
1098 }
1099
San Mehatb1043402010-02-05 08:26:50 -08001100 private boolean doGetVolumeShared(String path, String method) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001101 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001102 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001103 event = mConnector.execute("volume", "shared", path, method);
Kenny Roota80ce062010-06-01 13:23:53 -07001104 } catch (NativeDaemonConnectorException ex) {
1105 Slog.e(TAG, "Failed to read response to volume shared " + path + " " + method);
1106 return false;
1107 }
San Mehatb1043402010-02-05 08:26:50 -08001108
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001109 if (event.getCode() == VoldResponseCode.ShareEnabledResult) {
1110 return event.getMessage().endsWith("enabled");
1111 } else {
1112 return false;
San Mehatb1043402010-02-05 08:26:50 -08001113 }
San Mehatb1043402010-02-05 08:26:50 -08001114 }
1115
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001116 private void notifyShareAvailabilityChange(final boolean avail) {
San Mehat4270e1e2010-01-29 05:32:19 -08001117 synchronized (mListeners) {
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001118 mUmsAvailable = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001119 for (int i = mListeners.size() -1; i >= 0; i--) {
1120 MountServiceBinderListener bl = mListeners.get(i);
1121 try {
San Mehatb1043402010-02-05 08:26:50 -08001122 bl.mListener.onUsbMassStorageConnectionChanged(avail);
San Mehat4270e1e2010-01-29 05:32:19 -08001123 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001124 Slog.e(TAG, "Listener dead");
San Mehat4270e1e2010-01-29 05:32:19 -08001125 mListeners.remove(i);
1126 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001127 Slog.e(TAG, "Listener failed", ex);
San Mehat4270e1e2010-01-29 05:32:19 -08001128 }
1129 }
1130 }
1131
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001132 if (mSystemReady == true) {
San Mehat6a965af22010-02-24 17:47:30 -08001133 sendUmsIntent(avail);
1134 } else {
1135 mSendUmsConnectedOnBoot = avail;
San Mehat4270e1e2010-01-29 05:32:19 -08001136 }
San Mehat2fe718a2010-03-11 12:01:49 -08001137
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001138 final StorageVolume primary = getPrimaryPhysicalVolume();
1139 if (avail == false && primary != null
1140 && Environment.MEDIA_SHARED.equals(getVolumeState(primary.getPath()))) {
1141 final String path = primary.getPath();
San Mehat2fe718a2010-03-11 12:01:49 -08001142 /*
1143 * USB mass storage disconnected while enabled
1144 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001145 new Thread("MountService#AvailabilityChange") {
Jason parks5af0b912010-11-29 09:05:25 -06001146 @Override
San Mehat2fe718a2010-03-11 12:01:49 -08001147 public void run() {
1148 try {
1149 int rc;
San Mehata5078592010-03-25 09:36:54 -07001150 Slog.w(TAG, "Disabling UMS after cable disconnect");
San Mehat2fe718a2010-03-11 12:01:49 -08001151 doShareUnshareVolume(path, "ums", false);
1152 if ((rc = doMountVolume(path)) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001153 Slog.e(TAG, String.format(
San Mehat2fe718a2010-03-11 12:01:49 -08001154 "Failed to remount {%s} on UMS enabled-disconnect (%d)",
1155 path, rc));
1156 }
1157 } catch (Exception ex) {
San Mehata5078592010-03-25 09:36:54 -07001158 Slog.w(TAG, "Failed to mount media on UMS enabled-disconnect", ex);
San Mehat2fe718a2010-03-11 12:01:49 -08001159 }
1160 }
1161 }.start();
1162 }
San Mehat4270e1e2010-01-29 05:32:19 -08001163 }
1164
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001165 private void sendStorageIntent(String action, StorageVolume volume, UserHandle user) {
1166 final Intent intent = new Intent(action, Uri.parse("file://" + volume.getPath()));
1167 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, volume);
1168 Slog.d(TAG, "sendStorageIntent " + intent + " to " + user);
1169 mContext.sendBroadcastAsUser(intent, user);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001170 }
1171
San Mehat6a965af22010-02-24 17:47:30 -08001172 private void sendUmsIntent(boolean c) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001173 mContext.sendBroadcastAsUser(
1174 new Intent((c ? Intent.ACTION_UMS_CONNECTED : Intent.ACTION_UMS_DISCONNECTED)),
1175 UserHandle.ALL);
San Mehat6a965af22010-02-24 17:47:30 -08001176 }
1177
San Mehat207e5382010-02-04 20:46:54 -08001178 private void validatePermission(String perm) {
San Mehat4270e1e2010-01-29 05:32:19 -08001179 if (mContext.checkCallingOrSelfPermission(perm) != PackageManager.PERMISSION_GRANTED) {
1180 throw new SecurityException(String.format("Requires %s permission", perm));
1181 }
1182 }
1183
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001184 // Storage list XML tags
1185 private static final String TAG_STORAGE_LIST = "StorageList";
1186 private static final String TAG_STORAGE = "storage";
1187
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001188 private void readStorageListLocked() {
1189 mVolumes.clear();
1190 mVolumeStates.clear();
1191
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001192 Resources resources = mContext.getResources();
1193
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001194 int id = com.android.internal.R.xml.storage_list;
1195 XmlResourceParser parser = resources.getXml(id);
1196 AttributeSet attrs = Xml.asAttributeSet(parser);
1197
1198 try {
1199 XmlUtils.beginDocument(parser, TAG_STORAGE_LIST);
1200 while (true) {
1201 XmlUtils.nextElement(parser);
1202
1203 String element = parser.getName();
1204 if (element == null) break;
1205
1206 if (TAG_STORAGE.equals(element)) {
1207 TypedArray a = resources.obtainAttributes(attrs,
1208 com.android.internal.R.styleable.Storage);
1209
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001210 String path = a.getString(
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001211 com.android.internal.R.styleable.Storage_mountPoint);
Fabrice Di Meglio13fe2a52012-05-18 18:08:58 -07001212 int descriptionId = a.getResourceId(
1213 com.android.internal.R.styleable.Storage_storageDescription, -1);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001214 CharSequence description = a.getText(
1215 com.android.internal.R.styleable.Storage_storageDescription);
1216 boolean primary = a.getBoolean(
1217 com.android.internal.R.styleable.Storage_primary, false);
1218 boolean removable = a.getBoolean(
1219 com.android.internal.R.styleable.Storage_removable, false);
1220 boolean emulated = a.getBoolean(
1221 com.android.internal.R.styleable.Storage_emulated, false);
1222 int mtpReserve = a.getInt(
1223 com.android.internal.R.styleable.Storage_mtpReserve, 0);
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001224 boolean allowMassStorage = a.getBoolean(
1225 com.android.internal.R.styleable.Storage_allowMassStorage, false);
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001226 // resource parser does not support longs, so XML value is in megabytes
1227 long maxFileSize = a.getInt(
1228 com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001229
1230 Slog.d(TAG, "got storage path: " + path + " description: " + description +
1231 " primary: " + primary + " removable: " + removable +
Mike Lockwood8e8b2802011-06-07 08:03:33 -07001232 " emulated: " + emulated + " mtpReserve: " + mtpReserve +
Mike Lockwood7a59dd22011-07-11 09:18:03 -04001233 " allowMassStorage: " + allowMassStorage +
1234 " maxFileSize: " + maxFileSize);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001235
1236 if (emulated) {
1237 // For devices with emulated storage, we create separate
1238 // volumes for each known user.
1239 mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false,
1240 true, mtpReserve, false, maxFileSize, null);
1241
1242 final UserManagerService userManager = UserManagerService.getInstance();
Amith Yamasani920ace02012-09-20 22:15:37 -07001243 for (UserInfo user : userManager.getUsers(false)) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001244 createEmulatedVolumeForUserLocked(user.getUserHandle());
1245 }
1246
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001247 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001248 if (path == null || description == null) {
1249 Slog.e(TAG, "Missing storage path or description in readStorageList");
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001250 } else {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001251 final StorageVolume volume = new StorageVolume(new File(path),
1252 descriptionId, primary, removable, emulated, mtpReserve,
1253 allowMassStorage, maxFileSize, null);
1254 addVolumeLocked(volume);
Jeff Sharkey44cbdec2013-10-07 16:49:47 -07001255
1256 // Until we hear otherwise, treat as unmounted
1257 mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED);
Mike Lockwood2f6a3882011-05-09 19:08:06 -07001258 }
1259 }
Jeff Sharkeyb049e212012-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 Sharkeyb049e212012-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 Sharkeyb049e212012-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);
1301 }
1302 }
1303
1304 private void addVolumeLocked(StorageVolume volume) {
1305 Slog.d(TAG, "addVolumeLocked() " + volume);
1306 mVolumes.add(volume);
1307 final StorageVolume existing = mVolumesByPath.put(volume.getPath(), volume);
1308 if (existing != null) {
1309 throw new IllegalStateException(
1310 "Volume at " + volume.getPath() + " already exists: " + existing);
1311 }
1312 }
1313
1314 private void removeVolumeLocked(StorageVolume volume) {
1315 Slog.d(TAG, "removeVolumeLocked() " + volume);
1316 mVolumes.remove(volume);
1317 mVolumesByPath.remove(volume.getPath());
1318 mVolumeStates.remove(volume.getPath());
1319 }
1320
1321 private StorageVolume getPrimaryPhysicalVolume() {
1322 synchronized (mVolumesLock) {
1323 for (StorageVolume volume : mVolumes) {
1324 if (volume.isPrimary() && !volume.isEmulated()) {
1325 return volume;
1326 }
1327 }
1328 }
1329 return null;
1330 }
1331
1332 /**
San Mehat207e5382010-02-04 20:46:54 -08001333 * Constructs a new MountService instance
1334 *
1335 * @param context Binder context for this service
1336 */
1337 public MountService(Context context) {
1338 mContext = context;
1339
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001340 synchronized (mVolumesLock) {
1341 readStorageListLocked();
Mike Lockwood03559752010-07-19 18:25:03 -04001342 }
1343
San Mehat207e5382010-02-04 20:46:54 -08001344 // XXX: This will go away soon in favor of IMountServiceObserver
1345 mPms = (PackageManagerService) ServiceManager.getService("package");
1346
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001347 HandlerThread hthread = new HandlerThread(TAG);
1348 hthread.start();
1349 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001350
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001351 // Watch for user changes
1352 final IntentFilter userFilter = new IntentFilter();
1353 userFilter.addAction(Intent.ACTION_USER_ADDED);
1354 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1355 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1356
1357 // Watch for USB changes on primary volume
1358 final StorageVolume primary = getPrimaryPhysicalVolume();
1359 if (primary != null && primary.allowMassStorage()) {
1360 mContext.registerReceiver(
1361 mUsbReceiver, new IntentFilter(UsbManager.ACTION_USB_STATE), null, mHandler);
1362 }
1363
Svetoslava7452ee2013-03-20 12:06:59 -07001364 // Watch for idle maintenance changes
1365 IntentFilter idleMaintenanceFilter = new IntentFilter();
1366 idleMaintenanceFilter.addAction(Intent.ACTION_IDLE_MAINTENANCE_START);
1367 mContext.registerReceiverAsUser(mIdleMaintenanceReceiver, UserHandle.ALL,
1368 idleMaintenanceFilter, null, mHandler);
1369
Kenny Roota02b8b02010-08-05 16:14:17 -07001370 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001371 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001372
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001373 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001374 * Create the connection to vold with a maximum queue of twice the
1375 * amount of containers we'd ever expect to have. This keeps an
1376 * "asec list" from blocking a thread repeatedly.
1377 */
Robert Greenwalt470fd722012-01-18 12:51:15 -08001378 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25);
Kenny Root51a573c2012-05-17 13:30:28 -07001379
Kenny Root305bcbf2010-09-03 07:56:38 -07001380 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001381 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001382
Kenny Root07714d42011-08-17 17:49:28 -07001383 // Add ourself to the Watchdog monitors if enabled.
1384 if (WATCHDOG_ENABLE) {
1385 Watchdog.getInstance().addMonitor(this);
1386 }
San Mehat207e5382010-02-04 20:46:54 -08001387 }
1388
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001389 public void systemReady() {
1390 mSystemReady = true;
1391 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1392 }
1393
San Mehat207e5382010-02-04 20:46:54 -08001394 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001395 * Exposed API calls below here
1396 */
1397
1398 public void registerListener(IMountServiceListener listener) {
1399 synchronized (mListeners) {
1400 MountServiceBinderListener bl = new MountServiceBinderListener(listener);
1401 try {
1402 listener.asBinder().linkToDeath(bl, 0);
1403 mListeners.add(bl);
1404 } catch (RemoteException rex) {
San Mehata5078592010-03-25 09:36:54 -07001405 Slog.e(TAG, "Failed to link to listener death");
San Mehat4270e1e2010-01-29 05:32:19 -08001406 }
1407 }
1408 }
1409
1410 public void unregisterListener(IMountServiceListener listener) {
1411 synchronized (mListeners) {
1412 for(MountServiceBinderListener bl : mListeners) {
1413 if (bl.mListener == listener) {
1414 mListeners.remove(mListeners.indexOf(bl));
Vairavan Srinivasan5c25a2d2012-01-24 08:22:14 -08001415 listener.asBinder().unlinkToDeath(bl, 0);
San Mehat4270e1e2010-01-29 05:32:19 -08001416 return;
1417 }
1418 }
1419 }
1420 }
1421
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001422 public void shutdown(final IMountShutdownObserver observer) {
San Mehat4270e1e2010-01-29 05:32:19 -08001423 validatePermission(android.Manifest.permission.SHUTDOWN);
1424
San Mehata5078592010-03-25 09:36:54 -07001425 Slog.i(TAG, "Shutting down");
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001426 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001427 for (String path : mVolumeStates.keySet()) {
1428 String state = mVolumeStates.get(path);
San Mehat4270e1e2010-01-29 05:32:19 -08001429
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001430 if (state.equals(Environment.MEDIA_SHARED)) {
1431 /*
1432 * If the media is currently shared, unshare it.
1433 * XXX: This is still dangerous!. We should not
1434 * be rebooting at *all* if UMS is enabled, since
1435 * the UMS host could have dirty FAT cache entries
1436 * yet to flush.
1437 */
1438 setUsbMassStorageEnabled(false);
1439 } else if (state.equals(Environment.MEDIA_CHECKING)) {
1440 /*
1441 * If the media is being checked, then we need to wait for
1442 * it to complete before being able to proceed.
1443 */
1444 // XXX: @hackbod - Should we disable the ANR timer here?
1445 int retries = 30;
1446 while (state.equals(Environment.MEDIA_CHECKING) && (retries-- >=0)) {
1447 try {
1448 Thread.sleep(1000);
1449 } catch (InterruptedException iex) {
1450 Slog.e(TAG, "Interrupted while waiting for media", iex);
1451 break;
1452 }
1453 state = Environment.getExternalStorageState();
1454 }
1455 if (retries == 0) {
1456 Slog.e(TAG, "Timed out waiting for media to check");
1457 }
San Mehat91c77612010-01-07 10:39:41 -08001458 }
San Mehat91c77612010-01-07 10:39:41 -08001459
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001460 if (state.equals(Environment.MEDIA_MOUNTED)) {
1461 // Post a unmount message.
1462 ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
1463 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
1464 } else if (observer != null) {
1465 /*
1466 * Observer is waiting for onShutDownComplete when we are done.
1467 * Since nothing will be done send notification directly so shutdown
1468 * sequence can continue.
1469 */
1470 try {
1471 observer.onShutDownComplete(StorageResultCode.OperationSucceeded);
1472 } catch (RemoteException e) {
1473 Slog.w(TAG, "RemoteException when shutting down");
1474 }
1475 }
Johan Alfven5d0db4d2010-11-09 10:32:25 +01001476 }
San Mehat4270e1e2010-01-29 05:32:19 -08001477 }
1478 }
1479
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001480 private boolean getUmsEnabling() {
1481 synchronized (mListeners) {
1482 return mUmsEnabling;
1483 }
1484 }
1485
1486 private void setUmsEnabling(boolean enable) {
1487 synchronized (mListeners) {
Tony Wufc711252010-08-09 16:49:19 +08001488 mUmsEnabling = enable;
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001489 }
1490 }
1491
San Mehatb1043402010-02-05 08:26:50 -08001492 public boolean isUsbMassStorageConnected() {
San Mehat207e5382010-02-04 20:46:54 -08001493 waitForReady();
San Mehat91c77612010-01-07 10:39:41 -08001494
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001495 if (getUmsEnabling()) {
San Mehatb1043402010-02-05 08:26:50 -08001496 return true;
San Mehat7fd0fee2009-12-17 07:12:23 -08001497 }
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001498 synchronized (mListeners) {
1499 return mUmsAvailable;
1500 }
San Mehatb1043402010-02-05 08:26:50 -08001501 }
1502
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001503 public void setUsbMassStorageEnabled(boolean enable) {
San Mehatb1043402010-02-05 08:26:50 -08001504 waitForReady();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001505 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatb1043402010-02-05 08:26:50 -08001506
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001507 final StorageVolume primary = getPrimaryPhysicalVolume();
1508 if (primary == null) return;
1509
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001510 // TODO: Add support for multiple share methods
1511
1512 /*
1513 * If the volume is mounted and we're enabling then unmount it
1514 */
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001515 String path = primary.getPath();
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001516 String vs = getVolumeState(path);
1517 String method = "ums";
1518 if (enable && vs.equals(Environment.MEDIA_MOUNTED)) {
1519 // Override for isUsbMassStorageEnabled()
1520 setUmsEnabling(enable);
1521 UmsEnableCallBack umscb = new UmsEnableCallBack(path, method, true);
1522 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, umscb));
1523 // Clear override
1524 setUmsEnabling(false);
1525 }
1526 /*
1527 * If we disabled UMS then mount the volume
1528 */
1529 if (!enable) {
1530 doShareUnshareVolume(path, method, enable);
1531 if (doMountVolume(path) != StorageResultCode.OperationSucceeded) {
San Mehata5078592010-03-25 09:36:54 -07001532 Slog.e(TAG, "Failed to remount " + path +
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001533 " after disabling share method " + method);
1534 /*
1535 * Even though the mount failed, the unshare didn't so don't indicate an error.
1536 * The mountVolume() call will have set the storage state and sent the necessary
1537 * broadcasts.
1538 */
1539 }
1540 }
San Mehatb1043402010-02-05 08:26:50 -08001541 }
1542
1543 public boolean isUsbMassStorageEnabled() {
1544 waitForReady();
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001545
1546 final StorageVolume primary = getPrimaryPhysicalVolume();
1547 if (primary != null) {
1548 return doGetVolumeShared(primary.getPath(), "ums");
1549 } else {
1550 return false;
1551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001553
San Mehat7fd0fee2009-12-17 07:12:23 -08001554 /**
1555 * @return state of the volume at the specified mount point
1556 */
San Mehat4270e1e2010-01-29 05:32:19 -08001557 public String getVolumeState(String mountPoint) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001558 synchronized (mVolumesLock) {
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001559 String state = mVolumeStates.get(mountPoint);
1560 if (state == null) {
1561 Slog.w(TAG, "getVolumeState(" + mountPoint + "): Unknown volume");
Ken Sumrall18db5c52011-07-14 11:35:06 -07001562 if (SystemProperties.get("vold.encrypt_progress").length() != 0) {
1563 state = Environment.MEDIA_REMOVED;
1564 } else {
1565 throw new IllegalArgumentException();
1566 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001567 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001568
Mike Lockwood7fa24aa2011-03-23 14:52:34 -04001569 return state;
1570 }
San Mehat7fd0fee2009-12-17 07:12:23 -08001571 }
1572
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001573 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001574 public boolean isExternalStorageEmulated() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001575 return mEmulatedTemplate != null;
Kenny Roote1ff2142010-10-12 11:20:01 -07001576 }
1577
San Mehat4270e1e2010-01-29 05:32:19 -08001578 public int mountVolume(String path) {
1579 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat4270e1e2010-01-29 05:32:19 -08001580
San Mehat207e5382010-02-04 20:46:54 -08001581 waitForReady();
1582 return doMountVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
Ben Komalo13c71972011-09-07 16:35:56 -07001585 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
San Mehat4270e1e2010-01-29 05:32:19 -08001586 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001587 waitForReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001589 String volState = getVolumeState(path);
Ben Komalo13c71972011-09-07 16:35:56 -07001590 if (DEBUG_UNMOUNT) {
1591 Slog.i(TAG, "Unmounting " + path
1592 + " force = " + force
1593 + " removeEncryption = " + removeEncryption);
1594 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001595 if (Environment.MEDIA_UNMOUNTED.equals(volState) ||
1596 Environment.MEDIA_REMOVED.equals(volState) ||
1597 Environment.MEDIA_SHARED.equals(volState) ||
1598 Environment.MEDIA_UNMOUNTABLE.equals(volState)) {
1599 // Media already unmounted or cannot be unmounted.
1600 // TODO return valid return code when adding observer call back.
1601 return;
1602 }
Ben Komalo13c71972011-09-07 16:35:56 -07001603 UnmountCallBack ucb = new UnmountCallBack(path, force, removeEncryption);
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08001604 mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
San Mehat4270e1e2010-01-29 05:32:19 -08001607 public int formatVolume(String path) {
1608 validatePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001609 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001610
San Mehat207e5382010-02-04 20:46:54 -08001611 return doFormatVolume(path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
1613
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07001614 public int[] getStorageUsers(String path) {
San Mehatc1b4ce92010-02-16 17:13:03 -08001615 validatePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1616 waitForReady();
1617 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001618 final String[] r = NativeDaemonEvent.filterMessageList(
1619 mConnector.executeForList("storage", "users", path),
1620 VoldResponseCode.StorageUsersListResult);
1621
San Mehatc1b4ce92010-02-16 17:13:03 -08001622 // FMT: <pid> <process name>
1623 int[] data = new int[r.length];
1624 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001625 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08001626 try {
1627 data[i] = Integer.parseInt(tok[0]);
1628 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07001629 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08001630 return new int[0];
1631 }
1632 }
1633 return data;
1634 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07001635 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08001636 return new int[0];
1637 }
1638 }
1639
San Mehatb1043402010-02-05 08:26:50 -08001640 private void warnOnNotMounted() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001641 final StorageVolume primary = getPrimaryPhysicalVolume();
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001642 if (primary != null) {
1643 boolean mounted = false;
1644 try {
1645 mounted = Environment.MEDIA_MOUNTED.equals(getVolumeState(primary.getPath()));
Jeff Sharkey9ae62f52013-03-26 10:29:01 -07001646 } catch (IllegalArgumentException e) {
Jeff Sharkey32ee8312012-09-30 13:21:31 -07001647 }
1648
1649 if (!mounted) {
1650 Slog.w(TAG, "getSecureContainerList() called when storage not mounted");
1651 }
San Mehatb1043402010-02-05 08:26:50 -08001652 }
1653 }
1654
San Mehat4270e1e2010-01-29 05:32:19 -08001655 public String[] getSecureContainerList() {
1656 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001657 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001658 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001659
San Mehat4270e1e2010-01-29 05:32:19 -08001660 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001661 return NativeDaemonEvent.filterMessageList(
1662 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08001663 } catch (NativeDaemonConnectorException e) {
1664 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
San Mehat36972292010-01-06 11:06:32 -08001667
Kenny Root6dceb882012-04-12 14:23:49 -07001668 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
1669 int ownerUid, boolean external) {
San Mehat4270e1e2010-01-29 05:32:19 -08001670 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08001671 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001672 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001673
San Mehatb1043402010-02-05 08:26:50 -08001674 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001675 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001676 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
1677 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08001678 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001679 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001680 }
San Mehata181b212010-02-11 06:50:20 -08001681
1682 if (rc == StorageResultCode.OperationSucceeded) {
1683 synchronized (mAsecMountSet) {
1684 mAsecMountSet.add(id);
1685 }
1686 }
San Mehat4270e1e2010-01-29 05:32:19 -08001687 return rc;
San Mehat36972292010-01-06 11:06:32 -08001688 }
1689
San Mehat4270e1e2010-01-29 05:32:19 -08001690 public int finalizeSecureContainer(String id) {
1691 validatePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08001692 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001693
San Mehatb1043402010-02-05 08:26:50 -08001694 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001695 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001696 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08001697 /*
1698 * Finalization does a remount, so no need
1699 * to update mAsecMountSet
1700 */
San Mehat4270e1e2010-01-29 05:32:19 -08001701 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001702 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001703 }
San Mehat4270e1e2010-01-29 05:32:19 -08001704 return rc;
San Mehat36972292010-01-06 11:06:32 -08001705 }
1706
Kenny Root6dceb882012-04-12 14:23:49 -07001707 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
1708 validatePermission(android.Manifest.permission.ASEC_CREATE);
1709 warnOnNotMounted();
1710
1711 int rc = StorageResultCode.OperationSucceeded;
1712 try {
1713 mConnector.execute("asec", "fixperms", id, gid, filename);
1714 /*
1715 * Fix permissions does a remount, so no need to update
1716 * mAsecMountSet
1717 */
1718 } catch (NativeDaemonConnectorException e) {
1719 rc = StorageResultCode.OperationFailedInternalError;
1720 }
1721 return rc;
1722 }
1723
San Mehatd9709982010-02-18 11:43:03 -08001724 public int destroySecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001725 validatePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08001726 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001727 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001728
Kenny Rootaa485402010-09-14 14:49:41 -07001729 /*
1730 * Force a GC to make sure AssetManagers in other threads of the
1731 * system_server are cleaned up. We have to do this since AssetManager
1732 * instances are kept as a WeakReference and it's possible we have files
1733 * open on the external storage.
1734 */
1735 Runtime.getRuntime().gc();
1736
San Mehatb1043402010-02-05 08:26:50 -08001737 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001738 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001739 final Command cmd = new Command("asec", "destroy", id);
1740 if (force) {
1741 cmd.appendArg("force");
1742 }
1743 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001744 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001745 int code = e.getCode();
1746 if (code == VoldResponseCode.OpFailedStorageBusy) {
1747 rc = StorageResultCode.OperationFailedStorageBusy;
1748 } else {
1749 rc = StorageResultCode.OperationFailedInternalError;
1750 }
San Mehat02735bc2010-01-26 15:18:08 -08001751 }
San Mehata181b212010-02-11 06:50:20 -08001752
1753 if (rc == StorageResultCode.OperationSucceeded) {
1754 synchronized (mAsecMountSet) {
1755 if (mAsecMountSet.contains(id)) {
1756 mAsecMountSet.remove(id);
1757 }
1758 }
1759 }
1760
San Mehat4270e1e2010-01-29 05:32:19 -08001761 return rc;
San Mehat36972292010-01-06 11:06:32 -08001762 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001763
San Mehat4270e1e2010-01-29 05:32:19 -08001764 public int mountSecureContainer(String id, String key, int ownerUid) {
1765 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001766 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001767 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001768
San Mehata181b212010-02-11 06:50:20 -08001769 synchronized (mAsecMountSet) {
1770 if (mAsecMountSet.contains(id)) {
1771 return StorageResultCode.OperationFailedStorageMounted;
1772 }
1773 }
1774
San Mehatb1043402010-02-05 08:26:50 -08001775 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001776 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07001777 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid);
San Mehat4270e1e2010-01-29 05:32:19 -08001778 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07001779 int code = e.getCode();
1780 if (code != VoldResponseCode.OpFailedStorageBusy) {
1781 rc = StorageResultCode.OperationFailedInternalError;
1782 }
San Mehat02735bc2010-01-26 15:18:08 -08001783 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001784
1785 if (rc == StorageResultCode.OperationSucceeded) {
1786 synchronized (mAsecMountSet) {
1787 mAsecMountSet.add(id);
1788 }
1789 }
San Mehat4270e1e2010-01-29 05:32:19 -08001790 return rc;
San Mehat36972292010-01-06 11:06:32 -08001791 }
1792
San Mehatd9709982010-02-18 11:43:03 -08001793 public int unmountSecureContainer(String id, boolean force) {
San Mehat4270e1e2010-01-29 05:32:19 -08001794 validatePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08001795 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001796 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001797
San Mehat6cdd9c02010-02-09 14:45:20 -08001798 synchronized (mAsecMountSet) {
1799 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08001800 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08001801 }
1802 }
1803
Kenny Rootaa485402010-09-14 14:49:41 -07001804 /*
1805 * Force a GC to make sure AssetManagers in other threads of the
1806 * system_server are cleaned up. We have to do this since AssetManager
1807 * instances are kept as a WeakReference and it's possible we have files
1808 * open on the external storage.
1809 */
1810 Runtime.getRuntime().gc();
1811
San Mehatb1043402010-02-05 08:26:50 -08001812 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001813 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001814 final Command cmd = new Command("asec", "unmount", id);
1815 if (force) {
1816 cmd.appendArg("force");
1817 }
1818 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08001819 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08001820 int code = e.getCode();
1821 if (code == VoldResponseCode.OpFailedStorageBusy) {
1822 rc = StorageResultCode.OperationFailedStorageBusy;
1823 } else {
1824 rc = StorageResultCode.OperationFailedInternalError;
1825 }
San Mehat02735bc2010-01-26 15:18:08 -08001826 }
San Mehat6cdd9c02010-02-09 14:45:20 -08001827
1828 if (rc == StorageResultCode.OperationSucceeded) {
1829 synchronized (mAsecMountSet) {
1830 mAsecMountSet.remove(id);
1831 }
1832 }
San Mehat4270e1e2010-01-29 05:32:19 -08001833 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08001834 }
1835
San Mehat6cdd9c02010-02-09 14:45:20 -08001836 public boolean isSecureContainerMounted(String id) {
1837 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1838 waitForReady();
1839 warnOnNotMounted();
1840
1841 synchronized (mAsecMountSet) {
1842 return mAsecMountSet.contains(id);
1843 }
1844 }
1845
San Mehat4270e1e2010-01-29 05:32:19 -08001846 public int renameSecureContainer(String oldId, String newId) {
1847 validatePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08001848 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001849 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08001850
San Mehata181b212010-02-11 06:50:20 -08001851 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08001852 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06001853 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08001854 * changed while active, we must ensure both ids are not currently mounted.
1855 */
1856 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08001857 return StorageResultCode.OperationFailedStorageMounted;
1858 }
1859 }
1860
San Mehatb1043402010-02-05 08:26:50 -08001861 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08001862 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001863 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08001864 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08001865 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08001866 }
San Mehata181b212010-02-11 06:50:20 -08001867
San Mehat4270e1e2010-01-29 05:32:19 -08001868 return rc;
San Mehat45f61042010-01-23 08:12:43 -08001869 }
1870
San Mehat4270e1e2010-01-29 05:32:19 -08001871 public String getSecureContainerPath(String id) {
1872 validatePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08001873 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08001874 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08001875
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001876 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07001877 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001878 event = mConnector.execute("asec", "path", id);
1879 event.checkCode(VoldResponseCode.AsecPathResult);
1880 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07001881 } catch (NativeDaemonConnectorException e) {
1882 int code = e.getCode();
1883 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01001884 Slog.i(TAG, String.format("Container '%s' not found", id));
1885 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08001886 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07001887 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08001888 }
1889 }
San Mehat22dd86e2010-01-12 12:21:18 -08001890 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001891
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001892 public String getSecureContainerFilesystemPath(String id) {
1893 validatePermission(android.Manifest.permission.ASEC_ACCESS);
1894 waitForReady();
1895 warnOnNotMounted();
1896
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001897 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001898 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001899 event = mConnector.execute("asec", "fspath", id);
1900 event.checkCode(VoldResponseCode.AsecPathResult);
1901 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07001902 } catch (NativeDaemonConnectorException e) {
1903 int code = e.getCode();
1904 if (code == VoldResponseCode.OpFailedStorageNotFound) {
1905 Slog.i(TAG, String.format("Container '%s' not found", id));
1906 return null;
1907 } else {
1908 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1909 }
1910 }
1911 }
1912
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07001913 public void finishMediaUpdate() {
1914 mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
1915 }
Kenny Root02c87302010-07-01 08:10:18 -07001916
Kenny Roota02b8b02010-08-05 16:14:17 -07001917 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
1918 if (callerUid == android.os.Process.SYSTEM_UID) {
1919 return true;
1920 }
1921
Kenny Root02c87302010-07-01 08:10:18 -07001922 if (packageName == null) {
1923 return false;
1924 }
1925
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001926 final int packageUid = mPms.getPackageUid(packageName, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07001927
1928 if (DEBUG_OBB) {
1929 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
1930 packageUid + ", callerUid = " + callerUid);
1931 }
1932
1933 return callerUid == packageUid;
1934 }
1935
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001936 public String getMountedObbPath(String rawPath) {
1937 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001938
Kenny Root02c87302010-07-01 08:10:18 -07001939 waitForReady();
1940 warnOnNotMounted();
1941
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001942 final ObbState state;
1943 synchronized (mObbPathToStateMap) {
1944 state = mObbPathToStateMap.get(rawPath);
1945 }
1946 if (state == null) {
1947 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
1948 return null;
1949 }
1950
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001951 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07001952 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001953 event = mConnector.execute("obb", "path", state.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08001954 event.checkCode(VoldResponseCode.AsecPathResult);
1955 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07001956 } catch (NativeDaemonConnectorException e) {
1957 int code = e.getCode();
1958 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07001959 return null;
Kenny Root02c87302010-07-01 08:10:18 -07001960 } else {
1961 throw new IllegalStateException(String.format("Unexpected response code %d", code));
1962 }
1963 }
1964 }
1965
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001966 @Override
1967 public boolean isObbMounted(String rawPath) {
1968 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001969 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001970 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07001971 }
Kenny Root02c87302010-07-01 08:10:18 -07001972 }
1973
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001974 @Override
1975 public void mountObb(
1976 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
1977 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1978 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
1979 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07001980
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001981 final int callingUid = Binder.getCallingUid();
1982 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
1983 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07001984 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
1985
1986 if (DEBUG_OBB)
1987 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07001988 }
1989
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001990 @Override
1991 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
1992 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
1993
1994 final ObbState existingState;
1995 synchronized (mObbPathToStateMap) {
1996 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07001997 }
1998
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07001999 if (existingState != null) {
2000 // TODO: separate state object from request data
2001 final int callingUid = Binder.getCallingUid();
2002 final ObbState newState = new ObbState(
2003 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2004 final ObbAction action = new UnmountObbAction(newState, force);
2005 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002006
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002007 if (DEBUG_OBB)
2008 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2009 } else {
2010 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2011 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002012 }
2013
Ben Komalo444eca22011-09-01 15:17:44 -07002014 @Override
2015 public int getEncryptionState() {
2016 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2017 "no permission to access the crypt keeper");
2018
2019 waitForReady();
2020
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002021 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002022 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002023 event = mConnector.execute("cryptfs", "cryptocomplete");
2024 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002025 } catch (NumberFormatException e) {
2026 // Bad result - unexpected.
2027 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2028 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2029 } catch (NativeDaemonConnectorException e) {
2030 // Something bad happened.
2031 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2032 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2033 }
2034 }
2035
2036 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002037 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002038 if (TextUtils.isEmpty(password)) {
2039 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002040 }
2041
Jason parks8888c592011-01-20 22:46:41 -06002042 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2043 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002044
2045 waitForReady();
2046
2047 if (DEBUG_EVENTS) {
2048 Slog.i(TAG, "decrypting storage...");
2049 }
2050
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002051 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002052 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002053 event = mConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002054
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002055 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002056 if (code == 0) {
2057 // Decrypt was successful. Post a delayed message before restarting in order
2058 // to let the UI to clear itself
2059 mHandler.postDelayed(new Runnable() {
2060 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002061 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002062 mConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002063 } catch (NativeDaemonConnectorException e) {
2064 Slog.e(TAG, "problem executing in background", e);
2065 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002066 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002067 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002068 }
2069
2070 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002071 } catch (NativeDaemonConnectorException e) {
2072 // Decryption failed
2073 return e.getCode();
2074 }
Jason parks5af0b912010-11-29 09:05:25 -06002075 }
2076
Jason parks56aa5322011-01-07 09:01:15 -06002077 public int encryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002078 if (TextUtils.isEmpty(password)) {
2079 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002080 }
2081
Jason parks8888c592011-01-20 22:46:41 -06002082 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2083 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002084
2085 waitForReady();
2086
2087 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002088 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002089 }
2090
2091 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002092 mConnector.execute("cryptfs", "enablecrypto", "inplace", new SensitiveArg(password));
Jason parks56aa5322011-01-07 09:01:15 -06002093 } catch (NativeDaemonConnectorException e) {
2094 // Encryption failed
2095 return e.getCode();
2096 }
2097
2098 return 0;
2099 }
2100
Jason parksf7b3cd42011-01-27 09:28:25 -06002101 public int changeEncryptionPassword(String password) {
2102 if (TextUtils.isEmpty(password)) {
2103 throw new IllegalArgumentException("password cannot be empty");
2104 }
2105
2106 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2107 "no permission to access the crypt keeper");
2108
2109 waitForReady();
2110
2111 if (DEBUG_EVENTS) {
2112 Slog.i(TAG, "changing encryption password...");
2113 }
2114
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002115 final NativeDaemonEvent event;
Jason parksf7b3cd42011-01-27 09:28:25 -06002116 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002117 event = mConnector.execute("cryptfs", "changepw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002118 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002119 } catch (NativeDaemonConnectorException e) {
2120 // Encryption failed
2121 return e.getCode();
2122 }
2123 }
2124
Christopher Tate32418be2011-10-10 13:51:12 -07002125 /**
2126 * Validate a user-supplied password string with cryptfs
2127 */
2128 @Override
2129 public int verifyEncryptionPassword(String password) throws RemoteException {
2130 // Only the system process is permitted to validate passwords
2131 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2132 throw new SecurityException("no permission to access the crypt keeper");
2133 }
2134
2135 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2136 "no permission to access the crypt keeper");
2137
2138 if (TextUtils.isEmpty(password)) {
2139 throw new IllegalArgumentException("password cannot be empty");
2140 }
2141
2142 waitForReady();
2143
2144 if (DEBUG_EVENTS) {
2145 Slog.i(TAG, "validating encryption password...");
2146 }
2147
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002148 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002149 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002150 event = mConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002151 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2152 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002153 } catch (NativeDaemonConnectorException e) {
2154 // Encryption failed
2155 return e.getCode();
2156 }
2157 }
2158
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002159 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002160 public int mkdirs(String callingPkg, String appPath) {
2161 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2162 final UserEnvironment userEnv = new UserEnvironment(userId);
2163
2164 // Validate that reported package name belongs to caller
2165 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2166 Context.APP_OPS_SERVICE);
2167 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2168
2169 try {
2170 appPath = new File(appPath).getCanonicalPath();
2171 } catch (IOException e) {
2172 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2173 return -1;
2174 }
2175
Jeff Sharkey5786a272013-10-02 12:50:34 -07002176 if (!appPath.endsWith("/")) {
2177 appPath = appPath + "/";
2178 }
2179
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002180 // Try translating the app path into a vold path, but require that it
2181 // belong to the calling package.
2182 String voldPath = maybeTranslatePathForVold(appPath,
2183 userEnv.buildExternalStorageAppDataDirs(callingPkg),
2184 userEnv.buildExternalStorageAppDataDirsForVold(callingPkg));
2185 if (voldPath != null) {
2186 try {
2187 mConnector.execute("volume", "mkdirs", voldPath);
2188 return 0;
2189 } catch (NativeDaemonConnectorException e) {
2190 return e.getCode();
2191 }
2192 }
2193
2194 voldPath = maybeTranslatePathForVold(appPath,
2195 userEnv.buildExternalStorageAppObbDirs(callingPkg),
2196 userEnv.buildExternalStorageAppObbDirsForVold(callingPkg));
2197 if (voldPath != null) {
2198 try {
2199 mConnector.execute("volume", "mkdirs", voldPath);
2200 return 0;
2201 } catch (NativeDaemonConnectorException e) {
2202 return e.getCode();
2203 }
2204 }
2205
2206 throw new SecurityException("Invalid mkdirs path: " + appPath);
2207 }
2208
2209 /**
2210 * Translate the given path from an app-visible path to a vold-visible path,
2211 * but only if it's under the given whitelisted paths.
2212 *
2213 * @param path a canonicalized app-visible path.
2214 * @param appPaths list of app-visible paths that are allowed.
2215 * @param voldPaths list of vold-visible paths directly corresponding to the
2216 * allowed app-visible paths argument.
2217 * @return a vold-visible path representing the original path, or
2218 * {@code null} if the given path didn't have an app-to-vold
2219 * mapping.
2220 */
2221 @VisibleForTesting
2222 public static String maybeTranslatePathForVold(
2223 String path, File[] appPaths, File[] voldPaths) {
2224 if (appPaths.length != voldPaths.length) {
2225 throw new IllegalStateException("Paths must be 1:1 mapping");
2226 }
2227
2228 for (int i = 0; i < appPaths.length; i++) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002229 final String appPath = appPaths[i].getAbsolutePath() + "/";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002230 if (path.startsWith(appPath)) {
Jeff Sharkey5786a272013-10-02 12:50:34 -07002231 path = new File(voldPaths[i], path.substring(appPath.length()))
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002232 .getAbsolutePath();
2233 if (!path.endsWith("/")) {
2234 path = path + "/";
2235 }
2236 return path;
2237 }
2238 }
2239 return null;
2240 }
2241
2242 @Override
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002243 public StorageVolume[] getVolumeList() {
2244 final int callingUserId = UserHandle.getCallingUserId();
2245 final boolean accessAll = (mContext.checkPermission(
2246 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2247 Binder.getCallingPid(), Binder.getCallingUid()) == PERMISSION_GRANTED);
2248
2249 synchronized (mVolumesLock) {
2250 final ArrayList<StorageVolume> filtered = Lists.newArrayList();
2251 for (StorageVolume volume : mVolumes) {
2252 final UserHandle owner = volume.getOwner();
2253 final boolean ownerMatch = owner == null || owner.getIdentifier() == callingUserId;
2254 if (accessAll || ownerMatch) {
2255 filtered.add(volume);
2256 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002257 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002258 return filtered.toArray(new StorageVolume[filtered.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002259 }
2260 }
2261
Kenny Rootaf9d6672010-10-08 09:21:39 -07002262 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2263 final IBinder binder = obbState.getBinder();
2264 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07002265
Kenny Rootaf9d6672010-10-08 09:21:39 -07002266 if (obbStates == null) {
2267 obbStates = new ArrayList<ObbState>();
2268 mObbMounts.put(binder, obbStates);
2269 } else {
2270 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002271 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002272 throw new IllegalStateException("Attempt to add ObbState twice. "
2273 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07002274 }
2275 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002276 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002277
2278 obbStates.add(obbState);
2279 try {
2280 obbState.link();
2281 } catch (RemoteException e) {
2282 /*
2283 * The binder died before we could link it, so clean up our state
2284 * and return failure.
2285 */
2286 obbStates.remove(obbState);
2287 if (obbStates.isEmpty()) {
2288 mObbMounts.remove(binder);
2289 }
2290
2291 // Rethrow the error so mountObb can get it
2292 throw e;
2293 }
2294
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002295 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002296 }
2297
Kenny Rootaf9d6672010-10-08 09:21:39 -07002298 private void removeObbStateLocked(ObbState obbState) {
2299 final IBinder binder = obbState.getBinder();
2300 final List<ObbState> obbStates = mObbMounts.get(binder);
2301 if (obbStates != null) {
2302 if (obbStates.remove(obbState)) {
2303 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07002304 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002305 if (obbStates.isEmpty()) {
2306 mObbMounts.remove(binder);
2307 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002308 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002309
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002310 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002311 }
2312
Kenny Roota02b8b02010-08-05 16:14:17 -07002313 private class ObbActionHandler extends Handler {
2314 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07002315 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07002316
2317 ObbActionHandler(Looper l) {
2318 super(l);
2319 }
2320
2321 @Override
2322 public void handleMessage(Message msg) {
2323 switch (msg.what) {
2324 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07002325 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07002326
2327 if (DEBUG_OBB)
2328 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
2329
2330 // If a bind was already initiated we don't really
2331 // need to do anything. The pending install
2332 // will be processed later on.
2333 if (!mBound) {
2334 // If this is the only one pending we might
2335 // have to bind to the service again.
2336 if (!connectToService()) {
2337 Slog.e(TAG, "Failed to bind to media container service");
2338 action.handleError();
2339 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002340 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002341 }
Kenny Root735de3b2010-09-30 14:11:39 -07002342
Kenny Root735de3b2010-09-30 14:11:39 -07002343 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07002344 break;
2345 }
2346 case OBB_MCS_BOUND: {
2347 if (DEBUG_OBB)
2348 Slog.i(TAG, "OBB_MCS_BOUND");
2349 if (msg.obj != null) {
2350 mContainerService = (IMediaContainerService) msg.obj;
2351 }
2352 if (mContainerService == null) {
2353 // Something seriously wrong. Bail out
2354 Slog.e(TAG, "Cannot bind to media container service");
2355 for (ObbAction action : mActions) {
2356 // Indicate service bind error
2357 action.handleError();
2358 }
2359 mActions.clear();
2360 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07002361 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07002362 if (action != null) {
2363 action.execute(this);
2364 }
2365 } else {
2366 // Should never happen ideally.
2367 Slog.w(TAG, "Empty queue");
2368 }
2369 break;
2370 }
2371 case OBB_MCS_RECONNECT: {
2372 if (DEBUG_OBB)
2373 Slog.i(TAG, "OBB_MCS_RECONNECT");
2374 if (mActions.size() > 0) {
2375 if (mBound) {
2376 disconnectService();
2377 }
2378 if (!connectToService()) {
2379 Slog.e(TAG, "Failed to bind to media container service");
2380 for (ObbAction action : mActions) {
2381 // Indicate service bind error
2382 action.handleError();
2383 }
2384 mActions.clear();
2385 }
2386 }
2387 break;
2388 }
2389 case OBB_MCS_UNBIND: {
2390 if (DEBUG_OBB)
2391 Slog.i(TAG, "OBB_MCS_UNBIND");
2392
2393 // Delete pending install
2394 if (mActions.size() > 0) {
2395 mActions.remove(0);
2396 }
2397 if (mActions.size() == 0) {
2398 if (mBound) {
2399 disconnectService();
2400 }
2401 } else {
2402 // There are more pending requests in queue.
2403 // Just post MCS_BOUND message to trigger processing
2404 // of next pending install.
2405 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
2406 }
2407 break;
2408 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002409 case OBB_FLUSH_MOUNT_STATE: {
2410 final String path = (String) msg.obj;
2411
2412 if (DEBUG_OBB)
2413 Slog.i(TAG, "Flushing all OBB state for path " + path);
2414
2415 synchronized (mObbMounts) {
2416 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
2417
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002418 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002419 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002420 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002421
2422 /*
2423 * If this entry's source file is in the volume path
2424 * that got unmounted, remove it because it's no
2425 * longer valid.
2426 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002427 if (state.canonicalPath.startsWith(path)) {
2428 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002429 }
2430 }
2431
2432 for (final ObbState obbState : obbStatesToRemove) {
2433 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002434 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002435
2436 removeObbStateLocked(obbState);
2437
2438 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002439 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07002440 OnObbStateChangeListener.UNMOUNTED);
2441 } catch (RemoteException e) {
2442 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002443 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002444 }
2445 }
2446 }
2447 break;
2448 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002449 }
2450 }
2451
2452 private boolean connectToService() {
2453 if (DEBUG_OBB)
2454 Slog.i(TAG, "Trying to bind to DefaultContainerService");
2455
2456 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
2457 if (mContext.bindService(service, mDefContainerConn, Context.BIND_AUTO_CREATE)) {
2458 mBound = true;
2459 return true;
2460 }
2461 return false;
2462 }
2463
2464 private void disconnectService() {
2465 mContainerService = null;
2466 mBound = false;
2467 mContext.unbindService(mDefContainerConn);
2468 }
2469 }
2470
2471 abstract class ObbAction {
2472 private static final int MAX_RETRIES = 3;
2473 private int mRetries;
2474
2475 ObbState mObbState;
2476
2477 ObbAction(ObbState obbState) {
2478 mObbState = obbState;
2479 }
2480
2481 public void execute(ObbActionHandler handler) {
2482 try {
2483 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07002484 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07002485 mRetries++;
2486 if (mRetries > MAX_RETRIES) {
2487 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07002488 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002489 handleError();
2490 return;
2491 } else {
2492 handleExecute();
2493 if (DEBUG_OBB)
2494 Slog.i(TAG, "Posting install MCS_UNBIND");
2495 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
2496 }
2497 } catch (RemoteException e) {
2498 if (DEBUG_OBB)
2499 Slog.i(TAG, "Posting install MCS_RECONNECT");
2500 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
2501 } catch (Exception e) {
2502 if (DEBUG_OBB)
2503 Slog.d(TAG, "Error handling OBB action", e);
2504 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07002505 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07002506 }
2507 }
2508
Kenny Root05105f72010-09-22 17:29:43 -07002509 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07002510 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07002511
2512 protected ObbInfo getObbInfo() throws IOException {
2513 ObbInfo obbInfo;
2514 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002515 obbInfo = mContainerService.getObbInfo(mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002516 } catch (RemoteException e) {
2517 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002518 + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002519 obbInfo = null;
2520 }
2521 if (obbInfo == null) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002522 throw new IOException("Couldn't read OBB file: " + mObbState.ownerPath);
Kenny Root38cf8862010-09-26 14:18:51 -07002523 }
2524 return obbInfo;
2525 }
2526
Kenny Rootaf9d6672010-10-08 09:21:39 -07002527 protected void sendNewStatusOrIgnore(int status) {
2528 if (mObbState == null || mObbState.token == null) {
2529 return;
2530 }
2531
Kenny Root38cf8862010-09-26 14:18:51 -07002532 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002533 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07002534 } catch (RemoteException e) {
2535 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
2536 }
2537 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002538 }
2539
2540 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002541 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002542 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002543
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002544 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002545 super(obbState);
2546 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002547 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07002548 }
2549
Jason parks5af0b912010-11-29 09:05:25 -06002550 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07002551 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002552 waitForReady();
2553 warnOnNotMounted();
2554
Kenny Root38cf8862010-09-26 14:18:51 -07002555 final ObbInfo obbInfo = getObbInfo();
2556
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002557 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002558 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
2559 + " which is owned by " + obbInfo.packageName);
2560 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2561 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07002562 }
2563
Kenny Rootaf9d6672010-10-08 09:21:39 -07002564 final boolean isMounted;
2565 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002566 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002567 }
2568 if (isMounted) {
2569 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
2570 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
2571 return;
2572 }
2573
Kenny Rootaf9d6672010-10-08 09:21:39 -07002574 final String hashedKey;
2575 if (mKey == null) {
2576 hashedKey = "none";
2577 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002578 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07002579 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
2580
2581 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
2582 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
2583 SecretKey key = factory.generateSecret(ks);
2584 BigInteger bi = new BigInteger(key.getEncoded());
2585 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002586 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07002587 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
2588 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
2589 return;
2590 } catch (InvalidKeySpecException e) {
2591 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
2592 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07002593 return;
2594 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07002595 }
Kenny Root38cf8862010-09-26 14:18:51 -07002596
Kenny Rootaf9d6672010-10-08 09:21:39 -07002597 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002598 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002599 mConnector.execute("obb", "mount", mObbState.voldPath, new SensitiveArg(hashedKey),
2600 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002601 } catch (NativeDaemonConnectorException e) {
2602 int code = e.getCode();
2603 if (code != VoldResponseCode.OpFailedStorageBusy) {
2604 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002605 }
2606 }
2607
Kenny Rootaf9d6672010-10-08 09:21:39 -07002608 if (rc == StorageResultCode.OperationSucceeded) {
2609 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002610 Slog.d(TAG, "Successfully mounted OBB " + mObbState.voldPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002611
2612 synchronized (mObbMounts) {
2613 addObbStateLocked(mObbState);
2614 }
2615
2616 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07002617 } else {
Kenny Root05105f72010-09-22 17:29:43 -07002618 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07002619
Kenny Rootaf9d6672010-10-08 09:21:39 -07002620 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07002621 }
2622 }
2623
Jason parks5af0b912010-11-29 09:05:25 -06002624 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002625 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002626 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07002627 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002628
2629 @Override
2630 public String toString() {
2631 StringBuilder sb = new StringBuilder();
2632 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002633 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002634 sb.append('}');
2635 return sb.toString();
2636 }
2637 }
2638
2639 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07002640 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07002641
2642 UnmountObbAction(ObbState obbState, boolean force) {
2643 super(obbState);
2644 mForceUnmount = force;
2645 }
2646
Jason parks5af0b912010-11-29 09:05:25 -06002647 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07002648 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002649 waitForReady();
2650 warnOnNotMounted();
2651
Kenny Root38cf8862010-09-26 14:18:51 -07002652 final ObbInfo obbInfo = getObbInfo();
Kenny Roota02b8b02010-08-05 16:14:17 -07002653
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002654 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07002655 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002656 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002657 }
Kenny Root38cf8862010-09-26 14:18:51 -07002658
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002659 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002660 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
2661 return;
2662 }
2663
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002664 if (existingState.ownerGid != mObbState.ownerGid) {
2665 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
2666 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002667 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
2668 return;
2669 }
2670
Kenny Rootaf9d6672010-10-08 09:21:39 -07002671 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07002672 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002673 final Command cmd = new Command("obb", "unmount", mObbState.voldPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002674 if (mForceUnmount) {
2675 cmd.appendArg("force");
2676 }
2677 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002678 } catch (NativeDaemonConnectorException e) {
2679 int code = e.getCode();
2680 if (code == VoldResponseCode.OpFailedStorageBusy) {
2681 rc = StorageResultCode.OperationFailedStorageBusy;
2682 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
2683 // If it's not mounted then we've already won.
2684 rc = StorageResultCode.OperationSucceeded;
2685 } else {
2686 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07002687 }
2688 }
2689
Kenny Rootaf9d6672010-10-08 09:21:39 -07002690 if (rc == StorageResultCode.OperationSucceeded) {
2691 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002692 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07002693 }
2694
Kenny Rootaf9d6672010-10-08 09:21:39 -07002695 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07002696 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002697 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002698 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07002699 }
2700 }
2701
Jason parks5af0b912010-11-29 09:05:25 -06002702 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07002703 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07002704 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07002705 }
2706
2707 @Override
2708 public String toString() {
2709 StringBuilder sb = new StringBuilder();
2710 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002711 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07002712 sb.append(",force=");
2713 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07002714 sb.append('}');
2715 return sb.toString();
2716 }
Kenny Root02c87302010-07-01 08:10:18 -07002717 }
Kenny Root38cf8862010-09-26 14:18:51 -07002718
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002719 @VisibleForTesting
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002720 public static String buildObbPath(final String canonicalPath, int userId, boolean forVold) {
2721 // TODO: allow caller to provide Environment for full testing
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002722 // TODO: extend to support OBB mounts on secondary external storage
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002723
2724 // Only adjust paths when storage is emulated
2725 if (!Environment.isExternalStorageEmulated()) {
2726 return canonicalPath;
2727 }
2728
2729 String path = canonicalPath.toString();
2730
2731 // First trim off any external storage prefix
2732 final UserEnvironment userEnv = new UserEnvironment(userId);
2733
2734 // /storage/emulated/0
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002735 final String externalPath = userEnv.getExternalStorageDirectory().getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002736 // /storage/emulated_legacy
2737 final String legacyExternalPath = Environment.getLegacyExternalStorageDirectory()
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002738 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002739
2740 if (path.startsWith(externalPath)) {
2741 path = path.substring(externalPath.length() + 1);
2742 } else if (path.startsWith(legacyExternalPath)) {
2743 path = path.substring(legacyExternalPath.length() + 1);
2744 } else {
2745 return canonicalPath;
2746 }
2747
2748 // Handle special OBB paths on emulated storage
2749 final String obbPath = "Android/obb";
2750 if (path.startsWith(obbPath)) {
2751 path = path.substring(obbPath.length() + 1);
2752
2753 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002754 return new File(Environment.getEmulatedStorageObbSource(), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002755 } else {
2756 final UserEnvironment ownerEnv = new UserEnvironment(UserHandle.USER_OWNER);
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002757 return new File(ownerEnv.buildExternalStorageAndroidObbDirs()[0], path)
2758 .getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002759 }
2760 }
2761
2762 // Handle normal external storage paths
2763 if (forVold) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002764 return new File(Environment.getEmulatedStorageSource(userId), path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002765 } else {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002766 return new File(userEnv.getExternalDirsForApp()[0], path).getAbsolutePath();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002767 }
2768 }
2769
Kenny Root38cf8862010-09-26 14:18:51 -07002770 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002771 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2772 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2773
2774 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Kenny Root38cf8862010-09-26 14:18:51 -07002775
Kenny Root38cf8862010-09-26 14:18:51 -07002776 synchronized (mObbMounts) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002777 pw.println("mObbMounts:");
2778 pw.increaseIndent();
2779 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
2780 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002781 while (binders.hasNext()) {
2782 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002783 pw.println(e.getKey() + ":");
2784 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002785 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07002786 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002787 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07002788 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002789 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002790 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002791 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002792
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002793 pw.println();
2794 pw.println("mObbPathToStateMap:");
2795 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07002796 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
2797 while (maps.hasNext()) {
2798 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002799 pw.print(e.getKey());
2800 pw.print(" -> ");
2801 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07002802 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002803 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002804 }
Kenny Root4161f9b2011-07-13 09:48:33 -07002805
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002806 synchronized (mVolumesLock) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002807 pw.println();
2808 pw.println("mVolumes:");
2809 pw.increaseIndent();
2810 for (StorageVolume volume : mVolumes) {
2811 pw.println(volume);
2812 pw.increaseIndent();
2813 pw.println("Current state: " + mVolumeStates.get(volume.getPath()));
2814 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002815 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002816 pw.decreaseIndent();
Kenny Root4161f9b2011-07-13 09:48:33 -07002817 }
Robert Greenwalt470fd722012-01-18 12:51:15 -08002818
2819 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002820 pw.println("mConnection:");
2821 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08002822 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07002823 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07002824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002826 /** {@inheritDoc} */
2827 public void monitor() {
2828 if (mConnector != null) {
2829 mConnector.monitor();
2830 }
2831 }
2832}