blob: 25ce4856be1fe5e6256ae9b197c0598267c91ecf [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);
Jeff Sharkeycd575992016-03-29 14:12:49 -0600168 mMountService.start();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700169 }
170
171 @Override
172 public void onBootPhase(int phase) {
173 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
174 mMountService.systemReady();
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900175 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
176 mMountService.bootCompleted();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700177 }
178 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700179
180 @Override
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600181 public void onSwitchUser(int userHandle) {
182 mMountService.mCurrentUserId = userHandle;
183 }
184
185 @Override
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700186 public void onUnlockUser(int userHandle) {
187 mMountService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700188 }
189
190 @Override
191 public void onCleanupUser(int userHandle) {
192 mMountService.onCleanupUser(userHandle);
193 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700194 }
195
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800196 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800197 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700198
Kenny Root07714d42011-08-17 17:49:28 -0700199 // Disable this since it messes up long-running cryptfs operations.
200 private static final boolean WATCHDOG_ENABLE = false;
201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private static final String TAG = "MountService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700203
Jeff Sharkey9756d752015-05-14 21:07:42 -0700204 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700205 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Kenny Root305bcbf2010-09-03 07:56:38 -0700207 private static final String VOLD_TAG = "VoldConnector";
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700208 private static final String CRYPTD_TAG = "CryptdConnector";
Kenny Root305bcbf2010-09-03 07:56:38 -0700209
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700210 /** Maximum number of ASEC containers allowed to be mounted. */
211 private static final int MAX_CONTAINERS = 250;
212
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700213 /** Magic value sent by MoveTask.cpp */
214 private static final int MOVE_STATUS_COPY_FINISHED = 82;
215
San Mehat4270e1e2010-01-29 05:32:19 -0800216 /*
217 * Internal vold response code constants
218 */
San Mehat22dd86e2010-01-12 12:21:18 -0800219 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800220 /*
221 * 100 series - Requestion action was initiated; expect another reply
222 * before proceeding with a new command.
223 */
San Mehat22dd86e2010-01-12 12:21:18 -0800224 public static final int VolumeListResult = 110;
225 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800226 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700227 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800228
San Mehat4270e1e2010-01-29 05:32:19 -0800229 /*
230 * 200 series - Requestion action has been successfully completed.
231 */
232 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800233 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800234 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800235
San Mehat4270e1e2010-01-29 05:32:19 -0800236 /*
237 * 400 series - Command was accepted, but the requested action
238 * did not take place.
239 */
240 public static final int OpFailedNoMedia = 401;
241 public static final int OpFailedMediaBlank = 402;
242 public static final int OpFailedMediaCorrupt = 403;
243 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800244 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700245 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800246
247 /*
248 * 600 series - Unsolicited broadcasts.
249 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700250 public static final int DISK_CREATED = 640;
251 public static final int DISK_SIZE_CHANGED = 641;
252 public static final int DISK_LABEL_CHANGED = 642;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700253 public static final int DISK_SCANNED = 643;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700254 public static final int DISK_SYS_PATH_CHANGED = 644;
Jeff Sharkey48877892015-03-18 11:27:19 -0700255 public static final int DISK_DESTROYED = 649;
256
257 public static final int VOLUME_CREATED = 650;
258 public static final int VOLUME_STATE_CHANGED = 651;
259 public static final int VOLUME_FS_TYPE_CHANGED = 652;
260 public static final int VOLUME_FS_UUID_CHANGED = 653;
261 public static final int VOLUME_FS_LABEL_CHANGED = 654;
262 public static final int VOLUME_PATH_CHANGED = 655;
Jeff Sharkey50a05452015-04-29 11:24:52 -0700263 public static final int VOLUME_INTERNAL_PATH_CHANGED = 656;
Jeff Sharkey48877892015-03-18 11:27:19 -0700264 public static final int VOLUME_DESTROYED = 659;
Svetoslavf23b64d2013-04-25 14:45:54 -0700265
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700266 public static final int MOVE_STATUS = 660;
Jeff Sharkey9756d752015-05-14 21:07:42 -0700267 public static final int BENCHMARK_RESULT = 661;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700268 public static final int TRIM_RESULT = 662;
San Mehat22dd86e2010-01-12 12:21:18 -0800269 }
270
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700271 private static final int VERSION_INIT = 1;
272 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700273 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700274
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700275 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700276 private static final String ATTR_VERSION = "version";
277 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700278 private static final String ATTR_FORCE_ADOPTABLE = "forceAdoptable";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700279 private static final String TAG_VOLUME = "volume";
280 private static final String ATTR_TYPE = "type";
281 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700282 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700283 private static final String ATTR_NICKNAME = "nickname";
284 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700285 private static final String ATTR_CREATED_MILLIS = "createdMillis";
286 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
287 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700288
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700289 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700290
Jeff Sharkey48877892015-03-18 11:27:19 -0700291 /**
292 * <em>Never</em> hold the lock while performing downcalls into vold, since
293 * unsolicited events can suddenly appear to update data structures.
294 */
295 private final Object mLock = new Object();
296
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700297 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700298 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700299 private int[] mLocalUnlockedUsers = EmptyArray.INT;
300 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800301 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700302 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700303
304 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700305 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700306 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700307 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700308 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700309 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700310
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700311 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700312 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700313 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700314 @GuardedBy("mLock")
315 private String mPrimaryStorageUuid;
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700316 @GuardedBy("mLock")
317 private boolean mForceAdoptable;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700318
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700319 /** Map from disk ID to latches */
320 @GuardedBy("mLock")
321 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
322
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700323 @GuardedBy("mLock")
324 private IPackageMoveObserver mMoveCallback;
325 @GuardedBy("mLock")
326 private String mMoveTargetUuid;
327
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600328 private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
329
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700330 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700331 synchronized (mLock) {
332 final VolumeInfo vol = mVolumes.get(id);
333 if (vol != null) {
334 return vol;
335 }
336 }
337 throw new IllegalArgumentException("No volume found for ID " + id);
338 }
339
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700340 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700341 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700342 for (int i = 0; i < mVolumes.size(); i++) {
343 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700344 if (vol.path != null && path.startsWith(vol.path)) {
345 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700346 }
347 }
348 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700349 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700350 }
351
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700352 private VolumeRecord findRecordForPath(String path) {
353 synchronized (mLock) {
354 for (int i = 0; i < mVolumes.size(); i++) {
355 final VolumeInfo vol = mVolumes.valueAt(i);
356 if (vol.path != null && path.startsWith(vol.path)) {
357 return mRecords.get(vol.fsUuid);
358 }
359 }
360 }
361 return null;
362 }
363
364 private String scrubPath(String path) {
365 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
366 return "internal";
367 }
368 final VolumeRecord rec = findRecordForPath(path);
369 if (rec == null || rec.createdMillis == 0) {
370 return "unknown";
371 } else {
372 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
373 / DateUtils.WEEK_IN_MILLIS) + "w";
374 }
375 }
376
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700377 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700378 final StorageManager storage = mContext.getSystemService(StorageManager.class);
379 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700380 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700381 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
382 return storage.getPrimaryPhysicalVolume();
383 } else {
384 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
385 }
386 }
387
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700388 private boolean shouldBenchmark() {
389 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
390 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700391 if (benchInterval == -1) {
392 return false;
393 } else if (benchInterval == 0) {
394 return true;
395 }
396
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700397 synchronized (mLock) {
398 for (int i = 0; i < mVolumes.size(); i++) {
399 final VolumeInfo vol = mVolumes.valueAt(i);
400 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700401 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700402 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
403 if (benchAge >= benchInterval) {
404 return true;
405 }
406 }
407 }
408 return false;
409 }
410 }
411
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700412 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
413 synchronized (mLock) {
414 CountDownLatch latch = mDiskScanLatches.get(diskId);
415 if (latch == null) {
416 latch = new CountDownLatch(1);
417 mDiskScanLatches.put(diskId, latch);
418 }
419 return latch;
420 }
421 }
422
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800423 private static String escapeNull(String arg) {
424 if (TextUtils.isEmpty(arg)) {
425 return "!";
426 } else {
427 if (arg.indexOf('\0') != -1 || arg.indexOf(' ') != -1) {
428 throw new IllegalArgumentException(arg);
429 }
430 return arg;
431 }
432 }
433
Paul Lawrence8e397362014-01-27 15:22:30 -0800434 /** List of crypto types.
435 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
436 * corresponding commands in CommandListener.cpp */
437 public static final String[] CRYPTO_TYPES
438 = { "password", "default", "pattern", "pin" };
439
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700440 private final Context mContext;
Jeff Sharkeycd575992016-03-29 14:12:49 -0600441
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700442 private final NativeDaemonConnector mConnector;
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700443 private final NativeDaemonConnector mCryptConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700444
Jeff Sharkeycd575992016-03-29 14:12:49 -0600445 private final Thread mConnectorThread;
446 private final Thread mCryptConnectorThread;
447
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700448 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900449 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700450 private volatile boolean mDaemonConnected = false;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700451
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700452 private PackageManagerService mPms;
453
454 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700455 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700456
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700457 // Two connectors - mConnector & mCryptConnector
458 private final CountDownLatch mConnectedSignal = new CountDownLatch(2);
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800459 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
Jeff Sharkey48877892015-03-18 11:27:19 -0700460
461 private final Object mUnmountLock = new Object();
462 @GuardedBy("mUnmountLock")
463 private CountDownLatch mUnmountSignal;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800464
San Mehat6cdd9c02010-02-09 14:45:20 -0800465 /**
466 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800467 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800468 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800469 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800470
Kenny Root02c87302010-07-01 08:10:18 -0700471 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700472 * The size of the crypto algorithm key in bits for OBB files. Currently
473 * Twofish is used which takes 128-bit keys.
474 */
475 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
476
477 /**
478 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
479 * 1024 is reasonably secure and not too slow.
480 */
481 private static final int PBKDF2_HASH_ROUNDS = 1024;
482
483 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700484 * Mounted OBB tracking information. Used to track the current state of all
485 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700486 */
Kenny Root735de3b2010-09-30 14:11:39 -0700487 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700488
489 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700490 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
491
Svet Ganov6ee871e2015-07-10 14:29:33 -0700492 // Not guarded by a lock.
493 private final MountServiceInternalImpl mMountServiceInternal = new MountServiceInternalImpl();
494
Kenny Roota02b8b02010-08-05 16:14:17 -0700495 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700496 public ObbState(String rawPath, String canonicalPath, int callingUid,
497 IObbActionListener token, int nonce) {
498 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700499 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700500
501 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700502 this.token = token;
503 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700504 }
505
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700506 final String rawPath;
507 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700508
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700509 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700510
Kenny Rootaf9d6672010-10-08 09:21:39 -0700511 // Token of remote Binder caller
512 final IObbActionListener token;
513
514 // Identifier to pass back to the token
515 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700516
Kenny Root735de3b2010-09-30 14:11:39 -0700517 public IBinder getBinder() {
518 return token.asBinder();
519 }
520
Kenny Roota02b8b02010-08-05 16:14:17 -0700521 @Override
522 public void binderDied() {
523 ObbAction action = new UnmountObbAction(this, true);
524 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700525 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700526
Kenny Root5919ac62010-10-05 09:49:40 -0700527 public void link() throws RemoteException {
528 getBinder().linkToDeath(this, 0);
529 }
530
531 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700532 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700533 }
Kenny Root38cf8862010-09-26 14:18:51 -0700534
535 @Override
536 public String toString() {
537 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700538 sb.append("rawPath=").append(rawPath);
539 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700540 sb.append(",ownerGid=").append(ownerGid);
541 sb.append(",token=").append(token);
542 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700543 sb.append('}');
544 return sb.toString();
545 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700546 }
547
548 // OBB Action Handler
549 final private ObbActionHandler mObbActionHandler;
550
551 // OBB action handler messages
552 private static final int OBB_RUN_ACTION = 1;
553 private static final int OBB_MCS_BOUND = 2;
554 private static final int OBB_MCS_UNBIND = 3;
555 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700556 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700557
558 /*
559 * Default Container Service information
560 */
561 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
562 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
563
564 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
565
566 class DefaultContainerConnection implements ServiceConnection {
Jeff Sharkey48877892015-03-18 11:27:19 -0700567 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700568 public void onServiceConnected(ComponentName name, IBinder service) {
569 if (DEBUG_OBB)
570 Slog.i(TAG, "onServiceConnected");
571 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
572 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
573 }
574
Jeff Sharkey48877892015-03-18 11:27:19 -0700575 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700576 public void onServiceDisconnected(ComponentName name) {
577 if (DEBUG_OBB)
578 Slog.i(TAG, "onServiceDisconnected");
579 }
580 };
581
582 // Used in the ObbActionHandler
583 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700584
Christopher Tate7265abe2014-11-21 13:54:45 -0800585 // Last fstrim operation tracking
586 private static final String LAST_FSTRIM_FILE = "last-fstrim";
587 private final File mLastMaintenanceFile;
588 private long mLastMaintenance;
589
Kenny Root02c87302010-07-01 08:10:18 -0700590 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700591 private static final int H_SYSTEM_READY = 1;
592 private static final int H_DAEMON_CONNECTED = 2;
593 private static final int H_SHUTDOWN = 3;
594 private static final int H_FSTRIM = 4;
595 private static final int H_VOLUME_MOUNT = 5;
596 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700597 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700598 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800599 private static final int H_PARTITION_FORGET = 9;
600 private static final int H_RESET = 10;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800601
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400602 class MountServiceHandler extends Handler {
Jeff Sharkey48877892015-03-18 11:27:19 -0700603 public MountServiceHandler(Looper looper) {
604 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400605 }
606
Jason parks5af0b912010-11-29 09:05:25 -0600607 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800608 public void handleMessage(Message msg) {
609 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700610 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700611 handleSystemReady();
612 break;
613 }
614 case H_DAEMON_CONNECTED: {
615 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700616 break;
617 }
Christopher Tated417d622013-08-19 16:14:25 -0700618 case H_FSTRIM: {
Jeff Sharkey1783f142015-04-17 10:52:51 -0700619 if (!isReady()) {
620 Slog.i(TAG, "fstrim requested, but no daemon connection yet; trying again");
Christopher Tate7618db12015-04-28 16:32:55 -0700621 sendMessageDelayed(obtainMessage(H_FSTRIM, msg.obj),
622 DateUtils.SECOND_IN_MILLIS);
623 break;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700624 }
625
Christopher Tated417d622013-08-19 16:14:25 -0700626 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800627
628 // Remember when we kicked it off
629 try {
630 mLastMaintenance = System.currentTimeMillis();
631 mLastMaintenanceFile.setLastModified(mLastMaintenance);
632 } catch (Exception e) {
633 Slog.e(TAG, "Unable to record last fstrim!");
634 }
635
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700636 final boolean shouldBenchmark = shouldBenchmark();
Christopher Tated417d622013-08-19 16:14:25 -0700637 try {
638 // This method must be run on the main (handler) thread,
639 // so it is safe to directly call into vold.
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700640 mConnector.execute("fstrim", shouldBenchmark ? "dotrimbench" : "dotrim");
Christopher Tated417d622013-08-19 16:14:25 -0700641 } catch (NativeDaemonConnectorException ndce) {
642 Slog.e(TAG, "Failed to run fstrim!");
643 }
Christopher Tate7265abe2014-11-21 13:54:45 -0800644
Christopher Tated417d622013-08-19 16:14:25 -0700645 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700646 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700647 Runnable callback = (Runnable) msg.obj;
648 if (callback != null) {
649 callback.run();
650 }
651 break;
652 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700653 case H_SHUTDOWN: {
654 final IMountShutdownObserver obs = (IMountShutdownObserver) msg.obj;
655 boolean success = false;
656 try {
657 success = mConnector.execute("volume", "shutdown").isClassOk();
658 } catch (NativeDaemonConnectorException ignored) {
659 }
660 if (obs != null) {
661 try {
662 obs.onShutDownComplete(success ? 0 : -1);
663 } catch (RemoteException ignored) {
664 }
665 }
666 break;
667 }
668 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700669 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700670 if (isMountDisallowed(vol)) {
671 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
672 break;
673 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700674 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -0700675 mConnector.execute("volume", "mount", vol.id, vol.mountFlags,
676 vol.mountUserId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700677 } catch (NativeDaemonConnectorException ignored) {
678 }
679 break;
680 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700681 case H_VOLUME_UNMOUNT: {
682 final VolumeInfo vol = (VolumeInfo) msg.obj;
683 unmount(vol.getId());
684 break;
685 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700686 case H_VOLUME_BROADCAST: {
687 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700688 final String envState = userVol.getState();
689 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700690 + userVol.getOwner());
691
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700692 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700693 if (action != null) {
694 final Intent intent = new Intent(action,
695 Uri.fromFile(userVol.getPathFile()));
696 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
698 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
699 }
700 break;
701 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700702 case H_INTERNAL_BROADCAST: {
703 // Internal broadcasts aimed at system components, not for
704 // third-party apps.
705 final Intent intent = (Intent) msg.obj;
706 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
707 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800708 break;
709 }
710 case H_PARTITION_FORGET: {
711 final String partGuid = (String) msg.obj;
712 forgetPartition(partGuid);
713 break;
714 }
715 case H_RESET: {
716 resetIfReadyAndConnected();
717 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700718 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800719 }
720 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700721 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700722
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700723 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800724
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700725 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
726 @Override
727 public void onReceive(Context context, Intent intent) {
728 final String action = intent.getAction();
729 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700730 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700731
732 try {
733 if (Intent.ACTION_USER_ADDED.equals(action)) {
734 final UserManager um = mContext.getSystemService(UserManager.class);
735 final int userSerialNumber = um.getUserSerialNumber(userId);
736 mConnector.execute("volume", "user_added", userId, userSerialNumber);
737 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700738 synchronized (mVolumes) {
739 final int size = mVolumes.size();
740 for (int i = 0; i < size; i++) {
741 final VolumeInfo vol = mVolumes.valueAt(i);
742 if (vol.mountUserId == userId) {
743 vol.mountUserId = UserHandle.USER_NULL;
744 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
745 }
746 }
747 }
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700748 mConnector.execute("volume", "user_removed", userId);
749 }
750 } catch (NativeDaemonConnectorException e) {
751 Slog.w(TAG, "Failed to send user details to vold", e);
752 }
753 }
754 };
755
Jeff Sharkey56e62932015-03-21 20:41:00 -0700756 @Override
757 public void waitForAsecScan() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700758 waitForLatch(mAsecsScanned, "mAsecsScanned");
Kenny Root51a573c2012-05-17 13:30:28 -0700759 }
760
San Mehat207e5382010-02-04 20:46:54 -0800761 private void waitForReady() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700762 waitForLatch(mConnectedSignal, "mConnectedSignal");
Kenny Root51a573c2012-05-17 13:30:28 -0700763 }
764
Jeff Sharkey48877892015-03-18 11:27:19 -0700765 private void waitForLatch(CountDownLatch latch, String condition) {
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700766 try {
767 waitForLatch(latch, condition, -1);
768 } catch (TimeoutException ignored) {
769 }
770 }
771
772 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
773 throws TimeoutException {
774 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700775 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700776 try {
777 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800778 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700779 } else {
780 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700781 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800782 }
Kenny Root51a573c2012-05-17 13:30:28 -0700783 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700784 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800785 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700786 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
787 throw new TimeoutException("Thread " + Thread.currentThread().getName()
788 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
789 }
San Mehat207e5382010-02-04 20:46:54 -0800790 }
San Mehat1f6301e2010-01-07 22:40:27 -0800791 }
Kenny Root02c87302010-07-01 08:10:18 -0700792
Paul Lawrence945490c2014-03-27 16:37:28 +0000793 private boolean isReady() {
794 try {
795 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
796 } catch (InterruptedException e) {
797 return false;
798 }
799 }
800
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700801 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700802 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800803 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700804
Jeff Sharkey48877892015-03-18 11:27:19 -0700805 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700806 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700807 }
808
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700809 /**
810 * MediaProvider has a ton of code that makes assumptions about storage
811 * paths never changing, so we outright kill them to pick up new state.
812 */
813 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700814 private void killMediaProvider(List<UserInfo> users) {
815 if (users == null) return;
816
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700817 final long token = Binder.clearCallingIdentity();
818 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700819 for (UserInfo user : users) {
820 // System user does not have media provider, so skip.
821 if (user.isSystemOnly()) continue;
822
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -0700823 final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY,
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600824 PackageManager.MATCH_DIRECT_BOOT_AWARE
825 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
826 user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700827 if (provider != null) {
828 final IActivityManager am = ActivityManagerNative.getDefault();
829 try {
830 am.killApplicationWithAppId(provider.applicationInfo.packageName,
831 UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
832 // We only need to run this once. It will kill all users' media processes.
833 break;
834 } catch (RemoteException e) {
835 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700836 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700837 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700838 } finally {
839 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700840 }
841 }
842
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800843 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700844 // Create a stub volume that represents internal storage
845 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
846 VolumeInfo.TYPE_PRIVATE, null, null);
847 internal.state = VolumeInfo.STATE_MOUNTED;
848 internal.path = Environment.getDataDirectory().getAbsolutePath();
849 mVolumes.put(internal.id, internal);
850 }
851
Jeff Sharkey8924e872015-11-30 12:52:10 -0700852 private void initIfReadyAndConnected() {
853 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
854 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700855 if (mSystemReady && mDaemonConnected
Paul Lawrence20be5d62016-02-26 13:51:17 -0800856 && !StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700857 // When booting a device without native support, make sure that our
858 // user directories are locked or unlocked based on the current
859 // emulation status.
Paul Lawrence20be5d62016-02-26 13:51:17 -0800860 final boolean initLocked = StorageManager.isFileEncryptedEmulatedOnly();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000861 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700862 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700863 for (UserInfo user : users) {
864 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700865 if (initLocked) {
866 mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
867 } else {
868 mCryptConnector.execute("cryptfs", "unlock_user_key", user.id,
Paul Crowleyd94ab732016-02-15 06:44:51 +0000869 user.serialNumber, "!", "!");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700870 }
Jeff Sharkey8924e872015-11-30 12:52:10 -0700871 } catch (NativeDaemonConnectorException e) {
872 Slog.w(TAG, "Failed to init vold", e);
873 }
874 }
875 }
876 }
877
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800878 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700879 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
880 + ", mDaemonConnected=" + mDaemonConnected);
881 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800882 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700883 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700884
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700885 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800886 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700887 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700888
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800889 mDisks.clear();
890 mVolumes.clear();
891
892 addInternalVolumeLocked();
893 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700894
Jeff Sharkey48877892015-03-18 11:27:19 -0700895 try {
896 mConnector.execute("volume", "reset");
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700897
898 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700899 for (UserInfo user : users) {
900 mConnector.execute("volume", "user_added", user.id, user.serialNumber);
901 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700902 for (int userId : systemUnlockedUsers) {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700903 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700904 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700905 } catch (NativeDaemonConnectorException e) {
906 Slog.w(TAG, "Failed to reset vold", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700907 }
908 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700909 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700910
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700911 private void onUnlockUser(int userId) {
912 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700913
914 // We purposefully block here to make sure that user-specific
915 // staging area is ready so it's ready for zygote-forked apps to
916 // bind mount against.
917 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700918 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700919 } catch (NativeDaemonConnectorException ignored) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700920 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700921
922 // Record user as started so newly mounted volumes kick off events
923 // correctly, then synthesize events for any already-mounted volumes.
924 synchronized (mVolumes) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700925 for (int i = 0; i < mVolumes.size(); i++) {
926 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700927 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700928 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700929 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700930
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700931 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
932 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700933 }
934 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700935 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700936 }
937 }
938
939 private void onCleanupUser(int userId) {
940 Slog.d(TAG, "onCleanupUser " + userId);
941
942 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700943 mConnector.execute("volume", "user_stopped", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700944 } catch (NativeDaemonConnectorException ignored) {
945 }
946
947 synchronized (mVolumes) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700948 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700949 }
950 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700951
Christopher Tated417d622013-08-19 16:14:25 -0700952 void runIdleMaintenance(Runnable callback) {
953 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
954 }
955
Christopher Tate7265abe2014-11-21 13:54:45 -0800956 // Binder entry point for kicking off an immediate fstrim
957 @Override
958 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700959 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -0800960 runIdleMaintenance(null);
961 }
962
963 @Override
964 public long lastMaintenance() {
965 return mLastMaintenance;
966 }
967
San Mehat4270e1e2010-01-29 05:32:19 -0800968 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800969 * Callback from NativeDaemonConnector
970 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700971 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800972 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700973 mDaemonConnected = true;
974 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
975 }
976
977 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700978 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800979 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -0700980
San Mehat4270e1e2010-01-29 05:32:19 -0800981 /*
Jeff Sharkey48877892015-03-18 11:27:19 -0700982 * Now that we've done our initialization, release
983 * the hounds!
San Mehat4270e1e2010-01-29 05:32:19 -0800984 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700985 mConnectedSignal.countDown();
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700986 if (mConnectedSignal.getCount() != 0) {
987 // More daemons need to connect
988 return;
989 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400990
Jeff Sharkey48877892015-03-18 11:27:19 -0700991 // On an encrypted device we can't see system properties yet, so pull
992 // the system locale out of the mount service.
993 if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
994 copyLocaleFromMountService();
995 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700996
Jeff Sharkey48877892015-03-18 11:27:19 -0700997 // Let package manager load internal ASECs.
998 mPms.scanAvailableAsecs();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400999
Jeff Sharkey48877892015-03-18 11:27:19 -07001000 // Notify people waiting for ASECs to be scanned that it's done.
1001 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -08001002 }
1003
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001004 private void copyLocaleFromMountService() {
1005 String systemLocale;
1006 try {
1007 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
1008 } catch (RemoteException e) {
1009 return;
1010 }
1011 if (TextUtils.isEmpty(systemLocale)) {
1012 return;
1013 }
1014
1015 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1016 Locale locale = Locale.forLanguageTag(systemLocale);
1017 Configuration config = new Configuration();
1018 config.setLocale(locale);
1019 try {
Seigo Nonaka4963dfe2016-03-31 20:50:21 +09001020 ActivityManagerNative.getDefault().updatePersistentConfiguration(config);
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001021 } catch (RemoteException e) {
1022 Slog.e(TAG, "Error setting system locale from mount service", e);
1023 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001024
1025 // Temporary workaround for http://b/17945169.
1026 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001027 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001028 }
1029
San Mehat4270e1e2010-01-29 05:32:19 -08001030 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001031 * Callback from NativeDaemonConnector
1032 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001033 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001034 public boolean onCheckHoldWakeLock(int code) {
1035 return false;
1036 }
1037
1038 /**
1039 * Callback from NativeDaemonConnector
1040 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001041 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001042 public boolean onEvent(int code, String raw, String[] cooked) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001043 synchronized (mLock) {
1044 return onEventLocked(code, raw, cooked);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001045 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001046 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001047
Jeff Sharkey48877892015-03-18 11:27:19 -07001048 private boolean onEventLocked(int code, String raw, String[] cooked) {
1049 switch (code) {
1050 case VoldResponseCode.DISK_CREATED: {
1051 if (cooked.length != 3) break;
1052 final String id = cooked[1];
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001053 int flags = Integer.parseInt(cooked[2]);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001054 if (SystemProperties.getBoolean(StorageManager.PROP_FORCE_ADOPTABLE, false)
1055 || mForceAdoptable) {
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001056 flags |= DiskInfo.FLAG_ADOPTABLE;
1057 }
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001058 mDisks.put(id, new DiskInfo(id, flags));
Jeff Sharkey48877892015-03-18 11:27:19 -07001059 break;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001060 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001061 case VoldResponseCode.DISK_SIZE_CHANGED: {
1062 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001063 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001064 if (disk != null) {
1065 disk.size = Long.parseLong(cooked[2]);
San Mehat4270e1e2010-01-29 05:32:19 -08001066 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001067 break;
1068 }
1069 case VoldResponseCode.DISK_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001070 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001071 if (disk != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001072 final StringBuilder builder = new StringBuilder();
1073 for (int i = 2; i < cooked.length; i++) {
1074 builder.append(cooked[i]).append(' ');
1075 }
1076 disk.label = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001077 }
1078 break;
1079 }
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001080 case VoldResponseCode.DISK_SCANNED: {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001081 if (cooked.length != 2) break;
1082 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001083 if (disk != null) {
1084 onDiskScannedLocked(disk);
1085 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -07001086 break;
1087 }
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001088 case VoldResponseCode.DISK_SYS_PATH_CHANGED: {
1089 if (cooked.length != 3) break;
1090 final DiskInfo disk = mDisks.get(cooked[1]);
1091 if (disk != null) {
1092 disk.sysPath = cooked[2];
1093 }
1094 break;
1095 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001096 case VoldResponseCode.DISK_DESTROYED: {
1097 if (cooked.length != 2) break;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07001098 final DiskInfo disk = mDisks.remove(cooked[1]);
1099 if (disk != null) {
1100 mCallbacks.notifyDiskDestroyed(disk);
1101 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001102 break;
1103 }
San Mehat4270e1e2010-01-29 05:32:19 -08001104
Jeff Sharkey48877892015-03-18 11:27:19 -07001105 case VoldResponseCode.VOLUME_CREATED: {
Jeff Sharkey48877892015-03-18 11:27:19 -07001106 final String id = cooked[1];
1107 final int type = Integer.parseInt(cooked[2]);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001108 final String diskId = TextUtils.nullIfEmpty(cooked[3]);
1109 final String partGuid = TextUtils.nullIfEmpty(cooked[4]);
1110
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001111 final DiskInfo disk = mDisks.get(diskId);
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07001112 final VolumeInfo vol = new VolumeInfo(id, type, disk, partGuid);
Jeff Sharkey48877892015-03-18 11:27:19 -07001113 mVolumes.put(id, vol);
1114 onVolumeCreatedLocked(vol);
1115 break;
1116 }
1117 case VoldResponseCode.VOLUME_STATE_CHANGED: {
1118 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001119 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001120 if (vol != null) {
1121 final int oldState = vol.state;
1122 final int newState = Integer.parseInt(cooked[2]);
1123 vol.state = newState;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001124 onVolumeStateChangedLocked(vol, oldState, newState);
Jeff Sharkey48877892015-03-18 11:27:19 -07001125 }
1126 break;
1127 }
1128 case VoldResponseCode.VOLUME_FS_TYPE_CHANGED: {
1129 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001130 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001131 if (vol != null) {
1132 vol.fsType = cooked[2];
1133 }
1134 break;
1135 }
1136 case VoldResponseCode.VOLUME_FS_UUID_CHANGED: {
1137 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001138 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001139 if (vol != null) {
1140 vol.fsUuid = cooked[2];
1141 }
1142 break;
1143 }
1144 case VoldResponseCode.VOLUME_FS_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001145 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001146 if (vol != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001147 final StringBuilder builder = new StringBuilder();
1148 for (int i = 2; i < cooked.length; i++) {
1149 builder.append(cooked[i]).append(' ');
1150 }
1151 vol.fsLabel = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001152 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001153 // TODO: notify listeners that label changed
Jeff Sharkey48877892015-03-18 11:27:19 -07001154 break;
1155 }
1156 case VoldResponseCode.VOLUME_PATH_CHANGED: {
1157 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001158 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001159 if (vol != null) {
1160 vol.path = cooked[2];
1161 }
1162 break;
1163 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001164 case VoldResponseCode.VOLUME_INTERNAL_PATH_CHANGED: {
1165 if (cooked.length != 3) break;
1166 final VolumeInfo vol = mVolumes.get(cooked[1]);
1167 if (vol != null) {
1168 vol.internalPath = cooked[2];
1169 }
1170 break;
1171 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001172 case VoldResponseCode.VOLUME_DESTROYED: {
1173 if (cooked.length != 2) break;
1174 mVolumes.remove(cooked[1]);
1175 break;
1176 }
San Mehat4270e1e2010-01-29 05:32:19 -08001177
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001178 case VoldResponseCode.MOVE_STATUS: {
1179 final int status = Integer.parseInt(cooked[1]);
1180 onMoveStatusLocked(status);
1181 break;
1182 }
Jeff Sharkey9756d752015-05-14 21:07:42 -07001183 case VoldResponseCode.BENCHMARK_RESULT: {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001184 if (cooked.length != 7) break;
1185 final String path = cooked[1];
1186 final String ident = cooked[2];
1187 final long create = Long.parseLong(cooked[3]);
1188 final long drop = Long.parseLong(cooked[4]);
1189 final long run = Long.parseLong(cooked[5]);
1190 final long destroy = Long.parseLong(cooked[6]);
1191
Jeff Sharkey9756d752015-05-14 21:07:42 -07001192 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001193 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1194 + " " + ident + " " + create + " " + run + " " + destroy);
1195
1196 final VolumeRecord rec = findRecordForPath(path);
1197 if (rec != null) {
1198 rec.lastBenchMillis = System.currentTimeMillis();
1199 writeSettingsLocked();
1200 }
1201
1202 break;
1203 }
1204 case VoldResponseCode.TRIM_RESULT: {
1205 if (cooked.length != 4) break;
1206 final String path = cooked[1];
1207 final long bytes = Long.parseLong(cooked[2]);
1208 final long time = Long.parseLong(cooked[3]);
1209
1210 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1211 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path)
1212 + " " + bytes + " " + time);
1213
1214 final VolumeRecord rec = findRecordForPath(path);
1215 if (rec != null) {
1216 rec.lastTrimMillis = System.currentTimeMillis();
1217 writeSettingsLocked();
1218 }
1219
Jeff Sharkey9756d752015-05-14 21:07:42 -07001220 break;
1221 }
1222
Jeff Sharkey48877892015-03-18 11:27:19 -07001223 default: {
1224 Slog.d(TAG, "Unhandled vold event " + code);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001225 }
San Mehat4270e1e2010-01-29 05:32:19 -08001226 }
1227
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001228 return true;
San Mehat4270e1e2010-01-29 05:32:19 -08001229 }
1230
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001231 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001232 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001233 for (int i = 0; i < mVolumes.size(); i++) {
1234 final VolumeInfo vol = mVolumes.valueAt(i);
1235 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001236 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001237 }
1238 }
1239
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001240 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001241 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1242 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001243 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1244 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001245 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001246
1247 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1248 if (latch != null) {
1249 latch.countDown();
1250 }
1251
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001252 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001253 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001254 }
1255
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001256 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey6855c482016-03-31 14:34:38 -06001257 if (mPms.isOnlyCoreApps()) {
1258 Slog.d(TAG, "System booted in core-only mode; ignoring volume " + vol.getId());
1259 return;
1260 }
1261
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001262 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1263 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1264 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1265
1266 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1267 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1268 Slog.v(TAG, "Found primary storage at " + vol);
1269 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1270 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1271 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1272
1273 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1274 Slog.v(TAG, "Found primary storage at " + vol);
1275 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1276 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1277 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1278 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001279
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001280 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001281 // TODO: only look at first public partition
1282 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1283 && vol.disk.isDefaultPrimary()) {
1284 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001285 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1286 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001287 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001288
1289 // Adoptable public disks are visible to apps, since they meet
1290 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001291 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001292 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1293 }
1294
Jeff Sharkeyab15c392016-05-05 11:45:01 -06001295 vol.mountUserId = mCurrentUserId;
Jeff Sharkey48877892015-03-18 11:27:19 -07001296 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001297
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001298 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1299 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1300
San Mehat4270e1e2010-01-29 05:32:19 -08001301 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001302 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001303 }
1304 }
1305
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001306 private boolean isBroadcastWorthy(VolumeInfo vol) {
1307 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001308 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001309 case VolumeInfo.TYPE_PUBLIC:
1310 case VolumeInfo.TYPE_EMULATED:
1311 break;
1312 default:
1313 return false;
1314 }
1315
1316 switch (vol.getState()) {
1317 case VolumeInfo.STATE_MOUNTED:
1318 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1319 case VolumeInfo.STATE_EJECTING:
1320 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001321 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001322 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001323 break;
1324 default:
1325 return false;
1326 }
1327
1328 return true;
1329 }
1330
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001331 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001332 // Remember that we saw this volume so we're ready to accept user
1333 // metadata, or so we can annoy them when a private volume is ejected
1334 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001335 VolumeRecord rec = mRecords.get(vol.fsUuid);
1336 if (rec == null) {
1337 rec = new VolumeRecord(vol.type, vol.fsUuid);
1338 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001339 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001340 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1341 rec.nickname = vol.disk.getDescription();
1342 }
1343 mRecords.put(rec.fsUuid, rec);
1344 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001345 } else {
1346 // Handle upgrade case where we didn't store partition GUID
1347 if (TextUtils.isEmpty(rec.partGuid)) {
1348 rec.partGuid = vol.partGuid;
1349 writeSettingsLocked();
1350 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001351 }
1352 }
1353
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001354 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1355
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001356 // Do not broadcast before boot has completed to avoid launching the
1357 // processes that receive the intent unnecessarily.
1358 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001359 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001360 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1361 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001362 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001363 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1364 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001365 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001366 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001367
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001368 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1369 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001370
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001371 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1372 // Kick state changed event towards all started users. Any users
1373 // started after this point will trigger additional
1374 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001375 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001376 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001377 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001378 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001379
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001380 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1381 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001382 }
1383 }
1384 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001385
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001386 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001387 // TODO: this should eventually be handled by new ObbVolume state changes
1388 /*
1389 * Some OBBs might have been unmounted when this volume was
1390 * unmounted, so send a message to the handler to let it know to
1391 * remove those from the list of mounted OBBS.
1392 */
1393 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1394 OBB_FLUSH_MOUNT_STATE, vol.path));
1395 }
San Mehat4270e1e2010-01-29 05:32:19 -08001396 }
1397
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001398 private void onMoveStatusLocked(int status) {
1399 if (mMoveCallback == null) {
1400 Slog.w(TAG, "Odd, status but no move requested");
1401 return;
1402 }
1403
1404 // TODO: estimate remaining time
1405 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001406 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001407 } catch (RemoteException ignored) {
1408 }
1409
1410 // We've finished copying and we're about to clean up old data, so
1411 // remember that move was successful if we get rebooted
1412 if (status == MOVE_STATUS_COPY_FINISHED) {
1413 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1414
1415 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001416 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001417 }
1418
1419 if (PackageManager.isMoveStatusFinished(status)) {
1420 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1421
1422 mMoveCallback = null;
1423 mMoveTargetUuid = null;
1424 }
1425 }
1426
Jeff Sharkey48877892015-03-18 11:27:19 -07001427 private void enforcePermission(String perm) {
1428 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001429 }
1430
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001431 /**
1432 * Decide if volume is mountable per device policies.
1433 */
1434 private boolean isMountDisallowed(VolumeInfo vol) {
1435 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE) {
1436 final UserManager userManager = mContext.getSystemService(UserManager.class);
1437 return userManager.hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1438 Binder.getCallingUserHandle());
1439 } else {
1440 return false;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001441 }
1442 }
1443
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001444 private void enforceAdminUser() {
1445 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1446 final int callingUserId = UserHandle.getCallingUserId();
1447 boolean isAdmin;
1448 long token = Binder.clearCallingIdentity();
1449 try {
1450 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1451 } finally {
1452 Binder.restoreCallingIdentity(token);
1453 }
1454 if (!isAdmin) {
1455 throw new SecurityException("Only admin users can adopt sd cards");
1456 }
1457 }
1458
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001459 /**
San Mehat207e5382010-02-04 20:46:54 -08001460 * Constructs a new MountService instance
1461 *
1462 * @param context Binder context for this service
1463 */
1464 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001465 sSelf = this;
1466
San Mehat207e5382010-02-04 20:46:54 -08001467 mContext = context;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001468 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001469 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001470
San Mehat207e5382010-02-04 20:46:54 -08001471 // XXX: This will go away soon in favor of IMountServiceObserver
1472 mPms = (PackageManagerService) ServiceManager.getService("package");
1473
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001474 HandlerThread hthread = new HandlerThread(TAG);
1475 hthread.start();
1476 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001477
Kenny Roota02b8b02010-08-05 16:14:17 -07001478 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001479 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001480
Christopher Tate7265abe2014-11-21 13:54:45 -08001481 // Initialize the last-fstrim tracking if necessary
1482 File dataDir = Environment.getDataDirectory();
1483 File systemDir = new File(dataDir, "system");
1484 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1485 if (!mLastMaintenanceFile.exists()) {
1486 // Not setting mLastMaintenance here means that we will force an
1487 // fstrim during reboot following the OTA that installs this code.
1488 try {
1489 (new FileOutputStream(mLastMaintenanceFile)).close();
1490 } catch (IOException e) {
1491 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1492 }
1493 } else {
1494 mLastMaintenance = mLastMaintenanceFile.lastModified();
1495 }
1496
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001497 mSettingsFile = new AtomicFile(
Jeff Sharkey8212ae02016-02-10 14:46:43 -07001498 new File(Environment.getDataSystemDirectory(), "storage.xml"));
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001499
1500 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001501 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001502 }
1503
Svet Ganov6ee871e2015-07-10 14:29:33 -07001504 LocalServices.addService(MountServiceInternal.class, mMountServiceInternal);
1505
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001506 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001507 * Create the connection to vold with a maximum queue of twice the
1508 * amount of containers we'd ever expect to have. This keeps an
1509 * "asec list" from blocking a thread repeatedly.
1510 */
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001511
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001512 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1513 null);
Jeff Sharkey48877892015-03-18 11:27:19 -07001514 mConnector.setDebug(true);
Jeff Sharkey8948c012015-11-03 12:33:54 -08001515 mConnector.setWarnIfHeld(mLock);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001516 mConnectorThread = new Thread(mConnector, VOLD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001517
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001518 // Reuse parameters from first connector since they are tested and safe
1519 mCryptConnector = new NativeDaemonConnector(this, "cryptd",
1520 MAX_CONTAINERS * 2, CRYPTD_TAG, 25, null);
1521 mCryptConnector.setDebug(true);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001522 mCryptConnectorThread = new Thread(mCryptConnector, CRYPTD_TAG);
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001523
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001524 final IntentFilter userFilter = new IntentFilter();
1525 userFilter.addAction(Intent.ACTION_USER_ADDED);
1526 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1527 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1528
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001529 synchronized (mLock) {
1530 addInternalVolumeLocked();
1531 }
Amith Yamasania7892482015-08-07 11:09:05 -07001532
Kenny Root07714d42011-08-17 17:49:28 -07001533 // Add ourself to the Watchdog monitors if enabled.
1534 if (WATCHDOG_ENABLE) {
1535 Watchdog.getInstance().addMonitor(this);
1536 }
San Mehat207e5382010-02-04 20:46:54 -08001537 }
1538
Jeff Sharkeycd575992016-03-29 14:12:49 -06001539 private void start() {
1540 mConnectorThread.start();
1541 mCryptConnectorThread.start();
1542 }
1543
Jeff Sharkey56e62932015-03-21 20:41:00 -07001544 private void systemReady() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001545 mSystemReady = true;
1546 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1547 }
1548
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001549 private void bootCompleted() {
1550 mBootCompleted = true;
1551 }
1552
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001553 private String getDefaultPrimaryStorageUuid() {
1554 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1555 return StorageManager.UUID_PRIMARY_PHYSICAL;
1556 } else {
1557 return StorageManager.UUID_PRIVATE_INTERNAL;
1558 }
1559 }
1560
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001561 private void readSettingsLocked() {
1562 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001563 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001564 mForceAdoptable = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001565
1566 FileInputStream fis = null;
1567 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001568 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001569 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001570 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001571
1572 int type;
1573 while ((type = in.next()) != END_DOCUMENT) {
1574 if (type == START_TAG) {
1575 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001576 if (TAG_VOLUMES.equals(tag)) {
1577 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001578 final boolean primaryPhysical = SystemProperties.getBoolean(
1579 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1580 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1581 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1582 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001583 mPrimaryStorageUuid = readStringAttribute(in,
1584 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001585 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001586 mForceAdoptable = readBooleanAttribute(in, ATTR_FORCE_ADOPTABLE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001587
1588 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001589 final VolumeRecord rec = readVolumeRecord(in);
1590 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001591 }
1592 }
1593 }
1594 } catch (FileNotFoundException e) {
1595 // Missing metadata is okay, probably first boot
1596 } catch (IOException e) {
1597 Slog.wtf(TAG, "Failed reading metadata", e);
1598 } catch (XmlPullParserException e) {
1599 Slog.wtf(TAG, "Failed reading metadata", e);
1600 } finally {
1601 IoUtils.closeQuietly(fis);
1602 }
1603 }
1604
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001605 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001606 FileOutputStream fos = null;
1607 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001608 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001609
1610 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001611 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001612 out.startDocument(null, true);
1613 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001614 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001615 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001616 writeBooleanAttribute(out, ATTR_FORCE_ADOPTABLE, mForceAdoptable);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001617 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001618 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001619 final VolumeRecord rec = mRecords.valueAt(i);
1620 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001621 }
1622 out.endTag(null, TAG_VOLUMES);
1623 out.endDocument();
1624
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001625 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001626 } catch (IOException e) {
1627 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001628 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001629 }
1630 }
1631 }
1632
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001633 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1634 final int type = readIntAttribute(in, ATTR_TYPE);
1635 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1636 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001637 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001638 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1639 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001640 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1641 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1642 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001643 return meta;
1644 }
1645
1646 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1647 out.startTag(null, TAG_VOLUME);
1648 writeIntAttribute(out, ATTR_TYPE, rec.type);
1649 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001650 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001651 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1652 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001653 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1654 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1655 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001656 out.endTag(null, TAG_VOLUME);
1657 }
1658
San Mehat207e5382010-02-04 20:46:54 -08001659 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001660 * Exposed API calls below here
1661 */
1662
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001663 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001664 public void registerListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001665 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001666 }
1667
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001668 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001669 public void unregisterListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001670 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001671 }
1672
Jeff Sharkey48877892015-03-18 11:27:19 -07001673 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001674 public void shutdown(final IMountShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001675 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001676
San Mehata5078592010-03-25 09:36:54 -07001677 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001678 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001679 }
1680
Jeff Sharkey48877892015-03-18 11:27:19 -07001681 @Override
San Mehatb1043402010-02-05 08:26:50 -08001682 public boolean isUsbMassStorageConnected() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001683 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001684 }
1685
Jeff Sharkey48877892015-03-18 11:27:19 -07001686 @Override
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001687 public void setUsbMassStorageEnabled(boolean enable) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001688 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001689 }
1690
Jeff Sharkey48877892015-03-18 11:27:19 -07001691 @Override
San Mehatb1043402010-02-05 08:26:50 -08001692 public boolean isUsbMassStorageEnabled() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001693 throw new UnsupportedOperationException();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001695
Jeff Sharkey48877892015-03-18 11:27:19 -07001696 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001697 public String getVolumeState(String mountPoint) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001698 throw new UnsupportedOperationException();
San Mehat7fd0fee2009-12-17 07:12:23 -08001699 }
1700
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001701 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001702 public boolean isExternalStorageEmulated() {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001703 throw new UnsupportedOperationException();
Kenny Roote1ff2142010-10-12 11:20:01 -07001704 }
1705
Jeff Sharkey48877892015-03-18 11:27:19 -07001706 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001707 public int mountVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001708 mount(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001709 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
Jeff Sharkey48877892015-03-18 11:27:19 -07001712 @Override
Ben Komalo13c71972011-09-07 16:35:56 -07001713 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001714 unmount(findVolumeIdForPathOrThrow(path));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716
Jeff Sharkey48877892015-03-18 11:27:19 -07001717 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001718 public int formatVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001719 format(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001720 return 0;
1721 }
1722
1723 @Override
1724 public void mount(String volId) {
1725 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1726 waitForReady();
1727
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001728 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001729 if (isMountDisallowed(vol)) {
1730 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001731 }
1732 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001733 mConnector.execute("volume", "mount", vol.id, vol.mountFlags, vol.mountUserId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001734 } catch (NativeDaemonConnectorException e) {
1735 throw e.rethrowAsParcelableException();
1736 }
1737 }
1738
1739 @Override
1740 public void unmount(String volId) {
1741 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1742 waitForReady();
1743
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001744 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001745
1746 // TODO: expand PMS to know about multiple volumes
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001747 if (vol.isPrimaryPhysical()) {
1748 final long ident = Binder.clearCallingIdentity();
1749 try {
1750 synchronized (mUnmountLock) {
1751 mUnmountSignal = new CountDownLatch(1);
1752 mPms.updateExternalMediaStatus(false, true);
1753 waitForLatch(mUnmountSignal, "mUnmountSignal");
1754 mUnmountSignal = null;
1755 }
1756 } finally {
1757 Binder.restoreCallingIdentity(ident);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001758 }
1759 }
1760
1761 try {
1762 mConnector.execute("volume", "unmount", vol.id);
1763 } catch (NativeDaemonConnectorException e) {
1764 throw e.rethrowAsParcelableException();
1765 }
1766 }
1767
1768 @Override
1769 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001770 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001771 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001772
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001773 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001774 try {
Jeff Sharkey4e83cc92015-05-27 14:38:39 -07001775 mConnector.execute("volume", "format", vol.id, "auto");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001776 } catch (NativeDaemonConnectorException e) {
1777 throw e.rethrowAsParcelableException();
Jeff Sharkey48877892015-03-18 11:27:19 -07001778 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001779 }
1780
1781 @Override
Jeff Sharkey9756d752015-05-14 21:07:42 -07001782 public long benchmark(String volId) {
1783 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1784 waitForReady();
1785
1786 try {
Jeff Sharkey14cbe522015-07-08 14:06:37 -07001787 // TODO: make benchmark async so we don't block other commands
1788 final NativeDaemonEvent res = mConnector.execute(3 * DateUtils.MINUTE_IN_MILLIS,
1789 "volume", "benchmark", volId);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001790 return Long.parseLong(res.getMessage());
Todd Kennedy8101ee62015-06-23 13:35:28 -07001791 } catch (NativeDaemonTimeoutException e) {
1792 return Long.MAX_VALUE;
Jeff Sharkey9756d752015-05-14 21:07:42 -07001793 } catch (NativeDaemonConnectorException e) {
1794 throw e.rethrowAsParcelableException();
1795 }
1796 }
1797
1798 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001799 public void partitionPublic(String diskId) {
1800 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1801 waitForReady();
1802
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001803 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001804 try {
1805 mConnector.execute("volume", "partition", diskId, "public");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001806 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001807 } catch (NativeDaemonConnectorException e) {
1808 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001809 } catch (TimeoutException e) {
1810 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001811 }
1812 }
1813
1814 @Override
1815 public void partitionPrivate(String diskId) {
1816 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001817 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001818 waitForReady();
1819
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001820 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001821 try {
1822 mConnector.execute("volume", "partition", diskId, "private");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001823 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001824 } catch (NativeDaemonConnectorException e) {
1825 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001826 } catch (TimeoutException e) {
1827 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001828 }
1829 }
1830
1831 @Override
1832 public void partitionMixed(String diskId, int ratio) {
1833 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001834 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001835 waitForReady();
1836
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001837 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001838 try {
1839 mConnector.execute("volume", "partition", diskId, "mixed", ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001840 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001841 } catch (NativeDaemonConnectorException e) {
1842 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001843 } catch (TimeoutException e) {
1844 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
1847
Jeff Sharkey48877892015-03-18 11:27:19 -07001848 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001849 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001850 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1851 waitForReady();
1852
Jeff Sharkey50a05452015-04-29 11:24:52 -07001853 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001854 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001855 final VolumeRecord rec = mRecords.get(fsUuid);
1856 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07001857 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001858 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001859 }
1860 }
1861
1862 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001863 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001864 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1865 waitForReady();
1866
Jeff Sharkey50a05452015-04-29 11:24:52 -07001867 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001868 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001869 final VolumeRecord rec = mRecords.get(fsUuid);
1870 rec.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001871 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001872 writeSettingsLocked();
1873 }
1874 }
1875
1876 @Override
1877 public void forgetVolume(String fsUuid) {
1878 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1879 waitForReady();
1880
Jeff Sharkey50a05452015-04-29 11:24:52 -07001881 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001882
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001883 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001884 final VolumeRecord rec = mRecords.remove(fsUuid);
1885 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001886 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001887 }
1888 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001889
1890 // If this had been primary storage, revert back to internal and
1891 // reset vold so we bind into new volume into place.
1892 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001893 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001894 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001895 }
1896
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001897 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001898 }
1899 }
1900
Jeff Sharkey7d2af542015-05-12 15:27:15 -07001901 @Override
1902 public void forgetAllVolumes() {
1903 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1904 waitForReady();
1905
Jeff Sharkey50a05452015-04-29 11:24:52 -07001906 synchronized (mLock) {
1907 for (int i = 0; i < mRecords.size(); i++) {
1908 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001909 final VolumeRecord rec = mRecords.valueAt(i);
1910 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001911 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001912 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001913 mCallbacks.notifyVolumeForgotten(fsUuid);
1914 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001915 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001916
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001917 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
1918 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
1919 }
1920
1921 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001922 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001923 }
1924 }
1925
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001926 private void forgetPartition(String partGuid) {
1927 try {
1928 mConnector.execute("volume", "forget_partition", partGuid);
1929 } catch (NativeDaemonConnectorException e) {
1930 Slog.w(TAG, "Failed to forget key for " + partGuid + ": " + e);
1931 }
1932 }
1933
Svet Ganov6ee871e2015-07-10 14:29:33 -07001934 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07001935 waitForReady();
1936
Svet Ganov6ee871e2015-07-10 14:29:33 -07001937 String modeName = "none";
1938 switch (mode) {
1939 case Zygote.MOUNT_EXTERNAL_DEFAULT: {
1940 modeName = "default";
1941 } break;
1942
1943 case Zygote.MOUNT_EXTERNAL_READ: {
1944 modeName = "read";
1945 } break;
1946
1947 case Zygote.MOUNT_EXTERNAL_WRITE: {
1948 modeName = "write";
1949 } break;
Jeff Sharkey9527b222015-06-24 15:24:48 -07001950 }
1951
1952 try {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001953 mConnector.execute("volume", "remount_uid", uid, modeName);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001954 } catch (NativeDaemonConnectorException e) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001955 Slog.w(TAG, "Failed to remount UID " + uid + " as " + modeName + ": " + e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001956 }
1957 }
1958
1959 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001960 public void setDebugFlags(int flags, int mask) {
1961 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1962 waitForReady();
1963
Jeff Sharkeyba512352015-11-12 20:17:45 -08001964 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Paul Lawrence20be5d62016-02-26 13:51:17 -08001965 if (StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001966 throw new IllegalStateException(
1967 "Emulation not available on device with native FBE");
1968 }
Jeff Sharkey5a785162016-03-21 13:02:06 -06001969 if (mLockPatternUtils.isCredentialRequiredToDecrypt(false)) {
1970 throw new IllegalStateException(
1971 "Emulation requires disabling 'Secure start-up' in Settings > Security");
1972 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001973
Jeff Sharkey1176e512016-02-29 17:01:26 -07001974 final long token = Binder.clearCallingIdentity();
1975 try {
1976 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
1977 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001978
Jeff Sharkey1176e512016-02-29 17:01:26 -07001979 // Perform hard reboot to kick policy into place
1980 mContext.getSystemService(PowerManager.class).reboot(null);
1981 } finally {
1982 Binder.restoreCallingIdentity(token);
1983 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08001984 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001985
Jeff Sharkeyba512352015-11-12 20:17:45 -08001986 if ((mask & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0) {
1987 synchronized (mLock) {
1988 mForceAdoptable = (flags & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0;
1989
1990 writeSettingsLocked();
1991 mHandler.obtainMessage(H_RESET).sendToTarget();
1992 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001993 }
Jeff Sharkey33dd1562016-04-07 11:05:33 -06001994
1995 if ((mask & (StorageManager.DEBUG_SDCARDFS_FORCE_ON
1996 | StorageManager.DEBUG_SDCARDFS_FORCE_OFF)) != 0) {
1997 final String value;
1998 if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_ON) != 0) {
1999 value = "force_on";
2000 } else if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_OFF) != 0) {
2001 value = "force_off";
2002 } else {
2003 value = "";
2004 }
2005
2006 final long token = Binder.clearCallingIdentity();
2007 try {
2008 SystemProperties.set(StorageManager.PROP_SDCARDFS, value);
2009
2010 // Reset storage to kick new setting into place
2011 mHandler.obtainMessage(H_RESET).sendToTarget();
2012 } finally {
2013 Binder.restoreCallingIdentity(token);
2014 }
2015 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002016 }
2017
2018 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002019 public String getPrimaryStorageUuid() {
2020 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
2021 waitForReady();
2022
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002023 synchronized (mLock) {
2024 return mPrimaryStorageUuid;
2025 }
2026 }
2027
2028 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002029 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
2030 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
2031 waitForReady();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002032
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002033 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002034 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
2035 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002036 }
2037
2038 if (mMoveCallback != null) {
2039 throw new IllegalStateException("Move already in progress");
2040 }
2041 mMoveCallback = callback;
2042 mMoveTargetUuid = volumeUuid;
2043
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002044 // When moving to/from primary physical volume, we probably just nuked
2045 // the current storage location, so we have nothing to move.
2046 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
2047 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
2048 Slog.d(TAG, "Skipping move to/from primary physical");
2049 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
2050 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002051 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002052
2053 } else {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002054 final VolumeInfo from = findStorageForUuid(mPrimaryStorageUuid);
2055 final VolumeInfo to = findStorageForUuid(volumeUuid);
2056
2057 if (from == null) {
2058 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2059 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2060 return;
2061 } else if (to == null) {
2062 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2063 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2064 return;
2065 }
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002066
2067 try {
2068 mConnector.execute("volume", "move_storage", from.id, to.id);
2069 } catch (NativeDaemonConnectorException e) {
2070 throw e.rethrowAsParcelableException();
2071 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002072 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002073 }
2074 }
2075
2076 @Override
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07002077 public int[] getStorageUsers(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002078 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatc1b4ce92010-02-16 17:13:03 -08002079 waitForReady();
2080 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002081 final String[] r = NativeDaemonEvent.filterMessageList(
2082 mConnector.executeForList("storage", "users", path),
2083 VoldResponseCode.StorageUsersListResult);
2084
San Mehatc1b4ce92010-02-16 17:13:03 -08002085 // FMT: <pid> <process name>
2086 int[] data = new int[r.length];
2087 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002088 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08002089 try {
2090 data[i] = Integer.parseInt(tok[0]);
2091 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07002092 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08002093 return new int[0];
2094 }
2095 }
2096 return data;
2097 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07002098 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08002099 return new int[0];
2100 }
2101 }
2102
San Mehatb1043402010-02-05 08:26:50 -08002103 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002104 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002105 for (int i = 0; i < mVolumes.size(); i++) {
2106 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002107 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002108 // Cool beans, we have a mounted primary volume
2109 return;
2110 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002111 }
San Mehatb1043402010-02-05 08:26:50 -08002112 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002113
2114 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002115 }
2116
San Mehat4270e1e2010-01-29 05:32:19 -08002117 public String[] getSecureContainerList() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002118 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002119 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002120 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002121
San Mehat4270e1e2010-01-29 05:32:19 -08002122 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002123 return NativeDaemonEvent.filterMessageList(
2124 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08002125 } catch (NativeDaemonConnectorException e) {
2126 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
2128 }
San Mehat36972292010-01-06 11:06:32 -08002129
Kenny Root6dceb882012-04-12 14:23:49 -07002130 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
2131 int ownerUid, boolean external) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002132 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08002133 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002134 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002135
San Mehatb1043402010-02-05 08:26:50 -08002136 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002137 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002138 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
2139 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08002140 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002141 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002142 }
San Mehata181b212010-02-11 06:50:20 -08002143
2144 if (rc == StorageResultCode.OperationSucceeded) {
2145 synchronized (mAsecMountSet) {
2146 mAsecMountSet.add(id);
2147 }
2148 }
San Mehat4270e1e2010-01-29 05:32:19 -08002149 return rc;
San Mehat36972292010-01-06 11:06:32 -08002150 }
2151
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002152 @Override
2153 public int resizeSecureContainer(String id, int sizeMb, String key) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002154 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002155 waitForReady();
2156 warnOnNotMounted();
2157
2158 int rc = StorageResultCode.OperationSucceeded;
2159 try {
2160 mConnector.execute("asec", "resize", id, sizeMb, new SensitiveArg(key));
2161 } catch (NativeDaemonConnectorException e) {
2162 rc = StorageResultCode.OperationFailedInternalError;
2163 }
2164 return rc;
2165 }
2166
San Mehat4270e1e2010-01-29 05:32:19 -08002167 public int finalizeSecureContainer(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002168 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08002169 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002170
San Mehatb1043402010-02-05 08:26:50 -08002171 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002172 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002173 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08002174 /*
2175 * Finalization does a remount, so no need
2176 * to update mAsecMountSet
2177 */
San Mehat4270e1e2010-01-29 05:32:19 -08002178 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002179 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002180 }
San Mehat4270e1e2010-01-29 05:32:19 -08002181 return rc;
San Mehat36972292010-01-06 11:06:32 -08002182 }
2183
Kenny Root6dceb882012-04-12 14:23:49 -07002184 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002185 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Kenny Root6dceb882012-04-12 14:23:49 -07002186 warnOnNotMounted();
2187
2188 int rc = StorageResultCode.OperationSucceeded;
2189 try {
2190 mConnector.execute("asec", "fixperms", id, gid, filename);
2191 /*
2192 * Fix permissions does a remount, so no need to update
2193 * mAsecMountSet
2194 */
2195 } catch (NativeDaemonConnectorException e) {
2196 rc = StorageResultCode.OperationFailedInternalError;
2197 }
2198 return rc;
2199 }
2200
San Mehatd9709982010-02-18 11:43:03 -08002201 public int destroySecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002202 enforcePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08002203 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002204 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002205
Kenny Rootaa485402010-09-14 14:49:41 -07002206 /*
2207 * Force a GC to make sure AssetManagers in other threads of the
2208 * system_server are cleaned up. We have to do this since AssetManager
2209 * instances are kept as a WeakReference and it's possible we have files
2210 * open on the external storage.
2211 */
2212 Runtime.getRuntime().gc();
2213
San Mehatb1043402010-02-05 08:26:50 -08002214 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002215 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002216 final Command cmd = new Command("asec", "destroy", id);
2217 if (force) {
2218 cmd.appendArg("force");
2219 }
2220 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002221 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002222 int code = e.getCode();
2223 if (code == VoldResponseCode.OpFailedStorageBusy) {
2224 rc = StorageResultCode.OperationFailedStorageBusy;
2225 } else {
2226 rc = StorageResultCode.OperationFailedInternalError;
2227 }
San Mehat02735bc2010-01-26 15:18:08 -08002228 }
San Mehata181b212010-02-11 06:50:20 -08002229
2230 if (rc == StorageResultCode.OperationSucceeded) {
2231 synchronized (mAsecMountSet) {
2232 if (mAsecMountSet.contains(id)) {
2233 mAsecMountSet.remove(id);
2234 }
2235 }
2236 }
2237
San Mehat4270e1e2010-01-29 05:32:19 -08002238 return rc;
San Mehat36972292010-01-06 11:06:32 -08002239 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002240
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002241 public int mountSecureContainer(String id, String key, int ownerUid, boolean readOnly) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002242 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002243 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002244 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002245
San Mehata181b212010-02-11 06:50:20 -08002246 synchronized (mAsecMountSet) {
2247 if (mAsecMountSet.contains(id)) {
2248 return StorageResultCode.OperationFailedStorageMounted;
2249 }
2250 }
2251
San Mehatb1043402010-02-05 08:26:50 -08002252 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002253 try {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002254 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid,
2255 readOnly ? "ro" : "rw");
San Mehat4270e1e2010-01-29 05:32:19 -08002256 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07002257 int code = e.getCode();
2258 if (code != VoldResponseCode.OpFailedStorageBusy) {
2259 rc = StorageResultCode.OperationFailedInternalError;
2260 }
San Mehat02735bc2010-01-26 15:18:08 -08002261 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002262
2263 if (rc == StorageResultCode.OperationSucceeded) {
2264 synchronized (mAsecMountSet) {
2265 mAsecMountSet.add(id);
2266 }
2267 }
San Mehat4270e1e2010-01-29 05:32:19 -08002268 return rc;
San Mehat36972292010-01-06 11:06:32 -08002269 }
2270
San Mehatd9709982010-02-18 11:43:03 -08002271 public int unmountSecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002272 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
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 Mehat6cdd9c02010-02-09 14:45:20 -08002276 synchronized (mAsecMountSet) {
2277 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08002278 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08002279 }
2280 }
2281
Kenny Rootaa485402010-09-14 14:49:41 -07002282 /*
2283 * Force a GC to make sure AssetManagers in other threads of the
2284 * system_server are cleaned up. We have to do this since AssetManager
2285 * instances are kept as a WeakReference and it's possible we have files
2286 * open on the external storage.
2287 */
2288 Runtime.getRuntime().gc();
2289
San Mehatb1043402010-02-05 08:26:50 -08002290 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002291 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002292 final Command cmd = new Command("asec", "unmount", id);
2293 if (force) {
2294 cmd.appendArg("force");
2295 }
2296 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002297 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002298 int code = e.getCode();
2299 if (code == VoldResponseCode.OpFailedStorageBusy) {
2300 rc = StorageResultCode.OperationFailedStorageBusy;
2301 } else {
2302 rc = StorageResultCode.OperationFailedInternalError;
2303 }
San Mehat02735bc2010-01-26 15:18:08 -08002304 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002305
2306 if (rc == StorageResultCode.OperationSucceeded) {
2307 synchronized (mAsecMountSet) {
2308 mAsecMountSet.remove(id);
2309 }
2310 }
San Mehat4270e1e2010-01-29 05:32:19 -08002311 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08002312 }
2313
San Mehat6cdd9c02010-02-09 14:45:20 -08002314 public boolean isSecureContainerMounted(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002315 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat6cdd9c02010-02-09 14:45:20 -08002316 waitForReady();
2317 warnOnNotMounted();
2318
2319 synchronized (mAsecMountSet) {
2320 return mAsecMountSet.contains(id);
2321 }
2322 }
2323
San Mehat4270e1e2010-01-29 05:32:19 -08002324 public int renameSecureContainer(String oldId, String newId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002325 enforcePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08002326 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002327 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002328
San Mehata181b212010-02-11 06:50:20 -08002329 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08002330 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06002331 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08002332 * changed while active, we must ensure both ids are not currently mounted.
2333 */
2334 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08002335 return StorageResultCode.OperationFailedStorageMounted;
2336 }
2337 }
2338
San Mehatb1043402010-02-05 08:26:50 -08002339 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002340 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002341 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08002342 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002343 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002344 }
San Mehata181b212010-02-11 06:50:20 -08002345
San Mehat4270e1e2010-01-29 05:32:19 -08002346 return rc;
San Mehat45f61042010-01-23 08:12:43 -08002347 }
2348
San Mehat4270e1e2010-01-29 05:32:19 -08002349 public String getSecureContainerPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002350 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002351 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002352 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002353
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002354 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07002355 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002356 event = mConnector.execute("asec", "path", id);
2357 event.checkCode(VoldResponseCode.AsecPathResult);
2358 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07002359 } catch (NativeDaemonConnectorException e) {
2360 int code = e.getCode();
2361 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01002362 Slog.i(TAG, String.format("Container '%s' not found", id));
2363 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08002364 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07002365 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08002366 }
2367 }
San Mehat22dd86e2010-01-12 12:21:18 -08002368 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002369
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002370 public String getSecureContainerFilesystemPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002371 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002372 waitForReady();
2373 warnOnNotMounted();
2374
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002375 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002376 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002377 event = mConnector.execute("asec", "fspath", id);
2378 event.checkCode(VoldResponseCode.AsecPathResult);
2379 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002380 } catch (NativeDaemonConnectorException e) {
2381 int code = e.getCode();
2382 if (code == VoldResponseCode.OpFailedStorageNotFound) {
2383 Slog.i(TAG, String.format("Container '%s' not found", id));
2384 return null;
2385 } else {
2386 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2387 }
2388 }
2389 }
2390
Jeff Sharkey48877892015-03-18 11:27:19 -07002391 @Override
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002392 public void finishMediaUpdate() {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002393 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Rubin Xucd7a0142015-04-17 23:45:27 +01002394 throw new SecurityException("no permission to call finishMediaUpdate()");
2395 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002396 if (mUnmountSignal != null) {
2397 mUnmountSignal.countDown();
2398 } else {
2399 Slog.w(TAG, "Odd, nobody asked to unmount?");
2400 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002401 }
Kenny Root02c87302010-07-01 08:10:18 -07002402
Kenny Roota02b8b02010-08-05 16:14:17 -07002403 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2404 if (callerUid == android.os.Process.SYSTEM_UID) {
2405 return true;
2406 }
2407
Kenny Root02c87302010-07-01 08:10:18 -07002408 if (packageName == null) {
2409 return false;
2410 }
2411
Jeff Sharkeycd654482016-01-08 17:42:11 -07002412 final int packageUid = mPms.getPackageUid(packageName,
2413 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002414
2415 if (DEBUG_OBB) {
2416 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2417 packageUid + ", callerUid = " + callerUid);
2418 }
2419
2420 return callerUid == packageUid;
2421 }
2422
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002423 public String getMountedObbPath(String rawPath) {
2424 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002425
Kenny Root02c87302010-07-01 08:10:18 -07002426 waitForReady();
2427 warnOnNotMounted();
2428
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002429 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002430 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002431 state = mObbPathToStateMap.get(rawPath);
2432 }
2433 if (state == null) {
2434 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2435 return null;
2436 }
2437
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002438 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002439 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002440 event = mConnector.execute("obb", "path", state.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002441 event.checkCode(VoldResponseCode.AsecPathResult);
2442 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002443 } catch (NativeDaemonConnectorException e) {
2444 int code = e.getCode();
2445 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002446 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002447 } else {
2448 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2449 }
2450 }
2451 }
2452
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002453 @Override
2454 public boolean isObbMounted(String rawPath) {
2455 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002456 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002457 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002458 }
Kenny Root02c87302010-07-01 08:10:18 -07002459 }
2460
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002461 @Override
2462 public void mountObb(
2463 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2464 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2465 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2466 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002467
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002468 final int callingUid = Binder.getCallingUid();
2469 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2470 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002471 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2472
2473 if (DEBUG_OBB)
2474 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002475 }
2476
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002477 @Override
2478 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2479 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2480
2481 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002482 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002483 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002484 }
2485
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002486 if (existingState != null) {
2487 // TODO: separate state object from request data
2488 final int callingUid = Binder.getCallingUid();
2489 final ObbState newState = new ObbState(
2490 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2491 final ObbAction action = new UnmountObbAction(newState, force);
2492 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002493
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002494 if (DEBUG_OBB)
2495 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2496 } else {
2497 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2498 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002499 }
2500
Ben Komalo444eca22011-09-01 15:17:44 -07002501 @Override
2502 public int getEncryptionState() {
2503 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2504 "no permission to access the crypt keeper");
2505
2506 waitForReady();
2507
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002508 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002509 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002510 event = mCryptConnector.execute("cryptfs", "cryptocomplete");
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002511 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002512 } catch (NumberFormatException e) {
2513 // Bad result - unexpected.
2514 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2515 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2516 } catch (NativeDaemonConnectorException e) {
2517 // Something bad happened.
2518 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2519 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2520 }
2521 }
2522
2523 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002524 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002525 if (TextUtils.isEmpty(password)) {
2526 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002527 }
2528
Jason parks8888c592011-01-20 22:46:41 -06002529 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2530 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002531
2532 waitForReady();
2533
2534 if (DEBUG_EVENTS) {
2535 Slog.i(TAG, "decrypting storage...");
2536 }
2537
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002538 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002539 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002540 event = mCryptConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002541
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002542 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002543 if (code == 0) {
2544 // Decrypt was successful. Post a delayed message before restarting in order
2545 // to let the UI to clear itself
2546 mHandler.postDelayed(new Runnable() {
2547 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002548 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002549 mCryptConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002550 } catch (NativeDaemonConnectorException e) {
2551 Slog.e(TAG, "problem executing in background", e);
2552 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002553 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002554 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002555 }
2556
2557 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002558 } catch (NativeDaemonConnectorException e) {
2559 // Decryption failed
2560 return e.getCode();
2561 }
Jason parks5af0b912010-11-29 09:05:25 -06002562 }
2563
Paul Lawrence46791e72014-04-03 09:10:26 -07002564 public int encryptStorage(int type, String password) {
2565 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002566 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002567 }
2568
Jason parks8888c592011-01-20 22:46:41 -06002569 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2570 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002571
2572 waitForReady();
2573
2574 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002575 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002576 }
2577
2578 try {
Paul Lawrence5096d9e2015-09-09 13:05:45 -07002579 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2580 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2581 CRYPTO_TYPES[type]);
2582 } else {
2583 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2584 CRYPTO_TYPES[type], new SensitiveArg(password));
2585 }
Jason parks56aa5322011-01-07 09:01:15 -06002586 } catch (NativeDaemonConnectorException e) {
2587 // Encryption failed
2588 return e.getCode();
2589 }
2590
2591 return 0;
2592 }
2593
Paul Lawrence8e397362014-01-27 15:22:30 -08002594 /** Set the password for encrypting the master key.
2595 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2596 * @param password The password to set.
2597 */
2598 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002599 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2600 "no permission to access the crypt keeper");
2601
2602 waitForReady();
2603
2604 if (DEBUG_EVENTS) {
2605 Slog.i(TAG, "changing encryption password...");
2606 }
2607
2608 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002609 NativeDaemonEvent event = mCryptConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
Paul Lawrence05487612015-06-09 13:35:38 -07002610 new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002611 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002612 } catch (NativeDaemonConnectorException e) {
2613 // Encryption failed
2614 return e.getCode();
2615 }
2616 }
2617
Christopher Tate32418be2011-10-10 13:51:12 -07002618 /**
2619 * Validate a user-supplied password string with cryptfs
2620 */
2621 @Override
2622 public int verifyEncryptionPassword(String password) throws RemoteException {
2623 // Only the system process is permitted to validate passwords
2624 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2625 throw new SecurityException("no permission to access the crypt keeper");
2626 }
2627
2628 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2629 "no permission to access the crypt keeper");
2630
2631 if (TextUtils.isEmpty(password)) {
2632 throw new IllegalArgumentException("password cannot be empty");
2633 }
2634
2635 waitForReady();
2636
2637 if (DEBUG_EVENTS) {
2638 Slog.i(TAG, "validating encryption password...");
2639 }
2640
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002641 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002642 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002643 event = mCryptConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002644 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2645 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002646 } catch (NativeDaemonConnectorException e) {
2647 // Encryption failed
2648 return e.getCode();
2649 }
2650 }
2651
Paul Lawrence8e397362014-01-27 15:22:30 -08002652 /**
2653 * Get the type of encryption used to encrypt the master key.
2654 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2655 */
2656 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002657 public int getPasswordType() {
Paul Lawrence9de713d2016-05-02 22:45:33 +00002658 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
2659 "no permission to access the crypt keeper");
2660
Paul Lawrence8e397362014-01-27 15:22:30 -08002661 waitForReady();
2662
2663 final NativeDaemonEvent event;
2664 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002665 event = mCryptConnector.execute("cryptfs", "getpwtype");
Paul Lawrence8e397362014-01-27 15:22:30 -08002666 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2667 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2668 return i;
2669 }
2670
2671 throw new IllegalStateException("unexpected return from cryptfs");
2672 } catch (NativeDaemonConnectorException e) {
2673 throw e.rethrowAsParcelableException();
2674 }
2675 }
2676
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002677 /**
2678 * Set a field in the crypto header.
2679 * @param field field to set
2680 * @param contents contents to set in field
2681 */
2682 @Override
2683 public void setField(String field, String contents) throws RemoteException {
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002684 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
2685 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002686
2687 waitForReady();
2688
2689 final NativeDaemonEvent event;
2690 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002691 event = mCryptConnector.execute("cryptfs", "setfield", field, contents);
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002692 } catch (NativeDaemonConnectorException e) {
2693 throw e.rethrowAsParcelableException();
2694 }
2695 }
2696
2697 /**
2698 * Gets a field from the crypto header.
2699 * @param field field to get
2700 * @return contents of field
2701 */
2702 @Override
2703 public String getField(String field) throws RemoteException {
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002704 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
2705 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002706
2707 waitForReady();
2708
2709 final NativeDaemonEvent event;
2710 try {
2711 final String[] contents = NativeDaemonEvent.filterMessageList(
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002712 mCryptConnector.executeForList("cryptfs", "getfield", field),
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002713 VoldResponseCode.CryptfsGetfieldResult);
2714 String result = new String();
2715 for (String content : contents) {
2716 result += content;
2717 }
2718 return result;
2719 } catch (NativeDaemonConnectorException e) {
2720 throw e.rethrowAsParcelableException();
2721 }
2722 }
2723
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002724 /**
2725 * Is userdata convertible to file based encryption?
2726 * @return non zero for convertible
2727 */
2728 @Override
2729 public boolean isConvertibleToFBE() throws RemoteException {
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002730 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
2731 "no permission to access the crypt keeper");
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002732
2733 waitForReady();
2734
2735 final NativeDaemonEvent event;
2736 try {
2737 event = mCryptConnector.execute("cryptfs", "isConvertibleToFBE");
2738 return Integer.parseInt(event.getMessage()) != 0;
2739 } catch (NativeDaemonConnectorException e) {
2740 throw e.rethrowAsParcelableException();
2741 }
2742 }
2743
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002744 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002745 public String getPassword() throws RemoteException {
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002746 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
Rubin Xucd7a0142015-04-17 23:45:27 +01002747 "only keyguard can retrieve password");
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002748
Paul Lawrence945490c2014-03-27 16:37:28 +00002749 if (!isReady()) {
2750 return new String();
2751 }
2752
2753 final NativeDaemonEvent event;
2754 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002755 event = mCryptConnector.execute("cryptfs", "getpw");
Paul Lawrence24063b52015-01-06 13:11:23 -08002756 if ("-1".equals(event.getMessage())) {
2757 // -1 equals no password
2758 return null;
2759 }
Paul Lawrence05487612015-06-09 13:35:38 -07002760 return event.getMessage();
Paul Lawrence945490c2014-03-27 16:37:28 +00002761 } catch (NativeDaemonConnectorException e) {
2762 throw e.rethrowAsParcelableException();
Paul Lawrence24063b52015-01-06 13:11:23 -08002763 } catch (IllegalArgumentException e) {
2764 Slog.e(TAG, "Invalid response to getPassword");
2765 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002766 }
2767 }
2768
2769 @Override
2770 public void clearPassword() throws RemoteException {
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002771 mContext.enforceCallingOrSelfPermission(Manifest.permission.STORAGE_INTERNAL,
2772 "only keyguard can clear password");
2773
Paul Lawrence945490c2014-03-27 16:37:28 +00002774 if (!isReady()) {
2775 return;
2776 }
2777
2778 final NativeDaemonEvent event;
2779 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002780 event = mCryptConnector.execute("cryptfs", "clearpw");
Paul Lawrence945490c2014-03-27 16:37:28 +00002781 } catch (NativeDaemonConnectorException e) {
2782 throw e.rethrowAsParcelableException();
2783 }
2784 }
2785
2786 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002787 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002788 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002789 waitForReady();
2790
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002791 try {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002792 mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber,
2793 ephemeral ? 1 : 0);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002794 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002795 throw e.rethrowAsParcelableException();
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002796 }
2797 }
2798
Paul Crowley7ec733f2015-05-19 12:42:00 +01002799 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002800 public void destroyUserKey(int userId) {
2801 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002802 waitForReady();
2803
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002804 try {
2805 mCryptConnector.execute("cryptfs", "destroy_user_key", userId);
2806 } catch (NativeDaemonConnectorException e) {
2807 throw e.rethrowAsParcelableException();
2808 }
2809 }
2810
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002811 private SensitiveArg encodeBytes(byte[] bytes) {
2812 if (ArrayUtils.isEmpty(bytes)) {
2813 return new SensitiveArg("!");
2814 } else {
2815 return new SensitiveArg(HexDump.toHexString(bytes));
2816 }
2817 }
2818
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002819 @Override
Paul Crowleya1eb7502016-05-10 20:36:56 +00002820 public void changeUserKey(int userId, int serialNumber,
2821 byte[] token, byte[] oldSecret, byte[] newSecret) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002822 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2823 waitForReady();
2824
2825 try {
Paul Crowleya1eb7502016-05-10 20:36:56 +00002826 mCryptConnector.execute("cryptfs", "change_user_key", userId, serialNumber,
2827 encodeBytes(token), encodeBytes(oldSecret), encodeBytes(newSecret));
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002828 } catch (NativeDaemonConnectorException e) {
2829 throw e.rethrowAsParcelableException();
2830 }
2831 }
2832
2833 @Override
2834 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002835 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2836 waitForReady();
2837
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002838 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2839 // When a user has secure lock screen, require a challenge token to
2840 // actually unlock. This check is mostly in place for emulation mode.
2841 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
2842 throw new IllegalStateException("Token required to unlock secure user " + userId);
2843 }
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002844
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002845 try {
2846 mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
2847 encodeBytes(token), encodeBytes(secret));
2848 } catch (NativeDaemonConnectorException e) {
2849 throw e.rethrowAsParcelableException();
2850 }
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002851 }
2852
2853 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002854 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002855 }
2856 }
2857
2858 @Override
2859 public void lockUserKey(int userId) {
2860 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2861 waitForReady();
2862
2863 try {
2864 mCryptConnector.execute("cryptfs", "lock_user_key", userId);
2865 } catch (NativeDaemonConnectorException e) {
2866 throw e.rethrowAsParcelableException();
2867 }
2868
2869 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002870 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002871 }
2872 }
2873
2874 @Override
2875 public boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002876 synchronized (mLock) {
2877 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002878 }
2879 }
2880
2881 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002882 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002883 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2884 waitForReady();
2885
2886 try {
2887 mCryptConnector.execute("cryptfs", "prepare_user_storage", escapeNull(volumeUuid),
Jeff Sharkey47f71082016-02-01 17:03:54 -07002888 userId, serialNumber, flags);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002889 } catch (NativeDaemonConnectorException e) {
2890 throw e.rethrowAsParcelableException();
Paul Crowley7ec733f2015-05-19 12:42:00 +01002891 }
2892 }
2893
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002894 @Override
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002895 public void destroyUserStorage(String volumeUuid, int userId, int flags) {
2896 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2897 waitForReady();
2898
2899 try {
2900 mCryptConnector.execute("cryptfs", "destroy_user_storage", escapeNull(volumeUuid),
2901 userId, flags);
2902 } catch (NativeDaemonConnectorException e) {
2903 throw e.rethrowAsParcelableException();
2904 }
2905 }
2906
2907 @Override
Daichi Hirono91e3b502015-12-16 09:24:16 +09002908 public ParcelFileDescriptor mountAppFuse(final String name) throws RemoteException {
Daichi Hironobee50c02015-12-14 11:00:54 +09002909 try {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002910 final int uid = Binder.getCallingUid();
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002911 final int pid = Binder.getCallingPid();
Daichi Hironobee50c02015-12-14 11:00:54 +09002912 final NativeDaemonEvent event =
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002913 mConnector.execute("appfuse", "mount", uid, pid, name);
Daichi Hironobee50c02015-12-14 11:00:54 +09002914 if (event.getFileDescriptors() == null) {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002915 throw new RemoteException("AppFuse FD from vold is null.");
Daichi Hironobee50c02015-12-14 11:00:54 +09002916 }
Daichi Hirono91e3b502015-12-16 09:24:16 +09002917 return ParcelFileDescriptor.fromFd(
2918 event.getFileDescriptors()[0],
2919 mHandler,
2920 new ParcelFileDescriptor.OnCloseListener() {
2921 @Override
2922 public void onClose(IOException e) {
2923 try {
2924 final NativeDaemonEvent event = mConnector.execute(
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002925 "appfuse", "unmount", uid, pid, name);
Daichi Hirono91e3b502015-12-16 09:24:16 +09002926 } catch (NativeDaemonConnectorException unmountException) {
2927 Log.e(TAG, "Failed to unmount appfuse.");
2928 }
2929 }
2930 });
Daichi Hironobee50c02015-12-14 11:00:54 +09002931 } catch (NativeDaemonConnectorException e) {
2932 throw e.rethrowAsParcelableException();
Daichi Hirono91e3b502015-12-16 09:24:16 +09002933 } catch (IOException e) {
2934 throw new RemoteException(e.getMessage());
Daichi Hironobee50c02015-12-14 11:00:54 +09002935 }
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002936 }
2937
2938 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002939 public int mkdirs(String callingPkg, String appPath) {
2940 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2941 final UserEnvironment userEnv = new UserEnvironment(userId);
2942
2943 // Validate that reported package name belongs to caller
2944 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2945 Context.APP_OPS_SERVICE);
2946 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2947
Jeff Sharkey48877892015-03-18 11:27:19 -07002948 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002949 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002950 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002951 } catch (IOException e) {
2952 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2953 return -1;
2954 }
2955
2956 // Try translating the app path into a vold path, but require that it
2957 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07002958 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
2959 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
2960 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
2961 appPath = appFile.getAbsolutePath();
2962 if (!appPath.endsWith("/")) {
2963 appPath = appPath + "/";
2964 }
2965
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002966 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002967 mConnector.execute("volume", "mkdirs", appPath);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002968 return 0;
2969 } catch (NativeDaemonConnectorException e) {
2970 return e.getCode();
2971 }
2972 }
2973
Jeff Sharkey48877892015-03-18 11:27:19 -07002974 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002975 }
2976
2977 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07002978 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002979 final int userId = UserHandle.getUserId(uid);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002980
Jeff Sharkey46349872015-07-28 10:49:47 -07002981 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002982 final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0;
2983 final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0;
Jeff Sharkey46349872015-07-28 10:49:47 -07002984
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002985 final boolean userKeyUnlocked;
2986 final boolean storagePermission;
2987 final long token = Binder.clearCallingIdentity();
Svetoslav38c3dbb2015-07-14 11:27:06 -07002988 try {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002989 userKeyUnlocked = isUserKeyUnlocked(userId);
2990 storagePermission = mMountServiceInternal.hasExternalStorage(uid, packageName);
Svetoslav38c3dbb2015-07-14 11:27:06 -07002991 } finally {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002992 Binder.restoreCallingIdentity(token);
Svetoslav38c3dbb2015-07-14 11:27:06 -07002993 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07002994
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002995 boolean foundPrimary = false;
2996
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002997 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07002998 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002999 for (int i = 0; i < mVolumes.size(); i++) {
3000 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003001 switch (vol.getType()) {
3002 case VolumeInfo.TYPE_PUBLIC:
3003 case VolumeInfo.TYPE_EMULATED:
3004 break;
3005 default:
3006 continue;
3007 }
3008
3009 boolean match = false;
3010 if (forWrite) {
3011 match = vol.isVisibleForWrite(userId);
3012 } else {
3013 match = vol.isVisibleForRead(userId) || includeInvisible;
3014 }
3015 if (!match) continue;
3016
3017 boolean reportUnmounted = false;
3018 if ((vol.getType() == VolumeInfo.TYPE_EMULATED) && !userKeyUnlocked) {
3019 reportUnmounted = true;
3020 } else if (!storagePermission && !realState) {
3021 reportUnmounted = true;
3022 }
3023
3024 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
3025 reportUnmounted);
3026 if (vol.isPrimary()) {
3027 res.add(0, userVol);
3028 foundPrimary = true;
3029 } else {
3030 res.add(userVol);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07003031 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003032 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003033 }
Jeff Sharkey48877892015-03-18 11:27:19 -07003034
3035 if (!foundPrimary) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003036 Log.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07003037
3038 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003039 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07003040
3041 final String id = "stub_primary";
3042 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003043 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07003044 final boolean primary = true;
3045 final boolean removable = primaryPhysical;
3046 final boolean emulated = !primaryPhysical;
3047 final long mtpReserveSize = 0L;
3048 final boolean allowMassStorage = false;
3049 final long maxFileSize = 0L;
3050 final UserHandle owner = new UserHandle(userId);
3051 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07003052 final String state = Environment.MEDIA_REMOVED;
3053
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07003054 res.add(0, new StorageVolume(id, StorageVolume.STORAGE_ID_INVALID, path,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003055 description, primary, removable, emulated, mtpReserveSize,
3056 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07003057 }
3058
3059 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003060 }
3061
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003062 @Override
3063 public DiskInfo[] getDisks() {
3064 synchronized (mLock) {
3065 final DiskInfo[] res = new DiskInfo[mDisks.size()];
3066 for (int i = 0; i < mDisks.size(); i++) {
3067 res[i] = mDisks.valueAt(i);
3068 }
3069 return res;
3070 }
3071 }
3072
3073 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003074 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003075 synchronized (mLock) {
3076 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
3077 for (int i = 0; i < mVolumes.size(); i++) {
3078 res[i] = mVolumes.valueAt(i);
3079 }
3080 return res;
3081 }
3082 }
3083
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003084 @Override
3085 public VolumeRecord[] getVolumeRecords(int flags) {
3086 synchronized (mLock) {
3087 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
3088 for (int i = 0; i < mRecords.size(); i++) {
3089 res[i] = mRecords.valueAt(i);
3090 }
3091 return res;
3092 }
3093 }
3094
Kenny Rootaf9d6672010-10-08 09:21:39 -07003095 private void addObbStateLocked(ObbState obbState) throws RemoteException {
3096 final IBinder binder = obbState.getBinder();
3097 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003098
Kenny Rootaf9d6672010-10-08 09:21:39 -07003099 if (obbStates == null) {
3100 obbStates = new ArrayList<ObbState>();
3101 mObbMounts.put(binder, obbStates);
3102 } else {
3103 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003104 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003105 throw new IllegalStateException("Attempt to add ObbState twice. "
3106 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003107 }
3108 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003109 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003110
3111 obbStates.add(obbState);
3112 try {
3113 obbState.link();
3114 } catch (RemoteException e) {
3115 /*
3116 * The binder died before we could link it, so clean up our state
3117 * and return failure.
3118 */
3119 obbStates.remove(obbState);
3120 if (obbStates.isEmpty()) {
3121 mObbMounts.remove(binder);
3122 }
3123
3124 // Rethrow the error so mountObb can get it
3125 throw e;
3126 }
3127
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003128 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003129 }
3130
Kenny Rootaf9d6672010-10-08 09:21:39 -07003131 private void removeObbStateLocked(ObbState obbState) {
3132 final IBinder binder = obbState.getBinder();
3133 final List<ObbState> obbStates = mObbMounts.get(binder);
3134 if (obbStates != null) {
3135 if (obbStates.remove(obbState)) {
3136 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003137 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003138 if (obbStates.isEmpty()) {
3139 mObbMounts.remove(binder);
3140 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003141 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003142
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003143 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003144 }
3145
Kenny Roota02b8b02010-08-05 16:14:17 -07003146 private class ObbActionHandler extends Handler {
3147 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07003148 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07003149
3150 ObbActionHandler(Looper l) {
3151 super(l);
3152 }
3153
3154 @Override
3155 public void handleMessage(Message msg) {
3156 switch (msg.what) {
3157 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003158 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003159
3160 if (DEBUG_OBB)
3161 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3162
3163 // If a bind was already initiated we don't really
3164 // need to do anything. The pending install
3165 // will be processed later on.
3166 if (!mBound) {
3167 // If this is the only one pending we might
3168 // have to bind to the service again.
3169 if (!connectToService()) {
3170 Slog.e(TAG, "Failed to bind to media container service");
3171 action.handleError();
3172 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003173 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003174 }
Kenny Root735de3b2010-09-30 14:11:39 -07003175
Kenny Root735de3b2010-09-30 14:11:39 -07003176 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07003177 break;
3178 }
3179 case OBB_MCS_BOUND: {
3180 if (DEBUG_OBB)
3181 Slog.i(TAG, "OBB_MCS_BOUND");
3182 if (msg.obj != null) {
3183 mContainerService = (IMediaContainerService) msg.obj;
3184 }
3185 if (mContainerService == null) {
3186 // Something seriously wrong. Bail out
3187 Slog.e(TAG, "Cannot bind to media container service");
3188 for (ObbAction action : mActions) {
3189 // Indicate service bind error
3190 action.handleError();
3191 }
3192 mActions.clear();
3193 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07003194 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07003195 if (action != null) {
3196 action.execute(this);
3197 }
3198 } else {
3199 // Should never happen ideally.
3200 Slog.w(TAG, "Empty queue");
3201 }
3202 break;
3203 }
3204 case OBB_MCS_RECONNECT: {
3205 if (DEBUG_OBB)
3206 Slog.i(TAG, "OBB_MCS_RECONNECT");
3207 if (mActions.size() > 0) {
3208 if (mBound) {
3209 disconnectService();
3210 }
3211 if (!connectToService()) {
3212 Slog.e(TAG, "Failed to bind to media container service");
3213 for (ObbAction action : mActions) {
3214 // Indicate service bind error
3215 action.handleError();
3216 }
3217 mActions.clear();
3218 }
3219 }
3220 break;
3221 }
3222 case OBB_MCS_UNBIND: {
3223 if (DEBUG_OBB)
3224 Slog.i(TAG, "OBB_MCS_UNBIND");
3225
3226 // Delete pending install
3227 if (mActions.size() > 0) {
3228 mActions.remove(0);
3229 }
3230 if (mActions.size() == 0) {
3231 if (mBound) {
3232 disconnectService();
3233 }
3234 } else {
3235 // There are more pending requests in queue.
3236 // Just post MCS_BOUND message to trigger processing
3237 // of next pending install.
3238 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
3239 }
3240 break;
3241 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003242 case OBB_FLUSH_MOUNT_STATE: {
3243 final String path = (String) msg.obj;
3244
3245 if (DEBUG_OBB)
3246 Slog.i(TAG, "Flushing all OBB state for path " + path);
3247
3248 synchronized (mObbMounts) {
3249 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3250
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003251 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003252 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003253 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003254
3255 /*
3256 * If this entry's source file is in the volume path
3257 * that got unmounted, remove it because it's no
3258 * longer valid.
3259 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003260 if (state.canonicalPath.startsWith(path)) {
3261 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003262 }
3263 }
3264
3265 for (final ObbState obbState : obbStatesToRemove) {
3266 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003267 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003268
3269 removeObbStateLocked(obbState);
3270
3271 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003272 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003273 OnObbStateChangeListener.UNMOUNTED);
3274 } catch (RemoteException e) {
3275 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003276 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003277 }
3278 }
3279 }
3280 break;
3281 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003282 }
3283 }
3284
3285 private boolean connectToService() {
3286 if (DEBUG_OBB)
3287 Slog.i(TAG, "Trying to bind to DefaultContainerService");
3288
3289 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003290 if (mContext.bindServiceAsUser(service, mDefContainerConn, Context.BIND_AUTO_CREATE,
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003291 UserHandle.SYSTEM)) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003292 mBound = true;
3293 return true;
3294 }
3295 return false;
3296 }
3297
3298 private void disconnectService() {
3299 mContainerService = null;
3300 mBound = false;
3301 mContext.unbindService(mDefContainerConn);
3302 }
3303 }
3304
3305 abstract class ObbAction {
3306 private static final int MAX_RETRIES = 3;
3307 private int mRetries;
3308
3309 ObbState mObbState;
3310
3311 ObbAction(ObbState obbState) {
3312 mObbState = obbState;
3313 }
3314
3315 public void execute(ObbActionHandler handler) {
3316 try {
3317 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003318 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07003319 mRetries++;
3320 if (mRetries > MAX_RETRIES) {
3321 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07003322 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003323 handleError();
Kenny Roota02b8b02010-08-05 16:14:17 -07003324 } else {
3325 handleExecute();
3326 if (DEBUG_OBB)
3327 Slog.i(TAG, "Posting install MCS_UNBIND");
3328 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
3329 }
3330 } catch (RemoteException e) {
3331 if (DEBUG_OBB)
3332 Slog.i(TAG, "Posting install MCS_RECONNECT");
3333 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
3334 } catch (Exception e) {
3335 if (DEBUG_OBB)
3336 Slog.d(TAG, "Error handling OBB action", e);
3337 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07003338 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003339 }
3340 }
3341
Kenny Root05105f72010-09-22 17:29:43 -07003342 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07003343 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07003344
3345 protected ObbInfo getObbInfo() throws IOException {
3346 ObbInfo obbInfo;
3347 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003348 obbInfo = mContainerService.getObbInfo(mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003349 } catch (RemoteException e) {
3350 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003351 + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003352 obbInfo = null;
3353 }
3354 if (obbInfo == null) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003355 throw new IOException("Couldn't read OBB file: " + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003356 }
3357 return obbInfo;
3358 }
3359
Kenny Rootaf9d6672010-10-08 09:21:39 -07003360 protected void sendNewStatusOrIgnore(int status) {
3361 if (mObbState == null || mObbState.token == null) {
3362 return;
3363 }
3364
Kenny Root38cf8862010-09-26 14:18:51 -07003365 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003366 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003367 } catch (RemoteException e) {
3368 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
3369 }
3370 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003371 }
3372
3373 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003374 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003375 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003376
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003377 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003378 super(obbState);
3379 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003380 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003381 }
3382
Jason parks5af0b912010-11-29 09:05:25 -06003383 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07003384 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003385 waitForReady();
3386 warnOnNotMounted();
3387
Kenny Root38cf8862010-09-26 14:18:51 -07003388 final ObbInfo obbInfo = getObbInfo();
3389
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003390 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003391 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
3392 + " which is owned by " + obbInfo.packageName);
3393 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3394 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003395 }
3396
Kenny Rootaf9d6672010-10-08 09:21:39 -07003397 final boolean isMounted;
3398 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003399 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003400 }
3401 if (isMounted) {
3402 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
3403 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
3404 return;
3405 }
3406
Kenny Rootaf9d6672010-10-08 09:21:39 -07003407 final String hashedKey;
3408 if (mKey == null) {
3409 hashedKey = "none";
3410 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003411 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003412 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3413
3414 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
3415 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3416 SecretKey key = factory.generateSecret(ks);
3417 BigInteger bi = new BigInteger(key.getEncoded());
3418 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003419 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07003420 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
3421 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
3422 return;
3423 } catch (InvalidKeySpecException e) {
3424 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
3425 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07003426 return;
3427 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003428 }
Kenny Root38cf8862010-09-26 14:18:51 -07003429
Kenny Rootaf9d6672010-10-08 09:21:39 -07003430 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003431 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003432 mConnector.execute("obb", "mount", mObbState.canonicalPath, new SensitiveArg(hashedKey),
Jeff Sharkey56cd6462013-06-07 15:09:15 -07003433 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003434 } catch (NativeDaemonConnectorException e) {
3435 int code = e.getCode();
3436 if (code != VoldResponseCode.OpFailedStorageBusy) {
3437 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003438 }
3439 }
3440
Kenny Rootaf9d6672010-10-08 09:21:39 -07003441 if (rc == StorageResultCode.OperationSucceeded) {
3442 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003443 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003444
3445 synchronized (mObbMounts) {
3446 addObbStateLocked(mObbState);
3447 }
3448
3449 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07003450 } else {
Kenny Root05105f72010-09-22 17:29:43 -07003451 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07003452
Kenny Rootaf9d6672010-10-08 09:21:39 -07003453 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07003454 }
3455 }
3456
Jason parks5af0b912010-11-29 09:05:25 -06003457 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003458 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003459 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07003460 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003461
3462 @Override
3463 public String toString() {
3464 StringBuilder sb = new StringBuilder();
3465 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003466 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003467 sb.append('}');
3468 return sb.toString();
3469 }
3470 }
3471
3472 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003473 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003474
3475 UnmountObbAction(ObbState obbState, boolean force) {
3476 super(obbState);
3477 mForceUnmount = force;
3478 }
3479
Jason parks5af0b912010-11-29 09:05:25 -06003480 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07003481 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003482 waitForReady();
3483 warnOnNotMounted();
3484
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003485 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003486 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003487 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003488 }
Kenny Root38cf8862010-09-26 14:18:51 -07003489
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003490 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003491 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
3492 return;
3493 }
3494
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003495 if (existingState.ownerGid != mObbState.ownerGid) {
3496 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
3497 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003498 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3499 return;
3500 }
3501
Kenny Rootaf9d6672010-10-08 09:21:39 -07003502 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003503 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003504 final Command cmd = new Command("obb", "unmount", mObbState.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08003505 if (mForceUnmount) {
3506 cmd.appendArg("force");
3507 }
3508 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003509 } catch (NativeDaemonConnectorException e) {
3510 int code = e.getCode();
3511 if (code == VoldResponseCode.OpFailedStorageBusy) {
3512 rc = StorageResultCode.OperationFailedStorageBusy;
3513 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
3514 // If it's not mounted then we've already won.
3515 rc = StorageResultCode.OperationSucceeded;
3516 } else {
3517 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003518 }
3519 }
3520
Kenny Rootaf9d6672010-10-08 09:21:39 -07003521 if (rc == StorageResultCode.OperationSucceeded) {
3522 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003523 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003524 }
3525
Kenny Rootaf9d6672010-10-08 09:21:39 -07003526 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07003527 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003528 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003529 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07003530 }
3531 }
3532
Jason parks5af0b912010-11-29 09:05:25 -06003533 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003534 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003535 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07003536 }
3537
3538 @Override
3539 public String toString() {
3540 StringBuilder sb = new StringBuilder();
3541 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003542 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003543 sb.append(",force=");
3544 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003545 sb.append('}');
3546 return sb.toString();
3547 }
Kenny Root02c87302010-07-01 08:10:18 -07003548 }
Kenny Root38cf8862010-09-26 14:18:51 -07003549
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003550 private static class Callbacks extends Handler {
3551 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3552 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003553 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3554 private static final int MSG_VOLUME_FORGOTTEN = 4;
3555 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003556 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003557
3558 private final RemoteCallbackList<IMountServiceListener>
3559 mCallbacks = new RemoteCallbackList<>();
3560
3561 public Callbacks(Looper looper) {
3562 super(looper);
3563 }
3564
3565 public void register(IMountServiceListener callback) {
3566 mCallbacks.register(callback);
3567 }
3568
3569 public void unregister(IMountServiceListener callback) {
3570 mCallbacks.unregister(callback);
3571 }
3572
3573 @Override
3574 public void handleMessage(Message msg) {
3575 final SomeArgs args = (SomeArgs) msg.obj;
3576 final int n = mCallbacks.beginBroadcast();
3577 for (int i = 0; i < n; i++) {
3578 final IMountServiceListener callback = mCallbacks.getBroadcastItem(i);
3579 try {
3580 invokeCallback(callback, msg.what, args);
3581 } catch (RemoteException ignored) {
3582 }
3583 }
3584 mCallbacks.finishBroadcast();
3585 args.recycle();
3586 }
3587
3588 private void invokeCallback(IMountServiceListener callback, int what, SomeArgs args)
3589 throws RemoteException {
3590 switch (what) {
3591 case MSG_STORAGE_STATE_CHANGED: {
3592 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3593 (String) args.arg3);
3594 break;
3595 }
3596 case MSG_VOLUME_STATE_CHANGED: {
3597 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3598 break;
3599 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003600 case MSG_VOLUME_RECORD_CHANGED: {
3601 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3602 break;
3603 }
3604 case MSG_VOLUME_FORGOTTEN: {
3605 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003606 break;
3607 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003608 case MSG_DISK_SCANNED: {
3609 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003610 break;
3611 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003612 case MSG_DISK_DESTROYED: {
3613 callback.onDiskDestroyed((DiskInfo) args.arg1);
3614 break;
3615 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003616 }
3617 }
3618
3619 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3620 final SomeArgs args = SomeArgs.obtain();
3621 args.arg1 = path;
3622 args.arg2 = oldState;
3623 args.arg3 = newState;
3624 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3625 }
3626
3627 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3628 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003629 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003630 args.argi2 = oldState;
3631 args.argi3 = newState;
3632 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3633 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003634
Jeff Sharkey50a05452015-04-29 11:24:52 -07003635 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3636 final SomeArgs args = SomeArgs.obtain();
3637 args.arg1 = rec.clone();
3638 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3639 }
3640
3641 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003642 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003643 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003644 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003645 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003646
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003647 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003648 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003649 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003650 args.argi2 = volumeCount;
3651 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003652 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003653
3654 private void notifyDiskDestroyed(DiskInfo disk) {
3655 final SomeArgs args = SomeArgs.obtain();
3656 args.arg1 = disk.clone();
3657 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3658 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003659 }
3660
Kenny Root38cf8862010-09-26 14:18:51 -07003661 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003662 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
3664
3665 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003666 synchronized (mLock) {
3667 pw.println("Disks:");
3668 pw.increaseIndent();
3669 for (int i = 0; i < mDisks.size(); i++) {
3670 final DiskInfo disk = mDisks.valueAt(i);
3671 disk.dump(pw);
3672 }
3673 pw.decreaseIndent();
3674
3675 pw.println();
3676 pw.println("Volumes:");
3677 pw.increaseIndent();
3678 for (int i = 0; i < mVolumes.size(); i++) {
3679 final VolumeInfo vol = mVolumes.valueAt(i);
3680 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3681 vol.dump(pw);
3682 }
3683 pw.decreaseIndent();
3684
3685 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003686 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003687 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003688 for (int i = 0; i < mRecords.size(); i++) {
3689 final VolumeRecord note = mRecords.valueAt(i);
3690 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003691 }
3692 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003693
3694 pw.println();
3695 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07003696 pw.println("Force adoptable: " + mForceAdoptable);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08003697 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003698 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3699 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003700 }
Kenny Root38cf8862010-09-26 14:18:51 -07003701
Kenny Root38cf8862010-09-26 14:18:51 -07003702 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003703 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003704 pw.println("mObbMounts:");
3705 pw.increaseIndent();
3706 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3707 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003708 while (binders.hasNext()) {
3709 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003710 pw.println(e.getKey() + ":");
3711 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003712 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003713 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003714 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003715 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003716 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003717 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003718 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003719
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003720 pw.println();
3721 pw.println("mObbPathToStateMap:");
3722 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003723 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3724 while (maps.hasNext()) {
3725 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003726 pw.print(e.getKey());
3727 pw.print(" -> ");
3728 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003729 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003730 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003731 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003732
Robert Greenwalt470fd722012-01-18 12:51:15 -08003733 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003734 pw.println("mConnector:");
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003735 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003736 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003737 pw.decreaseIndent();
Christopher Tate7265abe2014-11-21 13:54:45 -08003738
Christopher Tate7265abe2014-11-21 13:54:45 -08003739 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003740 pw.println("mCryptConnector:");
3741 pw.increaseIndent();
3742 mCryptConnector.dump(fd, pw, args);
3743 pw.decreaseIndent();
3744
3745 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003746 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003747 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003750 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003751 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003752 public void monitor() {
3753 if (mConnector != null) {
3754 mConnector.monitor();
3755 }
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003756 if (mCryptConnector != null) {
3757 mCryptConnector.monitor();
3758 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003759 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003760
3761 private final class MountServiceInternalImpl extends MountServiceInternal {
3762 // Not guarded by a lock.
3763 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3764 new CopyOnWriteArrayList<>();
3765
3766 @Override
3767 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3768 // No locking - CopyOnWriteArrayList
3769 mPolicies.add(policy);
3770 }
3771
3772 @Override
3773 public void onExternalStoragePolicyChanged(int uid, String packageName) {
3774 final int mountMode = getExternalStorageMountMode(uid, packageName);
3775 remountUidExternalStorage(uid, mountMode);
3776 }
3777
3778 @Override
3779 public int getExternalStorageMountMode(int uid, String packageName) {
3780 // No locking - CopyOnWriteArrayList
3781 int mountMode = Integer.MAX_VALUE;
3782 for (ExternalStorageMountPolicy policy : mPolicies) {
3783 final int policyMode = policy.getMountMode(uid, packageName);
3784 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3785 return Zygote.MOUNT_EXTERNAL_NONE;
3786 }
3787 mountMode = Math.min(mountMode, policyMode);
3788 }
3789 if (mountMode == Integer.MAX_VALUE) {
3790 return Zygote.MOUNT_EXTERNAL_NONE;
3791 }
3792 return mountMode;
3793 }
3794
3795 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003796 // No need to check for system uid. This avoids a deadlock between
3797 // PackageManagerService and AppOpsService.
3798 if (uid == Process.SYSTEM_UID) {
3799 return true;
3800 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003801 // No locking - CopyOnWriteArrayList
3802 for (ExternalStorageMountPolicy policy : mPolicies) {
3803 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
3804 if (!policyHasStorage) {
3805 return false;
3806 }
3807 }
3808 return true;
3809 }
3810 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003811}