blob: 9e2f11670017dd1b756883f68952e1b79081e5f4 [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 Sharkeyce14cd02015-12-07 15:35:42 -0700181 public void onUnlockUser(int userHandle) {
182 mMountService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700183 }
184
185 @Override
186 public void onCleanupUser(int userHandle) {
187 mMountService.onCleanupUser(userHandle);
188 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700189 }
190
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800191 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800192 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700193
Kenny Root07714d42011-08-17 17:49:28 -0700194 // Disable this since it messes up long-running cryptfs operations.
195 private static final boolean WATCHDOG_ENABLE = false;
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 private static final String TAG = "MountService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700198
Jeff Sharkey9756d752015-05-14 21:07:42 -0700199 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700200 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Kenny Root305bcbf2010-09-03 07:56:38 -0700202 private static final String VOLD_TAG = "VoldConnector";
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700203 private static final String CRYPTD_TAG = "CryptdConnector";
Kenny Root305bcbf2010-09-03 07:56:38 -0700204
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700205 /** Maximum number of ASEC containers allowed to be mounted. */
206 private static final int MAX_CONTAINERS = 250;
207
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700208 /** Magic value sent by MoveTask.cpp */
209 private static final int MOVE_STATUS_COPY_FINISHED = 82;
210
San Mehat4270e1e2010-01-29 05:32:19 -0800211 /*
212 * Internal vold response code constants
213 */
San Mehat22dd86e2010-01-12 12:21:18 -0800214 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800215 /*
216 * 100 series - Requestion action was initiated; expect another reply
217 * before proceeding with a new command.
218 */
San Mehat22dd86e2010-01-12 12:21:18 -0800219 public static final int VolumeListResult = 110;
220 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800221 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700222 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800223
San Mehat4270e1e2010-01-29 05:32:19 -0800224 /*
225 * 200 series - Requestion action has been successfully completed.
226 */
227 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800228 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800229 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800230
San Mehat4270e1e2010-01-29 05:32:19 -0800231 /*
232 * 400 series - Command was accepted, but the requested action
233 * did not take place.
234 */
235 public static final int OpFailedNoMedia = 401;
236 public static final int OpFailedMediaBlank = 402;
237 public static final int OpFailedMediaCorrupt = 403;
238 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800239 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700240 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800241
242 /*
243 * 600 series - Unsolicited broadcasts.
244 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700245 public static final int DISK_CREATED = 640;
246 public static final int DISK_SIZE_CHANGED = 641;
247 public static final int DISK_LABEL_CHANGED = 642;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700248 public static final int DISK_SCANNED = 643;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700249 public static final int DISK_SYS_PATH_CHANGED = 644;
Jeff Sharkey48877892015-03-18 11:27:19 -0700250 public static final int DISK_DESTROYED = 649;
251
252 public static final int VOLUME_CREATED = 650;
253 public static final int VOLUME_STATE_CHANGED = 651;
254 public static final int VOLUME_FS_TYPE_CHANGED = 652;
255 public static final int VOLUME_FS_UUID_CHANGED = 653;
256 public static final int VOLUME_FS_LABEL_CHANGED = 654;
257 public static final int VOLUME_PATH_CHANGED = 655;
Jeff Sharkey50a05452015-04-29 11:24:52 -0700258 public static final int VOLUME_INTERNAL_PATH_CHANGED = 656;
Jeff Sharkey48877892015-03-18 11:27:19 -0700259 public static final int VOLUME_DESTROYED = 659;
Svetoslavf23b64d2013-04-25 14:45:54 -0700260
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700261 public static final int MOVE_STATUS = 660;
Jeff Sharkey9756d752015-05-14 21:07:42 -0700262 public static final int BENCHMARK_RESULT = 661;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700263 public static final int TRIM_RESULT = 662;
San Mehat22dd86e2010-01-12 12:21:18 -0800264 }
265
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700266 private static final int VERSION_INIT = 1;
267 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700268 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700269
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700270 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700271 private static final String ATTR_VERSION = "version";
272 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700273 private static final String ATTR_FORCE_ADOPTABLE = "forceAdoptable";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700274 private static final String TAG_VOLUME = "volume";
275 private static final String ATTR_TYPE = "type";
276 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700277 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700278 private static final String ATTR_NICKNAME = "nickname";
279 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700280 private static final String ATTR_CREATED_MILLIS = "createdMillis";
281 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
282 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700283
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700284 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700285
Jeff Sharkey48877892015-03-18 11:27:19 -0700286 /**
287 * <em>Never</em> hold the lock while performing downcalls into vold, since
288 * unsolicited events can suddenly appear to update data structures.
289 */
290 private final Object mLock = new Object();
291
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700292 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700293 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700294 private int[] mLocalUnlockedUsers = EmptyArray.INT;
295 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800296 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700297 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700298
299 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700300 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700301 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700302 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700303 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700304 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700305
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700306 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700307 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700308 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700309 @GuardedBy("mLock")
310 private String mPrimaryStorageUuid;
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700311 @GuardedBy("mLock")
312 private boolean mForceAdoptable;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700313
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700314 /** Map from disk ID to latches */
315 @GuardedBy("mLock")
316 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
317
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700318 @GuardedBy("mLock")
319 private IPackageMoveObserver mMoveCallback;
320 @GuardedBy("mLock")
321 private String mMoveTargetUuid;
322
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700323 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700324 synchronized (mLock) {
325 final VolumeInfo vol = mVolumes.get(id);
326 if (vol != null) {
327 return vol;
328 }
329 }
330 throw new IllegalArgumentException("No volume found for ID " + id);
331 }
332
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700333 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700334 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700335 for (int i = 0; i < mVolumes.size(); i++) {
336 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700337 if (vol.path != null && path.startsWith(vol.path)) {
338 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700339 }
340 }
341 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700342 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700343 }
344
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700345 private VolumeRecord findRecordForPath(String path) {
346 synchronized (mLock) {
347 for (int i = 0; i < mVolumes.size(); i++) {
348 final VolumeInfo vol = mVolumes.valueAt(i);
349 if (vol.path != null && path.startsWith(vol.path)) {
350 return mRecords.get(vol.fsUuid);
351 }
352 }
353 }
354 return null;
355 }
356
357 private String scrubPath(String path) {
358 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
359 return "internal";
360 }
361 final VolumeRecord rec = findRecordForPath(path);
362 if (rec == null || rec.createdMillis == 0) {
363 return "unknown";
364 } else {
365 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
366 / DateUtils.WEEK_IN_MILLIS) + "w";
367 }
368 }
369
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700370 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700371 final StorageManager storage = mContext.getSystemService(StorageManager.class);
372 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700373 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700374 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
375 return storage.getPrimaryPhysicalVolume();
376 } else {
377 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
378 }
379 }
380
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700381 private boolean shouldBenchmark() {
382 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
383 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700384 if (benchInterval == -1) {
385 return false;
386 } else if (benchInterval == 0) {
387 return true;
388 }
389
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700390 synchronized (mLock) {
391 for (int i = 0; i < mVolumes.size(); i++) {
392 final VolumeInfo vol = mVolumes.valueAt(i);
393 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700394 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700395 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
396 if (benchAge >= benchInterval) {
397 return true;
398 }
399 }
400 }
401 return false;
402 }
403 }
404
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700405 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
406 synchronized (mLock) {
407 CountDownLatch latch = mDiskScanLatches.get(diskId);
408 if (latch == null) {
409 latch = new CountDownLatch(1);
410 mDiskScanLatches.put(diskId, latch);
411 }
412 return latch;
413 }
414 }
415
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800416 private static String escapeNull(String arg) {
417 if (TextUtils.isEmpty(arg)) {
418 return "!";
419 } else {
420 if (arg.indexOf('\0') != -1 || arg.indexOf(' ') != -1) {
421 throw new IllegalArgumentException(arg);
422 }
423 return arg;
424 }
425 }
426
Paul Lawrence8e397362014-01-27 15:22:30 -0800427 /** List of crypto types.
428 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
429 * corresponding commands in CommandListener.cpp */
430 public static final String[] CRYPTO_TYPES
431 = { "password", "default", "pattern", "pin" };
432
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700433 private final Context mContext;
Jeff Sharkeycd575992016-03-29 14:12:49 -0600434
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700435 private final NativeDaemonConnector mConnector;
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700436 private final NativeDaemonConnector mCryptConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700437
Jeff Sharkeycd575992016-03-29 14:12:49 -0600438 private final Thread mConnectorThread;
439 private final Thread mCryptConnectorThread;
440
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700441 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900442 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700443 private volatile boolean mDaemonConnected = false;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700444
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700445 private PackageManagerService mPms;
446
447 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700448 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700449
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700450 // Two connectors - mConnector & mCryptConnector
451 private final CountDownLatch mConnectedSignal = new CountDownLatch(2);
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800452 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
Jeff Sharkey48877892015-03-18 11:27:19 -0700453
454 private final Object mUnmountLock = new Object();
455 @GuardedBy("mUnmountLock")
456 private CountDownLatch mUnmountSignal;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800457
San Mehat6cdd9c02010-02-09 14:45:20 -0800458 /**
459 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800460 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800461 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800462 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800463
Kenny Root02c87302010-07-01 08:10:18 -0700464 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700465 * The size of the crypto algorithm key in bits for OBB files. Currently
466 * Twofish is used which takes 128-bit keys.
467 */
468 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
469
470 /**
471 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
472 * 1024 is reasonably secure and not too slow.
473 */
474 private static final int PBKDF2_HASH_ROUNDS = 1024;
475
476 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700477 * Mounted OBB tracking information. Used to track the current state of all
478 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700479 */
Kenny Root735de3b2010-09-30 14:11:39 -0700480 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700481
482 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700483 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
484
Svet Ganov6ee871e2015-07-10 14:29:33 -0700485 // Not guarded by a lock.
486 private final MountServiceInternalImpl mMountServiceInternal = new MountServiceInternalImpl();
487
Kenny Roota02b8b02010-08-05 16:14:17 -0700488 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700489 public ObbState(String rawPath, String canonicalPath, int callingUid,
490 IObbActionListener token, int nonce) {
491 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700492 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700493
494 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700495 this.token = token;
496 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700497 }
498
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700499 final String rawPath;
500 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700501
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700502 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700503
Kenny Rootaf9d6672010-10-08 09:21:39 -0700504 // Token of remote Binder caller
505 final IObbActionListener token;
506
507 // Identifier to pass back to the token
508 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700509
Kenny Root735de3b2010-09-30 14:11:39 -0700510 public IBinder getBinder() {
511 return token.asBinder();
512 }
513
Kenny Roota02b8b02010-08-05 16:14:17 -0700514 @Override
515 public void binderDied() {
516 ObbAction action = new UnmountObbAction(this, true);
517 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700518 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700519
Kenny Root5919ac62010-10-05 09:49:40 -0700520 public void link() throws RemoteException {
521 getBinder().linkToDeath(this, 0);
522 }
523
524 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700525 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700526 }
Kenny Root38cf8862010-09-26 14:18:51 -0700527
528 @Override
529 public String toString() {
530 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700531 sb.append("rawPath=").append(rawPath);
532 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700533 sb.append(",ownerGid=").append(ownerGid);
534 sb.append(",token=").append(token);
535 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700536 sb.append('}');
537 return sb.toString();
538 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700539 }
540
541 // OBB Action Handler
542 final private ObbActionHandler mObbActionHandler;
543
544 // OBB action handler messages
545 private static final int OBB_RUN_ACTION = 1;
546 private static final int OBB_MCS_BOUND = 2;
547 private static final int OBB_MCS_UNBIND = 3;
548 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700549 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700550
551 /*
552 * Default Container Service information
553 */
554 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
555 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
556
557 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
558
559 class DefaultContainerConnection implements ServiceConnection {
Jeff Sharkey48877892015-03-18 11:27:19 -0700560 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700561 public void onServiceConnected(ComponentName name, IBinder service) {
562 if (DEBUG_OBB)
563 Slog.i(TAG, "onServiceConnected");
564 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
565 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
566 }
567
Jeff Sharkey48877892015-03-18 11:27:19 -0700568 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700569 public void onServiceDisconnected(ComponentName name) {
570 if (DEBUG_OBB)
571 Slog.i(TAG, "onServiceDisconnected");
572 }
573 };
574
575 // Used in the ObbActionHandler
576 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700577
Christopher Tate7265abe2014-11-21 13:54:45 -0800578 // Last fstrim operation tracking
579 private static final String LAST_FSTRIM_FILE = "last-fstrim";
580 private final File mLastMaintenanceFile;
581 private long mLastMaintenance;
582
Kenny Root02c87302010-07-01 08:10:18 -0700583 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700584 private static final int H_SYSTEM_READY = 1;
585 private static final int H_DAEMON_CONNECTED = 2;
586 private static final int H_SHUTDOWN = 3;
587 private static final int H_FSTRIM = 4;
588 private static final int H_VOLUME_MOUNT = 5;
589 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700590 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700591 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800592 private static final int H_PARTITION_FORGET = 9;
593 private static final int H_RESET = 10;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800594
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400595 class MountServiceHandler extends Handler {
Jeff Sharkey48877892015-03-18 11:27:19 -0700596 public MountServiceHandler(Looper looper) {
597 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400598 }
599
Jason parks5af0b912010-11-29 09:05:25 -0600600 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800601 public void handleMessage(Message msg) {
602 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700603 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700604 handleSystemReady();
605 break;
606 }
607 case H_DAEMON_CONNECTED: {
608 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700609 break;
610 }
Christopher Tated417d622013-08-19 16:14:25 -0700611 case H_FSTRIM: {
Jeff Sharkey1783f142015-04-17 10:52:51 -0700612 if (!isReady()) {
613 Slog.i(TAG, "fstrim requested, but no daemon connection yet; trying again");
Christopher Tate7618db12015-04-28 16:32:55 -0700614 sendMessageDelayed(obtainMessage(H_FSTRIM, msg.obj),
615 DateUtils.SECOND_IN_MILLIS);
616 break;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700617 }
618
Christopher Tated417d622013-08-19 16:14:25 -0700619 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800620
621 // Remember when we kicked it off
622 try {
623 mLastMaintenance = System.currentTimeMillis();
624 mLastMaintenanceFile.setLastModified(mLastMaintenance);
625 } catch (Exception e) {
626 Slog.e(TAG, "Unable to record last fstrim!");
627 }
628
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700629 final boolean shouldBenchmark = shouldBenchmark();
Christopher Tated417d622013-08-19 16:14:25 -0700630 try {
631 // This method must be run on the main (handler) thread,
632 // so it is safe to directly call into vold.
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700633 mConnector.execute("fstrim", shouldBenchmark ? "dotrimbench" : "dotrim");
Christopher Tated417d622013-08-19 16:14:25 -0700634 } catch (NativeDaemonConnectorException ndce) {
635 Slog.e(TAG, "Failed to run fstrim!");
636 }
Christopher Tate7265abe2014-11-21 13:54:45 -0800637
Christopher Tated417d622013-08-19 16:14:25 -0700638 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700639 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700640 Runnable callback = (Runnable) msg.obj;
641 if (callback != null) {
642 callback.run();
643 }
644 break;
645 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700646 case H_SHUTDOWN: {
647 final IMountShutdownObserver obs = (IMountShutdownObserver) msg.obj;
648 boolean success = false;
649 try {
650 success = mConnector.execute("volume", "shutdown").isClassOk();
651 } catch (NativeDaemonConnectorException ignored) {
652 }
653 if (obs != null) {
654 try {
655 obs.onShutDownComplete(success ? 0 : -1);
656 } catch (RemoteException ignored) {
657 }
658 }
659 break;
660 }
661 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700662 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700663 if (isMountDisallowed(vol)) {
664 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
665 break;
666 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700667 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -0700668 mConnector.execute("volume", "mount", vol.id, vol.mountFlags,
669 vol.mountUserId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700670 } catch (NativeDaemonConnectorException ignored) {
671 }
672 break;
673 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700674 case H_VOLUME_UNMOUNT: {
675 final VolumeInfo vol = (VolumeInfo) msg.obj;
676 unmount(vol.getId());
677 break;
678 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700679 case H_VOLUME_BROADCAST: {
680 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700681 final String envState = userVol.getState();
682 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700683 + userVol.getOwner());
684
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700685 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700686 if (action != null) {
687 final Intent intent = new Intent(action,
688 Uri.fromFile(userVol.getPathFile()));
689 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
690 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
691 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
692 }
693 break;
694 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700695 case H_INTERNAL_BROADCAST: {
696 // Internal broadcasts aimed at system components, not for
697 // third-party apps.
698 final Intent intent = (Intent) msg.obj;
699 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
700 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800701 break;
702 }
703 case H_PARTITION_FORGET: {
704 final String partGuid = (String) msg.obj;
705 forgetPartition(partGuid);
706 break;
707 }
708 case H_RESET: {
709 resetIfReadyAndConnected();
710 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700711 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800712 }
713 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700714 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700715
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700716 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800717
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700718 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
719 @Override
720 public void onReceive(Context context, Intent intent) {
721 final String action = intent.getAction();
722 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700723 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700724
725 try {
726 if (Intent.ACTION_USER_ADDED.equals(action)) {
727 final UserManager um = mContext.getSystemService(UserManager.class);
728 final int userSerialNumber = um.getUserSerialNumber(userId);
729 mConnector.execute("volume", "user_added", userId, userSerialNumber);
730 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700731 synchronized (mVolumes) {
732 final int size = mVolumes.size();
733 for (int i = 0; i < size; i++) {
734 final VolumeInfo vol = mVolumes.valueAt(i);
735 if (vol.mountUserId == userId) {
736 vol.mountUserId = UserHandle.USER_NULL;
737 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
738 }
739 }
740 }
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700741 mConnector.execute("volume", "user_removed", userId);
742 }
743 } catch (NativeDaemonConnectorException e) {
744 Slog.w(TAG, "Failed to send user details to vold", e);
745 }
746 }
747 };
748
Jeff Sharkey56e62932015-03-21 20:41:00 -0700749 @Override
750 public void waitForAsecScan() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700751 waitForLatch(mAsecsScanned, "mAsecsScanned");
Kenny Root51a573c2012-05-17 13:30:28 -0700752 }
753
San Mehat207e5382010-02-04 20:46:54 -0800754 private void waitForReady() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700755 waitForLatch(mConnectedSignal, "mConnectedSignal");
Kenny Root51a573c2012-05-17 13:30:28 -0700756 }
757
Jeff Sharkey48877892015-03-18 11:27:19 -0700758 private void waitForLatch(CountDownLatch latch, String condition) {
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700759 try {
760 waitForLatch(latch, condition, -1);
761 } catch (TimeoutException ignored) {
762 }
763 }
764
765 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
766 throws TimeoutException {
767 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700768 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700769 try {
770 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800771 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700772 } else {
773 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700774 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800775 }
Kenny Root51a573c2012-05-17 13:30:28 -0700776 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700777 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800778 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700779 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
780 throw new TimeoutException("Thread " + Thread.currentThread().getName()
781 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
782 }
San Mehat207e5382010-02-04 20:46:54 -0800783 }
San Mehat1f6301e2010-01-07 22:40:27 -0800784 }
Kenny Root02c87302010-07-01 08:10:18 -0700785
Paul Lawrence945490c2014-03-27 16:37:28 +0000786 private boolean isReady() {
787 try {
788 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
789 } catch (InterruptedException e) {
790 return false;
791 }
792 }
793
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700794 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700795 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800796 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700797
Jeff Sharkey48877892015-03-18 11:27:19 -0700798 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700799 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700800 }
801
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700802 /**
803 * MediaProvider has a ton of code that makes assumptions about storage
804 * paths never changing, so we outright kill them to pick up new state.
805 */
806 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700807 private void killMediaProvider(List<UserInfo> users) {
808 if (users == null) return;
809
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700810 final long token = Binder.clearCallingIdentity();
811 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700812 for (UserInfo user : users) {
813 // System user does not have media provider, so skip.
814 if (user.isSystemOnly()) continue;
815
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -0700816 final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY,
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600817 PackageManager.MATCH_DIRECT_BOOT_AWARE
818 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
819 user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700820 if (provider != null) {
821 final IActivityManager am = ActivityManagerNative.getDefault();
822 try {
823 am.killApplicationWithAppId(provider.applicationInfo.packageName,
824 UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
825 // We only need to run this once. It will kill all users' media processes.
826 break;
827 } catch (RemoteException e) {
828 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700829 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700830 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700831 } finally {
832 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700833 }
834 }
835
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800836 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700837 // Create a stub volume that represents internal storage
838 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
839 VolumeInfo.TYPE_PRIVATE, null, null);
840 internal.state = VolumeInfo.STATE_MOUNTED;
841 internal.path = Environment.getDataDirectory().getAbsolutePath();
842 mVolumes.put(internal.id, internal);
843 }
844
Jeff Sharkey8924e872015-11-30 12:52:10 -0700845 private void initIfReadyAndConnected() {
846 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
847 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700848 if (mSystemReady && mDaemonConnected
Paul Lawrence20be5d62016-02-26 13:51:17 -0800849 && !StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700850 // When booting a device without native support, make sure that our
851 // user directories are locked or unlocked based on the current
852 // emulation status.
Paul Lawrence20be5d62016-02-26 13:51:17 -0800853 final boolean initLocked = StorageManager.isFileEncryptedEmulatedOnly();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000854 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700855 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700856 for (UserInfo user : users) {
857 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700858 if (initLocked) {
859 mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
860 } else {
861 mCryptConnector.execute("cryptfs", "unlock_user_key", user.id,
Paul Crowleyd94ab732016-02-15 06:44:51 +0000862 user.serialNumber, "!", "!");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700863 }
Jeff Sharkey8924e872015-11-30 12:52:10 -0700864 } catch (NativeDaemonConnectorException e) {
865 Slog.w(TAG, "Failed to init vold", e);
866 }
867 }
868 }
869 }
870
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800871 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700872 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
873 + ", mDaemonConnected=" + mDaemonConnected);
874 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800875 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700876 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700877
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700878 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800879 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700880 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700881
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800882 mDisks.clear();
883 mVolumes.clear();
884
885 addInternalVolumeLocked();
886 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700887
Jeff Sharkey48877892015-03-18 11:27:19 -0700888 try {
889 mConnector.execute("volume", "reset");
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700890
891 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700892 for (UserInfo user : users) {
893 mConnector.execute("volume", "user_added", user.id, user.serialNumber);
894 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700895 for (int userId : systemUnlockedUsers) {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700896 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700897 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700898 } catch (NativeDaemonConnectorException e) {
899 Slog.w(TAG, "Failed to reset vold", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700900 }
901 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700902 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700903
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700904 private void onUnlockUser(int userId) {
905 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700906
907 // We purposefully block here to make sure that user-specific
908 // staging area is ready so it's ready for zygote-forked apps to
909 // bind mount against.
910 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700911 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700912 } catch (NativeDaemonConnectorException ignored) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700913 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700914
915 // Record user as started so newly mounted volumes kick off events
916 // correctly, then synthesize events for any already-mounted volumes.
917 synchronized (mVolumes) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700918 for (int i = 0; i < mVolumes.size(); i++) {
919 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700920 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700921 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700922 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700923
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700924 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
925 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700926 }
927 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700928 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700929 }
930 }
931
932 private void onCleanupUser(int userId) {
933 Slog.d(TAG, "onCleanupUser " + userId);
934
935 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700936 mConnector.execute("volume", "user_stopped", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700937 } catch (NativeDaemonConnectorException ignored) {
938 }
939
940 synchronized (mVolumes) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700941 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700942 }
943 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700944
Christopher Tated417d622013-08-19 16:14:25 -0700945 void runIdleMaintenance(Runnable callback) {
946 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
947 }
948
Christopher Tate7265abe2014-11-21 13:54:45 -0800949 // Binder entry point for kicking off an immediate fstrim
950 @Override
951 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700952 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -0800953 runIdleMaintenance(null);
954 }
955
956 @Override
957 public long lastMaintenance() {
958 return mLastMaintenance;
959 }
960
San Mehat4270e1e2010-01-29 05:32:19 -0800961 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800962 * Callback from NativeDaemonConnector
963 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700964 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800965 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700966 mDaemonConnected = true;
967 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
968 }
969
970 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700971 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800972 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -0700973
San Mehat4270e1e2010-01-29 05:32:19 -0800974 /*
Jeff Sharkey48877892015-03-18 11:27:19 -0700975 * Now that we've done our initialization, release
976 * the hounds!
San Mehat4270e1e2010-01-29 05:32:19 -0800977 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700978 mConnectedSignal.countDown();
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700979 if (mConnectedSignal.getCount() != 0) {
980 // More daemons need to connect
981 return;
982 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400983
Jeff Sharkey48877892015-03-18 11:27:19 -0700984 // On an encrypted device we can't see system properties yet, so pull
985 // the system locale out of the mount service.
986 if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
987 copyLocaleFromMountService();
988 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700989
Jeff Sharkey48877892015-03-18 11:27:19 -0700990 // Let package manager load internal ASECs.
991 mPms.scanAvailableAsecs();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400992
Jeff Sharkey48877892015-03-18 11:27:19 -0700993 // Notify people waiting for ASECs to be scanned that it's done.
994 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800995 }
996
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700997 private void copyLocaleFromMountService() {
998 String systemLocale;
999 try {
1000 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
1001 } catch (RemoteException e) {
1002 return;
1003 }
1004 if (TextUtils.isEmpty(systemLocale)) {
1005 return;
1006 }
1007
1008 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1009 Locale locale = Locale.forLanguageTag(systemLocale);
1010 Configuration config = new Configuration();
1011 config.setLocale(locale);
1012 try {
1013 ActivityManagerNative.getDefault().updateConfiguration(config);
1014 } catch (RemoteException e) {
1015 Slog.e(TAG, "Error setting system locale from mount service", e);
1016 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001017
1018 // Temporary workaround for http://b/17945169.
1019 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001020 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001021 }
1022
San Mehat4270e1e2010-01-29 05:32:19 -08001023 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001024 * Callback from NativeDaemonConnector
1025 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001026 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001027 public boolean onCheckHoldWakeLock(int code) {
1028 return false;
1029 }
1030
1031 /**
1032 * Callback from NativeDaemonConnector
1033 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001034 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001035 public boolean onEvent(int code, String raw, String[] cooked) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001036 synchronized (mLock) {
1037 return onEventLocked(code, raw, cooked);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001038 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001039 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001040
Jeff Sharkey48877892015-03-18 11:27:19 -07001041 private boolean onEventLocked(int code, String raw, String[] cooked) {
1042 switch (code) {
1043 case VoldResponseCode.DISK_CREATED: {
1044 if (cooked.length != 3) break;
1045 final String id = cooked[1];
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001046 int flags = Integer.parseInt(cooked[2]);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001047 if (SystemProperties.getBoolean(StorageManager.PROP_FORCE_ADOPTABLE, false)
1048 || mForceAdoptable) {
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001049 flags |= DiskInfo.FLAG_ADOPTABLE;
1050 }
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001051 mDisks.put(id, new DiskInfo(id, flags));
Jeff Sharkey48877892015-03-18 11:27:19 -07001052 break;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001053 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001054 case VoldResponseCode.DISK_SIZE_CHANGED: {
1055 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001056 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001057 if (disk != null) {
1058 disk.size = Long.parseLong(cooked[2]);
San Mehat4270e1e2010-01-29 05:32:19 -08001059 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001060 break;
1061 }
1062 case VoldResponseCode.DISK_LABEL_CHANGED: {
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) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001065 final StringBuilder builder = new StringBuilder();
1066 for (int i = 2; i < cooked.length; i++) {
1067 builder.append(cooked[i]).append(' ');
1068 }
1069 disk.label = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001070 }
1071 break;
1072 }
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001073 case VoldResponseCode.DISK_SCANNED: {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001074 if (cooked.length != 2) break;
1075 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001076 if (disk != null) {
1077 onDiskScannedLocked(disk);
1078 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -07001079 break;
1080 }
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001081 case VoldResponseCode.DISK_SYS_PATH_CHANGED: {
1082 if (cooked.length != 3) break;
1083 final DiskInfo disk = mDisks.get(cooked[1]);
1084 if (disk != null) {
1085 disk.sysPath = cooked[2];
1086 }
1087 break;
1088 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001089 case VoldResponseCode.DISK_DESTROYED: {
1090 if (cooked.length != 2) break;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07001091 final DiskInfo disk = mDisks.remove(cooked[1]);
1092 if (disk != null) {
1093 mCallbacks.notifyDiskDestroyed(disk);
1094 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001095 break;
1096 }
San Mehat4270e1e2010-01-29 05:32:19 -08001097
Jeff Sharkey48877892015-03-18 11:27:19 -07001098 case VoldResponseCode.VOLUME_CREATED: {
Jeff Sharkey48877892015-03-18 11:27:19 -07001099 final String id = cooked[1];
1100 final int type = Integer.parseInt(cooked[2]);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001101 final String diskId = TextUtils.nullIfEmpty(cooked[3]);
1102 final String partGuid = TextUtils.nullIfEmpty(cooked[4]);
1103
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001104 final DiskInfo disk = mDisks.get(diskId);
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07001105 final VolumeInfo vol = new VolumeInfo(id, type, disk, partGuid);
Jeff Sharkey48877892015-03-18 11:27:19 -07001106 mVolumes.put(id, vol);
1107 onVolumeCreatedLocked(vol);
1108 break;
1109 }
1110 case VoldResponseCode.VOLUME_STATE_CHANGED: {
1111 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001112 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001113 if (vol != null) {
1114 final int oldState = vol.state;
1115 final int newState = Integer.parseInt(cooked[2]);
1116 vol.state = newState;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001117 onVolumeStateChangedLocked(vol, oldState, newState);
Jeff Sharkey48877892015-03-18 11:27:19 -07001118 }
1119 break;
1120 }
1121 case VoldResponseCode.VOLUME_FS_TYPE_CHANGED: {
1122 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001123 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001124 if (vol != null) {
1125 vol.fsType = cooked[2];
1126 }
1127 break;
1128 }
1129 case VoldResponseCode.VOLUME_FS_UUID_CHANGED: {
1130 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001131 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001132 if (vol != null) {
1133 vol.fsUuid = cooked[2];
1134 }
1135 break;
1136 }
1137 case VoldResponseCode.VOLUME_FS_LABEL_CHANGED: {
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) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001140 final StringBuilder builder = new StringBuilder();
1141 for (int i = 2; i < cooked.length; i++) {
1142 builder.append(cooked[i]).append(' ');
1143 }
1144 vol.fsLabel = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001145 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001146 // TODO: notify listeners that label changed
Jeff Sharkey48877892015-03-18 11:27:19 -07001147 break;
1148 }
1149 case VoldResponseCode.VOLUME_PATH_CHANGED: {
1150 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001151 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001152 if (vol != null) {
1153 vol.path = cooked[2];
1154 }
1155 break;
1156 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001157 case VoldResponseCode.VOLUME_INTERNAL_PATH_CHANGED: {
1158 if (cooked.length != 3) break;
1159 final VolumeInfo vol = mVolumes.get(cooked[1]);
1160 if (vol != null) {
1161 vol.internalPath = cooked[2];
1162 }
1163 break;
1164 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001165 case VoldResponseCode.VOLUME_DESTROYED: {
1166 if (cooked.length != 2) break;
1167 mVolumes.remove(cooked[1]);
1168 break;
1169 }
San Mehat4270e1e2010-01-29 05:32:19 -08001170
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001171 case VoldResponseCode.MOVE_STATUS: {
1172 final int status = Integer.parseInt(cooked[1]);
1173 onMoveStatusLocked(status);
1174 break;
1175 }
Jeff Sharkey9756d752015-05-14 21:07:42 -07001176 case VoldResponseCode.BENCHMARK_RESULT: {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001177 if (cooked.length != 7) break;
1178 final String path = cooked[1];
1179 final String ident = cooked[2];
1180 final long create = Long.parseLong(cooked[3]);
1181 final long drop = Long.parseLong(cooked[4]);
1182 final long run = Long.parseLong(cooked[5]);
1183 final long destroy = Long.parseLong(cooked[6]);
1184
Jeff Sharkey9756d752015-05-14 21:07:42 -07001185 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001186 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1187 + " " + ident + " " + create + " " + run + " " + destroy);
1188
1189 final VolumeRecord rec = findRecordForPath(path);
1190 if (rec != null) {
1191 rec.lastBenchMillis = System.currentTimeMillis();
1192 writeSettingsLocked();
1193 }
1194
1195 break;
1196 }
1197 case VoldResponseCode.TRIM_RESULT: {
1198 if (cooked.length != 4) break;
1199 final String path = cooked[1];
1200 final long bytes = Long.parseLong(cooked[2]);
1201 final long time = Long.parseLong(cooked[3]);
1202
1203 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1204 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path)
1205 + " " + bytes + " " + time);
1206
1207 final VolumeRecord rec = findRecordForPath(path);
1208 if (rec != null) {
1209 rec.lastTrimMillis = System.currentTimeMillis();
1210 writeSettingsLocked();
1211 }
1212
Jeff Sharkey9756d752015-05-14 21:07:42 -07001213 break;
1214 }
1215
Jeff Sharkey48877892015-03-18 11:27:19 -07001216 default: {
1217 Slog.d(TAG, "Unhandled vold event " + code);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001218 }
San Mehat4270e1e2010-01-29 05:32:19 -08001219 }
1220
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001221 return true;
San Mehat4270e1e2010-01-29 05:32:19 -08001222 }
1223
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001224 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001225 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001226 for (int i = 0; i < mVolumes.size(); i++) {
1227 final VolumeInfo vol = mVolumes.valueAt(i);
1228 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001229 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001230 }
1231 }
1232
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001233 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
1234 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1235 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1236 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001237 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001238
1239 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1240 if (latch != null) {
1241 latch.countDown();
1242 }
1243
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001244 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001245 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001246 }
1247
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001248 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001249 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1250 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1251 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1252
1253 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1254 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1255 Slog.v(TAG, "Found primary storage at " + vol);
1256 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1257 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1258 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1259
1260 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1261 Slog.v(TAG, "Found primary storage at " + vol);
1262 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1263 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1264 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1265 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001266
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001267 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001268 // TODO: only look at first public partition
1269 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1270 && vol.disk.isDefaultPrimary()) {
1271 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001272 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1273 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001274 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001275
1276 // Adoptable public disks are visible to apps, since they meet
1277 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001278 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001279 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1280 }
1281
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001282 vol.mountUserId = ActivityManager.getCurrentUser();
Jeff Sharkey48877892015-03-18 11:27:19 -07001283 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001284
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001285 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1286 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1287
San Mehat4270e1e2010-01-29 05:32:19 -08001288 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001289 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001290 }
1291 }
1292
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001293 private boolean isBroadcastWorthy(VolumeInfo vol) {
1294 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001295 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001296 case VolumeInfo.TYPE_PUBLIC:
1297 case VolumeInfo.TYPE_EMULATED:
1298 break;
1299 default:
1300 return false;
1301 }
1302
1303 switch (vol.getState()) {
1304 case VolumeInfo.STATE_MOUNTED:
1305 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1306 case VolumeInfo.STATE_EJECTING:
1307 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001308 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001309 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001310 break;
1311 default:
1312 return false;
1313 }
1314
1315 return true;
1316 }
1317
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001318 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001319 // Remember that we saw this volume so we're ready to accept user
1320 // metadata, or so we can annoy them when a private volume is ejected
1321 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001322 VolumeRecord rec = mRecords.get(vol.fsUuid);
1323 if (rec == null) {
1324 rec = new VolumeRecord(vol.type, vol.fsUuid);
1325 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001326 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001327 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1328 rec.nickname = vol.disk.getDescription();
1329 }
1330 mRecords.put(rec.fsUuid, rec);
1331 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001332 } else {
1333 // Handle upgrade case where we didn't store partition GUID
1334 if (TextUtils.isEmpty(rec.partGuid)) {
1335 rec.partGuid = vol.partGuid;
1336 writeSettingsLocked();
1337 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001338 }
1339 }
1340
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001341 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1342
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001343 // Do not broadcast before boot has completed to avoid launching the
1344 // processes that receive the intent unnecessarily.
1345 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001346 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001347 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1348 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001349 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001350 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001351 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001352 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001353
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001354 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1355 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001356
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001357 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1358 // Kick state changed event towards all started users. Any users
1359 // started after this point will trigger additional
1360 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001361 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001362 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001363 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001364 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001365
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001366 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1367 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001368 }
1369 }
1370 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001371
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001372 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001373 // TODO: this should eventually be handled by new ObbVolume state changes
1374 /*
1375 * Some OBBs might have been unmounted when this volume was
1376 * unmounted, so send a message to the handler to let it know to
1377 * remove those from the list of mounted OBBS.
1378 */
1379 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1380 OBB_FLUSH_MOUNT_STATE, vol.path));
1381 }
San Mehat4270e1e2010-01-29 05:32:19 -08001382 }
1383
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001384 private void onMoveStatusLocked(int status) {
1385 if (mMoveCallback == null) {
1386 Slog.w(TAG, "Odd, status but no move requested");
1387 return;
1388 }
1389
1390 // TODO: estimate remaining time
1391 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001392 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001393 } catch (RemoteException ignored) {
1394 }
1395
1396 // We've finished copying and we're about to clean up old data, so
1397 // remember that move was successful if we get rebooted
1398 if (status == MOVE_STATUS_COPY_FINISHED) {
1399 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1400
1401 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001402 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001403 }
1404
1405 if (PackageManager.isMoveStatusFinished(status)) {
1406 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1407
1408 mMoveCallback = null;
1409 mMoveTargetUuid = null;
1410 }
1411 }
1412
Jeff Sharkey48877892015-03-18 11:27:19 -07001413 private void enforcePermission(String perm) {
1414 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001415 }
1416
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001417 /**
1418 * Decide if volume is mountable per device policies.
1419 */
1420 private boolean isMountDisallowed(VolumeInfo vol) {
1421 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE) {
1422 final UserManager userManager = mContext.getSystemService(UserManager.class);
1423 return userManager.hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1424 Binder.getCallingUserHandle());
1425 } else {
1426 return false;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001427 }
1428 }
1429
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001430 private void enforceAdminUser() {
1431 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1432 final int callingUserId = UserHandle.getCallingUserId();
1433 boolean isAdmin;
1434 long token = Binder.clearCallingIdentity();
1435 try {
1436 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1437 } finally {
1438 Binder.restoreCallingIdentity(token);
1439 }
1440 if (!isAdmin) {
1441 throw new SecurityException("Only admin users can adopt sd cards");
1442 }
1443 }
1444
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001445 /**
San Mehat207e5382010-02-04 20:46:54 -08001446 * Constructs a new MountService instance
1447 *
1448 * @param context Binder context for this service
1449 */
1450 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001451 sSelf = this;
1452
San Mehat207e5382010-02-04 20:46:54 -08001453 mContext = context;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001454 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001455 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001456
San Mehat207e5382010-02-04 20:46:54 -08001457 // XXX: This will go away soon in favor of IMountServiceObserver
1458 mPms = (PackageManagerService) ServiceManager.getService("package");
1459
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001460 HandlerThread hthread = new HandlerThread(TAG);
1461 hthread.start();
1462 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001463
Kenny Roota02b8b02010-08-05 16:14:17 -07001464 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001465 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001466
Christopher Tate7265abe2014-11-21 13:54:45 -08001467 // Initialize the last-fstrim tracking if necessary
1468 File dataDir = Environment.getDataDirectory();
1469 File systemDir = new File(dataDir, "system");
1470 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1471 if (!mLastMaintenanceFile.exists()) {
1472 // Not setting mLastMaintenance here means that we will force an
1473 // fstrim during reboot following the OTA that installs this code.
1474 try {
1475 (new FileOutputStream(mLastMaintenanceFile)).close();
1476 } catch (IOException e) {
1477 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1478 }
1479 } else {
1480 mLastMaintenance = mLastMaintenanceFile.lastModified();
1481 }
1482
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001483 mSettingsFile = new AtomicFile(
Jeff Sharkey8212ae02016-02-10 14:46:43 -07001484 new File(Environment.getDataSystemDirectory(), "storage.xml"));
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001485
1486 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001487 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001488 }
1489
Svet Ganov6ee871e2015-07-10 14:29:33 -07001490 LocalServices.addService(MountServiceInternal.class, mMountServiceInternal);
1491
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001492 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001493 * Create the connection to vold with a maximum queue of twice the
1494 * amount of containers we'd ever expect to have. This keeps an
1495 * "asec list" from blocking a thread repeatedly.
1496 */
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001497
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001498 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1499 null);
Jeff Sharkey48877892015-03-18 11:27:19 -07001500 mConnector.setDebug(true);
Jeff Sharkey8948c012015-11-03 12:33:54 -08001501 mConnector.setWarnIfHeld(mLock);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001502 mConnectorThread = new Thread(mConnector, VOLD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001503
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001504 // Reuse parameters from first connector since they are tested and safe
1505 mCryptConnector = new NativeDaemonConnector(this, "cryptd",
1506 MAX_CONTAINERS * 2, CRYPTD_TAG, 25, null);
1507 mCryptConnector.setDebug(true);
Jeff Sharkeycd575992016-03-29 14:12:49 -06001508 mCryptConnectorThread = new Thread(mCryptConnector, CRYPTD_TAG);
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001509
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001510 final IntentFilter userFilter = new IntentFilter();
1511 userFilter.addAction(Intent.ACTION_USER_ADDED);
1512 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1513 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1514
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001515 synchronized (mLock) {
1516 addInternalVolumeLocked();
1517 }
Amith Yamasania7892482015-08-07 11:09:05 -07001518
Kenny Root07714d42011-08-17 17:49:28 -07001519 // Add ourself to the Watchdog monitors if enabled.
1520 if (WATCHDOG_ENABLE) {
1521 Watchdog.getInstance().addMonitor(this);
1522 }
San Mehat207e5382010-02-04 20:46:54 -08001523 }
1524
Jeff Sharkeycd575992016-03-29 14:12:49 -06001525 private void start() {
1526 mConnectorThread.start();
1527 mCryptConnectorThread.start();
1528 }
1529
Jeff Sharkey56e62932015-03-21 20:41:00 -07001530 private void systemReady() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001531 mSystemReady = true;
1532 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1533 }
1534
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001535 private void bootCompleted() {
1536 mBootCompleted = true;
1537 }
1538
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001539 private String getDefaultPrimaryStorageUuid() {
1540 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1541 return StorageManager.UUID_PRIMARY_PHYSICAL;
1542 } else {
1543 return StorageManager.UUID_PRIVATE_INTERNAL;
1544 }
1545 }
1546
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001547 private void readSettingsLocked() {
1548 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001549 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001550 mForceAdoptable = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001551
1552 FileInputStream fis = null;
1553 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001554 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001555 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001556 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001557
1558 int type;
1559 while ((type = in.next()) != END_DOCUMENT) {
1560 if (type == START_TAG) {
1561 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001562 if (TAG_VOLUMES.equals(tag)) {
1563 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001564 final boolean primaryPhysical = SystemProperties.getBoolean(
1565 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1566 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1567 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1568 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001569 mPrimaryStorageUuid = readStringAttribute(in,
1570 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001571 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001572 mForceAdoptable = readBooleanAttribute(in, ATTR_FORCE_ADOPTABLE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001573
1574 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001575 final VolumeRecord rec = readVolumeRecord(in);
1576 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001577 }
1578 }
1579 }
1580 } catch (FileNotFoundException e) {
1581 // Missing metadata is okay, probably first boot
1582 } catch (IOException e) {
1583 Slog.wtf(TAG, "Failed reading metadata", e);
1584 } catch (XmlPullParserException e) {
1585 Slog.wtf(TAG, "Failed reading metadata", e);
1586 } finally {
1587 IoUtils.closeQuietly(fis);
1588 }
1589 }
1590
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001591 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001592 FileOutputStream fos = null;
1593 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001594 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001595
1596 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001597 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001598 out.startDocument(null, true);
1599 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001600 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001601 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001602 writeBooleanAttribute(out, ATTR_FORCE_ADOPTABLE, mForceAdoptable);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001603 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001604 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001605 final VolumeRecord rec = mRecords.valueAt(i);
1606 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001607 }
1608 out.endTag(null, TAG_VOLUMES);
1609 out.endDocument();
1610
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001611 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001612 } catch (IOException e) {
1613 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001614 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001615 }
1616 }
1617 }
1618
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001619 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1620 final int type = readIntAttribute(in, ATTR_TYPE);
1621 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1622 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001623 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001624 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1625 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001626 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1627 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1628 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001629 return meta;
1630 }
1631
1632 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1633 out.startTag(null, TAG_VOLUME);
1634 writeIntAttribute(out, ATTR_TYPE, rec.type);
1635 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001636 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001637 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1638 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001639 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1640 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1641 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001642 out.endTag(null, TAG_VOLUME);
1643 }
1644
San Mehat207e5382010-02-04 20:46:54 -08001645 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001646 * Exposed API calls below here
1647 */
1648
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001649 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001650 public void registerListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001651 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001652 }
1653
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001654 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001655 public void unregisterListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001656 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001657 }
1658
Jeff Sharkey48877892015-03-18 11:27:19 -07001659 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001660 public void shutdown(final IMountShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001661 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001662
San Mehata5078592010-03-25 09:36:54 -07001663 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001664 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001665 }
1666
Jeff Sharkey48877892015-03-18 11:27:19 -07001667 @Override
San Mehatb1043402010-02-05 08:26:50 -08001668 public boolean isUsbMassStorageConnected() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001669 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001670 }
1671
Jeff Sharkey48877892015-03-18 11:27:19 -07001672 @Override
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001673 public void setUsbMassStorageEnabled(boolean enable) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001674 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001675 }
1676
Jeff Sharkey48877892015-03-18 11:27:19 -07001677 @Override
San Mehatb1043402010-02-05 08:26:50 -08001678 public boolean isUsbMassStorageEnabled() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001679 throw new UnsupportedOperationException();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001681
Jeff Sharkey48877892015-03-18 11:27:19 -07001682 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001683 public String getVolumeState(String mountPoint) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001684 throw new UnsupportedOperationException();
San Mehat7fd0fee2009-12-17 07:12:23 -08001685 }
1686
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001687 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001688 public boolean isExternalStorageEmulated() {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001689 throw new UnsupportedOperationException();
Kenny Roote1ff2142010-10-12 11:20:01 -07001690 }
1691
Jeff Sharkey48877892015-03-18 11:27:19 -07001692 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001693 public int mountVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001694 mount(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001695 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697
Jeff Sharkey48877892015-03-18 11:27:19 -07001698 @Override
Ben Komalo13c71972011-09-07 16:35:56 -07001699 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001700 unmount(findVolumeIdForPathOrThrow(path));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702
Jeff Sharkey48877892015-03-18 11:27:19 -07001703 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001704 public int formatVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001705 format(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001706 return 0;
1707 }
1708
1709 @Override
1710 public void mount(String volId) {
1711 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1712 waitForReady();
1713
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001714 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001715 if (isMountDisallowed(vol)) {
1716 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001717 }
1718 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001719 mConnector.execute("volume", "mount", vol.id, vol.mountFlags, vol.mountUserId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001720 } catch (NativeDaemonConnectorException e) {
1721 throw e.rethrowAsParcelableException();
1722 }
1723 }
1724
1725 @Override
1726 public void unmount(String volId) {
1727 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1728 waitForReady();
1729
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001730 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001731
1732 // TODO: expand PMS to know about multiple volumes
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001733 if (vol.isPrimaryPhysical()) {
1734 final long ident = Binder.clearCallingIdentity();
1735 try {
1736 synchronized (mUnmountLock) {
1737 mUnmountSignal = new CountDownLatch(1);
1738 mPms.updateExternalMediaStatus(false, true);
1739 waitForLatch(mUnmountSignal, "mUnmountSignal");
1740 mUnmountSignal = null;
1741 }
1742 } finally {
1743 Binder.restoreCallingIdentity(ident);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001744 }
1745 }
1746
1747 try {
1748 mConnector.execute("volume", "unmount", vol.id);
1749 } catch (NativeDaemonConnectorException e) {
1750 throw e.rethrowAsParcelableException();
1751 }
1752 }
1753
1754 @Override
1755 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001756 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001757 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001758
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001759 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001760 try {
Jeff Sharkey4e83cc92015-05-27 14:38:39 -07001761 mConnector.execute("volume", "format", vol.id, "auto");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001762 } catch (NativeDaemonConnectorException e) {
1763 throw e.rethrowAsParcelableException();
Jeff Sharkey48877892015-03-18 11:27:19 -07001764 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001765 }
1766
1767 @Override
Jeff Sharkey9756d752015-05-14 21:07:42 -07001768 public long benchmark(String volId) {
1769 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1770 waitForReady();
1771
1772 try {
Jeff Sharkey14cbe522015-07-08 14:06:37 -07001773 // TODO: make benchmark async so we don't block other commands
1774 final NativeDaemonEvent res = mConnector.execute(3 * DateUtils.MINUTE_IN_MILLIS,
1775 "volume", "benchmark", volId);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001776 return Long.parseLong(res.getMessage());
Todd Kennedy8101ee62015-06-23 13:35:28 -07001777 } catch (NativeDaemonTimeoutException e) {
1778 return Long.MAX_VALUE;
Jeff Sharkey9756d752015-05-14 21:07:42 -07001779 } catch (NativeDaemonConnectorException e) {
1780 throw e.rethrowAsParcelableException();
1781 }
1782 }
1783
1784 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001785 public void partitionPublic(String diskId) {
1786 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1787 waitForReady();
1788
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001789 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001790 try {
1791 mConnector.execute("volume", "partition", diskId, "public");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001792 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001793 } catch (NativeDaemonConnectorException e) {
1794 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001795 } catch (TimeoutException e) {
1796 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001797 }
1798 }
1799
1800 @Override
1801 public void partitionPrivate(String diskId) {
1802 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001803 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001804 waitForReady();
1805
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001806 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001807 try {
1808 mConnector.execute("volume", "partition", diskId, "private");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001809 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001810 } catch (NativeDaemonConnectorException e) {
1811 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001812 } catch (TimeoutException e) {
1813 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001814 }
1815 }
1816
1817 @Override
1818 public void partitionMixed(String diskId, int ratio) {
1819 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001820 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001821 waitForReady();
1822
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001823 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001824 try {
1825 mConnector.execute("volume", "partition", diskId, "mixed", ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001826 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001827 } catch (NativeDaemonConnectorException e) {
1828 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001829 } catch (TimeoutException e) {
1830 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
1833
Jeff Sharkey48877892015-03-18 11:27:19 -07001834 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001835 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001836 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1837 waitForReady();
1838
Jeff Sharkey50a05452015-04-29 11:24:52 -07001839 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001840 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001841 final VolumeRecord rec = mRecords.get(fsUuid);
1842 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07001843 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001844 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001845 }
1846 }
1847
1848 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001849 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
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.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001857 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001858 writeSettingsLocked();
1859 }
1860 }
1861
1862 @Override
1863 public void forgetVolume(String fsUuid) {
1864 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1865 waitForReady();
1866
Jeff Sharkey50a05452015-04-29 11:24:52 -07001867 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001868
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001869 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001870 final VolumeRecord rec = mRecords.remove(fsUuid);
1871 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001872 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001873 }
1874 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001875
1876 // If this had been primary storage, revert back to internal and
1877 // reset vold so we bind into new volume into place.
1878 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001879 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001880 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001881 }
1882
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001883 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001884 }
1885 }
1886
Jeff Sharkey7d2af542015-05-12 15:27:15 -07001887 @Override
1888 public void forgetAllVolumes() {
1889 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1890 waitForReady();
1891
Jeff Sharkey50a05452015-04-29 11:24:52 -07001892 synchronized (mLock) {
1893 for (int i = 0; i < mRecords.size(); i++) {
1894 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001895 final VolumeRecord rec = mRecords.valueAt(i);
1896 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001897 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001898 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001899 mCallbacks.notifyVolumeForgotten(fsUuid);
1900 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001901 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001902
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001903 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
1904 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
1905 }
1906
1907 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001908 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001909 }
1910 }
1911
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001912 private void forgetPartition(String partGuid) {
1913 try {
1914 mConnector.execute("volume", "forget_partition", partGuid);
1915 } catch (NativeDaemonConnectorException e) {
1916 Slog.w(TAG, "Failed to forget key for " + partGuid + ": " + e);
1917 }
1918 }
1919
Svet Ganov6ee871e2015-07-10 14:29:33 -07001920 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07001921 waitForReady();
1922
Svet Ganov6ee871e2015-07-10 14:29:33 -07001923 String modeName = "none";
1924 switch (mode) {
1925 case Zygote.MOUNT_EXTERNAL_DEFAULT: {
1926 modeName = "default";
1927 } break;
1928
1929 case Zygote.MOUNT_EXTERNAL_READ: {
1930 modeName = "read";
1931 } break;
1932
1933 case Zygote.MOUNT_EXTERNAL_WRITE: {
1934 modeName = "write";
1935 } break;
Jeff Sharkey9527b222015-06-24 15:24:48 -07001936 }
1937
1938 try {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001939 mConnector.execute("volume", "remount_uid", uid, modeName);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001940 } catch (NativeDaemonConnectorException e) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001941 Slog.w(TAG, "Failed to remount UID " + uid + " as " + modeName + ": " + e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001942 }
1943 }
1944
1945 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001946 public void setDebugFlags(int flags, int mask) {
1947 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1948 waitForReady();
1949
Jeff Sharkeyba512352015-11-12 20:17:45 -08001950 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Paul Lawrence20be5d62016-02-26 13:51:17 -08001951 if (StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001952 throw new IllegalStateException(
1953 "Emulation not available on device with native FBE");
1954 }
Jeff Sharkey5a785162016-03-21 13:02:06 -06001955 if (mLockPatternUtils.isCredentialRequiredToDecrypt(false)) {
1956 throw new IllegalStateException(
1957 "Emulation requires disabling 'Secure start-up' in Settings > Security");
1958 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001959
Jeff Sharkey1176e512016-02-29 17:01:26 -07001960 final long token = Binder.clearCallingIdentity();
1961 try {
1962 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
1963 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001964
Jeff Sharkey1176e512016-02-29 17:01:26 -07001965 // Perform hard reboot to kick policy into place
1966 mContext.getSystemService(PowerManager.class).reboot(null);
1967 } finally {
1968 Binder.restoreCallingIdentity(token);
1969 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08001970 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001971
Jeff Sharkeyba512352015-11-12 20:17:45 -08001972 if ((mask & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0) {
1973 synchronized (mLock) {
1974 mForceAdoptable = (flags & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0;
1975
1976 writeSettingsLocked();
1977 mHandler.obtainMessage(H_RESET).sendToTarget();
1978 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001979 }
1980 }
1981
1982 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001983 public String getPrimaryStorageUuid() {
1984 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1985 waitForReady();
1986
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001987 synchronized (mLock) {
1988 return mPrimaryStorageUuid;
1989 }
1990 }
1991
1992 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001993 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
1994 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1995 waitForReady();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001996
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001997 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001998 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
1999 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002000 }
2001
2002 if (mMoveCallback != null) {
2003 throw new IllegalStateException("Move already in progress");
2004 }
2005 mMoveCallback = callback;
2006 mMoveTargetUuid = volumeUuid;
2007
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002008 // When moving to/from primary physical volume, we probably just nuked
2009 // the current storage location, so we have nothing to move.
2010 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
2011 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
2012 Slog.d(TAG, "Skipping move to/from primary physical");
2013 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
2014 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002015 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002016
2017 } else {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002018 final VolumeInfo from = findStorageForUuid(mPrimaryStorageUuid);
2019 final VolumeInfo to = findStorageForUuid(volumeUuid);
2020
2021 if (from == null) {
2022 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2023 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2024 return;
2025 } else if (to == null) {
2026 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2027 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2028 return;
2029 }
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002030
2031 try {
2032 mConnector.execute("volume", "move_storage", from.id, to.id);
2033 } catch (NativeDaemonConnectorException e) {
2034 throw e.rethrowAsParcelableException();
2035 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002036 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002037 }
2038 }
2039
2040 @Override
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07002041 public int[] getStorageUsers(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002042 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatc1b4ce92010-02-16 17:13:03 -08002043 waitForReady();
2044 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002045 final String[] r = NativeDaemonEvent.filterMessageList(
2046 mConnector.executeForList("storage", "users", path),
2047 VoldResponseCode.StorageUsersListResult);
2048
San Mehatc1b4ce92010-02-16 17:13:03 -08002049 // FMT: <pid> <process name>
2050 int[] data = new int[r.length];
2051 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002052 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08002053 try {
2054 data[i] = Integer.parseInt(tok[0]);
2055 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07002056 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08002057 return new int[0];
2058 }
2059 }
2060 return data;
2061 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07002062 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08002063 return new int[0];
2064 }
2065 }
2066
San Mehatb1043402010-02-05 08:26:50 -08002067 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002068 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002069 for (int i = 0; i < mVolumes.size(); i++) {
2070 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002071 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002072 // Cool beans, we have a mounted primary volume
2073 return;
2074 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002075 }
San Mehatb1043402010-02-05 08:26:50 -08002076 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002077
2078 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002079 }
2080
San Mehat4270e1e2010-01-29 05:32:19 -08002081 public String[] getSecureContainerList() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002082 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002083 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002084 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002085
San Mehat4270e1e2010-01-29 05:32:19 -08002086 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002087 return NativeDaemonEvent.filterMessageList(
2088 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08002089 } catch (NativeDaemonConnectorException e) {
2090 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
San Mehat36972292010-01-06 11:06:32 -08002093
Kenny Root6dceb882012-04-12 14:23:49 -07002094 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
2095 int ownerUid, boolean external) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002096 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08002097 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002098 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002099
San Mehatb1043402010-02-05 08:26:50 -08002100 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002101 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002102 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
2103 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08002104 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002105 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002106 }
San Mehata181b212010-02-11 06:50:20 -08002107
2108 if (rc == StorageResultCode.OperationSucceeded) {
2109 synchronized (mAsecMountSet) {
2110 mAsecMountSet.add(id);
2111 }
2112 }
San Mehat4270e1e2010-01-29 05:32:19 -08002113 return rc;
San Mehat36972292010-01-06 11:06:32 -08002114 }
2115
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002116 @Override
2117 public int resizeSecureContainer(String id, int sizeMb, String key) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002118 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002119 waitForReady();
2120 warnOnNotMounted();
2121
2122 int rc = StorageResultCode.OperationSucceeded;
2123 try {
2124 mConnector.execute("asec", "resize", id, sizeMb, new SensitiveArg(key));
2125 } catch (NativeDaemonConnectorException e) {
2126 rc = StorageResultCode.OperationFailedInternalError;
2127 }
2128 return rc;
2129 }
2130
San Mehat4270e1e2010-01-29 05:32:19 -08002131 public int finalizeSecureContainer(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002132 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08002133 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002134
San Mehatb1043402010-02-05 08:26:50 -08002135 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002136 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002137 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08002138 /*
2139 * Finalization does a remount, so no need
2140 * to update mAsecMountSet
2141 */
San Mehat4270e1e2010-01-29 05:32:19 -08002142 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002143 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002144 }
San Mehat4270e1e2010-01-29 05:32:19 -08002145 return rc;
San Mehat36972292010-01-06 11:06:32 -08002146 }
2147
Kenny Root6dceb882012-04-12 14:23:49 -07002148 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002149 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Kenny Root6dceb882012-04-12 14:23:49 -07002150 warnOnNotMounted();
2151
2152 int rc = StorageResultCode.OperationSucceeded;
2153 try {
2154 mConnector.execute("asec", "fixperms", id, gid, filename);
2155 /*
2156 * Fix permissions does a remount, so no need to update
2157 * mAsecMountSet
2158 */
2159 } catch (NativeDaemonConnectorException e) {
2160 rc = StorageResultCode.OperationFailedInternalError;
2161 }
2162 return rc;
2163 }
2164
San Mehatd9709982010-02-18 11:43:03 -08002165 public int destroySecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002166 enforcePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08002167 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002168 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002169
Kenny Rootaa485402010-09-14 14:49:41 -07002170 /*
2171 * Force a GC to make sure AssetManagers in other threads of the
2172 * system_server are cleaned up. We have to do this since AssetManager
2173 * instances are kept as a WeakReference and it's possible we have files
2174 * open on the external storage.
2175 */
2176 Runtime.getRuntime().gc();
2177
San Mehatb1043402010-02-05 08:26:50 -08002178 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002179 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002180 final Command cmd = new Command("asec", "destroy", id);
2181 if (force) {
2182 cmd.appendArg("force");
2183 }
2184 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002185 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002186 int code = e.getCode();
2187 if (code == VoldResponseCode.OpFailedStorageBusy) {
2188 rc = StorageResultCode.OperationFailedStorageBusy;
2189 } else {
2190 rc = StorageResultCode.OperationFailedInternalError;
2191 }
San Mehat02735bc2010-01-26 15:18:08 -08002192 }
San Mehata181b212010-02-11 06:50:20 -08002193
2194 if (rc == StorageResultCode.OperationSucceeded) {
2195 synchronized (mAsecMountSet) {
2196 if (mAsecMountSet.contains(id)) {
2197 mAsecMountSet.remove(id);
2198 }
2199 }
2200 }
2201
San Mehat4270e1e2010-01-29 05:32:19 -08002202 return rc;
San Mehat36972292010-01-06 11:06:32 -08002203 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002204
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002205 public int mountSecureContainer(String id, String key, int ownerUid, boolean readOnly) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002206 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002207 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002208 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002209
San Mehata181b212010-02-11 06:50:20 -08002210 synchronized (mAsecMountSet) {
2211 if (mAsecMountSet.contains(id)) {
2212 return StorageResultCode.OperationFailedStorageMounted;
2213 }
2214 }
2215
San Mehatb1043402010-02-05 08:26:50 -08002216 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002217 try {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002218 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid,
2219 readOnly ? "ro" : "rw");
San Mehat4270e1e2010-01-29 05:32:19 -08002220 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07002221 int code = e.getCode();
2222 if (code != VoldResponseCode.OpFailedStorageBusy) {
2223 rc = StorageResultCode.OperationFailedInternalError;
2224 }
San Mehat02735bc2010-01-26 15:18:08 -08002225 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002226
2227 if (rc == StorageResultCode.OperationSucceeded) {
2228 synchronized (mAsecMountSet) {
2229 mAsecMountSet.add(id);
2230 }
2231 }
San Mehat4270e1e2010-01-29 05:32:19 -08002232 return rc;
San Mehat36972292010-01-06 11:06:32 -08002233 }
2234
San Mehatd9709982010-02-18 11:43:03 -08002235 public int unmountSecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002236 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002237 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002238 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002239
San Mehat6cdd9c02010-02-09 14:45:20 -08002240 synchronized (mAsecMountSet) {
2241 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08002242 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08002243 }
2244 }
2245
Kenny Rootaa485402010-09-14 14:49:41 -07002246 /*
2247 * Force a GC to make sure AssetManagers in other threads of the
2248 * system_server are cleaned up. We have to do this since AssetManager
2249 * instances are kept as a WeakReference and it's possible we have files
2250 * open on the external storage.
2251 */
2252 Runtime.getRuntime().gc();
2253
San Mehatb1043402010-02-05 08:26:50 -08002254 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002255 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002256 final Command cmd = new Command("asec", "unmount", id);
2257 if (force) {
2258 cmd.appendArg("force");
2259 }
2260 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002261 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002262 int code = e.getCode();
2263 if (code == VoldResponseCode.OpFailedStorageBusy) {
2264 rc = StorageResultCode.OperationFailedStorageBusy;
2265 } else {
2266 rc = StorageResultCode.OperationFailedInternalError;
2267 }
San Mehat02735bc2010-01-26 15:18:08 -08002268 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002269
2270 if (rc == StorageResultCode.OperationSucceeded) {
2271 synchronized (mAsecMountSet) {
2272 mAsecMountSet.remove(id);
2273 }
2274 }
San Mehat4270e1e2010-01-29 05:32:19 -08002275 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08002276 }
2277
San Mehat6cdd9c02010-02-09 14:45:20 -08002278 public boolean isSecureContainerMounted(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002279 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat6cdd9c02010-02-09 14:45:20 -08002280 waitForReady();
2281 warnOnNotMounted();
2282
2283 synchronized (mAsecMountSet) {
2284 return mAsecMountSet.contains(id);
2285 }
2286 }
2287
San Mehat4270e1e2010-01-29 05:32:19 -08002288 public int renameSecureContainer(String oldId, String newId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002289 enforcePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08002290 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002291 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002292
San Mehata181b212010-02-11 06:50:20 -08002293 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08002294 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06002295 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08002296 * changed while active, we must ensure both ids are not currently mounted.
2297 */
2298 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08002299 return StorageResultCode.OperationFailedStorageMounted;
2300 }
2301 }
2302
San Mehatb1043402010-02-05 08:26:50 -08002303 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002304 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002305 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08002306 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002307 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002308 }
San Mehata181b212010-02-11 06:50:20 -08002309
San Mehat4270e1e2010-01-29 05:32:19 -08002310 return rc;
San Mehat45f61042010-01-23 08:12:43 -08002311 }
2312
San Mehat4270e1e2010-01-29 05:32:19 -08002313 public String getSecureContainerPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002314 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002315 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002316 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002317
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002318 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07002319 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002320 event = mConnector.execute("asec", "path", id);
2321 event.checkCode(VoldResponseCode.AsecPathResult);
2322 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07002323 } catch (NativeDaemonConnectorException e) {
2324 int code = e.getCode();
2325 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01002326 Slog.i(TAG, String.format("Container '%s' not found", id));
2327 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08002328 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07002329 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08002330 }
2331 }
San Mehat22dd86e2010-01-12 12:21:18 -08002332 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002333
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002334 public String getSecureContainerFilesystemPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002335 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002336 waitForReady();
2337 warnOnNotMounted();
2338
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002339 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002340 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002341 event = mConnector.execute("asec", "fspath", id);
2342 event.checkCode(VoldResponseCode.AsecPathResult);
2343 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002344 } catch (NativeDaemonConnectorException e) {
2345 int code = e.getCode();
2346 if (code == VoldResponseCode.OpFailedStorageNotFound) {
2347 Slog.i(TAG, String.format("Container '%s' not found", id));
2348 return null;
2349 } else {
2350 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2351 }
2352 }
2353 }
2354
Jeff Sharkey48877892015-03-18 11:27:19 -07002355 @Override
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002356 public void finishMediaUpdate() {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002357 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Rubin Xucd7a0142015-04-17 23:45:27 +01002358 throw new SecurityException("no permission to call finishMediaUpdate()");
2359 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002360 if (mUnmountSignal != null) {
2361 mUnmountSignal.countDown();
2362 } else {
2363 Slog.w(TAG, "Odd, nobody asked to unmount?");
2364 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002365 }
Kenny Root02c87302010-07-01 08:10:18 -07002366
Kenny Roota02b8b02010-08-05 16:14:17 -07002367 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2368 if (callerUid == android.os.Process.SYSTEM_UID) {
2369 return true;
2370 }
2371
Kenny Root02c87302010-07-01 08:10:18 -07002372 if (packageName == null) {
2373 return false;
2374 }
2375
Jeff Sharkeycd654482016-01-08 17:42:11 -07002376 final int packageUid = mPms.getPackageUid(packageName,
2377 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002378
2379 if (DEBUG_OBB) {
2380 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2381 packageUid + ", callerUid = " + callerUid);
2382 }
2383
2384 return callerUid == packageUid;
2385 }
2386
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002387 public String getMountedObbPath(String rawPath) {
2388 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002389
Kenny Root02c87302010-07-01 08:10:18 -07002390 waitForReady();
2391 warnOnNotMounted();
2392
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002393 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002394 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002395 state = mObbPathToStateMap.get(rawPath);
2396 }
2397 if (state == null) {
2398 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2399 return null;
2400 }
2401
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002402 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002403 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002404 event = mConnector.execute("obb", "path", state.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002405 event.checkCode(VoldResponseCode.AsecPathResult);
2406 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002407 } catch (NativeDaemonConnectorException e) {
2408 int code = e.getCode();
2409 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002410 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002411 } else {
2412 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2413 }
2414 }
2415 }
2416
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002417 @Override
2418 public boolean isObbMounted(String rawPath) {
2419 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002420 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002422 }
Kenny Root02c87302010-07-01 08:10:18 -07002423 }
2424
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002425 @Override
2426 public void mountObb(
2427 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2428 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2429 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2430 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002431
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002432 final int callingUid = Binder.getCallingUid();
2433 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2434 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002435 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2436
2437 if (DEBUG_OBB)
2438 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002439 }
2440
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002441 @Override
2442 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2443 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2444
2445 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002446 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002447 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002448 }
2449
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002450 if (existingState != null) {
2451 // TODO: separate state object from request data
2452 final int callingUid = Binder.getCallingUid();
2453 final ObbState newState = new ObbState(
2454 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2455 final ObbAction action = new UnmountObbAction(newState, force);
2456 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002457
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002458 if (DEBUG_OBB)
2459 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2460 } else {
2461 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2462 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002463 }
2464
Ben Komalo444eca22011-09-01 15:17:44 -07002465 @Override
2466 public int getEncryptionState() {
2467 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2468 "no permission to access the crypt keeper");
2469
2470 waitForReady();
2471
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002472 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002473 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002474 event = mCryptConnector.execute("cryptfs", "cryptocomplete");
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002475 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002476 } catch (NumberFormatException e) {
2477 // Bad result - unexpected.
2478 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2479 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2480 } catch (NativeDaemonConnectorException e) {
2481 // Something bad happened.
2482 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2483 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2484 }
2485 }
2486
2487 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002488 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002489 if (TextUtils.isEmpty(password)) {
2490 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002491 }
2492
Jason parks8888c592011-01-20 22:46:41 -06002493 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2494 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002495
2496 waitForReady();
2497
2498 if (DEBUG_EVENTS) {
2499 Slog.i(TAG, "decrypting storage...");
2500 }
2501
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002502 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002503 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002504 event = mCryptConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002505
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002506 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002507 if (code == 0) {
2508 // Decrypt was successful. Post a delayed message before restarting in order
2509 // to let the UI to clear itself
2510 mHandler.postDelayed(new Runnable() {
2511 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002512 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002513 mCryptConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002514 } catch (NativeDaemonConnectorException e) {
2515 Slog.e(TAG, "problem executing in background", e);
2516 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002517 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002518 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002519 }
2520
2521 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002522 } catch (NativeDaemonConnectorException e) {
2523 // Decryption failed
2524 return e.getCode();
2525 }
Jason parks5af0b912010-11-29 09:05:25 -06002526 }
2527
Paul Lawrence46791e72014-04-03 09:10:26 -07002528 public int encryptStorage(int type, String password) {
2529 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002530 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002531 }
2532
Jason parks8888c592011-01-20 22:46:41 -06002533 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2534 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002535
2536 waitForReady();
2537
2538 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002539 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002540 }
2541
2542 try {
Paul Lawrence5096d9e2015-09-09 13:05:45 -07002543 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2544 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2545 CRYPTO_TYPES[type]);
2546 } else {
2547 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2548 CRYPTO_TYPES[type], new SensitiveArg(password));
2549 }
Jason parks56aa5322011-01-07 09:01:15 -06002550 } catch (NativeDaemonConnectorException e) {
2551 // Encryption failed
2552 return e.getCode();
2553 }
2554
2555 return 0;
2556 }
2557
Paul Lawrence8e397362014-01-27 15:22:30 -08002558 /** Set the password for encrypting the master key.
2559 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2560 * @param password The password to set.
2561 */
2562 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002563 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2564 "no permission to access the crypt keeper");
2565
2566 waitForReady();
2567
2568 if (DEBUG_EVENTS) {
2569 Slog.i(TAG, "changing encryption password...");
2570 }
2571
2572 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002573 NativeDaemonEvent event = mCryptConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
Paul Lawrence05487612015-06-09 13:35:38 -07002574 new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002575 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002576 } catch (NativeDaemonConnectorException e) {
2577 // Encryption failed
2578 return e.getCode();
2579 }
2580 }
2581
Christopher Tate32418be2011-10-10 13:51:12 -07002582 /**
2583 * Validate a user-supplied password string with cryptfs
2584 */
2585 @Override
2586 public int verifyEncryptionPassword(String password) throws RemoteException {
2587 // Only the system process is permitted to validate passwords
2588 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2589 throw new SecurityException("no permission to access the crypt keeper");
2590 }
2591
2592 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2593 "no permission to access the crypt keeper");
2594
2595 if (TextUtils.isEmpty(password)) {
2596 throw new IllegalArgumentException("password cannot be empty");
2597 }
2598
2599 waitForReady();
2600
2601 if (DEBUG_EVENTS) {
2602 Slog.i(TAG, "validating encryption password...");
2603 }
2604
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002605 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002606 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002607 event = mCryptConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002608 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2609 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002610 } catch (NativeDaemonConnectorException e) {
2611 // Encryption failed
2612 return e.getCode();
2613 }
2614 }
2615
Paul Lawrence8e397362014-01-27 15:22:30 -08002616 /**
2617 * Get the type of encryption used to encrypt the master key.
2618 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2619 */
2620 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002621 public int getPasswordType() {
Paul Lawrence8e397362014-01-27 15:22:30 -08002622
2623 waitForReady();
2624
2625 final NativeDaemonEvent event;
2626 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002627 event = mCryptConnector.execute("cryptfs", "getpwtype");
Paul Lawrence8e397362014-01-27 15:22:30 -08002628 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2629 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2630 return i;
2631 }
2632
2633 throw new IllegalStateException("unexpected return from cryptfs");
2634 } catch (NativeDaemonConnectorException e) {
2635 throw e.rethrowAsParcelableException();
2636 }
2637 }
2638
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002639 /**
2640 * Set a field in the crypto header.
2641 * @param field field to set
2642 * @param contents contents to set in field
2643 */
2644 @Override
2645 public void setField(String field, String contents) throws RemoteException {
2646
2647 waitForReady();
2648
2649 final NativeDaemonEvent event;
2650 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002651 event = mCryptConnector.execute("cryptfs", "setfield", field, contents);
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002652 } catch (NativeDaemonConnectorException e) {
2653 throw e.rethrowAsParcelableException();
2654 }
2655 }
2656
2657 /**
2658 * Gets a field from the crypto header.
2659 * @param field field to get
2660 * @return contents of field
2661 */
2662 @Override
2663 public String getField(String field) throws RemoteException {
2664
2665 waitForReady();
2666
2667 final NativeDaemonEvent event;
2668 try {
2669 final String[] contents = NativeDaemonEvent.filterMessageList(
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002670 mCryptConnector.executeForList("cryptfs", "getfield", field),
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002671 VoldResponseCode.CryptfsGetfieldResult);
2672 String result = new String();
2673 for (String content : contents) {
2674 result += content;
2675 }
2676 return result;
2677 } catch (NativeDaemonConnectorException e) {
2678 throw e.rethrowAsParcelableException();
2679 }
2680 }
2681
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002682 /**
2683 * Is userdata convertible to file based encryption?
2684 * @return non zero for convertible
2685 */
2686 @Override
2687 public boolean isConvertibleToFBE() throws RemoteException {
2688
2689 waitForReady();
2690
2691 final NativeDaemonEvent event;
2692 try {
2693 event = mCryptConnector.execute("cryptfs", "isConvertibleToFBE");
2694 return Integer.parseInt(event.getMessage()) != 0;
2695 } catch (NativeDaemonConnectorException e) {
2696 throw e.rethrowAsParcelableException();
2697 }
2698 }
2699
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002700 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002701 public String getPassword() throws RemoteException {
Rubin Xucd7a0142015-04-17 23:45:27 +01002702 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE,
2703 "only keyguard can retrieve password");
Paul Lawrence945490c2014-03-27 16:37:28 +00002704 if (!isReady()) {
2705 return new String();
2706 }
2707
2708 final NativeDaemonEvent event;
2709 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002710 event = mCryptConnector.execute("cryptfs", "getpw");
Paul Lawrence24063b52015-01-06 13:11:23 -08002711 if ("-1".equals(event.getMessage())) {
2712 // -1 equals no password
2713 return null;
2714 }
Paul Lawrence05487612015-06-09 13:35:38 -07002715 return event.getMessage();
Paul Lawrence945490c2014-03-27 16:37:28 +00002716 } catch (NativeDaemonConnectorException e) {
2717 throw e.rethrowAsParcelableException();
Paul Lawrence24063b52015-01-06 13:11:23 -08002718 } catch (IllegalArgumentException e) {
2719 Slog.e(TAG, "Invalid response to getPassword");
2720 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002721 }
2722 }
2723
2724 @Override
2725 public void clearPassword() throws RemoteException {
2726 if (!isReady()) {
2727 return;
2728 }
2729
2730 final NativeDaemonEvent event;
2731 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002732 event = mCryptConnector.execute("cryptfs", "clearpw");
Paul Lawrence945490c2014-03-27 16:37:28 +00002733 } catch (NativeDaemonConnectorException e) {
2734 throw e.rethrowAsParcelableException();
2735 }
2736 }
2737
2738 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002739 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002740 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002741 waitForReady();
2742
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002743 try {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002744 mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber,
2745 ephemeral ? 1 : 0);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002746 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002747 throw e.rethrowAsParcelableException();
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002748 }
2749 }
2750
Paul Crowley7ec733f2015-05-19 12:42:00 +01002751 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002752 public void destroyUserKey(int userId) {
2753 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002754 waitForReady();
2755
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002756 try {
2757 mCryptConnector.execute("cryptfs", "destroy_user_key", userId);
2758 } catch (NativeDaemonConnectorException e) {
2759 throw e.rethrowAsParcelableException();
2760 }
2761 }
2762
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002763 private SensitiveArg encodeBytes(byte[] bytes) {
2764 if (ArrayUtils.isEmpty(bytes)) {
2765 return new SensitiveArg("!");
2766 } else {
2767 return new SensitiveArg(HexDump.toHexString(bytes));
2768 }
2769 }
2770
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002771 @Override
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002772 public void changeUserKey(int userId, int serialNumber,
2773 byte[] token, byte[] oldSecret, byte[] newSecret) {
2774 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2775 waitForReady();
2776
2777 try {
2778 mCryptConnector.execute("cryptfs", "change_user_key", userId, serialNumber,
2779 encodeBytes(token), encodeBytes(oldSecret), encodeBytes(newSecret));
2780 } catch (NativeDaemonConnectorException e) {
2781 throw e.rethrowAsParcelableException();
2782 }
2783 }
2784
2785 @Override
2786 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002787 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2788 waitForReady();
2789
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002790 // When a user has secure lock screen, require a challenge token to
2791 // actually unlock. This check is mostly in place for emulation mode.
2792 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
2793 throw new IllegalStateException("Token required to unlock secure user " + userId);
2794 }
2795
Paul Crowley7ec733f2015-05-19 12:42:00 +01002796 try {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002797 mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002798 encodeBytes(token), encodeBytes(secret));
Paul Crowley7ec733f2015-05-19 12:42:00 +01002799 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002800 throw e.rethrowAsParcelableException();
2801 }
2802
2803 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002804 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002805 }
2806 }
2807
2808 @Override
2809 public void lockUserKey(int userId) {
2810 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2811 waitForReady();
2812
2813 try {
2814 mCryptConnector.execute("cryptfs", "lock_user_key", userId);
2815 } catch (NativeDaemonConnectorException e) {
2816 throw e.rethrowAsParcelableException();
2817 }
2818
2819 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002820 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002821 }
2822 }
2823
2824 @Override
2825 public boolean isUserKeyUnlocked(int userId) {
Paul Lawrence20be5d62016-02-26 13:51:17 -08002826 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002827 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002828 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002829 }
2830 } else {
2831 return true;
2832 }
2833 }
2834
2835 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002836 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002837 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2838 waitForReady();
2839
2840 try {
2841 mCryptConnector.execute("cryptfs", "prepare_user_storage", escapeNull(volumeUuid),
Jeff Sharkey47f71082016-02-01 17:03:54 -07002842 userId, serialNumber, flags);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002843 } catch (NativeDaemonConnectorException e) {
2844 throw e.rethrowAsParcelableException();
Paul Crowley7ec733f2015-05-19 12:42:00 +01002845 }
2846 }
2847
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002848 @Override
Daichi Hirono91e3b502015-12-16 09:24:16 +09002849 public ParcelFileDescriptor mountAppFuse(final String name) throws RemoteException {
Daichi Hironobee50c02015-12-14 11:00:54 +09002850 try {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002851 final int uid = Binder.getCallingUid();
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002852 final int pid = Binder.getCallingPid();
Daichi Hironobee50c02015-12-14 11:00:54 +09002853 final NativeDaemonEvent event =
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002854 mConnector.execute("appfuse", "mount", uid, pid, name);
Daichi Hironobee50c02015-12-14 11:00:54 +09002855 if (event.getFileDescriptors() == null) {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002856 throw new RemoteException("AppFuse FD from vold is null.");
Daichi Hironobee50c02015-12-14 11:00:54 +09002857 }
Daichi Hirono91e3b502015-12-16 09:24:16 +09002858 return ParcelFileDescriptor.fromFd(
2859 event.getFileDescriptors()[0],
2860 mHandler,
2861 new ParcelFileDescriptor.OnCloseListener() {
2862 @Override
2863 public void onClose(IOException e) {
2864 try {
2865 final NativeDaemonEvent event = mConnector.execute(
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002866 "appfuse", "unmount", uid, pid, name);
Daichi Hirono91e3b502015-12-16 09:24:16 +09002867 } catch (NativeDaemonConnectorException unmountException) {
2868 Log.e(TAG, "Failed to unmount appfuse.");
2869 }
2870 }
2871 });
Daichi Hironobee50c02015-12-14 11:00:54 +09002872 } catch (NativeDaemonConnectorException e) {
2873 throw e.rethrowAsParcelableException();
Daichi Hirono91e3b502015-12-16 09:24:16 +09002874 } catch (IOException e) {
2875 throw new RemoteException(e.getMessage());
Daichi Hironobee50c02015-12-14 11:00:54 +09002876 }
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002877 }
2878
2879 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002880 public int mkdirs(String callingPkg, String appPath) {
2881 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2882 final UserEnvironment userEnv = new UserEnvironment(userId);
2883
2884 // Validate that reported package name belongs to caller
2885 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2886 Context.APP_OPS_SERVICE);
2887 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2888
Jeff Sharkey48877892015-03-18 11:27:19 -07002889 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002890 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002891 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002892 } catch (IOException e) {
2893 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2894 return -1;
2895 }
2896
2897 // Try translating the app path into a vold path, but require that it
2898 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07002899 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
2900 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
2901 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
2902 appPath = appFile.getAbsolutePath();
2903 if (!appPath.endsWith("/")) {
2904 appPath = appPath + "/";
2905 }
2906
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002907 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002908 mConnector.execute("volume", "mkdirs", appPath);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002909 return 0;
2910 } catch (NativeDaemonConnectorException e) {
2911 return e.getCode();
2912 }
2913 }
2914
Jeff Sharkey48877892015-03-18 11:27:19 -07002915 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002916 }
2917
2918 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07002919 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002920 final int userId = UserHandle.getUserId(uid);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002921
Jeff Sharkey46349872015-07-28 10:49:47 -07002922 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002923 final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0;
2924 final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0;
Jeff Sharkey46349872015-07-28 10:49:47 -07002925
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002926 final boolean userKeyUnlocked;
2927 final boolean storagePermission;
2928 final long token = Binder.clearCallingIdentity();
Svetoslav38c3dbb2015-07-14 11:27:06 -07002929 try {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002930 userKeyUnlocked = isUserKeyUnlocked(userId);
2931 storagePermission = mMountServiceInternal.hasExternalStorage(uid, packageName);
Svetoslav38c3dbb2015-07-14 11:27:06 -07002932 } finally {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002933 Binder.restoreCallingIdentity(token);
Svetoslav38c3dbb2015-07-14 11:27:06 -07002934 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07002935
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002936 boolean foundPrimary = false;
2937
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002938 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07002939 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002940 for (int i = 0; i < mVolumes.size(); i++) {
2941 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002942 switch (vol.getType()) {
2943 case VolumeInfo.TYPE_PUBLIC:
2944 case VolumeInfo.TYPE_EMULATED:
2945 break;
2946 default:
2947 continue;
2948 }
2949
2950 boolean match = false;
2951 if (forWrite) {
2952 match = vol.isVisibleForWrite(userId);
2953 } else {
2954 match = vol.isVisibleForRead(userId) || includeInvisible;
2955 }
2956 if (!match) continue;
2957
2958 boolean reportUnmounted = false;
2959 if ((vol.getType() == VolumeInfo.TYPE_EMULATED) && !userKeyUnlocked) {
2960 reportUnmounted = true;
2961 } else if (!storagePermission && !realState) {
2962 reportUnmounted = true;
2963 }
2964
2965 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
2966 reportUnmounted);
2967 if (vol.isPrimary()) {
2968 res.add(0, userVol);
2969 foundPrimary = true;
2970 } else {
2971 res.add(userVol);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002972 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002973 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002974 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002975
2976 if (!foundPrimary) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002977 Log.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07002978
2979 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002980 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07002981
2982 final String id = "stub_primary";
2983 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002984 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07002985 final boolean primary = true;
2986 final boolean removable = primaryPhysical;
2987 final boolean emulated = !primaryPhysical;
2988 final long mtpReserveSize = 0L;
2989 final boolean allowMassStorage = false;
2990 final long maxFileSize = 0L;
2991 final UserHandle owner = new UserHandle(userId);
2992 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07002993 final String state = Environment.MEDIA_REMOVED;
2994
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07002995 res.add(0, new StorageVolume(id, StorageVolume.STORAGE_ID_INVALID, path,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002996 description, primary, removable, emulated, mtpReserveSize,
2997 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07002998 }
2999
3000 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003001 }
3002
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003003 @Override
3004 public DiskInfo[] getDisks() {
3005 synchronized (mLock) {
3006 final DiskInfo[] res = new DiskInfo[mDisks.size()];
3007 for (int i = 0; i < mDisks.size(); i++) {
3008 res[i] = mDisks.valueAt(i);
3009 }
3010 return res;
3011 }
3012 }
3013
3014 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003015 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003016 synchronized (mLock) {
3017 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
3018 for (int i = 0; i < mVolumes.size(); i++) {
3019 res[i] = mVolumes.valueAt(i);
3020 }
3021 return res;
3022 }
3023 }
3024
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003025 @Override
3026 public VolumeRecord[] getVolumeRecords(int flags) {
3027 synchronized (mLock) {
3028 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
3029 for (int i = 0; i < mRecords.size(); i++) {
3030 res[i] = mRecords.valueAt(i);
3031 }
3032 return res;
3033 }
3034 }
3035
Kenny Rootaf9d6672010-10-08 09:21:39 -07003036 private void addObbStateLocked(ObbState obbState) throws RemoteException {
3037 final IBinder binder = obbState.getBinder();
3038 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003039
Kenny Rootaf9d6672010-10-08 09:21:39 -07003040 if (obbStates == null) {
3041 obbStates = new ArrayList<ObbState>();
3042 mObbMounts.put(binder, obbStates);
3043 } else {
3044 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003045 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003046 throw new IllegalStateException("Attempt to add ObbState twice. "
3047 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003048 }
3049 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003050 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003051
3052 obbStates.add(obbState);
3053 try {
3054 obbState.link();
3055 } catch (RemoteException e) {
3056 /*
3057 * The binder died before we could link it, so clean up our state
3058 * and return failure.
3059 */
3060 obbStates.remove(obbState);
3061 if (obbStates.isEmpty()) {
3062 mObbMounts.remove(binder);
3063 }
3064
3065 // Rethrow the error so mountObb can get it
3066 throw e;
3067 }
3068
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003069 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003070 }
3071
Kenny Rootaf9d6672010-10-08 09:21:39 -07003072 private void removeObbStateLocked(ObbState obbState) {
3073 final IBinder binder = obbState.getBinder();
3074 final List<ObbState> obbStates = mObbMounts.get(binder);
3075 if (obbStates != null) {
3076 if (obbStates.remove(obbState)) {
3077 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003078 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003079 if (obbStates.isEmpty()) {
3080 mObbMounts.remove(binder);
3081 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003082 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003083
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003084 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003085 }
3086
Kenny Roota02b8b02010-08-05 16:14:17 -07003087 private class ObbActionHandler extends Handler {
3088 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07003089 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07003090
3091 ObbActionHandler(Looper l) {
3092 super(l);
3093 }
3094
3095 @Override
3096 public void handleMessage(Message msg) {
3097 switch (msg.what) {
3098 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003099 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003100
3101 if (DEBUG_OBB)
3102 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3103
3104 // If a bind was already initiated we don't really
3105 // need to do anything. The pending install
3106 // will be processed later on.
3107 if (!mBound) {
3108 // If this is the only one pending we might
3109 // have to bind to the service again.
3110 if (!connectToService()) {
3111 Slog.e(TAG, "Failed to bind to media container service");
3112 action.handleError();
3113 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003114 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003115 }
Kenny Root735de3b2010-09-30 14:11:39 -07003116
Kenny Root735de3b2010-09-30 14:11:39 -07003117 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07003118 break;
3119 }
3120 case OBB_MCS_BOUND: {
3121 if (DEBUG_OBB)
3122 Slog.i(TAG, "OBB_MCS_BOUND");
3123 if (msg.obj != null) {
3124 mContainerService = (IMediaContainerService) msg.obj;
3125 }
3126 if (mContainerService == null) {
3127 // Something seriously wrong. Bail out
3128 Slog.e(TAG, "Cannot bind to media container service");
3129 for (ObbAction action : mActions) {
3130 // Indicate service bind error
3131 action.handleError();
3132 }
3133 mActions.clear();
3134 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07003135 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07003136 if (action != null) {
3137 action.execute(this);
3138 }
3139 } else {
3140 // Should never happen ideally.
3141 Slog.w(TAG, "Empty queue");
3142 }
3143 break;
3144 }
3145 case OBB_MCS_RECONNECT: {
3146 if (DEBUG_OBB)
3147 Slog.i(TAG, "OBB_MCS_RECONNECT");
3148 if (mActions.size() > 0) {
3149 if (mBound) {
3150 disconnectService();
3151 }
3152 if (!connectToService()) {
3153 Slog.e(TAG, "Failed to bind to media container service");
3154 for (ObbAction action : mActions) {
3155 // Indicate service bind error
3156 action.handleError();
3157 }
3158 mActions.clear();
3159 }
3160 }
3161 break;
3162 }
3163 case OBB_MCS_UNBIND: {
3164 if (DEBUG_OBB)
3165 Slog.i(TAG, "OBB_MCS_UNBIND");
3166
3167 // Delete pending install
3168 if (mActions.size() > 0) {
3169 mActions.remove(0);
3170 }
3171 if (mActions.size() == 0) {
3172 if (mBound) {
3173 disconnectService();
3174 }
3175 } else {
3176 // There are more pending requests in queue.
3177 // Just post MCS_BOUND message to trigger processing
3178 // of next pending install.
3179 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
3180 }
3181 break;
3182 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003183 case OBB_FLUSH_MOUNT_STATE: {
3184 final String path = (String) msg.obj;
3185
3186 if (DEBUG_OBB)
3187 Slog.i(TAG, "Flushing all OBB state for path " + path);
3188
3189 synchronized (mObbMounts) {
3190 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3191
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003192 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003193 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003194 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003195
3196 /*
3197 * If this entry's source file is in the volume path
3198 * that got unmounted, remove it because it's no
3199 * longer valid.
3200 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003201 if (state.canonicalPath.startsWith(path)) {
3202 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003203 }
3204 }
3205
3206 for (final ObbState obbState : obbStatesToRemove) {
3207 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003208 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003209
3210 removeObbStateLocked(obbState);
3211
3212 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003213 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003214 OnObbStateChangeListener.UNMOUNTED);
3215 } catch (RemoteException e) {
3216 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003217 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003218 }
3219 }
3220 }
3221 break;
3222 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003223 }
3224 }
3225
3226 private boolean connectToService() {
3227 if (DEBUG_OBB)
3228 Slog.i(TAG, "Trying to bind to DefaultContainerService");
3229
3230 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003231 if (mContext.bindServiceAsUser(service, mDefContainerConn, Context.BIND_AUTO_CREATE,
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003232 UserHandle.SYSTEM)) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003233 mBound = true;
3234 return true;
3235 }
3236 return false;
3237 }
3238
3239 private void disconnectService() {
3240 mContainerService = null;
3241 mBound = false;
3242 mContext.unbindService(mDefContainerConn);
3243 }
3244 }
3245
3246 abstract class ObbAction {
3247 private static final int MAX_RETRIES = 3;
3248 private int mRetries;
3249
3250 ObbState mObbState;
3251
3252 ObbAction(ObbState obbState) {
3253 mObbState = obbState;
3254 }
3255
3256 public void execute(ObbActionHandler handler) {
3257 try {
3258 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003259 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07003260 mRetries++;
3261 if (mRetries > MAX_RETRIES) {
3262 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07003263 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003264 handleError();
Kenny Roota02b8b02010-08-05 16:14:17 -07003265 } else {
3266 handleExecute();
3267 if (DEBUG_OBB)
3268 Slog.i(TAG, "Posting install MCS_UNBIND");
3269 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
3270 }
3271 } catch (RemoteException e) {
3272 if (DEBUG_OBB)
3273 Slog.i(TAG, "Posting install MCS_RECONNECT");
3274 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
3275 } catch (Exception e) {
3276 if (DEBUG_OBB)
3277 Slog.d(TAG, "Error handling OBB action", e);
3278 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07003279 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003280 }
3281 }
3282
Kenny Root05105f72010-09-22 17:29:43 -07003283 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07003284 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07003285
3286 protected ObbInfo getObbInfo() throws IOException {
3287 ObbInfo obbInfo;
3288 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003289 obbInfo = mContainerService.getObbInfo(mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003290 } catch (RemoteException e) {
3291 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003292 + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003293 obbInfo = null;
3294 }
3295 if (obbInfo == null) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003296 throw new IOException("Couldn't read OBB file: " + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003297 }
3298 return obbInfo;
3299 }
3300
Kenny Rootaf9d6672010-10-08 09:21:39 -07003301 protected void sendNewStatusOrIgnore(int status) {
3302 if (mObbState == null || mObbState.token == null) {
3303 return;
3304 }
3305
Kenny Root38cf8862010-09-26 14:18:51 -07003306 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003307 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003308 } catch (RemoteException e) {
3309 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
3310 }
3311 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003312 }
3313
3314 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003315 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003316 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003317
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003318 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003319 super(obbState);
3320 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003321 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003322 }
3323
Jason parks5af0b912010-11-29 09:05:25 -06003324 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07003325 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003326 waitForReady();
3327 warnOnNotMounted();
3328
Kenny Root38cf8862010-09-26 14:18:51 -07003329 final ObbInfo obbInfo = getObbInfo();
3330
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003331 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003332 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
3333 + " which is owned by " + obbInfo.packageName);
3334 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3335 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003336 }
3337
Kenny Rootaf9d6672010-10-08 09:21:39 -07003338 final boolean isMounted;
3339 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003340 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003341 }
3342 if (isMounted) {
3343 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
3344 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
3345 return;
3346 }
3347
Kenny Rootaf9d6672010-10-08 09:21:39 -07003348 final String hashedKey;
3349 if (mKey == null) {
3350 hashedKey = "none";
3351 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003352 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003353 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3354
3355 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
3356 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3357 SecretKey key = factory.generateSecret(ks);
3358 BigInteger bi = new BigInteger(key.getEncoded());
3359 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003360 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07003361 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
3362 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
3363 return;
3364 } catch (InvalidKeySpecException e) {
3365 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
3366 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07003367 return;
3368 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003369 }
Kenny Root38cf8862010-09-26 14:18:51 -07003370
Kenny Rootaf9d6672010-10-08 09:21:39 -07003371 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003372 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003373 mConnector.execute("obb", "mount", mObbState.canonicalPath, new SensitiveArg(hashedKey),
Jeff Sharkey56cd6462013-06-07 15:09:15 -07003374 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003375 } catch (NativeDaemonConnectorException e) {
3376 int code = e.getCode();
3377 if (code != VoldResponseCode.OpFailedStorageBusy) {
3378 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003379 }
3380 }
3381
Kenny Rootaf9d6672010-10-08 09:21:39 -07003382 if (rc == StorageResultCode.OperationSucceeded) {
3383 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003384 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003385
3386 synchronized (mObbMounts) {
3387 addObbStateLocked(mObbState);
3388 }
3389
3390 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07003391 } else {
Kenny Root05105f72010-09-22 17:29:43 -07003392 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07003393
Kenny Rootaf9d6672010-10-08 09:21:39 -07003394 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07003395 }
3396 }
3397
Jason parks5af0b912010-11-29 09:05:25 -06003398 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003399 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003400 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07003401 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003402
3403 @Override
3404 public String toString() {
3405 StringBuilder sb = new StringBuilder();
3406 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003407 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003408 sb.append('}');
3409 return sb.toString();
3410 }
3411 }
3412
3413 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003414 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003415
3416 UnmountObbAction(ObbState obbState, boolean force) {
3417 super(obbState);
3418 mForceUnmount = force;
3419 }
3420
Jason parks5af0b912010-11-29 09:05:25 -06003421 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07003422 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003423 waitForReady();
3424 warnOnNotMounted();
3425
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003426 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003427 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003428 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003429 }
Kenny Root38cf8862010-09-26 14:18:51 -07003430
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003431 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003432 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
3433 return;
3434 }
3435
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003436 if (existingState.ownerGid != mObbState.ownerGid) {
3437 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
3438 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003439 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3440 return;
3441 }
3442
Kenny Rootaf9d6672010-10-08 09:21:39 -07003443 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003444 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003445 final Command cmd = new Command("obb", "unmount", mObbState.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08003446 if (mForceUnmount) {
3447 cmd.appendArg("force");
3448 }
3449 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003450 } catch (NativeDaemonConnectorException e) {
3451 int code = e.getCode();
3452 if (code == VoldResponseCode.OpFailedStorageBusy) {
3453 rc = StorageResultCode.OperationFailedStorageBusy;
3454 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
3455 // If it's not mounted then we've already won.
3456 rc = StorageResultCode.OperationSucceeded;
3457 } else {
3458 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003459 }
3460 }
3461
Kenny Rootaf9d6672010-10-08 09:21:39 -07003462 if (rc == StorageResultCode.OperationSucceeded) {
3463 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003464 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003465 }
3466
Kenny Rootaf9d6672010-10-08 09:21:39 -07003467 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07003468 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003469 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003470 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07003471 }
3472 }
3473
Jason parks5af0b912010-11-29 09:05:25 -06003474 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003475 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003476 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07003477 }
3478
3479 @Override
3480 public String toString() {
3481 StringBuilder sb = new StringBuilder();
3482 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003483 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003484 sb.append(",force=");
3485 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003486 sb.append('}');
3487 return sb.toString();
3488 }
Kenny Root02c87302010-07-01 08:10:18 -07003489 }
Kenny Root38cf8862010-09-26 14:18:51 -07003490
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003491 private static class Callbacks extends Handler {
3492 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3493 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003494 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3495 private static final int MSG_VOLUME_FORGOTTEN = 4;
3496 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003497 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003498
3499 private final RemoteCallbackList<IMountServiceListener>
3500 mCallbacks = new RemoteCallbackList<>();
3501
3502 public Callbacks(Looper looper) {
3503 super(looper);
3504 }
3505
3506 public void register(IMountServiceListener callback) {
3507 mCallbacks.register(callback);
3508 }
3509
3510 public void unregister(IMountServiceListener callback) {
3511 mCallbacks.unregister(callback);
3512 }
3513
3514 @Override
3515 public void handleMessage(Message msg) {
3516 final SomeArgs args = (SomeArgs) msg.obj;
3517 final int n = mCallbacks.beginBroadcast();
3518 for (int i = 0; i < n; i++) {
3519 final IMountServiceListener callback = mCallbacks.getBroadcastItem(i);
3520 try {
3521 invokeCallback(callback, msg.what, args);
3522 } catch (RemoteException ignored) {
3523 }
3524 }
3525 mCallbacks.finishBroadcast();
3526 args.recycle();
3527 }
3528
3529 private void invokeCallback(IMountServiceListener callback, int what, SomeArgs args)
3530 throws RemoteException {
3531 switch (what) {
3532 case MSG_STORAGE_STATE_CHANGED: {
3533 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3534 (String) args.arg3);
3535 break;
3536 }
3537 case MSG_VOLUME_STATE_CHANGED: {
3538 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3539 break;
3540 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003541 case MSG_VOLUME_RECORD_CHANGED: {
3542 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3543 break;
3544 }
3545 case MSG_VOLUME_FORGOTTEN: {
3546 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003547 break;
3548 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003549 case MSG_DISK_SCANNED: {
3550 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003551 break;
3552 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003553 case MSG_DISK_DESTROYED: {
3554 callback.onDiskDestroyed((DiskInfo) args.arg1);
3555 break;
3556 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003557 }
3558 }
3559
3560 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3561 final SomeArgs args = SomeArgs.obtain();
3562 args.arg1 = path;
3563 args.arg2 = oldState;
3564 args.arg3 = newState;
3565 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3566 }
3567
3568 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3569 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003570 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003571 args.argi2 = oldState;
3572 args.argi3 = newState;
3573 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3574 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003575
Jeff Sharkey50a05452015-04-29 11:24:52 -07003576 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3577 final SomeArgs args = SomeArgs.obtain();
3578 args.arg1 = rec.clone();
3579 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3580 }
3581
3582 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003583 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003584 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003585 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003586 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003587
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003588 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003589 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003590 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003591 args.argi2 = volumeCount;
3592 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003593 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003594
3595 private void notifyDiskDestroyed(DiskInfo disk) {
3596 final SomeArgs args = SomeArgs.obtain();
3597 args.arg1 = disk.clone();
3598 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3599 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003600 }
3601
Kenny Root38cf8862010-09-26 14:18:51 -07003602 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003603 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
3605
3606 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003607 synchronized (mLock) {
3608 pw.println("Disks:");
3609 pw.increaseIndent();
3610 for (int i = 0; i < mDisks.size(); i++) {
3611 final DiskInfo disk = mDisks.valueAt(i);
3612 disk.dump(pw);
3613 }
3614 pw.decreaseIndent();
3615
3616 pw.println();
3617 pw.println("Volumes:");
3618 pw.increaseIndent();
3619 for (int i = 0; i < mVolumes.size(); i++) {
3620 final VolumeInfo vol = mVolumes.valueAt(i);
3621 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3622 vol.dump(pw);
3623 }
3624 pw.decreaseIndent();
3625
3626 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003627 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003628 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003629 for (int i = 0; i < mRecords.size(); i++) {
3630 final VolumeRecord note = mRecords.valueAt(i);
3631 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003632 }
3633 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003634
3635 pw.println();
3636 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07003637 pw.println("Force adoptable: " + mForceAdoptable);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08003638 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003639 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3640 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003641 }
Kenny Root38cf8862010-09-26 14:18:51 -07003642
Kenny Root38cf8862010-09-26 14:18:51 -07003643 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003644 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003645 pw.println("mObbMounts:");
3646 pw.increaseIndent();
3647 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3648 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003649 while (binders.hasNext()) {
3650 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003651 pw.println(e.getKey() + ":");
3652 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003653 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003654 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003655 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003656 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003657 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003658 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003659 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003660
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003661 pw.println();
3662 pw.println("mObbPathToStateMap:");
3663 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003664 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3665 while (maps.hasNext()) {
3666 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003667 pw.print(e.getKey());
3668 pw.print(" -> ");
3669 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003670 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003671 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003672 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003673
Robert Greenwalt470fd722012-01-18 12:51:15 -08003674 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003675 pw.println("mConnector:");
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003676 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003677 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003678 pw.decreaseIndent();
Christopher Tate7265abe2014-11-21 13:54:45 -08003679
Christopher Tate7265abe2014-11-21 13:54:45 -08003680 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003681 pw.println("mCryptConnector:");
3682 pw.increaseIndent();
3683 mCryptConnector.dump(fd, pw, args);
3684 pw.decreaseIndent();
3685
3686 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003687 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003688 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003691 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003692 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003693 public void monitor() {
3694 if (mConnector != null) {
3695 mConnector.monitor();
3696 }
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003697 if (mCryptConnector != null) {
3698 mCryptConnector.monitor();
3699 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003700 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003701
3702 private final class MountServiceInternalImpl extends MountServiceInternal {
3703 // Not guarded by a lock.
3704 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3705 new CopyOnWriteArrayList<>();
3706
3707 @Override
3708 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3709 // No locking - CopyOnWriteArrayList
3710 mPolicies.add(policy);
3711 }
3712
3713 @Override
3714 public void onExternalStoragePolicyChanged(int uid, String packageName) {
3715 final int mountMode = getExternalStorageMountMode(uid, packageName);
3716 remountUidExternalStorage(uid, mountMode);
3717 }
3718
3719 @Override
3720 public int getExternalStorageMountMode(int uid, String packageName) {
3721 // No locking - CopyOnWriteArrayList
3722 int mountMode = Integer.MAX_VALUE;
3723 for (ExternalStorageMountPolicy policy : mPolicies) {
3724 final int policyMode = policy.getMountMode(uid, packageName);
3725 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3726 return Zygote.MOUNT_EXTERNAL_NONE;
3727 }
3728 mountMode = Math.min(mountMode, policyMode);
3729 }
3730 if (mountMode == Integer.MAX_VALUE) {
3731 return Zygote.MOUNT_EXTERNAL_NONE;
3732 }
3733 return mountMode;
3734 }
3735
3736 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003737 // No need to check for system uid. This avoids a deadlock between
3738 // PackageManagerService and AppOpsService.
3739 if (uid == Process.SYSTEM_UID) {
3740 return true;
3741 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003742 // No locking - CopyOnWriteArrayList
3743 for (ExternalStorageMountPolicy policy : mPolicies) {
3744 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
3745 if (!policyHasStorage) {
3746 return false;
3747 }
3748 }
3749 return true;
3750 }
3751 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003752}