blob: 53923ba972c71882ce03a8d919abf6f0c52057de [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 Sharkey4c099d02015-05-15 13:45:00 -070019import static com.android.internal.util.XmlUtils.readBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070020import static com.android.internal.util.XmlUtils.readIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070021import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070022import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkey4c099d02015-05-15 13:45:00 -070023import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070024import static com.android.internal.util.XmlUtils.writeIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070025import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070026import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey5217cac2015-12-20 15:34:01 -070027
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070028import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
29import static org.xmlpull.v1.XmlPullParser.START_TAG;
30
Jason parks8888c592011-01-20 22:46:41 -060031import android.Manifest;
Jeff Sharkeyef10ee02015-07-05 14:17:27 -070032import android.annotation.Nullable;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -070033import android.app.ActivityManager;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070034import android.app.ActivityManagerNative;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070035import android.app.AppOpsManager;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070036import android.app.IActivityManager;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070037import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.Context;
40import android.content.Intent;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070041import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.content.ServiceConnection;
Jeff Sharkey275e3e42015-04-24 16:10:32 -070043import android.content.pm.IPackageMoveObserver;
44import android.content.pm.PackageManager;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070045import android.content.pm.ProviderInfo;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070046import android.content.pm.UserInfo;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070047import android.content.res.Configuration;
Kenny Root02c87302010-07-01 08:10:18 -070048import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070050import android.os.Binder;
Jeff Sharkey4c099d02015-05-15 13:45:00 -070051import android.os.DropBoxManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070052import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070053import android.os.Environment.UserEnvironment;
Jeff Sharkey48877892015-03-18 11:27:19 -070054import android.os.FileUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080055import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070056import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040058import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080059import android.os.Message;
Daichi Hirono9e8d9e22015-11-13 14:37:00 +090060import android.os.ParcelFileDescriptor;
Jeff Sharkeyce14cd02015-12-07 15:35:42 -070061import android.os.PowerManager;
Jeff Sharkey9527b222015-06-24 15:24:48 -070062import android.os.Process;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -070063import android.os.RemoteCallbackList;
San Mehat4270e1e2010-01-29 05:32:19 -080064import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080065import android.os.ServiceManager;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -070066import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Emily Bernier92aa5a22014-07-07 10:11:48 -040069import android.os.UserManager;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070070import android.os.storage.DiskInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -070071import android.os.storage.IMountService;
72import android.os.storage.IMountServiceListener;
73import android.os.storage.IMountShutdownObserver;
74import android.os.storage.IObbActionListener;
Svet Ganov6ee871e2015-07-10 14:29:33 -070075import android.os.storage.MountServiceInternal;
Kenny Rootaf9d6672010-10-08 09:21:39 -070076import android.os.storage.OnObbStateChangeListener;
Paul Lawrence46791e72014-04-03 09:10:26 -070077import android.os.storage.StorageManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070078import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070079import android.os.storage.StorageVolume;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070080import android.os.storage.VolumeInfo;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -070081import android.os.storage.VolumeRecord;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070082import android.provider.MediaStore;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070083import android.provider.Settings;
Jason parksf7b3cd42011-01-27 09:28:25 -060084import android.text.TextUtils;
Jeff Sharkey1783f142015-04-17 10:52:51 -070085import android.text.format.DateUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -070086import android.util.ArrayMap;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070087import android.util.AtomicFile;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070088import android.util.Log;
San Mehata5078592010-03-25 09:36:54 -070089import android.util.Slog;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070090import android.util.TimeUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070091import android.util.Xml;
Jeff Sharkey48877892015-03-18 11:27:19 -070092
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080093import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070094import com.android.internal.app.IMediaContainerService;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -070095import com.android.internal.os.SomeArgs;
Jeff Sharkey9527b222015-06-24 15:24:48 -070096import com.android.internal.os.Zygote;
Jeff Sharkey48877892015-03-18 11:27:19 -070097import com.android.internal.util.ArrayUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070098import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080099import com.android.internal.util.HexDump;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700100import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700101import com.android.internal.util.Preconditions;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700102import com.android.internal.widget.LockPatternUtils;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700103import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700104import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700105import com.android.server.pm.PackageManagerService;
Kenny Roota02b8b02010-08-05 16:14:17 -0700106
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700107import libcore.io.IoUtils;
108import libcore.util.EmptyArray;
109
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700114import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -0700115import java.io.FileDescriptor;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700116import java.io.FileInputStream;
117import java.io.FileNotFoundException;
Christopher Tate7265abe2014-11-21 13:54:45 -0800118import java.io.FileOutputStream;
Kenny Root05105f72010-09-22 17:29:43 -0700119import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -0700120import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -0700121import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -0800122import java.nio.charset.StandardCharsets;
Kenny Root735de3b2010-09-30 14:11:39 -0700123import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -0700124import java.security.spec.InvalidKeySpecException;
125import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -0800126import java.util.ArrayList;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800127import java.util.Arrays;
Kenny Roota02b8b02010-08-05 16:14:17 -0700128import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -0800129import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -0700130import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -0700131import java.util.LinkedList;
132import java.util.List;
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700133import java.util.Locale;
Kenny Roota02b8b02010-08-05 16:14:17 -0700134import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -0700135import java.util.Map.Entry;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700136import java.util.Objects;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700137import java.util.concurrent.CopyOnWriteArrayList;
Kenny Root51a573c2012-05-17 13:30:28 -0700138import java.util.concurrent.CountDownLatch;
139import java.util.concurrent.TimeUnit;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700140import java.util.concurrent.TimeoutException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Kenny Root3b1abba2010-10-13 15:00:07 -0700142import javax.crypto.SecretKey;
143import javax.crypto.SecretKeyFactory;
144import javax.crypto.spec.PBEKeySpec;
145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146/**
Jeff Sharkey48877892015-03-18 11:27:19 -0700147 * Service responsible for various storage media. Connects to {@code vold} to
148 * watch for and manage dynamically added storage, such as SD cards and USB mass
149 * storage. Also decides how storage should be presented to users on the device.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700151class MountService extends IMountService.Stub
152 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600153
Christopher Tated417d622013-08-19 16:14:25 -0700154 // Static direct instance pointer for the tightly-coupled idle service to use
155 static MountService sSelf = null;
156
Jeff Sharkey56e62932015-03-21 20:41:00 -0700157 public static class Lifecycle extends SystemService {
158 private MountService mMountService;
159
160 public Lifecycle(Context context) {
161 super(context);
162 }
163
164 @Override
165 public void onStart() {
166 mMountService = new MountService(getContext());
167 publishBinderService("mount", mMountService);
168 }
169
170 @Override
171 public void onBootPhase(int phase) {
172 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
173 mMountService.systemReady();
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900174 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
175 mMountService.bootCompleted();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700176 }
177 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700178
179 @Override
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700180 public void onUnlockUser(int userHandle) {
181 mMountService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700182 }
183
184 @Override
185 public void onCleanupUser(int userHandle) {
186 mMountService.onCleanupUser(userHandle);
187 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700188 }
189
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800190 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800191 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700192
Kenny Root07714d42011-08-17 17:49:28 -0700193 // Disable this since it messes up long-running cryptfs operations.
194 private static final boolean WATCHDOG_ENABLE = false;
195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private static final String TAG = "MountService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700197
Jeff Sharkey9756d752015-05-14 21:07:42 -0700198 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700199 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Kenny Root305bcbf2010-09-03 07:56:38 -0700201 private static final String VOLD_TAG = "VoldConnector";
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700202 private static final String CRYPTD_TAG = "CryptdConnector";
Kenny Root305bcbf2010-09-03 07:56:38 -0700203
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700204 /** Maximum number of ASEC containers allowed to be mounted. */
205 private static final int MAX_CONTAINERS = 250;
206
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700207 /** Magic value sent by MoveTask.cpp */
208 private static final int MOVE_STATUS_COPY_FINISHED = 82;
209
San Mehat4270e1e2010-01-29 05:32:19 -0800210 /*
211 * Internal vold response code constants
212 */
San Mehat22dd86e2010-01-12 12:21:18 -0800213 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800214 /*
215 * 100 series - Requestion action was initiated; expect another reply
216 * before proceeding with a new command.
217 */
San Mehat22dd86e2010-01-12 12:21:18 -0800218 public static final int VolumeListResult = 110;
219 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800220 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700221 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800222
San Mehat4270e1e2010-01-29 05:32:19 -0800223 /*
224 * 200 series - Requestion action has been successfully completed.
225 */
226 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800227 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800228 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800229
San Mehat4270e1e2010-01-29 05:32:19 -0800230 /*
231 * 400 series - Command was accepted, but the requested action
232 * did not take place.
233 */
234 public static final int OpFailedNoMedia = 401;
235 public static final int OpFailedMediaBlank = 402;
236 public static final int OpFailedMediaCorrupt = 403;
237 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800238 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700239 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800240
241 /*
242 * 600 series - Unsolicited broadcasts.
243 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700244 public static final int DISK_CREATED = 640;
245 public static final int DISK_SIZE_CHANGED = 641;
246 public static final int DISK_LABEL_CHANGED = 642;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700247 public static final int DISK_SCANNED = 643;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700248 public static final int DISK_SYS_PATH_CHANGED = 644;
Jeff Sharkey48877892015-03-18 11:27:19 -0700249 public static final int DISK_DESTROYED = 649;
250
251 public static final int VOLUME_CREATED = 650;
252 public static final int VOLUME_STATE_CHANGED = 651;
253 public static final int VOLUME_FS_TYPE_CHANGED = 652;
254 public static final int VOLUME_FS_UUID_CHANGED = 653;
255 public static final int VOLUME_FS_LABEL_CHANGED = 654;
256 public static final int VOLUME_PATH_CHANGED = 655;
Jeff Sharkey50a05452015-04-29 11:24:52 -0700257 public static final int VOLUME_INTERNAL_PATH_CHANGED = 656;
Jeff Sharkey48877892015-03-18 11:27:19 -0700258 public static final int VOLUME_DESTROYED = 659;
Svetoslavf23b64d2013-04-25 14:45:54 -0700259
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700260 public static final int MOVE_STATUS = 660;
Jeff Sharkey9756d752015-05-14 21:07:42 -0700261 public static final int BENCHMARK_RESULT = 661;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700262 public static final int TRIM_RESULT = 662;
San Mehat22dd86e2010-01-12 12:21:18 -0800263 }
264
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700265 private static final int VERSION_INIT = 1;
266 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700267 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700268
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700269 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700270 private static final String ATTR_VERSION = "version";
271 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700272 private static final String ATTR_FORCE_ADOPTABLE = "forceAdoptable";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700273 private static final String TAG_VOLUME = "volume";
274 private static final String ATTR_TYPE = "type";
275 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700276 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700277 private static final String ATTR_NICKNAME = "nickname";
278 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700279 private static final String ATTR_CREATED_MILLIS = "createdMillis";
280 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
281 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700282
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700283 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700284
Jeff Sharkey48877892015-03-18 11:27:19 -0700285 /**
286 * <em>Never</em> hold the lock while performing downcalls into vold, since
287 * unsolicited events can suddenly appear to update data structures.
288 */
289 private final Object mLock = new Object();
290
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700291 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700292 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700293 private int[] mLocalUnlockedUsers = EmptyArray.INT;
294 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800295 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700296 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700297
298 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700299 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700300 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700301 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700302 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700303 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700304
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700305 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700306 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700307 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700308 @GuardedBy("mLock")
309 private String mPrimaryStorageUuid;
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700310 @GuardedBy("mLock")
311 private boolean mForceAdoptable;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700312
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700313 /** Map from disk ID to latches */
314 @GuardedBy("mLock")
315 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
316
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700317 @GuardedBy("mLock")
318 private IPackageMoveObserver mMoveCallback;
319 @GuardedBy("mLock")
320 private String mMoveTargetUuid;
321
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700322 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700323 synchronized (mLock) {
324 final VolumeInfo vol = mVolumes.get(id);
325 if (vol != null) {
326 return vol;
327 }
328 }
329 throw new IllegalArgumentException("No volume found for ID " + id);
330 }
331
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700332 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700333 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700334 for (int i = 0; i < mVolumes.size(); i++) {
335 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700336 if (vol.path != null && path.startsWith(vol.path)) {
337 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700338 }
339 }
340 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700341 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700342 }
343
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700344 private VolumeRecord findRecordForPath(String path) {
345 synchronized (mLock) {
346 for (int i = 0; i < mVolumes.size(); i++) {
347 final VolumeInfo vol = mVolumes.valueAt(i);
348 if (vol.path != null && path.startsWith(vol.path)) {
349 return mRecords.get(vol.fsUuid);
350 }
351 }
352 }
353 return null;
354 }
355
356 private String scrubPath(String path) {
357 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
358 return "internal";
359 }
360 final VolumeRecord rec = findRecordForPath(path);
361 if (rec == null || rec.createdMillis == 0) {
362 return "unknown";
363 } else {
364 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
365 / DateUtils.WEEK_IN_MILLIS) + "w";
366 }
367 }
368
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700369 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700370 final StorageManager storage = mContext.getSystemService(StorageManager.class);
371 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700372 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700373 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
374 return storage.getPrimaryPhysicalVolume();
375 } else {
376 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
377 }
378 }
379
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700380 private boolean shouldBenchmark() {
381 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
382 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700383 if (benchInterval == -1) {
384 return false;
385 } else if (benchInterval == 0) {
386 return true;
387 }
388
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700389 synchronized (mLock) {
390 for (int i = 0; i < mVolumes.size(); i++) {
391 final VolumeInfo vol = mVolumes.valueAt(i);
392 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700393 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700394 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
395 if (benchAge >= benchInterval) {
396 return true;
397 }
398 }
399 }
400 return false;
401 }
402 }
403
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700404 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
405 synchronized (mLock) {
406 CountDownLatch latch = mDiskScanLatches.get(diskId);
407 if (latch == null) {
408 latch = new CountDownLatch(1);
409 mDiskScanLatches.put(diskId, latch);
410 }
411 return latch;
412 }
413 }
414
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800415 private static String escapeNull(String arg) {
416 if (TextUtils.isEmpty(arg)) {
417 return "!";
418 } else {
419 if (arg.indexOf('\0') != -1 || arg.indexOf(' ') != -1) {
420 throw new IllegalArgumentException(arg);
421 }
422 return arg;
423 }
424 }
425
Paul Lawrence8e397362014-01-27 15:22:30 -0800426 /** List of crypto types.
427 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
428 * corresponding commands in CommandListener.cpp */
429 public static final String[] CRYPTO_TYPES
430 = { "password", "default", "pattern", "pin" };
431
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700432 private final Context mContext;
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700433 private final NativeDaemonConnector mConnector;
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700434 private final NativeDaemonConnector mCryptConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700435
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700436 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900437 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700438 private volatile boolean mDaemonConnected = false;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700439
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700440 private PackageManagerService mPms;
441
442 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700443 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700444
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700445 // Two connectors - mConnector & mCryptConnector
446 private final CountDownLatch mConnectedSignal = new CountDownLatch(2);
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800447 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
Jeff Sharkey48877892015-03-18 11:27:19 -0700448
449 private final Object mUnmountLock = new Object();
450 @GuardedBy("mUnmountLock")
451 private CountDownLatch mUnmountSignal;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800452
San Mehat6cdd9c02010-02-09 14:45:20 -0800453 /**
454 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800455 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800456 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800457 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800458
Kenny Root02c87302010-07-01 08:10:18 -0700459 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700460 * The size of the crypto algorithm key in bits for OBB files. Currently
461 * Twofish is used which takes 128-bit keys.
462 */
463 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
464
465 /**
466 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
467 * 1024 is reasonably secure and not too slow.
468 */
469 private static final int PBKDF2_HASH_ROUNDS = 1024;
470
471 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700472 * Mounted OBB tracking information. Used to track the current state of all
473 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700474 */
Kenny Root735de3b2010-09-30 14:11:39 -0700475 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700476
477 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700478 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
479
Svet Ganov6ee871e2015-07-10 14:29:33 -0700480 // Not guarded by a lock.
481 private final MountServiceInternalImpl mMountServiceInternal = new MountServiceInternalImpl();
482
Kenny Roota02b8b02010-08-05 16:14:17 -0700483 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700484 public ObbState(String rawPath, String canonicalPath, int callingUid,
485 IObbActionListener token, int nonce) {
486 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700487 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700488
489 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700490 this.token = token;
491 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700492 }
493
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700494 final String rawPath;
495 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700496
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700497 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700498
Kenny Rootaf9d6672010-10-08 09:21:39 -0700499 // Token of remote Binder caller
500 final IObbActionListener token;
501
502 // Identifier to pass back to the token
503 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700504
Kenny Root735de3b2010-09-30 14:11:39 -0700505 public IBinder getBinder() {
506 return token.asBinder();
507 }
508
Kenny Roota02b8b02010-08-05 16:14:17 -0700509 @Override
510 public void binderDied() {
511 ObbAction action = new UnmountObbAction(this, true);
512 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700513 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700514
Kenny Root5919ac62010-10-05 09:49:40 -0700515 public void link() throws RemoteException {
516 getBinder().linkToDeath(this, 0);
517 }
518
519 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700520 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700521 }
Kenny Root38cf8862010-09-26 14:18:51 -0700522
523 @Override
524 public String toString() {
525 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700526 sb.append("rawPath=").append(rawPath);
527 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700528 sb.append(",ownerGid=").append(ownerGid);
529 sb.append(",token=").append(token);
530 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700531 sb.append('}');
532 return sb.toString();
533 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700534 }
535
536 // OBB Action Handler
537 final private ObbActionHandler mObbActionHandler;
538
539 // OBB action handler messages
540 private static final int OBB_RUN_ACTION = 1;
541 private static final int OBB_MCS_BOUND = 2;
542 private static final int OBB_MCS_UNBIND = 3;
543 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700544 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700545
546 /*
547 * Default Container Service information
548 */
549 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
550 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
551
552 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
553
554 class DefaultContainerConnection implements ServiceConnection {
Jeff Sharkey48877892015-03-18 11:27:19 -0700555 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700556 public void onServiceConnected(ComponentName name, IBinder service) {
557 if (DEBUG_OBB)
558 Slog.i(TAG, "onServiceConnected");
559 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
560 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
561 }
562
Jeff Sharkey48877892015-03-18 11:27:19 -0700563 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700564 public void onServiceDisconnected(ComponentName name) {
565 if (DEBUG_OBB)
566 Slog.i(TAG, "onServiceDisconnected");
567 }
568 };
569
570 // Used in the ObbActionHandler
571 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700572
Christopher Tate7265abe2014-11-21 13:54:45 -0800573 // Last fstrim operation tracking
574 private static final String LAST_FSTRIM_FILE = "last-fstrim";
575 private final File mLastMaintenanceFile;
576 private long mLastMaintenance;
577
Kenny Root02c87302010-07-01 08:10:18 -0700578 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700579 private static final int H_SYSTEM_READY = 1;
580 private static final int H_DAEMON_CONNECTED = 2;
581 private static final int H_SHUTDOWN = 3;
582 private static final int H_FSTRIM = 4;
583 private static final int H_VOLUME_MOUNT = 5;
584 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700585 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700586 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800587 private static final int H_PARTITION_FORGET = 9;
588 private static final int H_RESET = 10;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800589
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400590 class MountServiceHandler extends Handler {
Jeff Sharkey48877892015-03-18 11:27:19 -0700591 public MountServiceHandler(Looper looper) {
592 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400593 }
594
Jason parks5af0b912010-11-29 09:05:25 -0600595 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800596 public void handleMessage(Message msg) {
597 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700598 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700599 handleSystemReady();
600 break;
601 }
602 case H_DAEMON_CONNECTED: {
603 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700604 break;
605 }
Christopher Tated417d622013-08-19 16:14:25 -0700606 case H_FSTRIM: {
Jeff Sharkey1783f142015-04-17 10:52:51 -0700607 if (!isReady()) {
608 Slog.i(TAG, "fstrim requested, but no daemon connection yet; trying again");
Christopher Tate7618db12015-04-28 16:32:55 -0700609 sendMessageDelayed(obtainMessage(H_FSTRIM, msg.obj),
610 DateUtils.SECOND_IN_MILLIS);
611 break;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700612 }
613
Christopher Tated417d622013-08-19 16:14:25 -0700614 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800615
616 // Remember when we kicked it off
617 try {
618 mLastMaintenance = System.currentTimeMillis();
619 mLastMaintenanceFile.setLastModified(mLastMaintenance);
620 } catch (Exception e) {
621 Slog.e(TAG, "Unable to record last fstrim!");
622 }
623
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700624 final boolean shouldBenchmark = shouldBenchmark();
Christopher Tated417d622013-08-19 16:14:25 -0700625 try {
626 // This method must be run on the main (handler) thread,
627 // so it is safe to directly call into vold.
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700628 mConnector.execute("fstrim", shouldBenchmark ? "dotrimbench" : "dotrim");
Christopher Tated417d622013-08-19 16:14:25 -0700629 } catch (NativeDaemonConnectorException ndce) {
630 Slog.e(TAG, "Failed to run fstrim!");
631 }
Christopher Tate7265abe2014-11-21 13:54:45 -0800632
Christopher Tated417d622013-08-19 16:14:25 -0700633 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700634 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700635 Runnable callback = (Runnable) msg.obj;
636 if (callback != null) {
637 callback.run();
638 }
639 break;
640 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700641 case H_SHUTDOWN: {
642 final IMountShutdownObserver obs = (IMountShutdownObserver) msg.obj;
643 boolean success = false;
644 try {
645 success = mConnector.execute("volume", "shutdown").isClassOk();
646 } catch (NativeDaemonConnectorException ignored) {
647 }
648 if (obs != null) {
649 try {
650 obs.onShutDownComplete(success ? 0 : -1);
651 } catch (RemoteException ignored) {
652 }
653 }
654 break;
655 }
656 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700657 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700658 if (isMountDisallowed(vol)) {
659 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
660 break;
661 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700662 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -0700663 mConnector.execute("volume", "mount", vol.id, vol.mountFlags,
664 vol.mountUserId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700665 } catch (NativeDaemonConnectorException ignored) {
666 }
667 break;
668 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700669 case H_VOLUME_UNMOUNT: {
670 final VolumeInfo vol = (VolumeInfo) msg.obj;
671 unmount(vol.getId());
672 break;
673 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700674 case H_VOLUME_BROADCAST: {
675 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700676 final String envState = userVol.getState();
677 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700678 + userVol.getOwner());
679
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700680 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700681 if (action != null) {
682 final Intent intent = new Intent(action,
683 Uri.fromFile(userVol.getPathFile()));
684 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
686 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
687 }
688 break;
689 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700690 case H_INTERNAL_BROADCAST: {
691 // Internal broadcasts aimed at system components, not for
692 // third-party apps.
693 final Intent intent = (Intent) msg.obj;
694 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
695 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800696 break;
697 }
698 case H_PARTITION_FORGET: {
699 final String partGuid = (String) msg.obj;
700 forgetPartition(partGuid);
701 break;
702 }
703 case H_RESET: {
704 resetIfReadyAndConnected();
705 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700706 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800707 }
708 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700709 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700710
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700711 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800712
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700713 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
714 @Override
715 public void onReceive(Context context, Intent intent) {
716 final String action = intent.getAction();
717 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700718 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700719
720 try {
721 if (Intent.ACTION_USER_ADDED.equals(action)) {
722 final UserManager um = mContext.getSystemService(UserManager.class);
723 final int userSerialNumber = um.getUserSerialNumber(userId);
724 mConnector.execute("volume", "user_added", userId, userSerialNumber);
725 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700726 synchronized (mVolumes) {
727 final int size = mVolumes.size();
728 for (int i = 0; i < size; i++) {
729 final VolumeInfo vol = mVolumes.valueAt(i);
730 if (vol.mountUserId == userId) {
731 vol.mountUserId = UserHandle.USER_NULL;
732 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
733 }
734 }
735 }
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700736 mConnector.execute("volume", "user_removed", userId);
737 }
738 } catch (NativeDaemonConnectorException e) {
739 Slog.w(TAG, "Failed to send user details to vold", e);
740 }
741 }
742 };
743
Jeff Sharkey56e62932015-03-21 20:41:00 -0700744 @Override
745 public void waitForAsecScan() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700746 waitForLatch(mAsecsScanned, "mAsecsScanned");
Kenny Root51a573c2012-05-17 13:30:28 -0700747 }
748
San Mehat207e5382010-02-04 20:46:54 -0800749 private void waitForReady() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700750 waitForLatch(mConnectedSignal, "mConnectedSignal");
Kenny Root51a573c2012-05-17 13:30:28 -0700751 }
752
Jeff Sharkey48877892015-03-18 11:27:19 -0700753 private void waitForLatch(CountDownLatch latch, String condition) {
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700754 try {
755 waitForLatch(latch, condition, -1);
756 } catch (TimeoutException ignored) {
757 }
758 }
759
760 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
761 throws TimeoutException {
762 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700763 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700764 try {
765 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800766 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700767 } else {
768 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700769 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800770 }
Kenny Root51a573c2012-05-17 13:30:28 -0700771 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700772 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800773 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700774 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
775 throw new TimeoutException("Thread " + Thread.currentThread().getName()
776 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
777 }
San Mehat207e5382010-02-04 20:46:54 -0800778 }
San Mehat1f6301e2010-01-07 22:40:27 -0800779 }
Kenny Root02c87302010-07-01 08:10:18 -0700780
Paul Lawrence945490c2014-03-27 16:37:28 +0000781 private boolean isReady() {
782 try {
783 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
784 } catch (InterruptedException e) {
785 return false;
786 }
787 }
788
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700789 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700790 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800791 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700792
Jeff Sharkey48877892015-03-18 11:27:19 -0700793 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700794 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700795 }
796
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700797 /**
798 * MediaProvider has a ton of code that makes assumptions about storage
799 * paths never changing, so we outright kill them to pick up new state.
800 */
801 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700802 private void killMediaProvider(List<UserInfo> users) {
803 if (users == null) return;
804
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700805 final long token = Binder.clearCallingIdentity();
806 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700807 for (UserInfo user : users) {
808 // System user does not have media provider, so skip.
809 if (user.isSystemOnly()) continue;
810
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -0700811 final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY,
812 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE, user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700813 if (provider != null) {
814 final IActivityManager am = ActivityManagerNative.getDefault();
815 try {
816 am.killApplicationWithAppId(provider.applicationInfo.packageName,
817 UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
818 // We only need to run this once. It will kill all users' media processes.
819 break;
820 } catch (RemoteException e) {
821 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700822 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700823 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700824 } finally {
825 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700826 }
827 }
828
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800829 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700830 // Create a stub volume that represents internal storage
831 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
832 VolumeInfo.TYPE_PRIVATE, null, null);
833 internal.state = VolumeInfo.STATE_MOUNTED;
834 internal.path = Environment.getDataDirectory().getAbsolutePath();
835 mVolumes.put(internal.id, internal);
836 }
837
Jeff Sharkey8924e872015-11-30 12:52:10 -0700838 private void initIfReadyAndConnected() {
839 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
840 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700841 if (mSystemReady && mDaemonConnected
842 && !StorageManager.isNativeFileBasedEncryptionEnabled()) {
843 // When booting a device without native support, make sure that our
844 // user directories are locked or unlocked based on the current
845 // emulation status.
846 final boolean initLocked = StorageManager.isEmulatedFileBasedEncryptionEnabled();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000847 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700848 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700849 for (UserInfo user : users) {
850 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700851 if (initLocked) {
852 mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
853 } else {
854 mCryptConnector.execute("cryptfs", "unlock_user_key", user.id,
Paul Crowleyd94ab732016-02-15 06:44:51 +0000855 user.serialNumber, "!", "!");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700856 }
Jeff Sharkey8924e872015-11-30 12:52:10 -0700857 } catch (NativeDaemonConnectorException e) {
858 Slog.w(TAG, "Failed to init vold", e);
859 }
860 }
861 }
862 }
863
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800864 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700865 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
866 + ", mDaemonConnected=" + mDaemonConnected);
867 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800868 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700869 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700870
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700871 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800872 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700873 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700874
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800875 mDisks.clear();
876 mVolumes.clear();
877
878 addInternalVolumeLocked();
879 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700880
Jeff Sharkey48877892015-03-18 11:27:19 -0700881 try {
882 mConnector.execute("volume", "reset");
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700883
884 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700885 for (UserInfo user : users) {
886 mConnector.execute("volume", "user_added", user.id, user.serialNumber);
887 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700888 for (int userId : systemUnlockedUsers) {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700889 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700890 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700891 } catch (NativeDaemonConnectorException e) {
892 Slog.w(TAG, "Failed to reset vold", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700893 }
894 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700895 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700896
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700897 private void onUnlockUser(int userId) {
898 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700899
900 // We purposefully block here to make sure that user-specific
901 // staging area is ready so it's ready for zygote-forked apps to
902 // bind mount against.
903 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700904 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700905 } catch (NativeDaemonConnectorException ignored) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700906 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700907
908 // Record user as started so newly mounted volumes kick off events
909 // correctly, then synthesize events for any already-mounted volumes.
910 synchronized (mVolumes) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700911 for (int i = 0; i < mVolumes.size(); i++) {
912 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700913 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700914 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700915 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700916
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700917 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
918 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700919 }
920 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700921 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700922 }
923 }
924
925 private void onCleanupUser(int userId) {
926 Slog.d(TAG, "onCleanupUser " + userId);
927
928 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700929 mConnector.execute("volume", "user_stopped", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700930 } catch (NativeDaemonConnectorException ignored) {
931 }
932
933 synchronized (mVolumes) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700934 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700935 }
936 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700937
Christopher Tated417d622013-08-19 16:14:25 -0700938 void runIdleMaintenance(Runnable callback) {
939 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
940 }
941
Christopher Tate7265abe2014-11-21 13:54:45 -0800942 // Binder entry point for kicking off an immediate fstrim
943 @Override
944 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700945 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -0800946 runIdleMaintenance(null);
947 }
948
949 @Override
950 public long lastMaintenance() {
951 return mLastMaintenance;
952 }
953
San Mehat4270e1e2010-01-29 05:32:19 -0800954 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800955 * Callback from NativeDaemonConnector
956 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700957 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800958 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700959 mDaemonConnected = true;
960 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
961 }
962
963 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700964 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800965 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -0700966
San Mehat4270e1e2010-01-29 05:32:19 -0800967 /*
Jeff Sharkey48877892015-03-18 11:27:19 -0700968 * Now that we've done our initialization, release
969 * the hounds!
San Mehat4270e1e2010-01-29 05:32:19 -0800970 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700971 mConnectedSignal.countDown();
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700972 if (mConnectedSignal.getCount() != 0) {
973 // More daemons need to connect
974 return;
975 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400976
Jeff Sharkey48877892015-03-18 11:27:19 -0700977 // On an encrypted device we can't see system properties yet, so pull
978 // the system locale out of the mount service.
979 if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
980 copyLocaleFromMountService();
981 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700982
Jeff Sharkey48877892015-03-18 11:27:19 -0700983 // Let package manager load internal ASECs.
984 mPms.scanAvailableAsecs();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400985
Jeff Sharkey48877892015-03-18 11:27:19 -0700986 // Notify people waiting for ASECs to be scanned that it's done.
987 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800988 }
989
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700990 private void copyLocaleFromMountService() {
991 String systemLocale;
992 try {
993 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
994 } catch (RemoteException e) {
995 return;
996 }
997 if (TextUtils.isEmpty(systemLocale)) {
998 return;
999 }
1000
1001 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1002 Locale locale = Locale.forLanguageTag(systemLocale);
1003 Configuration config = new Configuration();
1004 config.setLocale(locale);
1005 try {
1006 ActivityManagerNative.getDefault().updateConfiguration(config);
1007 } catch (RemoteException e) {
1008 Slog.e(TAG, "Error setting system locale from mount service", e);
1009 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001010
1011 // Temporary workaround for http://b/17945169.
1012 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001013 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001014 }
1015
San Mehat4270e1e2010-01-29 05:32:19 -08001016 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001017 * Callback from NativeDaemonConnector
1018 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001019 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001020 public boolean onCheckHoldWakeLock(int code) {
1021 return false;
1022 }
1023
1024 /**
1025 * Callback from NativeDaemonConnector
1026 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001027 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001028 public boolean onEvent(int code, String raw, String[] cooked) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001029 synchronized (mLock) {
1030 return onEventLocked(code, raw, cooked);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001031 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001032 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001033
Jeff Sharkey48877892015-03-18 11:27:19 -07001034 private boolean onEventLocked(int code, String raw, String[] cooked) {
1035 switch (code) {
1036 case VoldResponseCode.DISK_CREATED: {
1037 if (cooked.length != 3) break;
1038 final String id = cooked[1];
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001039 int flags = Integer.parseInt(cooked[2]);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001040 if (SystemProperties.getBoolean(StorageManager.PROP_FORCE_ADOPTABLE, false)
1041 || mForceAdoptable) {
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001042 flags |= DiskInfo.FLAG_ADOPTABLE;
1043 }
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001044 mDisks.put(id, new DiskInfo(id, flags));
Jeff Sharkey48877892015-03-18 11:27:19 -07001045 break;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001046 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001047 case VoldResponseCode.DISK_SIZE_CHANGED: {
1048 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001049 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001050 if (disk != null) {
1051 disk.size = Long.parseLong(cooked[2]);
San Mehat4270e1e2010-01-29 05:32:19 -08001052 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001053 break;
1054 }
1055 case VoldResponseCode.DISK_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001056 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001057 if (disk != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001058 final StringBuilder builder = new StringBuilder();
1059 for (int i = 2; i < cooked.length; i++) {
1060 builder.append(cooked[i]).append(' ');
1061 }
1062 disk.label = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001063 }
1064 break;
1065 }
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001066 case VoldResponseCode.DISK_SCANNED: {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001067 if (cooked.length != 2) break;
1068 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001069 if (disk != null) {
1070 onDiskScannedLocked(disk);
1071 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -07001072 break;
1073 }
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001074 case VoldResponseCode.DISK_SYS_PATH_CHANGED: {
1075 if (cooked.length != 3) break;
1076 final DiskInfo disk = mDisks.get(cooked[1]);
1077 if (disk != null) {
1078 disk.sysPath = cooked[2];
1079 }
1080 break;
1081 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001082 case VoldResponseCode.DISK_DESTROYED: {
1083 if (cooked.length != 2) break;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07001084 final DiskInfo disk = mDisks.remove(cooked[1]);
1085 if (disk != null) {
1086 mCallbacks.notifyDiskDestroyed(disk);
1087 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001088 break;
1089 }
San Mehat4270e1e2010-01-29 05:32:19 -08001090
Jeff Sharkey48877892015-03-18 11:27:19 -07001091 case VoldResponseCode.VOLUME_CREATED: {
Jeff Sharkey48877892015-03-18 11:27:19 -07001092 final String id = cooked[1];
1093 final int type = Integer.parseInt(cooked[2]);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001094 final String diskId = TextUtils.nullIfEmpty(cooked[3]);
1095 final String partGuid = TextUtils.nullIfEmpty(cooked[4]);
1096
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001097 final DiskInfo disk = mDisks.get(diskId);
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07001098 final VolumeInfo vol = new VolumeInfo(id, type, disk, partGuid);
Jeff Sharkey48877892015-03-18 11:27:19 -07001099 mVolumes.put(id, vol);
1100 onVolumeCreatedLocked(vol);
1101 break;
1102 }
1103 case VoldResponseCode.VOLUME_STATE_CHANGED: {
1104 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001105 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001106 if (vol != null) {
1107 final int oldState = vol.state;
1108 final int newState = Integer.parseInt(cooked[2]);
1109 vol.state = newState;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001110 onVolumeStateChangedLocked(vol, oldState, newState);
Jeff Sharkey48877892015-03-18 11:27:19 -07001111 }
1112 break;
1113 }
1114 case VoldResponseCode.VOLUME_FS_TYPE_CHANGED: {
1115 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001116 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001117 if (vol != null) {
1118 vol.fsType = cooked[2];
1119 }
1120 break;
1121 }
1122 case VoldResponseCode.VOLUME_FS_UUID_CHANGED: {
1123 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001124 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001125 if (vol != null) {
1126 vol.fsUuid = cooked[2];
1127 }
1128 break;
1129 }
1130 case VoldResponseCode.VOLUME_FS_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001131 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001132 if (vol != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001133 final StringBuilder builder = new StringBuilder();
1134 for (int i = 2; i < cooked.length; i++) {
1135 builder.append(cooked[i]).append(' ');
1136 }
1137 vol.fsLabel = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001138 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001139 // TODO: notify listeners that label changed
Jeff Sharkey48877892015-03-18 11:27:19 -07001140 break;
1141 }
1142 case VoldResponseCode.VOLUME_PATH_CHANGED: {
1143 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001144 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001145 if (vol != null) {
1146 vol.path = cooked[2];
1147 }
1148 break;
1149 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001150 case VoldResponseCode.VOLUME_INTERNAL_PATH_CHANGED: {
1151 if (cooked.length != 3) break;
1152 final VolumeInfo vol = mVolumes.get(cooked[1]);
1153 if (vol != null) {
1154 vol.internalPath = cooked[2];
1155 }
1156 break;
1157 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001158 case VoldResponseCode.VOLUME_DESTROYED: {
1159 if (cooked.length != 2) break;
1160 mVolumes.remove(cooked[1]);
1161 break;
1162 }
San Mehat4270e1e2010-01-29 05:32:19 -08001163
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001164 case VoldResponseCode.MOVE_STATUS: {
1165 final int status = Integer.parseInt(cooked[1]);
1166 onMoveStatusLocked(status);
1167 break;
1168 }
Jeff Sharkey9756d752015-05-14 21:07:42 -07001169 case VoldResponseCode.BENCHMARK_RESULT: {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001170 if (cooked.length != 7) break;
1171 final String path = cooked[1];
1172 final String ident = cooked[2];
1173 final long create = Long.parseLong(cooked[3]);
1174 final long drop = Long.parseLong(cooked[4]);
1175 final long run = Long.parseLong(cooked[5]);
1176 final long destroy = Long.parseLong(cooked[6]);
1177
Jeff Sharkey9756d752015-05-14 21:07:42 -07001178 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001179 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1180 + " " + ident + " " + create + " " + run + " " + destroy);
1181
1182 final VolumeRecord rec = findRecordForPath(path);
1183 if (rec != null) {
1184 rec.lastBenchMillis = System.currentTimeMillis();
1185 writeSettingsLocked();
1186 }
1187
1188 break;
1189 }
1190 case VoldResponseCode.TRIM_RESULT: {
1191 if (cooked.length != 4) break;
1192 final String path = cooked[1];
1193 final long bytes = Long.parseLong(cooked[2]);
1194 final long time = Long.parseLong(cooked[3]);
1195
1196 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1197 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path)
1198 + " " + bytes + " " + time);
1199
1200 final VolumeRecord rec = findRecordForPath(path);
1201 if (rec != null) {
1202 rec.lastTrimMillis = System.currentTimeMillis();
1203 writeSettingsLocked();
1204 }
1205
Jeff Sharkey9756d752015-05-14 21:07:42 -07001206 break;
1207 }
1208
Jeff Sharkey48877892015-03-18 11:27:19 -07001209 default: {
1210 Slog.d(TAG, "Unhandled vold event " + code);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001211 }
San Mehat4270e1e2010-01-29 05:32:19 -08001212 }
1213
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001214 return true;
San Mehat4270e1e2010-01-29 05:32:19 -08001215 }
1216
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001217 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001218 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001219 for (int i = 0; i < mVolumes.size(); i++) {
1220 final VolumeInfo vol = mVolumes.valueAt(i);
1221 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001222 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001223 }
1224 }
1225
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001226 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
1227 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1228 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1229 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001230 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001231
1232 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1233 if (latch != null) {
1234 latch.countDown();
1235 }
1236
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001237 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001238 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001239 }
1240
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001241 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001242 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1243 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1244 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1245
1246 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1247 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1248 Slog.v(TAG, "Found primary storage at " + vol);
1249 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1250 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1251 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1252
1253 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1254 Slog.v(TAG, "Found primary storage at " + vol);
1255 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1256 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1257 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1258 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001259
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001260 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001261 // TODO: only look at first public partition
1262 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1263 && vol.disk.isDefaultPrimary()) {
1264 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001265 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1266 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001267 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001268
1269 // Adoptable public disks are visible to apps, since they meet
1270 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001271 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001272 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1273 }
1274
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001275 vol.mountUserId = ActivityManager.getCurrentUser();
Jeff Sharkey48877892015-03-18 11:27:19 -07001276 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001277
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001278 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1279 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1280
San Mehat4270e1e2010-01-29 05:32:19 -08001281 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001282 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001283 }
1284 }
1285
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001286 private boolean isBroadcastWorthy(VolumeInfo vol) {
1287 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001288 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001289 case VolumeInfo.TYPE_PUBLIC:
1290 case VolumeInfo.TYPE_EMULATED:
1291 break;
1292 default:
1293 return false;
1294 }
1295
1296 switch (vol.getState()) {
1297 case VolumeInfo.STATE_MOUNTED:
1298 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1299 case VolumeInfo.STATE_EJECTING:
1300 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001301 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001302 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001303 break;
1304 default:
1305 return false;
1306 }
1307
1308 return true;
1309 }
1310
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001311 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001312 // Remember that we saw this volume so we're ready to accept user
1313 // metadata, or so we can annoy them when a private volume is ejected
1314 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001315 VolumeRecord rec = mRecords.get(vol.fsUuid);
1316 if (rec == null) {
1317 rec = new VolumeRecord(vol.type, vol.fsUuid);
1318 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001319 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001320 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1321 rec.nickname = vol.disk.getDescription();
1322 }
1323 mRecords.put(rec.fsUuid, rec);
1324 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001325 } else {
1326 // Handle upgrade case where we didn't store partition GUID
1327 if (TextUtils.isEmpty(rec.partGuid)) {
1328 rec.partGuid = vol.partGuid;
1329 writeSettingsLocked();
1330 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001331 }
1332 }
1333
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001334 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1335
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001336 // Do not broadcast before boot has completed to avoid launching the
1337 // processes that receive the intent unnecessarily.
1338 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001339 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001340 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1341 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001342 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001343 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001344 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001345 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001346
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001347 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1348 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001349
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001350 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1351 // Kick state changed event towards all started users. Any users
1352 // started after this point will trigger additional
1353 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001354 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001355 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001356 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001357 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001358
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001359 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1360 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001361 }
1362 }
1363 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001364
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001365 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001366 // TODO: this should eventually be handled by new ObbVolume state changes
1367 /*
1368 * Some OBBs might have been unmounted when this volume was
1369 * unmounted, so send a message to the handler to let it know to
1370 * remove those from the list of mounted OBBS.
1371 */
1372 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1373 OBB_FLUSH_MOUNT_STATE, vol.path));
1374 }
San Mehat4270e1e2010-01-29 05:32:19 -08001375 }
1376
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001377 private void onMoveStatusLocked(int status) {
1378 if (mMoveCallback == null) {
1379 Slog.w(TAG, "Odd, status but no move requested");
1380 return;
1381 }
1382
1383 // TODO: estimate remaining time
1384 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001385 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001386 } catch (RemoteException ignored) {
1387 }
1388
1389 // We've finished copying and we're about to clean up old data, so
1390 // remember that move was successful if we get rebooted
1391 if (status == MOVE_STATUS_COPY_FINISHED) {
1392 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1393
1394 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001395 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001396 }
1397
1398 if (PackageManager.isMoveStatusFinished(status)) {
1399 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1400
1401 mMoveCallback = null;
1402 mMoveTargetUuid = null;
1403 }
1404 }
1405
Jeff Sharkey48877892015-03-18 11:27:19 -07001406 private void enforcePermission(String perm) {
1407 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001408 }
1409
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001410 /**
1411 * Decide if volume is mountable per device policies.
1412 */
1413 private boolean isMountDisallowed(VolumeInfo vol) {
1414 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE) {
1415 final UserManager userManager = mContext.getSystemService(UserManager.class);
1416 return userManager.hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1417 Binder.getCallingUserHandle());
1418 } else {
1419 return false;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001420 }
1421 }
1422
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001423 private void enforceAdminUser() {
1424 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1425 final int callingUserId = UserHandle.getCallingUserId();
1426 boolean isAdmin;
1427 long token = Binder.clearCallingIdentity();
1428 try {
1429 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1430 } finally {
1431 Binder.restoreCallingIdentity(token);
1432 }
1433 if (!isAdmin) {
1434 throw new SecurityException("Only admin users can adopt sd cards");
1435 }
1436 }
1437
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001438 /**
San Mehat207e5382010-02-04 20:46:54 -08001439 * Constructs a new MountService instance
1440 *
1441 * @param context Binder context for this service
1442 */
1443 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001444 sSelf = this;
1445
San Mehat207e5382010-02-04 20:46:54 -08001446 mContext = context;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001447 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001448 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001449
San Mehat207e5382010-02-04 20:46:54 -08001450 // XXX: This will go away soon in favor of IMountServiceObserver
1451 mPms = (PackageManagerService) ServiceManager.getService("package");
1452
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001453 HandlerThread hthread = new HandlerThread(TAG);
1454 hthread.start();
1455 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001456
Kenny Roota02b8b02010-08-05 16:14:17 -07001457 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001458 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001459
Christopher Tate7265abe2014-11-21 13:54:45 -08001460 // Initialize the last-fstrim tracking if necessary
1461 File dataDir = Environment.getDataDirectory();
1462 File systemDir = new File(dataDir, "system");
1463 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1464 if (!mLastMaintenanceFile.exists()) {
1465 // Not setting mLastMaintenance here means that we will force an
1466 // fstrim during reboot following the OTA that installs this code.
1467 try {
1468 (new FileOutputStream(mLastMaintenanceFile)).close();
1469 } catch (IOException e) {
1470 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1471 }
1472 } else {
1473 mLastMaintenance = mLastMaintenanceFile.lastModified();
1474 }
1475
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001476 mSettingsFile = new AtomicFile(
Jeff Sharkey8212ae02016-02-10 14:46:43 -07001477 new File(Environment.getDataSystemDirectory(), "storage.xml"));
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001478
1479 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001480 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001481 }
1482
Svet Ganov6ee871e2015-07-10 14:29:33 -07001483 LocalServices.addService(MountServiceInternal.class, mMountServiceInternal);
1484
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001485 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001486 * Create the connection to vold with a maximum queue of twice the
1487 * amount of containers we'd ever expect to have. This keeps an
1488 * "asec list" from blocking a thread repeatedly.
1489 */
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001490
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001491 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1492 null);
Jeff Sharkey48877892015-03-18 11:27:19 -07001493 mConnector.setDebug(true);
Jeff Sharkey8948c012015-11-03 12:33:54 -08001494 mConnector.setWarnIfHeld(mLock);
Kenny Root51a573c2012-05-17 13:30:28 -07001495
Kenny Root305bcbf2010-09-03 07:56:38 -07001496 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001497 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001498
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001499 // Reuse parameters from first connector since they are tested and safe
1500 mCryptConnector = new NativeDaemonConnector(this, "cryptd",
1501 MAX_CONTAINERS * 2, CRYPTD_TAG, 25, null);
1502 mCryptConnector.setDebug(true);
1503
1504 Thread crypt_thread = new Thread(mCryptConnector, CRYPTD_TAG);
1505 crypt_thread.start();
1506
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001507 final IntentFilter userFilter = new IntentFilter();
1508 userFilter.addAction(Intent.ACTION_USER_ADDED);
1509 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1510 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1511
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001512 synchronized (mLock) {
1513 addInternalVolumeLocked();
1514 }
Amith Yamasania7892482015-08-07 11:09:05 -07001515
Kenny Root07714d42011-08-17 17:49:28 -07001516 // Add ourself to the Watchdog monitors if enabled.
1517 if (WATCHDOG_ENABLE) {
1518 Watchdog.getInstance().addMonitor(this);
1519 }
San Mehat207e5382010-02-04 20:46:54 -08001520 }
1521
Jeff Sharkey56e62932015-03-21 20:41:00 -07001522 private void systemReady() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001523 mSystemReady = true;
1524 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1525 }
1526
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001527 private void bootCompleted() {
1528 mBootCompleted = true;
1529 }
1530
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001531 private String getDefaultPrimaryStorageUuid() {
1532 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1533 return StorageManager.UUID_PRIMARY_PHYSICAL;
1534 } else {
1535 return StorageManager.UUID_PRIVATE_INTERNAL;
1536 }
1537 }
1538
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001539 private void readSettingsLocked() {
1540 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001541 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001542 mForceAdoptable = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001543
1544 FileInputStream fis = null;
1545 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001546 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001547 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001548 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001549
1550 int type;
1551 while ((type = in.next()) != END_DOCUMENT) {
1552 if (type == START_TAG) {
1553 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001554 if (TAG_VOLUMES.equals(tag)) {
1555 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001556 final boolean primaryPhysical = SystemProperties.getBoolean(
1557 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1558 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1559 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1560 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001561 mPrimaryStorageUuid = readStringAttribute(in,
1562 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001563 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001564 mForceAdoptable = readBooleanAttribute(in, ATTR_FORCE_ADOPTABLE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001565
1566 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001567 final VolumeRecord rec = readVolumeRecord(in);
1568 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001569 }
1570 }
1571 }
1572 } catch (FileNotFoundException e) {
1573 // Missing metadata is okay, probably first boot
1574 } catch (IOException e) {
1575 Slog.wtf(TAG, "Failed reading metadata", e);
1576 } catch (XmlPullParserException e) {
1577 Slog.wtf(TAG, "Failed reading metadata", e);
1578 } finally {
1579 IoUtils.closeQuietly(fis);
1580 }
1581 }
1582
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001583 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001584 FileOutputStream fos = null;
1585 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001586 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001587
1588 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001589 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001590 out.startDocument(null, true);
1591 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001592 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001593 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001594 writeBooleanAttribute(out, ATTR_FORCE_ADOPTABLE, mForceAdoptable);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001595 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001596 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001597 final VolumeRecord rec = mRecords.valueAt(i);
1598 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001599 }
1600 out.endTag(null, TAG_VOLUMES);
1601 out.endDocument();
1602
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001603 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001604 } catch (IOException e) {
1605 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001606 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001607 }
1608 }
1609 }
1610
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001611 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1612 final int type = readIntAttribute(in, ATTR_TYPE);
1613 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1614 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001615 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001616 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1617 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001618 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1619 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1620 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001621 return meta;
1622 }
1623
1624 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1625 out.startTag(null, TAG_VOLUME);
1626 writeIntAttribute(out, ATTR_TYPE, rec.type);
1627 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001628 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001629 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1630 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001631 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1632 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1633 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001634 out.endTag(null, TAG_VOLUME);
1635 }
1636
San Mehat207e5382010-02-04 20:46:54 -08001637 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001638 * Exposed API calls below here
1639 */
1640
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001641 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001642 public void registerListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001643 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001644 }
1645
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001646 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001647 public void unregisterListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001648 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001649 }
1650
Jeff Sharkey48877892015-03-18 11:27:19 -07001651 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001652 public void shutdown(final IMountShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001653 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001654
San Mehata5078592010-03-25 09:36:54 -07001655 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001656 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001657 }
1658
Jeff Sharkey48877892015-03-18 11:27:19 -07001659 @Override
San Mehatb1043402010-02-05 08:26:50 -08001660 public boolean isUsbMassStorageConnected() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001661 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001662 }
1663
Jeff Sharkey48877892015-03-18 11:27:19 -07001664 @Override
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001665 public void setUsbMassStorageEnabled(boolean enable) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001666 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001667 }
1668
Jeff Sharkey48877892015-03-18 11:27:19 -07001669 @Override
San Mehatb1043402010-02-05 08:26:50 -08001670 public boolean isUsbMassStorageEnabled() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001671 throw new UnsupportedOperationException();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001673
Jeff Sharkey48877892015-03-18 11:27:19 -07001674 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001675 public String getVolumeState(String mountPoint) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001676 throw new UnsupportedOperationException();
San Mehat7fd0fee2009-12-17 07:12:23 -08001677 }
1678
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001679 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001680 public boolean isExternalStorageEmulated() {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001681 throw new UnsupportedOperationException();
Kenny Roote1ff2142010-10-12 11:20:01 -07001682 }
1683
Jeff Sharkey48877892015-03-18 11:27:19 -07001684 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001685 public int mountVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001686 mount(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001687 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689
Jeff Sharkey48877892015-03-18 11:27:19 -07001690 @Override
Ben Komalo13c71972011-09-07 16:35:56 -07001691 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001692 unmount(findVolumeIdForPathOrThrow(path));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
Jeff Sharkey48877892015-03-18 11:27:19 -07001695 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001696 public int formatVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001697 format(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001698 return 0;
1699 }
1700
1701 @Override
1702 public void mount(String volId) {
1703 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1704 waitForReady();
1705
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001706 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001707 if (isMountDisallowed(vol)) {
1708 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001709 }
1710 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001711 mConnector.execute("volume", "mount", vol.id, vol.mountFlags, vol.mountUserId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001712 } catch (NativeDaemonConnectorException e) {
1713 throw e.rethrowAsParcelableException();
1714 }
1715 }
1716
1717 @Override
1718 public void unmount(String volId) {
1719 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1720 waitForReady();
1721
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001722 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001723
1724 // TODO: expand PMS to know about multiple volumes
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001725 if (vol.isPrimaryPhysical()) {
1726 final long ident = Binder.clearCallingIdentity();
1727 try {
1728 synchronized (mUnmountLock) {
1729 mUnmountSignal = new CountDownLatch(1);
1730 mPms.updateExternalMediaStatus(false, true);
1731 waitForLatch(mUnmountSignal, "mUnmountSignal");
1732 mUnmountSignal = null;
1733 }
1734 } finally {
1735 Binder.restoreCallingIdentity(ident);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001736 }
1737 }
1738
1739 try {
1740 mConnector.execute("volume", "unmount", vol.id);
1741 } catch (NativeDaemonConnectorException e) {
1742 throw e.rethrowAsParcelableException();
1743 }
1744 }
1745
1746 @Override
1747 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001748 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001749 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001750
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001751 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001752 try {
Jeff Sharkey4e83cc92015-05-27 14:38:39 -07001753 mConnector.execute("volume", "format", vol.id, "auto");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001754 } catch (NativeDaemonConnectorException e) {
1755 throw e.rethrowAsParcelableException();
Jeff Sharkey48877892015-03-18 11:27:19 -07001756 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001757 }
1758
1759 @Override
Jeff Sharkey9756d752015-05-14 21:07:42 -07001760 public long benchmark(String volId) {
1761 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1762 waitForReady();
1763
1764 try {
Jeff Sharkey14cbe522015-07-08 14:06:37 -07001765 // TODO: make benchmark async so we don't block other commands
1766 final NativeDaemonEvent res = mConnector.execute(3 * DateUtils.MINUTE_IN_MILLIS,
1767 "volume", "benchmark", volId);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001768 return Long.parseLong(res.getMessage());
Todd Kennedy8101ee62015-06-23 13:35:28 -07001769 } catch (NativeDaemonTimeoutException e) {
1770 return Long.MAX_VALUE;
Jeff Sharkey9756d752015-05-14 21:07:42 -07001771 } catch (NativeDaemonConnectorException e) {
1772 throw e.rethrowAsParcelableException();
1773 }
1774 }
1775
1776 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001777 public void partitionPublic(String diskId) {
1778 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1779 waitForReady();
1780
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001781 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001782 try {
1783 mConnector.execute("volume", "partition", diskId, "public");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001784 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001785 } catch (NativeDaemonConnectorException e) {
1786 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001787 } catch (TimeoutException e) {
1788 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001789 }
1790 }
1791
1792 @Override
1793 public void partitionPrivate(String diskId) {
1794 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001795 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001796 waitForReady();
1797
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001798 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001799 try {
1800 mConnector.execute("volume", "partition", diskId, "private");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001801 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001802 } catch (NativeDaemonConnectorException e) {
1803 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001804 } catch (TimeoutException e) {
1805 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001806 }
1807 }
1808
1809 @Override
1810 public void partitionMixed(String diskId, int ratio) {
1811 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001812 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001813 waitForReady();
1814
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001815 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001816 try {
1817 mConnector.execute("volume", "partition", diskId, "mixed", ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001818 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001819 } catch (NativeDaemonConnectorException e) {
1820 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001821 } catch (TimeoutException e) {
1822 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825
Jeff Sharkey48877892015-03-18 11:27:19 -07001826 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001827 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001828 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1829 waitForReady();
1830
Jeff Sharkey50a05452015-04-29 11:24:52 -07001831 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001832 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001833 final VolumeRecord rec = mRecords.get(fsUuid);
1834 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07001835 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001836 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001837 }
1838 }
1839
1840 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001841 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001842 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1843 waitForReady();
1844
Jeff Sharkey50a05452015-04-29 11:24:52 -07001845 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001846 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001847 final VolumeRecord rec = mRecords.get(fsUuid);
1848 rec.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001849 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001850 writeSettingsLocked();
1851 }
1852 }
1853
1854 @Override
1855 public void forgetVolume(String fsUuid) {
1856 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1857 waitForReady();
1858
Jeff Sharkey50a05452015-04-29 11:24:52 -07001859 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001860
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001861 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001862 final VolumeRecord rec = mRecords.remove(fsUuid);
1863 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001864 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001865 }
1866 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001867
1868 // If this had been primary storage, revert back to internal and
1869 // reset vold so we bind into new volume into place.
1870 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001871 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001872 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001873 }
1874
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001875 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001876 }
1877 }
1878
Jeff Sharkey7d2af542015-05-12 15:27:15 -07001879 @Override
1880 public void forgetAllVolumes() {
1881 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1882 waitForReady();
1883
Jeff Sharkey50a05452015-04-29 11:24:52 -07001884 synchronized (mLock) {
1885 for (int i = 0; i < mRecords.size(); i++) {
1886 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001887 final VolumeRecord rec = mRecords.valueAt(i);
1888 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001889 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001890 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001891 mCallbacks.notifyVolumeForgotten(fsUuid);
1892 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001893 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001894
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001895 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
1896 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
1897 }
1898
1899 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001900 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001901 }
1902 }
1903
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001904 private void forgetPartition(String partGuid) {
1905 try {
1906 mConnector.execute("volume", "forget_partition", partGuid);
1907 } catch (NativeDaemonConnectorException e) {
1908 Slog.w(TAG, "Failed to forget key for " + partGuid + ": " + e);
1909 }
1910 }
1911
Svet Ganov6ee871e2015-07-10 14:29:33 -07001912 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07001913 waitForReady();
1914
Svet Ganov6ee871e2015-07-10 14:29:33 -07001915 String modeName = "none";
1916 switch (mode) {
1917 case Zygote.MOUNT_EXTERNAL_DEFAULT: {
1918 modeName = "default";
1919 } break;
1920
1921 case Zygote.MOUNT_EXTERNAL_READ: {
1922 modeName = "read";
1923 } break;
1924
1925 case Zygote.MOUNT_EXTERNAL_WRITE: {
1926 modeName = "write";
1927 } break;
Jeff Sharkey9527b222015-06-24 15:24:48 -07001928 }
1929
1930 try {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001931 mConnector.execute("volume", "remount_uid", uid, modeName);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001932 } catch (NativeDaemonConnectorException e) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001933 Slog.w(TAG, "Failed to remount UID " + uid + " as " + modeName + ": " + e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001934 }
1935 }
1936
1937 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001938 public void setDebugFlags(int flags, int mask) {
1939 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1940 waitForReady();
1941
Jeff Sharkeyba512352015-11-12 20:17:45 -08001942 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001943 if (StorageManager.isNativeFileBasedEncryptionEnabled()) {
1944 throw new IllegalStateException(
1945 "Emulation not available on device with native FBE");
1946 }
1947
Jeff Sharkeyba512352015-11-12 20:17:45 -08001948 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
1949 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001950
1951 // Perform hard reboot to kick policy into place
1952 mContext.getSystemService(PowerManager.class).reboot(null);
Jeff Sharkeyba512352015-11-12 20:17:45 -08001953 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001954
Jeff Sharkeyba512352015-11-12 20:17:45 -08001955 if ((mask & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0) {
1956 synchronized (mLock) {
1957 mForceAdoptable = (flags & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0;
1958
1959 writeSettingsLocked();
1960 mHandler.obtainMessage(H_RESET).sendToTarget();
1961 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001962 }
1963 }
1964
1965 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001966 public String getPrimaryStorageUuid() {
1967 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1968 waitForReady();
1969
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001970 synchronized (mLock) {
1971 return mPrimaryStorageUuid;
1972 }
1973 }
1974
1975 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001976 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
1977 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1978 waitForReady();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001979
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001980 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001981 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
1982 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001983 }
1984
1985 if (mMoveCallback != null) {
1986 throw new IllegalStateException("Move already in progress");
1987 }
1988 mMoveCallback = callback;
1989 mMoveTargetUuid = volumeUuid;
1990
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001991 // When moving to/from primary physical volume, we probably just nuked
1992 // the current storage location, so we have nothing to move.
1993 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1994 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
1995 Slog.d(TAG, "Skipping move to/from primary physical");
1996 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
1997 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001998 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001999
2000 } else {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002001 final VolumeInfo from = findStorageForUuid(mPrimaryStorageUuid);
2002 final VolumeInfo to = findStorageForUuid(volumeUuid);
2003
2004 if (from == null) {
2005 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2006 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2007 return;
2008 } else if (to == null) {
2009 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2010 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2011 return;
2012 }
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002013
2014 try {
2015 mConnector.execute("volume", "move_storage", from.id, to.id);
2016 } catch (NativeDaemonConnectorException e) {
2017 throw e.rethrowAsParcelableException();
2018 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002019 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002020 }
2021 }
2022
2023 @Override
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07002024 public int[] getStorageUsers(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002025 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatc1b4ce92010-02-16 17:13:03 -08002026 waitForReady();
2027 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002028 final String[] r = NativeDaemonEvent.filterMessageList(
2029 mConnector.executeForList("storage", "users", path),
2030 VoldResponseCode.StorageUsersListResult);
2031
San Mehatc1b4ce92010-02-16 17:13:03 -08002032 // FMT: <pid> <process name>
2033 int[] data = new int[r.length];
2034 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002035 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08002036 try {
2037 data[i] = Integer.parseInt(tok[0]);
2038 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07002039 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08002040 return new int[0];
2041 }
2042 }
2043 return data;
2044 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07002045 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08002046 return new int[0];
2047 }
2048 }
2049
San Mehatb1043402010-02-05 08:26:50 -08002050 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002051 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002052 for (int i = 0; i < mVolumes.size(); i++) {
2053 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002054 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002055 // Cool beans, we have a mounted primary volume
2056 return;
2057 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002058 }
San Mehatb1043402010-02-05 08:26:50 -08002059 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002060
2061 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002062 }
2063
San Mehat4270e1e2010-01-29 05:32:19 -08002064 public String[] getSecureContainerList() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002065 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002066 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002067 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002068
San Mehat4270e1e2010-01-29 05:32:19 -08002069 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002070 return NativeDaemonEvent.filterMessageList(
2071 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08002072 } catch (NativeDaemonConnectorException e) {
2073 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075 }
San Mehat36972292010-01-06 11:06:32 -08002076
Kenny Root6dceb882012-04-12 14:23:49 -07002077 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
2078 int ownerUid, boolean external) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002079 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08002080 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002081 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002082
San Mehatb1043402010-02-05 08:26:50 -08002083 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002084 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002085 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
2086 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08002087 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002088 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002089 }
San Mehata181b212010-02-11 06:50:20 -08002090
2091 if (rc == StorageResultCode.OperationSucceeded) {
2092 synchronized (mAsecMountSet) {
2093 mAsecMountSet.add(id);
2094 }
2095 }
San Mehat4270e1e2010-01-29 05:32:19 -08002096 return rc;
San Mehat36972292010-01-06 11:06:32 -08002097 }
2098
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002099 @Override
2100 public int resizeSecureContainer(String id, int sizeMb, String key) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002101 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002102 waitForReady();
2103 warnOnNotMounted();
2104
2105 int rc = StorageResultCode.OperationSucceeded;
2106 try {
2107 mConnector.execute("asec", "resize", id, sizeMb, new SensitiveArg(key));
2108 } catch (NativeDaemonConnectorException e) {
2109 rc = StorageResultCode.OperationFailedInternalError;
2110 }
2111 return rc;
2112 }
2113
San Mehat4270e1e2010-01-29 05:32:19 -08002114 public int finalizeSecureContainer(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002115 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08002116 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002117
San Mehatb1043402010-02-05 08:26:50 -08002118 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002119 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002120 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08002121 /*
2122 * Finalization does a remount, so no need
2123 * to update mAsecMountSet
2124 */
San Mehat4270e1e2010-01-29 05:32:19 -08002125 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002126 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002127 }
San Mehat4270e1e2010-01-29 05:32:19 -08002128 return rc;
San Mehat36972292010-01-06 11:06:32 -08002129 }
2130
Kenny Root6dceb882012-04-12 14:23:49 -07002131 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002132 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Kenny Root6dceb882012-04-12 14:23:49 -07002133 warnOnNotMounted();
2134
2135 int rc = StorageResultCode.OperationSucceeded;
2136 try {
2137 mConnector.execute("asec", "fixperms", id, gid, filename);
2138 /*
2139 * Fix permissions does a remount, so no need to update
2140 * mAsecMountSet
2141 */
2142 } catch (NativeDaemonConnectorException e) {
2143 rc = StorageResultCode.OperationFailedInternalError;
2144 }
2145 return rc;
2146 }
2147
San Mehatd9709982010-02-18 11:43:03 -08002148 public int destroySecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002149 enforcePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08002150 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002151 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002152
Kenny Rootaa485402010-09-14 14:49:41 -07002153 /*
2154 * Force a GC to make sure AssetManagers in other threads of the
2155 * system_server are cleaned up. We have to do this since AssetManager
2156 * instances are kept as a WeakReference and it's possible we have files
2157 * open on the external storage.
2158 */
2159 Runtime.getRuntime().gc();
2160
San Mehatb1043402010-02-05 08:26:50 -08002161 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002162 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002163 final Command cmd = new Command("asec", "destroy", id);
2164 if (force) {
2165 cmd.appendArg("force");
2166 }
2167 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002168 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002169 int code = e.getCode();
2170 if (code == VoldResponseCode.OpFailedStorageBusy) {
2171 rc = StorageResultCode.OperationFailedStorageBusy;
2172 } else {
2173 rc = StorageResultCode.OperationFailedInternalError;
2174 }
San Mehat02735bc2010-01-26 15:18:08 -08002175 }
San Mehata181b212010-02-11 06:50:20 -08002176
2177 if (rc == StorageResultCode.OperationSucceeded) {
2178 synchronized (mAsecMountSet) {
2179 if (mAsecMountSet.contains(id)) {
2180 mAsecMountSet.remove(id);
2181 }
2182 }
2183 }
2184
San Mehat4270e1e2010-01-29 05:32:19 -08002185 return rc;
San Mehat36972292010-01-06 11:06:32 -08002186 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002187
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002188 public int mountSecureContainer(String id, String key, int ownerUid, boolean readOnly) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002189 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002190 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002191 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002192
San Mehata181b212010-02-11 06:50:20 -08002193 synchronized (mAsecMountSet) {
2194 if (mAsecMountSet.contains(id)) {
2195 return StorageResultCode.OperationFailedStorageMounted;
2196 }
2197 }
2198
San Mehatb1043402010-02-05 08:26:50 -08002199 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002200 try {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002201 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid,
2202 readOnly ? "ro" : "rw");
San Mehat4270e1e2010-01-29 05:32:19 -08002203 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07002204 int code = e.getCode();
2205 if (code != VoldResponseCode.OpFailedStorageBusy) {
2206 rc = StorageResultCode.OperationFailedInternalError;
2207 }
San Mehat02735bc2010-01-26 15:18:08 -08002208 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002209
2210 if (rc == StorageResultCode.OperationSucceeded) {
2211 synchronized (mAsecMountSet) {
2212 mAsecMountSet.add(id);
2213 }
2214 }
San Mehat4270e1e2010-01-29 05:32:19 -08002215 return rc;
San Mehat36972292010-01-06 11:06:32 -08002216 }
2217
San Mehatd9709982010-02-18 11:43:03 -08002218 public int unmountSecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002219 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002220 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002221 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002222
San Mehat6cdd9c02010-02-09 14:45:20 -08002223 synchronized (mAsecMountSet) {
2224 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08002225 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08002226 }
2227 }
2228
Kenny Rootaa485402010-09-14 14:49:41 -07002229 /*
2230 * Force a GC to make sure AssetManagers in other threads of the
2231 * system_server are cleaned up. We have to do this since AssetManager
2232 * instances are kept as a WeakReference and it's possible we have files
2233 * open on the external storage.
2234 */
2235 Runtime.getRuntime().gc();
2236
San Mehatb1043402010-02-05 08:26:50 -08002237 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002238 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002239 final Command cmd = new Command("asec", "unmount", id);
2240 if (force) {
2241 cmd.appendArg("force");
2242 }
2243 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002244 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002245 int code = e.getCode();
2246 if (code == VoldResponseCode.OpFailedStorageBusy) {
2247 rc = StorageResultCode.OperationFailedStorageBusy;
2248 } else {
2249 rc = StorageResultCode.OperationFailedInternalError;
2250 }
San Mehat02735bc2010-01-26 15:18:08 -08002251 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002252
2253 if (rc == StorageResultCode.OperationSucceeded) {
2254 synchronized (mAsecMountSet) {
2255 mAsecMountSet.remove(id);
2256 }
2257 }
San Mehat4270e1e2010-01-29 05:32:19 -08002258 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08002259 }
2260
San Mehat6cdd9c02010-02-09 14:45:20 -08002261 public boolean isSecureContainerMounted(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002262 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat6cdd9c02010-02-09 14:45:20 -08002263 waitForReady();
2264 warnOnNotMounted();
2265
2266 synchronized (mAsecMountSet) {
2267 return mAsecMountSet.contains(id);
2268 }
2269 }
2270
San Mehat4270e1e2010-01-29 05:32:19 -08002271 public int renameSecureContainer(String oldId, String newId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002272 enforcePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08002273 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002274 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002275
San Mehata181b212010-02-11 06:50:20 -08002276 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08002277 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06002278 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08002279 * changed while active, we must ensure both ids are not currently mounted.
2280 */
2281 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08002282 return StorageResultCode.OperationFailedStorageMounted;
2283 }
2284 }
2285
San Mehatb1043402010-02-05 08:26:50 -08002286 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002287 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002288 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08002289 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002290 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002291 }
San Mehata181b212010-02-11 06:50:20 -08002292
San Mehat4270e1e2010-01-29 05:32:19 -08002293 return rc;
San Mehat45f61042010-01-23 08:12:43 -08002294 }
2295
San Mehat4270e1e2010-01-29 05:32:19 -08002296 public String getSecureContainerPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002297 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002298 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002299 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002300
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002301 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07002302 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002303 event = mConnector.execute("asec", "path", id);
2304 event.checkCode(VoldResponseCode.AsecPathResult);
2305 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07002306 } catch (NativeDaemonConnectorException e) {
2307 int code = e.getCode();
2308 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01002309 Slog.i(TAG, String.format("Container '%s' not found", id));
2310 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08002311 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07002312 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08002313 }
2314 }
San Mehat22dd86e2010-01-12 12:21:18 -08002315 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002316
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002317 public String getSecureContainerFilesystemPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002318 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002319 waitForReady();
2320 warnOnNotMounted();
2321
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002322 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002323 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002324 event = mConnector.execute("asec", "fspath", id);
2325 event.checkCode(VoldResponseCode.AsecPathResult);
2326 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002327 } catch (NativeDaemonConnectorException e) {
2328 int code = e.getCode();
2329 if (code == VoldResponseCode.OpFailedStorageNotFound) {
2330 Slog.i(TAG, String.format("Container '%s' not found", id));
2331 return null;
2332 } else {
2333 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2334 }
2335 }
2336 }
2337
Jeff Sharkey48877892015-03-18 11:27:19 -07002338 @Override
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002339 public void finishMediaUpdate() {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002340 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Rubin Xucd7a0142015-04-17 23:45:27 +01002341 throw new SecurityException("no permission to call finishMediaUpdate()");
2342 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002343 if (mUnmountSignal != null) {
2344 mUnmountSignal.countDown();
2345 } else {
2346 Slog.w(TAG, "Odd, nobody asked to unmount?");
2347 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002348 }
Kenny Root02c87302010-07-01 08:10:18 -07002349
Kenny Roota02b8b02010-08-05 16:14:17 -07002350 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2351 if (callerUid == android.os.Process.SYSTEM_UID) {
2352 return true;
2353 }
2354
Kenny Root02c87302010-07-01 08:10:18 -07002355 if (packageName == null) {
2356 return false;
2357 }
2358
Jeff Sharkeycd654482016-01-08 17:42:11 -07002359 final int packageUid = mPms.getPackageUid(packageName,
2360 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002361
2362 if (DEBUG_OBB) {
2363 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2364 packageUid + ", callerUid = " + callerUid);
2365 }
2366
2367 return callerUid == packageUid;
2368 }
2369
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002370 public String getMountedObbPath(String rawPath) {
2371 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002372
Kenny Root02c87302010-07-01 08:10:18 -07002373 waitForReady();
2374 warnOnNotMounted();
2375
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002376 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002377 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002378 state = mObbPathToStateMap.get(rawPath);
2379 }
2380 if (state == null) {
2381 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2382 return null;
2383 }
2384
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002385 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002386 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002387 event = mConnector.execute("obb", "path", state.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002388 event.checkCode(VoldResponseCode.AsecPathResult);
2389 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002390 } catch (NativeDaemonConnectorException e) {
2391 int code = e.getCode();
2392 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002393 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002394 } else {
2395 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2396 }
2397 }
2398 }
2399
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002400 @Override
2401 public boolean isObbMounted(String rawPath) {
2402 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002403 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002404 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002405 }
Kenny Root02c87302010-07-01 08:10:18 -07002406 }
2407
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002408 @Override
2409 public void mountObb(
2410 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2411 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2412 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2413 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002414
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002415 final int callingUid = Binder.getCallingUid();
2416 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2417 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002418 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2419
2420 if (DEBUG_OBB)
2421 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002422 }
2423
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002424 @Override
2425 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2426 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2427
2428 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002429 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002430 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002431 }
2432
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002433 if (existingState != null) {
2434 // TODO: separate state object from request data
2435 final int callingUid = Binder.getCallingUid();
2436 final ObbState newState = new ObbState(
2437 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2438 final ObbAction action = new UnmountObbAction(newState, force);
2439 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002440
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002441 if (DEBUG_OBB)
2442 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2443 } else {
2444 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2445 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002446 }
2447
Ben Komalo444eca22011-09-01 15:17:44 -07002448 @Override
2449 public int getEncryptionState() {
2450 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2451 "no permission to access the crypt keeper");
2452
2453 waitForReady();
2454
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002455 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002456 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002457 event = mCryptConnector.execute("cryptfs", "cryptocomplete");
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002458 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002459 } catch (NumberFormatException e) {
2460 // Bad result - unexpected.
2461 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2462 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2463 } catch (NativeDaemonConnectorException e) {
2464 // Something bad happened.
2465 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2466 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2467 }
2468 }
2469
2470 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002471 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002472 if (TextUtils.isEmpty(password)) {
2473 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002474 }
2475
Jason parks8888c592011-01-20 22:46:41 -06002476 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2477 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002478
2479 waitForReady();
2480
2481 if (DEBUG_EVENTS) {
2482 Slog.i(TAG, "decrypting storage...");
2483 }
2484
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002485 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002486 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002487 event = mCryptConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002488
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002489 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002490 if (code == 0) {
2491 // Decrypt was successful. Post a delayed message before restarting in order
2492 // to let the UI to clear itself
2493 mHandler.postDelayed(new Runnable() {
2494 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002495 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002496 mCryptConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002497 } catch (NativeDaemonConnectorException e) {
2498 Slog.e(TAG, "problem executing in background", e);
2499 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002500 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002501 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002502 }
2503
2504 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002505 } catch (NativeDaemonConnectorException e) {
2506 // Decryption failed
2507 return e.getCode();
2508 }
Jason parks5af0b912010-11-29 09:05:25 -06002509 }
2510
Paul Lawrence46791e72014-04-03 09:10:26 -07002511 public int encryptStorage(int type, String password) {
2512 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002513 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002514 }
2515
Jason parks8888c592011-01-20 22:46:41 -06002516 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2517 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002518
2519 waitForReady();
2520
2521 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002522 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002523 }
2524
2525 try {
Paul Lawrence5096d9e2015-09-09 13:05:45 -07002526 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2527 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2528 CRYPTO_TYPES[type]);
2529 } else {
2530 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2531 CRYPTO_TYPES[type], new SensitiveArg(password));
2532 }
Jason parks56aa5322011-01-07 09:01:15 -06002533 } catch (NativeDaemonConnectorException e) {
2534 // Encryption failed
2535 return e.getCode();
2536 }
2537
2538 return 0;
2539 }
2540
Paul Lawrence8e397362014-01-27 15:22:30 -08002541 /** Set the password for encrypting the master key.
2542 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2543 * @param password The password to set.
2544 */
2545 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002546 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2547 "no permission to access the crypt keeper");
2548
2549 waitForReady();
2550
2551 if (DEBUG_EVENTS) {
2552 Slog.i(TAG, "changing encryption password...");
2553 }
2554
2555 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002556 NativeDaemonEvent event = mCryptConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
Paul Lawrence05487612015-06-09 13:35:38 -07002557 new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002558 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002559 } catch (NativeDaemonConnectorException e) {
2560 // Encryption failed
2561 return e.getCode();
2562 }
2563 }
2564
Christopher Tate32418be2011-10-10 13:51:12 -07002565 /**
2566 * Validate a user-supplied password string with cryptfs
2567 */
2568 @Override
2569 public int verifyEncryptionPassword(String password) throws RemoteException {
2570 // Only the system process is permitted to validate passwords
2571 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2572 throw new SecurityException("no permission to access the crypt keeper");
2573 }
2574
2575 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2576 "no permission to access the crypt keeper");
2577
2578 if (TextUtils.isEmpty(password)) {
2579 throw new IllegalArgumentException("password cannot be empty");
2580 }
2581
2582 waitForReady();
2583
2584 if (DEBUG_EVENTS) {
2585 Slog.i(TAG, "validating encryption password...");
2586 }
2587
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002588 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002589 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002590 event = mCryptConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002591 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2592 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002593 } catch (NativeDaemonConnectorException e) {
2594 // Encryption failed
2595 return e.getCode();
2596 }
2597 }
2598
Paul Lawrence8e397362014-01-27 15:22:30 -08002599 /**
2600 * Get the type of encryption used to encrypt the master key.
2601 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2602 */
2603 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002604 public int getPasswordType() {
Paul Lawrence8e397362014-01-27 15:22:30 -08002605
2606 waitForReady();
2607
2608 final NativeDaemonEvent event;
2609 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002610 event = mCryptConnector.execute("cryptfs", "getpwtype");
Paul Lawrence8e397362014-01-27 15:22:30 -08002611 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2612 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2613 return i;
2614 }
2615
2616 throw new IllegalStateException("unexpected return from cryptfs");
2617 } catch (NativeDaemonConnectorException e) {
2618 throw e.rethrowAsParcelableException();
2619 }
2620 }
2621
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002622 /**
2623 * Set a field in the crypto header.
2624 * @param field field to set
2625 * @param contents contents to set in field
2626 */
2627 @Override
2628 public void setField(String field, String contents) throws RemoteException {
2629
2630 waitForReady();
2631
2632 final NativeDaemonEvent event;
2633 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002634 event = mCryptConnector.execute("cryptfs", "setfield", field, contents);
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002635 } catch (NativeDaemonConnectorException e) {
2636 throw e.rethrowAsParcelableException();
2637 }
2638 }
2639
2640 /**
2641 * Gets a field from the crypto header.
2642 * @param field field to get
2643 * @return contents of field
2644 */
2645 @Override
2646 public String getField(String field) throws RemoteException {
2647
2648 waitForReady();
2649
2650 final NativeDaemonEvent event;
2651 try {
2652 final String[] contents = NativeDaemonEvent.filterMessageList(
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002653 mCryptConnector.executeForList("cryptfs", "getfield", field),
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002654 VoldResponseCode.CryptfsGetfieldResult);
2655 String result = new String();
2656 for (String content : contents) {
2657 result += content;
2658 }
2659 return result;
2660 } catch (NativeDaemonConnectorException e) {
2661 throw e.rethrowAsParcelableException();
2662 }
2663 }
2664
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002665 /**
2666 * Is userdata convertible to file based encryption?
2667 * @return non zero for convertible
2668 */
2669 @Override
2670 public boolean isConvertibleToFBE() throws RemoteException {
2671
2672 waitForReady();
2673
2674 final NativeDaemonEvent event;
2675 try {
2676 event = mCryptConnector.execute("cryptfs", "isConvertibleToFBE");
2677 return Integer.parseInt(event.getMessage()) != 0;
2678 } catch (NativeDaemonConnectorException e) {
2679 throw e.rethrowAsParcelableException();
2680 }
2681 }
2682
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002683 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002684 public String getPassword() throws RemoteException {
Rubin Xucd7a0142015-04-17 23:45:27 +01002685 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE,
2686 "only keyguard can retrieve password");
Paul Lawrence945490c2014-03-27 16:37:28 +00002687 if (!isReady()) {
2688 return new String();
2689 }
2690
2691 final NativeDaemonEvent event;
2692 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002693 event = mCryptConnector.execute("cryptfs", "getpw");
Paul Lawrence24063b52015-01-06 13:11:23 -08002694 if ("-1".equals(event.getMessage())) {
2695 // -1 equals no password
2696 return null;
2697 }
Paul Lawrence05487612015-06-09 13:35:38 -07002698 return event.getMessage();
Paul Lawrence945490c2014-03-27 16:37:28 +00002699 } catch (NativeDaemonConnectorException e) {
2700 throw e.rethrowAsParcelableException();
Paul Lawrence24063b52015-01-06 13:11:23 -08002701 } catch (IllegalArgumentException e) {
2702 Slog.e(TAG, "Invalid response to getPassword");
2703 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002704 }
2705 }
2706
2707 @Override
2708 public void clearPassword() throws RemoteException {
2709 if (!isReady()) {
2710 return;
2711 }
2712
2713 final NativeDaemonEvent event;
2714 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002715 event = mCryptConnector.execute("cryptfs", "clearpw");
Paul Lawrence945490c2014-03-27 16:37:28 +00002716 } catch (NativeDaemonConnectorException e) {
2717 throw e.rethrowAsParcelableException();
2718 }
2719 }
2720
2721 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002722 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002723 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002724 waitForReady();
2725
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002726 try {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002727 mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber,
2728 ephemeral ? 1 : 0);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002729 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002730 throw e.rethrowAsParcelableException();
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002731 }
2732 }
2733
Paul Crowley7ec733f2015-05-19 12:42:00 +01002734 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002735 public void destroyUserKey(int userId) {
2736 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002737 waitForReady();
2738
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002739 try {
2740 mCryptConnector.execute("cryptfs", "destroy_user_key", userId);
2741 } catch (NativeDaemonConnectorException e) {
2742 throw e.rethrowAsParcelableException();
2743 }
2744 }
2745
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002746 private SensitiveArg encodeBytes(byte[] bytes) {
2747 if (ArrayUtils.isEmpty(bytes)) {
2748 return new SensitiveArg("!");
2749 } else {
2750 return new SensitiveArg(HexDump.toHexString(bytes));
2751 }
2752 }
2753
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002754 @Override
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002755 public void changeUserKey(int userId, int serialNumber,
2756 byte[] token, byte[] oldSecret, byte[] newSecret) {
2757 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2758 waitForReady();
2759
2760 try {
2761 mCryptConnector.execute("cryptfs", "change_user_key", userId, serialNumber,
2762 encodeBytes(token), encodeBytes(oldSecret), encodeBytes(newSecret));
2763 } catch (NativeDaemonConnectorException e) {
2764 throw e.rethrowAsParcelableException();
2765 }
2766 }
2767
2768 @Override
2769 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002770 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2771 waitForReady();
2772
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002773 // When a user has secure lock screen, require a challenge token to
2774 // actually unlock. This check is mostly in place for emulation mode.
2775 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
2776 throw new IllegalStateException("Token required to unlock secure user " + userId);
2777 }
2778
Paul Crowley7ec733f2015-05-19 12:42:00 +01002779 try {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002780 mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002781 encodeBytes(token), encodeBytes(secret));
Paul Crowley7ec733f2015-05-19 12:42:00 +01002782 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002783 throw e.rethrowAsParcelableException();
2784 }
2785
2786 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002787 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002788 }
2789 }
2790
2791 @Override
2792 public void lockUserKey(int userId) {
2793 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2794 waitForReady();
2795
2796 try {
2797 mCryptConnector.execute("cryptfs", "lock_user_key", userId);
2798 } catch (NativeDaemonConnectorException e) {
2799 throw e.rethrowAsParcelableException();
2800 }
2801
2802 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002803 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002804 }
2805 }
2806
2807 @Override
2808 public boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyba512352015-11-12 20:17:45 -08002809 if (StorageManager.isFileBasedEncryptionEnabled()) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002810 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002811 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002812 }
2813 } else {
2814 return true;
2815 }
2816 }
2817
2818 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002819 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002820 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2821 waitForReady();
2822
2823 try {
2824 mCryptConnector.execute("cryptfs", "prepare_user_storage", escapeNull(volumeUuid),
Jeff Sharkey47f71082016-02-01 17:03:54 -07002825 userId, serialNumber, flags);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002826 } catch (NativeDaemonConnectorException e) {
2827 throw e.rethrowAsParcelableException();
Paul Crowley7ec733f2015-05-19 12:42:00 +01002828 }
2829 }
2830
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002831 @Override
Daichi Hirono91e3b502015-12-16 09:24:16 +09002832 public ParcelFileDescriptor mountAppFuse(final String name) throws RemoteException {
Daichi Hironobee50c02015-12-14 11:00:54 +09002833 try {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002834 final int uid = Binder.getCallingUid();
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002835 final int pid = Binder.getCallingPid();
Daichi Hironobee50c02015-12-14 11:00:54 +09002836 final NativeDaemonEvent event =
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002837 mConnector.execute("appfuse", "mount", uid, pid, name);
Daichi Hironobee50c02015-12-14 11:00:54 +09002838 if (event.getFileDescriptors() == null) {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002839 throw new RemoteException("AppFuse FD from vold is null.");
Daichi Hironobee50c02015-12-14 11:00:54 +09002840 }
Daichi Hirono91e3b502015-12-16 09:24:16 +09002841 return ParcelFileDescriptor.fromFd(
2842 event.getFileDescriptors()[0],
2843 mHandler,
2844 new ParcelFileDescriptor.OnCloseListener() {
2845 @Override
2846 public void onClose(IOException e) {
2847 try {
2848 final NativeDaemonEvent event = mConnector.execute(
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002849 "appfuse", "unmount", uid, pid, name);
Daichi Hirono91e3b502015-12-16 09:24:16 +09002850 } catch (NativeDaemonConnectorException unmountException) {
2851 Log.e(TAG, "Failed to unmount appfuse.");
2852 }
2853 }
2854 });
Daichi Hironobee50c02015-12-14 11:00:54 +09002855 } catch (NativeDaemonConnectorException e) {
2856 throw e.rethrowAsParcelableException();
Daichi Hirono91e3b502015-12-16 09:24:16 +09002857 } catch (IOException e) {
2858 throw new RemoteException(e.getMessage());
Daichi Hironobee50c02015-12-14 11:00:54 +09002859 }
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002860 }
2861
2862 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002863 public int mkdirs(String callingPkg, String appPath) {
2864 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2865 final UserEnvironment userEnv = new UserEnvironment(userId);
2866
2867 // Validate that reported package name belongs to caller
2868 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2869 Context.APP_OPS_SERVICE);
2870 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2871
Jeff Sharkey48877892015-03-18 11:27:19 -07002872 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002873 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002874 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002875 } catch (IOException e) {
2876 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2877 return -1;
2878 }
2879
2880 // Try translating the app path into a vold path, but require that it
2881 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07002882 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
2883 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
2884 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
2885 appPath = appFile.getAbsolutePath();
2886 if (!appPath.endsWith("/")) {
2887 appPath = appPath + "/";
2888 }
2889
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002890 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002891 mConnector.execute("volume", "mkdirs", appPath);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002892 return 0;
2893 } catch (NativeDaemonConnectorException e) {
2894 return e.getCode();
2895 }
2896 }
2897
Jeff Sharkey48877892015-03-18 11:27:19 -07002898 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002899 }
2900
2901 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07002902 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002903 final int userId = UserHandle.getUserId(uid);
Jeff Sharkey46349872015-07-28 10:49:47 -07002904 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
2905
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002906 boolean reportUnmounted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -07002907 boolean foundPrimary = false;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002908
Svetoslav38c3dbb2015-07-14 11:27:06 -07002909 final long identity = Binder.clearCallingIdentity();
2910 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002911 if (!mMountServiceInternal.hasExternalStorage(uid, packageName)) {
2912 reportUnmounted = true;
2913 }
2914 if (!isUserKeyUnlocked(userId)) {
2915 reportUnmounted = true;
2916 }
Svetoslav38c3dbb2015-07-14 11:27:06 -07002917 } finally {
2918 Binder.restoreCallingIdentity(identity);
2919 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07002920
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002921 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07002922 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002923 for (int i = 0; i < mVolumes.size(); i++) {
2924 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -07002925 if (forWrite ? vol.isVisibleForWrite(userId) : vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07002926 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
2927 reportUnmounted);
Jeff Sharkey48877892015-03-18 11:27:19 -07002928 if (vol.isPrimary()) {
2929 res.add(0, userVol);
2930 foundPrimary = true;
2931 } else {
2932 res.add(userVol);
2933 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002934 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002935 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002936 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002937
2938 if (!foundPrimary) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002939 Log.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07002940
2941 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002942 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07002943
2944 final String id = "stub_primary";
2945 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002946 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07002947 final boolean primary = true;
2948 final boolean removable = primaryPhysical;
2949 final boolean emulated = !primaryPhysical;
2950 final long mtpReserveSize = 0L;
2951 final boolean allowMassStorage = false;
2952 final long maxFileSize = 0L;
2953 final UserHandle owner = new UserHandle(userId);
2954 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07002955 final String state = Environment.MEDIA_REMOVED;
2956
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07002957 res.add(0, new StorageVolume(id, StorageVolume.STORAGE_ID_INVALID, path,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002958 description, primary, removable, emulated, mtpReserveSize,
2959 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07002960 }
2961
2962 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002963 }
2964
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002965 @Override
2966 public DiskInfo[] getDisks() {
2967 synchronized (mLock) {
2968 final DiskInfo[] res = new DiskInfo[mDisks.size()];
2969 for (int i = 0; i < mDisks.size(); i++) {
2970 res[i] = mDisks.valueAt(i);
2971 }
2972 return res;
2973 }
2974 }
2975
2976 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002977 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002978 synchronized (mLock) {
2979 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
2980 for (int i = 0; i < mVolumes.size(); i++) {
2981 res[i] = mVolumes.valueAt(i);
2982 }
2983 return res;
2984 }
2985 }
2986
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002987 @Override
2988 public VolumeRecord[] getVolumeRecords(int flags) {
2989 synchronized (mLock) {
2990 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
2991 for (int i = 0; i < mRecords.size(); i++) {
2992 res[i] = mRecords.valueAt(i);
2993 }
2994 return res;
2995 }
2996 }
2997
Kenny Rootaf9d6672010-10-08 09:21:39 -07002998 private void addObbStateLocked(ObbState obbState) throws RemoteException {
2999 final IBinder binder = obbState.getBinder();
3000 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003001
Kenny Rootaf9d6672010-10-08 09:21:39 -07003002 if (obbStates == null) {
3003 obbStates = new ArrayList<ObbState>();
3004 mObbMounts.put(binder, obbStates);
3005 } else {
3006 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003007 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003008 throw new IllegalStateException("Attempt to add ObbState twice. "
3009 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003010 }
3011 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003012 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003013
3014 obbStates.add(obbState);
3015 try {
3016 obbState.link();
3017 } catch (RemoteException e) {
3018 /*
3019 * The binder died before we could link it, so clean up our state
3020 * and return failure.
3021 */
3022 obbStates.remove(obbState);
3023 if (obbStates.isEmpty()) {
3024 mObbMounts.remove(binder);
3025 }
3026
3027 // Rethrow the error so mountObb can get it
3028 throw e;
3029 }
3030
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003031 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003032 }
3033
Kenny Rootaf9d6672010-10-08 09:21:39 -07003034 private void removeObbStateLocked(ObbState obbState) {
3035 final IBinder binder = obbState.getBinder();
3036 final List<ObbState> obbStates = mObbMounts.get(binder);
3037 if (obbStates != null) {
3038 if (obbStates.remove(obbState)) {
3039 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003040 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003041 if (obbStates.isEmpty()) {
3042 mObbMounts.remove(binder);
3043 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003044 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003045
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003046 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003047 }
3048
Kenny Roota02b8b02010-08-05 16:14:17 -07003049 private class ObbActionHandler extends Handler {
3050 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07003051 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07003052
3053 ObbActionHandler(Looper l) {
3054 super(l);
3055 }
3056
3057 @Override
3058 public void handleMessage(Message msg) {
3059 switch (msg.what) {
3060 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003061 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003062
3063 if (DEBUG_OBB)
3064 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3065
3066 // If a bind was already initiated we don't really
3067 // need to do anything. The pending install
3068 // will be processed later on.
3069 if (!mBound) {
3070 // If this is the only one pending we might
3071 // have to bind to the service again.
3072 if (!connectToService()) {
3073 Slog.e(TAG, "Failed to bind to media container service");
3074 action.handleError();
3075 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003076 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003077 }
Kenny Root735de3b2010-09-30 14:11:39 -07003078
Kenny Root735de3b2010-09-30 14:11:39 -07003079 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07003080 break;
3081 }
3082 case OBB_MCS_BOUND: {
3083 if (DEBUG_OBB)
3084 Slog.i(TAG, "OBB_MCS_BOUND");
3085 if (msg.obj != null) {
3086 mContainerService = (IMediaContainerService) msg.obj;
3087 }
3088 if (mContainerService == null) {
3089 // Something seriously wrong. Bail out
3090 Slog.e(TAG, "Cannot bind to media container service");
3091 for (ObbAction action : mActions) {
3092 // Indicate service bind error
3093 action.handleError();
3094 }
3095 mActions.clear();
3096 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07003097 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07003098 if (action != null) {
3099 action.execute(this);
3100 }
3101 } else {
3102 // Should never happen ideally.
3103 Slog.w(TAG, "Empty queue");
3104 }
3105 break;
3106 }
3107 case OBB_MCS_RECONNECT: {
3108 if (DEBUG_OBB)
3109 Slog.i(TAG, "OBB_MCS_RECONNECT");
3110 if (mActions.size() > 0) {
3111 if (mBound) {
3112 disconnectService();
3113 }
3114 if (!connectToService()) {
3115 Slog.e(TAG, "Failed to bind to media container service");
3116 for (ObbAction action : mActions) {
3117 // Indicate service bind error
3118 action.handleError();
3119 }
3120 mActions.clear();
3121 }
3122 }
3123 break;
3124 }
3125 case OBB_MCS_UNBIND: {
3126 if (DEBUG_OBB)
3127 Slog.i(TAG, "OBB_MCS_UNBIND");
3128
3129 // Delete pending install
3130 if (mActions.size() > 0) {
3131 mActions.remove(0);
3132 }
3133 if (mActions.size() == 0) {
3134 if (mBound) {
3135 disconnectService();
3136 }
3137 } else {
3138 // There are more pending requests in queue.
3139 // Just post MCS_BOUND message to trigger processing
3140 // of next pending install.
3141 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
3142 }
3143 break;
3144 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003145 case OBB_FLUSH_MOUNT_STATE: {
3146 final String path = (String) msg.obj;
3147
3148 if (DEBUG_OBB)
3149 Slog.i(TAG, "Flushing all OBB state for path " + path);
3150
3151 synchronized (mObbMounts) {
3152 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3153
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003154 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003155 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003156 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003157
3158 /*
3159 * If this entry's source file is in the volume path
3160 * that got unmounted, remove it because it's no
3161 * longer valid.
3162 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003163 if (state.canonicalPath.startsWith(path)) {
3164 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003165 }
3166 }
3167
3168 for (final ObbState obbState : obbStatesToRemove) {
3169 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003170 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003171
3172 removeObbStateLocked(obbState);
3173
3174 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003175 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003176 OnObbStateChangeListener.UNMOUNTED);
3177 } catch (RemoteException e) {
3178 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003179 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003180 }
3181 }
3182 }
3183 break;
3184 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003185 }
3186 }
3187
3188 private boolean connectToService() {
3189 if (DEBUG_OBB)
3190 Slog.i(TAG, "Trying to bind to DefaultContainerService");
3191
3192 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003193 if (mContext.bindServiceAsUser(service, mDefContainerConn, Context.BIND_AUTO_CREATE,
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003194 UserHandle.SYSTEM)) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003195 mBound = true;
3196 return true;
3197 }
3198 return false;
3199 }
3200
3201 private void disconnectService() {
3202 mContainerService = null;
3203 mBound = false;
3204 mContext.unbindService(mDefContainerConn);
3205 }
3206 }
3207
3208 abstract class ObbAction {
3209 private static final int MAX_RETRIES = 3;
3210 private int mRetries;
3211
3212 ObbState mObbState;
3213
3214 ObbAction(ObbState obbState) {
3215 mObbState = obbState;
3216 }
3217
3218 public void execute(ObbActionHandler handler) {
3219 try {
3220 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003221 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07003222 mRetries++;
3223 if (mRetries > MAX_RETRIES) {
3224 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07003225 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003226 handleError();
Kenny Roota02b8b02010-08-05 16:14:17 -07003227 } else {
3228 handleExecute();
3229 if (DEBUG_OBB)
3230 Slog.i(TAG, "Posting install MCS_UNBIND");
3231 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
3232 }
3233 } catch (RemoteException e) {
3234 if (DEBUG_OBB)
3235 Slog.i(TAG, "Posting install MCS_RECONNECT");
3236 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
3237 } catch (Exception e) {
3238 if (DEBUG_OBB)
3239 Slog.d(TAG, "Error handling OBB action", e);
3240 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07003241 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003242 }
3243 }
3244
Kenny Root05105f72010-09-22 17:29:43 -07003245 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07003246 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07003247
3248 protected ObbInfo getObbInfo() throws IOException {
3249 ObbInfo obbInfo;
3250 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003251 obbInfo = mContainerService.getObbInfo(mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003252 } catch (RemoteException e) {
3253 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003254 + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003255 obbInfo = null;
3256 }
3257 if (obbInfo == null) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003258 throw new IOException("Couldn't read OBB file: " + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003259 }
3260 return obbInfo;
3261 }
3262
Kenny Rootaf9d6672010-10-08 09:21:39 -07003263 protected void sendNewStatusOrIgnore(int status) {
3264 if (mObbState == null || mObbState.token == null) {
3265 return;
3266 }
3267
Kenny Root38cf8862010-09-26 14:18:51 -07003268 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003269 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003270 } catch (RemoteException e) {
3271 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
3272 }
3273 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003274 }
3275
3276 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003277 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003278 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003279
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003280 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003281 super(obbState);
3282 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003283 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003284 }
3285
Jason parks5af0b912010-11-29 09:05:25 -06003286 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07003287 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003288 waitForReady();
3289 warnOnNotMounted();
3290
Kenny Root38cf8862010-09-26 14:18:51 -07003291 final ObbInfo obbInfo = getObbInfo();
3292
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003293 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003294 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
3295 + " which is owned by " + obbInfo.packageName);
3296 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3297 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003298 }
3299
Kenny Rootaf9d6672010-10-08 09:21:39 -07003300 final boolean isMounted;
3301 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003302 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003303 }
3304 if (isMounted) {
3305 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
3306 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
3307 return;
3308 }
3309
Kenny Rootaf9d6672010-10-08 09:21:39 -07003310 final String hashedKey;
3311 if (mKey == null) {
3312 hashedKey = "none";
3313 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003314 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003315 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3316
3317 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
3318 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3319 SecretKey key = factory.generateSecret(ks);
3320 BigInteger bi = new BigInteger(key.getEncoded());
3321 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003322 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07003323 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
3324 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
3325 return;
3326 } catch (InvalidKeySpecException e) {
3327 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
3328 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07003329 return;
3330 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003331 }
Kenny Root38cf8862010-09-26 14:18:51 -07003332
Kenny Rootaf9d6672010-10-08 09:21:39 -07003333 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003334 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003335 mConnector.execute("obb", "mount", mObbState.canonicalPath, new SensitiveArg(hashedKey),
Jeff Sharkey56cd6462013-06-07 15:09:15 -07003336 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003337 } catch (NativeDaemonConnectorException e) {
3338 int code = e.getCode();
3339 if (code != VoldResponseCode.OpFailedStorageBusy) {
3340 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003341 }
3342 }
3343
Kenny Rootaf9d6672010-10-08 09:21:39 -07003344 if (rc == StorageResultCode.OperationSucceeded) {
3345 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003346 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003347
3348 synchronized (mObbMounts) {
3349 addObbStateLocked(mObbState);
3350 }
3351
3352 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07003353 } else {
Kenny Root05105f72010-09-22 17:29:43 -07003354 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07003355
Kenny Rootaf9d6672010-10-08 09:21:39 -07003356 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07003357 }
3358 }
3359
Jason parks5af0b912010-11-29 09:05:25 -06003360 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003361 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003362 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07003363 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003364
3365 @Override
3366 public String toString() {
3367 StringBuilder sb = new StringBuilder();
3368 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003369 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003370 sb.append('}');
3371 return sb.toString();
3372 }
3373 }
3374
3375 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003376 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003377
3378 UnmountObbAction(ObbState obbState, boolean force) {
3379 super(obbState);
3380 mForceUnmount = force;
3381 }
3382
Jason parks5af0b912010-11-29 09:05:25 -06003383 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07003384 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003385 waitForReady();
3386 warnOnNotMounted();
3387
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003388 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003389 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003390 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003391 }
Kenny Root38cf8862010-09-26 14:18:51 -07003392
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003393 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003394 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
3395 return;
3396 }
3397
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003398 if (existingState.ownerGid != mObbState.ownerGid) {
3399 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
3400 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003401 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3402 return;
3403 }
3404
Kenny Rootaf9d6672010-10-08 09:21:39 -07003405 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003406 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003407 final Command cmd = new Command("obb", "unmount", mObbState.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08003408 if (mForceUnmount) {
3409 cmd.appendArg("force");
3410 }
3411 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003412 } catch (NativeDaemonConnectorException e) {
3413 int code = e.getCode();
3414 if (code == VoldResponseCode.OpFailedStorageBusy) {
3415 rc = StorageResultCode.OperationFailedStorageBusy;
3416 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
3417 // If it's not mounted then we've already won.
3418 rc = StorageResultCode.OperationSucceeded;
3419 } else {
3420 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003421 }
3422 }
3423
Kenny Rootaf9d6672010-10-08 09:21:39 -07003424 if (rc == StorageResultCode.OperationSucceeded) {
3425 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003426 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003427 }
3428
Kenny Rootaf9d6672010-10-08 09:21:39 -07003429 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07003430 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003431 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003432 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07003433 }
3434 }
3435
Jason parks5af0b912010-11-29 09:05:25 -06003436 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003437 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003438 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07003439 }
3440
3441 @Override
3442 public String toString() {
3443 StringBuilder sb = new StringBuilder();
3444 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003445 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003446 sb.append(",force=");
3447 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003448 sb.append('}');
3449 return sb.toString();
3450 }
Kenny Root02c87302010-07-01 08:10:18 -07003451 }
Kenny Root38cf8862010-09-26 14:18:51 -07003452
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003453 private static class Callbacks extends Handler {
3454 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3455 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003456 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3457 private static final int MSG_VOLUME_FORGOTTEN = 4;
3458 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003459 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003460
3461 private final RemoteCallbackList<IMountServiceListener>
3462 mCallbacks = new RemoteCallbackList<>();
3463
3464 public Callbacks(Looper looper) {
3465 super(looper);
3466 }
3467
3468 public void register(IMountServiceListener callback) {
3469 mCallbacks.register(callback);
3470 }
3471
3472 public void unregister(IMountServiceListener callback) {
3473 mCallbacks.unregister(callback);
3474 }
3475
3476 @Override
3477 public void handleMessage(Message msg) {
3478 final SomeArgs args = (SomeArgs) msg.obj;
3479 final int n = mCallbacks.beginBroadcast();
3480 for (int i = 0; i < n; i++) {
3481 final IMountServiceListener callback = mCallbacks.getBroadcastItem(i);
3482 try {
3483 invokeCallback(callback, msg.what, args);
3484 } catch (RemoteException ignored) {
3485 }
3486 }
3487 mCallbacks.finishBroadcast();
3488 args.recycle();
3489 }
3490
3491 private void invokeCallback(IMountServiceListener callback, int what, SomeArgs args)
3492 throws RemoteException {
3493 switch (what) {
3494 case MSG_STORAGE_STATE_CHANGED: {
3495 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3496 (String) args.arg3);
3497 break;
3498 }
3499 case MSG_VOLUME_STATE_CHANGED: {
3500 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3501 break;
3502 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003503 case MSG_VOLUME_RECORD_CHANGED: {
3504 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3505 break;
3506 }
3507 case MSG_VOLUME_FORGOTTEN: {
3508 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003509 break;
3510 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003511 case MSG_DISK_SCANNED: {
3512 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003513 break;
3514 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003515 case MSG_DISK_DESTROYED: {
3516 callback.onDiskDestroyed((DiskInfo) args.arg1);
3517 break;
3518 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003519 }
3520 }
3521
3522 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3523 final SomeArgs args = SomeArgs.obtain();
3524 args.arg1 = path;
3525 args.arg2 = oldState;
3526 args.arg3 = newState;
3527 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3528 }
3529
3530 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3531 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003532 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003533 args.argi2 = oldState;
3534 args.argi3 = newState;
3535 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3536 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003537
Jeff Sharkey50a05452015-04-29 11:24:52 -07003538 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3539 final SomeArgs args = SomeArgs.obtain();
3540 args.arg1 = rec.clone();
3541 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3542 }
3543
3544 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003545 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003546 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003547 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003548 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003549
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003550 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003551 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003552 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003553 args.argi2 = volumeCount;
3554 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003555 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003556
3557 private void notifyDiskDestroyed(DiskInfo disk) {
3558 final SomeArgs args = SomeArgs.obtain();
3559 args.arg1 = disk.clone();
3560 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3561 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003562 }
3563
Kenny Root38cf8862010-09-26 14:18:51 -07003564 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003565 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
3567
3568 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003569 synchronized (mLock) {
3570 pw.println("Disks:");
3571 pw.increaseIndent();
3572 for (int i = 0; i < mDisks.size(); i++) {
3573 final DiskInfo disk = mDisks.valueAt(i);
3574 disk.dump(pw);
3575 }
3576 pw.decreaseIndent();
3577
3578 pw.println();
3579 pw.println("Volumes:");
3580 pw.increaseIndent();
3581 for (int i = 0; i < mVolumes.size(); i++) {
3582 final VolumeInfo vol = mVolumes.valueAt(i);
3583 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3584 vol.dump(pw);
3585 }
3586 pw.decreaseIndent();
3587
3588 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003589 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003590 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003591 for (int i = 0; i < mRecords.size(); i++) {
3592 final VolumeRecord note = mRecords.valueAt(i);
3593 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003594 }
3595 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003596
3597 pw.println();
3598 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07003599 pw.println("Force adoptable: " + mForceAdoptable);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08003600 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003601 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3602 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003603 }
Kenny Root38cf8862010-09-26 14:18:51 -07003604
Kenny Root38cf8862010-09-26 14:18:51 -07003605 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003606 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003607 pw.println("mObbMounts:");
3608 pw.increaseIndent();
3609 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3610 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003611 while (binders.hasNext()) {
3612 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003613 pw.println(e.getKey() + ":");
3614 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003615 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003616 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003617 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003618 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003619 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003620 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003621 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003622
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003623 pw.println();
3624 pw.println("mObbPathToStateMap:");
3625 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003626 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3627 while (maps.hasNext()) {
3628 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003629 pw.print(e.getKey());
3630 pw.print(" -> ");
3631 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003632 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003633 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003634 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003635
Robert Greenwalt470fd722012-01-18 12:51:15 -08003636 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003637 pw.println("mConnector:");
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003638 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003639 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003640 pw.decreaseIndent();
Christopher Tate7265abe2014-11-21 13:54:45 -08003641
Christopher Tate7265abe2014-11-21 13:54:45 -08003642 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003643 pw.println("mCryptConnector:");
3644 pw.increaseIndent();
3645 mCryptConnector.dump(fd, pw, args);
3646 pw.decreaseIndent();
3647
3648 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003649 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003650 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003653 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003654 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003655 public void monitor() {
3656 if (mConnector != null) {
3657 mConnector.monitor();
3658 }
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003659 if (mCryptConnector != null) {
3660 mCryptConnector.monitor();
3661 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003662 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003663
3664 private final class MountServiceInternalImpl extends MountServiceInternal {
3665 // Not guarded by a lock.
3666 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3667 new CopyOnWriteArrayList<>();
3668
3669 @Override
3670 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3671 // No locking - CopyOnWriteArrayList
3672 mPolicies.add(policy);
3673 }
3674
3675 @Override
3676 public void onExternalStoragePolicyChanged(int uid, String packageName) {
3677 final int mountMode = getExternalStorageMountMode(uid, packageName);
3678 remountUidExternalStorage(uid, mountMode);
3679 }
3680
3681 @Override
3682 public int getExternalStorageMountMode(int uid, String packageName) {
3683 // No locking - CopyOnWriteArrayList
3684 int mountMode = Integer.MAX_VALUE;
3685 for (ExternalStorageMountPolicy policy : mPolicies) {
3686 final int policyMode = policy.getMountMode(uid, packageName);
3687 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3688 return Zygote.MOUNT_EXTERNAL_NONE;
3689 }
3690 mountMode = Math.min(mountMode, policyMode);
3691 }
3692 if (mountMode == Integer.MAX_VALUE) {
3693 return Zygote.MOUNT_EXTERNAL_NONE;
3694 }
3695 return mountMode;
3696 }
3697
3698 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003699 // No need to check for system uid. This avoids a deadlock between
3700 // PackageManagerService and AppOpsService.
3701 if (uid == Process.SYSTEM_UID) {
3702 return true;
3703 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003704 // No locking - CopyOnWriteArrayList
3705 for (ExternalStorageMountPolicy policy : mPolicies) {
3706 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
3707 if (!policyHasStorage) {
3708 return false;
3709 }
3710 }
3711 return true;
3712 }
3713 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003714}