blob: a3322fc99677271b012381312470014520a76372 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4c099d02015-05-15 13:45:00 -070019import static com.android.internal.util.XmlUtils.readBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070020import static com.android.internal.util.XmlUtils.readIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070021import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070022import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkey4c099d02015-05-15 13:45:00 -070023import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070024import static com.android.internal.util.XmlUtils.writeIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070025import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070026import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey5217cac2015-12-20 15:34:01 -070027
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070028import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
29import static org.xmlpull.v1.XmlPullParser.START_TAG;
30
Jason parks8888c592011-01-20 22:46:41 -060031import android.Manifest;
Jeff Sharkeyef10ee02015-07-05 14:17:27 -070032import android.annotation.Nullable;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -070033import android.app.ActivityManager;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070034import android.app.ActivityManagerNative;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070035import android.app.AppOpsManager;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070036import android.app.IActivityManager;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070037import android.content.BroadcastReceiver;
Kenny Roota02b8b02010-08-05 16:14:17 -070038import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.Context;
40import android.content.Intent;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070041import android.content.IntentFilter;
Kenny Roota02b8b02010-08-05 16:14:17 -070042import android.content.ServiceConnection;
Jeff Sharkey275e3e42015-04-24 16:10:32 -070043import android.content.pm.IPackageMoveObserver;
44import android.content.pm.PackageManager;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070045import android.content.pm.ProviderInfo;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070046import android.content.pm.UserInfo;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070047import android.content.res.Configuration;
Kenny Root02c87302010-07-01 08:10:18 -070048import android.content.res.ObbInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070050import android.os.Binder;
Jeff Sharkey4c099d02015-05-15 13:45:00 -070051import android.os.DropBoxManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070052import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070053import android.os.Environment.UserEnvironment;
Jeff Sharkey48877892015-03-18 11:27:19 -070054import android.os.FileUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080055import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070056import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070057import android.os.IBinder;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040058import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080059import android.os.Message;
Daichi Hirono9e8d9e22015-11-13 14:37:00 +090060import android.os.ParcelFileDescriptor;
Jeff Sharkeyce14cd02015-12-07 15:35:42 -070061import android.os.PowerManager;
Jeff Sharkey9527b222015-06-24 15:24:48 -070062import android.os.Process;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -070063import android.os.RemoteCallbackList;
San Mehat4270e1e2010-01-29 05:32:19 -080064import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080065import android.os.ServiceManager;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -070066import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Emily Bernier92aa5a22014-07-07 10:11:48 -040069import android.os.UserManager;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070070import android.os.storage.DiskInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -070071import android.os.storage.IMountService;
72import android.os.storage.IMountServiceListener;
73import android.os.storage.IMountShutdownObserver;
74import android.os.storage.IObbActionListener;
Svet Ganov6ee871e2015-07-10 14:29:33 -070075import android.os.storage.MountServiceInternal;
Kenny Rootaf9d6672010-10-08 09:21:39 -070076import android.os.storage.OnObbStateChangeListener;
Paul Lawrence46791e72014-04-03 09:10:26 -070077import android.os.storage.StorageManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070078import android.os.storage.StorageResultCode;
Mike Lockwood2f6a3882011-05-09 19:08:06 -070079import android.os.storage.StorageVolume;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070080import android.os.storage.VolumeInfo;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -070081import android.os.storage.VolumeRecord;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070082import android.provider.MediaStore;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070083import android.provider.Settings;
Jason parksf7b3cd42011-01-27 09:28:25 -060084import android.text.TextUtils;
Jeff Sharkey1783f142015-04-17 10:52:51 -070085import android.text.format.DateUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -070086import android.util.ArrayMap;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070087import android.util.AtomicFile;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -070088import android.util.Log;
San Mehata5078592010-03-25 09:36:54 -070089import android.util.Slog;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070090import android.util.TimeUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070091import android.util.Xml;
Jeff Sharkey48877892015-03-18 11:27:19 -070092
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080093import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070094import com.android.internal.app.IMediaContainerService;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -070095import com.android.internal.os.SomeArgs;
Jeff Sharkey9527b222015-06-24 15:24:48 -070096import com.android.internal.os.Zygote;
Jeff Sharkey48877892015-03-18 11:27:19 -070097import com.android.internal.util.ArrayUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070098import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080099import com.android.internal.util.HexDump;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700100import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700101import com.android.internal.util.Preconditions;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700102import com.android.internal.widget.LockPatternUtils;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700103import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700104import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700105import com.android.server.pm.PackageManagerService;
Kenny Roota02b8b02010-08-05 16:14:17 -0700106
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700107import libcore.io.IoUtils;
108import libcore.util.EmptyArray;
109
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700114import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -0700115import java.io.FileDescriptor;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700116import java.io.FileInputStream;
117import java.io.FileNotFoundException;
Christopher Tate7265abe2014-11-21 13:54:45 -0800118import java.io.FileOutputStream;
Kenny Root05105f72010-09-22 17:29:43 -0700119import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -0700120import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -0700121import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -0800122import java.nio.charset.StandardCharsets;
Kenny Root735de3b2010-09-30 14:11:39 -0700123import java.security.NoSuchAlgorithmException;
Kenny Root3b1abba2010-10-13 15:00:07 -0700124import java.security.spec.InvalidKeySpecException;
125import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -0800126import java.util.ArrayList;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800127import java.util.Arrays;
Kenny Roota02b8b02010-08-05 16:14:17 -0700128import java.util.HashMap;
San Mehat6cdd9c02010-02-09 14:45:20 -0800129import java.util.HashSet;
Kenny Root38cf8862010-09-26 14:18:51 -0700130import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -0700131import java.util.LinkedList;
132import java.util.List;
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700133import java.util.Locale;
Kenny Roota02b8b02010-08-05 16:14:17 -0700134import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -0700135import java.util.Map.Entry;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700136import java.util.Objects;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700137import java.util.concurrent.CopyOnWriteArrayList;
Kenny Root51a573c2012-05-17 13:30:28 -0700138import java.util.concurrent.CountDownLatch;
139import java.util.concurrent.TimeUnit;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700140import java.util.concurrent.TimeoutException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Kenny Root3b1abba2010-10-13 15:00:07 -0700142import javax.crypto.SecretKey;
143import javax.crypto.SecretKeyFactory;
144import javax.crypto.spec.PBEKeySpec;
145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146/**
Jeff Sharkey48877892015-03-18 11:27:19 -0700147 * Service responsible for various storage media. Connects to {@code vold} to
148 * watch for and manage dynamically added storage, such as SD cards and USB mass
149 * storage. Also decides how storage should be presented to users on the device.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700151class MountService extends IMountService.Stub
152 implements INativeDaemonConnectorCallbacks, Watchdog.Monitor {
Jason parks5af0b912010-11-29 09:05:25 -0600153
Christopher Tated417d622013-08-19 16:14:25 -0700154 // Static direct instance pointer for the tightly-coupled idle service to use
155 static MountService sSelf = null;
156
Jeff Sharkey56e62932015-03-21 20:41:00 -0700157 public static class Lifecycle extends SystemService {
158 private MountService mMountService;
159
160 public Lifecycle(Context context) {
161 super(context);
162 }
163
164 @Override
165 public void onStart() {
166 mMountService = new MountService(getContext());
167 publishBinderService("mount", mMountService);
168 }
169
170 @Override
171 public void onBootPhase(int phase) {
172 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
173 mMountService.systemReady();
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900174 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
175 mMountService.bootCompleted();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700176 }
177 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700178
179 @Override
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700180 public void onUnlockUser(int userHandle) {
181 mMountService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700182 }
183
184 @Override
185 public void onCleanupUser(int userHandle) {
186 mMountService.onCleanupUser(userHandle);
187 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700188 }
189
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800190 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800191 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700192
Kenny Root07714d42011-08-17 17:49:28 -0700193 // Disable this since it messes up long-running cryptfs operations.
194 private static final boolean WATCHDOG_ENABLE = false;
195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 private static final String TAG = "MountService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700197
Jeff Sharkey9756d752015-05-14 21:07:42 -0700198 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700199 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Kenny Root305bcbf2010-09-03 07:56:38 -0700201 private static final String VOLD_TAG = "VoldConnector";
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700202 private static final String CRYPTD_TAG = "CryptdConnector";
Kenny Root305bcbf2010-09-03 07:56:38 -0700203
Kenny Rootcf0b38c2011-03-22 14:17:59 -0700204 /** Maximum number of ASEC containers allowed to be mounted. */
205 private static final int MAX_CONTAINERS = 250;
206
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700207 /** Magic value sent by MoveTask.cpp */
208 private static final int MOVE_STATUS_COPY_FINISHED = 82;
209
San Mehat4270e1e2010-01-29 05:32:19 -0800210 /*
211 * Internal vold response code constants
212 */
San Mehat22dd86e2010-01-12 12:21:18 -0800213 class VoldResponseCode {
San Mehat4270e1e2010-01-29 05:32:19 -0800214 /*
215 * 100 series - Requestion action was initiated; expect another reply
216 * before proceeding with a new command.
217 */
San Mehat22dd86e2010-01-12 12:21:18 -0800218 public static final int VolumeListResult = 110;
219 public static final int AsecListResult = 111;
San Mehatc1b4ce92010-02-16 17:13:03 -0800220 public static final int StorageUsersListResult = 112;
Paul Lawrencee51dcf92014-03-18 10:56:00 -0700221 public static final int CryptfsGetfieldResult = 113;
San Mehat22dd86e2010-01-12 12:21:18 -0800222
San Mehat4270e1e2010-01-29 05:32:19 -0800223 /*
224 * 200 series - Requestion action has been successfully completed.
225 */
226 public static final int ShareStatusResult = 210;
San Mehat22dd86e2010-01-12 12:21:18 -0800227 public static final int AsecPathResult = 211;
San Mehat4270e1e2010-01-29 05:32:19 -0800228 public static final int ShareEnabledResult = 212;
San Mehat22dd86e2010-01-12 12:21:18 -0800229
San Mehat4270e1e2010-01-29 05:32:19 -0800230 /*
231 * 400 series - Command was accepted, but the requested action
232 * did not take place.
233 */
234 public static final int OpFailedNoMedia = 401;
235 public static final int OpFailedMediaBlank = 402;
236 public static final int OpFailedMediaCorrupt = 403;
237 public static final int OpFailedVolNotMounted = 404;
San Mehatd9709982010-02-18 11:43:03 -0800238 public static final int OpFailedStorageBusy = 405;
San Mehat2d66cef2010-03-23 11:12:52 -0700239 public static final int OpFailedStorageNotFound = 406;
San Mehat4270e1e2010-01-29 05:32:19 -0800240
241 /*
242 * 600 series - Unsolicited broadcasts.
243 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700244 public static final int DISK_CREATED = 640;
245 public static final int DISK_SIZE_CHANGED = 641;
246 public static final int DISK_LABEL_CHANGED = 642;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700247 public static final int DISK_SCANNED = 643;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700248 public static final int DISK_SYS_PATH_CHANGED = 644;
Jeff Sharkey48877892015-03-18 11:27:19 -0700249 public static final int DISK_DESTROYED = 649;
250
251 public static final int VOLUME_CREATED = 650;
252 public static final int VOLUME_STATE_CHANGED = 651;
253 public static final int VOLUME_FS_TYPE_CHANGED = 652;
254 public static final int VOLUME_FS_UUID_CHANGED = 653;
255 public static final int VOLUME_FS_LABEL_CHANGED = 654;
256 public static final int VOLUME_PATH_CHANGED = 655;
Jeff Sharkey50a05452015-04-29 11:24:52 -0700257 public static final int VOLUME_INTERNAL_PATH_CHANGED = 656;
Jeff Sharkey48877892015-03-18 11:27:19 -0700258 public static final int VOLUME_DESTROYED = 659;
Svetoslavf23b64d2013-04-25 14:45:54 -0700259
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700260 public static final int MOVE_STATUS = 660;
Jeff Sharkey9756d752015-05-14 21:07:42 -0700261 public static final int BENCHMARK_RESULT = 661;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700262 public static final int TRIM_RESULT = 662;
San Mehat22dd86e2010-01-12 12:21:18 -0800263 }
264
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700265 private static final int VERSION_INIT = 1;
266 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700267 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700268
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700269 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700270 private static final String ATTR_VERSION = "version";
271 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700272 private static final String ATTR_FORCE_ADOPTABLE = "forceAdoptable";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700273 private static final String TAG_VOLUME = "volume";
274 private static final String ATTR_TYPE = "type";
275 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700276 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700277 private static final String ATTR_NICKNAME = "nickname";
278 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700279 private static final String ATTR_CREATED_MILLIS = "createdMillis";
280 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
281 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700282
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700283 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700284
Jeff Sharkey48877892015-03-18 11:27:19 -0700285 /**
286 * <em>Never</em> hold the lock while performing downcalls into vold, since
287 * unsolicited events can suddenly appear to update data structures.
288 */
289 private final Object mLock = new Object();
290
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700291 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700292 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700293 private int[] mLocalUnlockedUsers = EmptyArray.INT;
294 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800295 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700296 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700297
298 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700299 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700300 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700301 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700302 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700303 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700304
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700305 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700306 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700307 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700308 @GuardedBy("mLock")
309 private String mPrimaryStorageUuid;
Jeff Sharkey4c099d02015-05-15 13:45:00 -0700310 @GuardedBy("mLock")
311 private boolean mForceAdoptable;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700312
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700313 /** Map from disk ID to latches */
314 @GuardedBy("mLock")
315 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
316
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700317 @GuardedBy("mLock")
318 private IPackageMoveObserver mMoveCallback;
319 @GuardedBy("mLock")
320 private String mMoveTargetUuid;
321
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700322 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700323 synchronized (mLock) {
324 final VolumeInfo vol = mVolumes.get(id);
325 if (vol != null) {
326 return vol;
327 }
328 }
329 throw new IllegalArgumentException("No volume found for ID " + id);
330 }
331
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700332 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700333 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700334 for (int i = 0; i < mVolumes.size(); i++) {
335 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700336 if (vol.path != null && path.startsWith(vol.path)) {
337 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700338 }
339 }
340 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700341 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700342 }
343
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700344 private VolumeRecord findRecordForPath(String path) {
345 synchronized (mLock) {
346 for (int i = 0; i < mVolumes.size(); i++) {
347 final VolumeInfo vol = mVolumes.valueAt(i);
348 if (vol.path != null && path.startsWith(vol.path)) {
349 return mRecords.get(vol.fsUuid);
350 }
351 }
352 }
353 return null;
354 }
355
356 private String scrubPath(String path) {
357 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
358 return "internal";
359 }
360 final VolumeRecord rec = findRecordForPath(path);
361 if (rec == null || rec.createdMillis == 0) {
362 return "unknown";
363 } else {
364 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
365 / DateUtils.WEEK_IN_MILLIS) + "w";
366 }
367 }
368
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700369 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700370 final StorageManager storage = mContext.getSystemService(StorageManager.class);
371 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700372 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700373 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
374 return storage.getPrimaryPhysicalVolume();
375 } else {
376 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
377 }
378 }
379
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700380 private boolean shouldBenchmark() {
381 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
382 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700383 if (benchInterval == -1) {
384 return false;
385 } else if (benchInterval == 0) {
386 return true;
387 }
388
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700389 synchronized (mLock) {
390 for (int i = 0; i < mVolumes.size(); i++) {
391 final VolumeInfo vol = mVolumes.valueAt(i);
392 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700393 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700394 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
395 if (benchAge >= benchInterval) {
396 return true;
397 }
398 }
399 }
400 return false;
401 }
402 }
403
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700404 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
405 synchronized (mLock) {
406 CountDownLatch latch = mDiskScanLatches.get(diskId);
407 if (latch == null) {
408 latch = new CountDownLatch(1);
409 mDiskScanLatches.put(diskId, latch);
410 }
411 return latch;
412 }
413 }
414
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800415 private static String escapeNull(String arg) {
416 if (TextUtils.isEmpty(arg)) {
417 return "!";
418 } else {
419 if (arg.indexOf('\0') != -1 || arg.indexOf(' ') != -1) {
420 throw new IllegalArgumentException(arg);
421 }
422 return arg;
423 }
424 }
425
Paul Lawrence8e397362014-01-27 15:22:30 -0800426 /** List of crypto types.
427 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
428 * corresponding commands in CommandListener.cpp */
429 public static final String[] CRYPTO_TYPES
430 = { "password", "default", "pattern", "pin" };
431
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700432 private final Context mContext;
Brian Carlstromdfad99a2014-05-07 15:21:14 -0700433 private final NativeDaemonConnector mConnector;
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700434 private final NativeDaemonConnector mCryptConnector;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700435
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700436 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900437 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700438 private volatile boolean mDaemonConnected = false;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700439
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700440 private PackageManagerService mPms;
441
442 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700443 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700444
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700445 // Two connectors - mConnector & mCryptConnector
446 private final CountDownLatch mConnectedSignal = new CountDownLatch(2);
Jeff Sharkey0be607c2012-11-14 14:39:19 -0800447 private final CountDownLatch mAsecsScanned = new CountDownLatch(1);
Jeff Sharkey48877892015-03-18 11:27:19 -0700448
449 private final Object mUnmountLock = new Object();
450 @GuardedBy("mUnmountLock")
451 private CountDownLatch mUnmountSignal;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -0800452
San Mehat6cdd9c02010-02-09 14:45:20 -0800453 /**
454 * Private hash of currently mounted secure containers.
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800455 * Used as a lock in methods to manipulate secure containers.
San Mehat6cdd9c02010-02-09 14:45:20 -0800456 */
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -0800457 final private HashSet<String> mAsecMountSet = new HashSet<String>();
San Mehat6cdd9c02010-02-09 14:45:20 -0800458
Kenny Root02c87302010-07-01 08:10:18 -0700459 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700460 * The size of the crypto algorithm key in bits for OBB files. Currently
461 * Twofish is used which takes 128-bit keys.
462 */
463 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
464
465 /**
466 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
467 * 1024 is reasonably secure and not too slow.
468 */
469 private static final int PBKDF2_HASH_ROUNDS = 1024;
470
471 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700472 * Mounted OBB tracking information. Used to track the current state of all
473 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700474 */
Kenny Root735de3b2010-09-30 14:11:39 -0700475 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700476
477 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700478 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
479
Svet Ganov6ee871e2015-07-10 14:29:33 -0700480 // Not guarded by a lock.
481 private final MountServiceInternalImpl mMountServiceInternal = new MountServiceInternalImpl();
482
Kenny Roota02b8b02010-08-05 16:14:17 -0700483 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700484 public ObbState(String rawPath, String canonicalPath, int callingUid,
485 IObbActionListener token, int nonce) {
486 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700487 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700488
489 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700490 this.token = token;
491 this.nonce = nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700492 }
493
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700494 final String rawPath;
495 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700496
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700497 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700498
Kenny Rootaf9d6672010-10-08 09:21:39 -0700499 // Token of remote Binder caller
500 final IObbActionListener token;
501
502 // Identifier to pass back to the token
503 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700504
Kenny Root735de3b2010-09-30 14:11:39 -0700505 public IBinder getBinder() {
506 return token.asBinder();
507 }
508
Kenny Roota02b8b02010-08-05 16:14:17 -0700509 @Override
510 public void binderDied() {
511 ObbAction action = new UnmountObbAction(this, true);
512 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700513 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700514
Kenny Root5919ac62010-10-05 09:49:40 -0700515 public void link() throws RemoteException {
516 getBinder().linkToDeath(this, 0);
517 }
518
519 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700520 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700521 }
Kenny Root38cf8862010-09-26 14:18:51 -0700522
523 @Override
524 public String toString() {
525 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700526 sb.append("rawPath=").append(rawPath);
527 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700528 sb.append(",ownerGid=").append(ownerGid);
529 sb.append(",token=").append(token);
530 sb.append(",binder=").append(getBinder());
Kenny Root38cf8862010-09-26 14:18:51 -0700531 sb.append('}');
532 return sb.toString();
533 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700534 }
535
536 // OBB Action Handler
537 final private ObbActionHandler mObbActionHandler;
538
539 // OBB action handler messages
540 private static final int OBB_RUN_ACTION = 1;
541 private static final int OBB_MCS_BOUND = 2;
542 private static final int OBB_MCS_UNBIND = 3;
543 private static final int OBB_MCS_RECONNECT = 4;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700544 private static final int OBB_FLUSH_MOUNT_STATE = 5;
Kenny Roota02b8b02010-08-05 16:14:17 -0700545
546 /*
547 * Default Container Service information
548 */
549 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
550 "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService");
551
552 final private DefaultContainerConnection mDefContainerConn = new DefaultContainerConnection();
553
554 class DefaultContainerConnection implements ServiceConnection {
Jeff Sharkey48877892015-03-18 11:27:19 -0700555 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700556 public void onServiceConnected(ComponentName name, IBinder service) {
557 if (DEBUG_OBB)
558 Slog.i(TAG, "onServiceConnected");
559 IMediaContainerService imcs = IMediaContainerService.Stub.asInterface(service);
560 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_MCS_BOUND, imcs));
561 }
562
Jeff Sharkey48877892015-03-18 11:27:19 -0700563 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -0700564 public void onServiceDisconnected(ComponentName name) {
565 if (DEBUG_OBB)
566 Slog.i(TAG, "onServiceDisconnected");
567 }
568 };
569
570 // Used in the ObbActionHandler
571 private IMediaContainerService mContainerService = null;
Kenny Root02c87302010-07-01 08:10:18 -0700572
Christopher Tate7265abe2014-11-21 13:54:45 -0800573 // Last fstrim operation tracking
574 private static final String LAST_FSTRIM_FILE = "last-fstrim";
575 private final File mLastMaintenanceFile;
576 private long mLastMaintenance;
577
Kenny Root02c87302010-07-01 08:10:18 -0700578 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700579 private static final int H_SYSTEM_READY = 1;
580 private static final int H_DAEMON_CONNECTED = 2;
581 private static final int H_SHUTDOWN = 3;
582 private static final int H_FSTRIM = 4;
583 private static final int H_VOLUME_MOUNT = 5;
584 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700585 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700586 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800587 private static final int H_PARTITION_FORGET = 9;
588 private static final int H_RESET = 10;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800589
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400590 class MountServiceHandler extends Handler {
Jeff Sharkey48877892015-03-18 11:27:19 -0700591 public MountServiceHandler(Looper looper) {
592 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400593 }
594
Jason parks5af0b912010-11-29 09:05:25 -0600595 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800596 public void handleMessage(Message msg) {
597 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700598 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700599 handleSystemReady();
600 break;
601 }
602 case H_DAEMON_CONNECTED: {
603 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700604 break;
605 }
Christopher Tated417d622013-08-19 16:14:25 -0700606 case H_FSTRIM: {
Jeff Sharkey1783f142015-04-17 10:52:51 -0700607 if (!isReady()) {
608 Slog.i(TAG, "fstrim requested, but no daemon connection yet; trying again");
Christopher Tate7618db12015-04-28 16:32:55 -0700609 sendMessageDelayed(obtainMessage(H_FSTRIM, msg.obj),
610 DateUtils.SECOND_IN_MILLIS);
611 break;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700612 }
613
Christopher Tated417d622013-08-19 16:14:25 -0700614 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800615
616 // Remember when we kicked it off
617 try {
618 mLastMaintenance = System.currentTimeMillis();
619 mLastMaintenanceFile.setLastModified(mLastMaintenance);
620 } catch (Exception e) {
621 Slog.e(TAG, "Unable to record last fstrim!");
622 }
623
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700624 final boolean shouldBenchmark = shouldBenchmark();
Christopher Tated417d622013-08-19 16:14:25 -0700625 try {
626 // This method must be run on the main (handler) thread,
627 // so it is safe to directly call into vold.
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700628 mConnector.execute("fstrim", shouldBenchmark ? "dotrimbench" : "dotrim");
Christopher Tated417d622013-08-19 16:14:25 -0700629 } catch (NativeDaemonConnectorException ndce) {
630 Slog.e(TAG, "Failed to run fstrim!");
631 }
Christopher Tate7265abe2014-11-21 13:54:45 -0800632
Christopher Tated417d622013-08-19 16:14:25 -0700633 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700634 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700635 Runnable callback = (Runnable) msg.obj;
636 if (callback != null) {
637 callback.run();
638 }
639 break;
640 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700641 case H_SHUTDOWN: {
642 final IMountShutdownObserver obs = (IMountShutdownObserver) msg.obj;
643 boolean success = false;
644 try {
645 success = mConnector.execute("volume", "shutdown").isClassOk();
646 } catch (NativeDaemonConnectorException ignored) {
647 }
648 if (obs != null) {
649 try {
650 obs.onShutDownComplete(success ? 0 : -1);
651 } catch (RemoteException ignored) {
652 }
653 }
654 break;
655 }
656 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700657 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700658 if (isMountDisallowed(vol)) {
659 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
660 break;
661 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700662 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -0700663 mConnector.execute("volume", "mount", vol.id, vol.mountFlags,
664 vol.mountUserId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700665 } catch (NativeDaemonConnectorException ignored) {
666 }
667 break;
668 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700669 case H_VOLUME_UNMOUNT: {
670 final VolumeInfo vol = (VolumeInfo) msg.obj;
671 unmount(vol.getId());
672 break;
673 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700674 case H_VOLUME_BROADCAST: {
675 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700676 final String envState = userVol.getState();
677 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700678 + userVol.getOwner());
679
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700680 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700681 if (action != null) {
682 final Intent intent = new Intent(action,
683 Uri.fromFile(userVol.getPathFile()));
684 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
686 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
687 }
688 break;
689 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700690 case H_INTERNAL_BROADCAST: {
691 // Internal broadcasts aimed at system components, not for
692 // third-party apps.
693 final Intent intent = (Intent) msg.obj;
694 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
695 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800696 break;
697 }
698 case H_PARTITION_FORGET: {
699 final String partGuid = (String) msg.obj;
700 forgetPartition(partGuid);
701 break;
702 }
703 case H_RESET: {
704 resetIfReadyAndConnected();
705 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700706 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800707 }
708 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700709 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700710
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700711 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800712
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700713 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
714 @Override
715 public void onReceive(Context context, Intent intent) {
716 final String action = intent.getAction();
717 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700718 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700719
720 try {
721 if (Intent.ACTION_USER_ADDED.equals(action)) {
722 final UserManager um = mContext.getSystemService(UserManager.class);
723 final int userSerialNumber = um.getUserSerialNumber(userId);
724 mConnector.execute("volume", "user_added", userId, userSerialNumber);
725 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700726 synchronized (mVolumes) {
727 final int size = mVolumes.size();
728 for (int i = 0; i < size; i++) {
729 final VolumeInfo vol = mVolumes.valueAt(i);
730 if (vol.mountUserId == userId) {
731 vol.mountUserId = UserHandle.USER_NULL;
732 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
733 }
734 }
735 }
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700736 mConnector.execute("volume", "user_removed", userId);
737 }
738 } catch (NativeDaemonConnectorException e) {
739 Slog.w(TAG, "Failed to send user details to vold", e);
740 }
741 }
742 };
743
Jeff Sharkey56e62932015-03-21 20:41:00 -0700744 @Override
745 public void waitForAsecScan() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700746 waitForLatch(mAsecsScanned, "mAsecsScanned");
Kenny Root51a573c2012-05-17 13:30:28 -0700747 }
748
San Mehat207e5382010-02-04 20:46:54 -0800749 private void waitForReady() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700750 waitForLatch(mConnectedSignal, "mConnectedSignal");
Kenny Root51a573c2012-05-17 13:30:28 -0700751 }
752
Jeff Sharkey48877892015-03-18 11:27:19 -0700753 private void waitForLatch(CountDownLatch latch, String condition) {
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700754 try {
755 waitForLatch(latch, condition, -1);
756 } catch (TimeoutException ignored) {
757 }
758 }
759
760 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
761 throws TimeoutException {
762 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700763 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700764 try {
765 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800766 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700767 } else {
768 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700769 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800770 }
Kenny Root51a573c2012-05-17 13:30:28 -0700771 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700772 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800773 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700774 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
775 throw new TimeoutException("Thread " + Thread.currentThread().getName()
776 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
777 }
San Mehat207e5382010-02-04 20:46:54 -0800778 }
San Mehat1f6301e2010-01-07 22:40:27 -0800779 }
Kenny Root02c87302010-07-01 08:10:18 -0700780
Paul Lawrence945490c2014-03-27 16:37:28 +0000781 private boolean isReady() {
782 try {
783 return mConnectedSignal.await(0, TimeUnit.MILLISECONDS);
784 } catch (InterruptedException e) {
785 return false;
786 }
787 }
788
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700789 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700790 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800791 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700792
Jeff Sharkey48877892015-03-18 11:27:19 -0700793 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700794 MountServiceIdler.scheduleIdlePass(mContext);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700795 }
796
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700797 /**
798 * MediaProvider has a ton of code that makes assumptions about storage
799 * paths never changing, so we outright kill them to pick up new state.
800 */
801 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700802 private void killMediaProvider(List<UserInfo> users) {
803 if (users == null) return;
804
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700805 final long token = Binder.clearCallingIdentity();
806 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700807 for (UserInfo user : users) {
808 // System user does not have media provider, so skip.
809 if (user.isSystemOnly()) continue;
810
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -0700811 final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY,
812 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE, user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700813 if (provider != null) {
814 final IActivityManager am = ActivityManagerNative.getDefault();
815 try {
816 am.killApplicationWithAppId(provider.applicationInfo.packageName,
817 UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
818 // We only need to run this once. It will kill all users' media processes.
819 break;
820 } catch (RemoteException e) {
821 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700822 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700823 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700824 } finally {
825 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700826 }
827 }
828
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800829 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700830 // Create a stub volume that represents internal storage
831 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
832 VolumeInfo.TYPE_PRIVATE, null, null);
833 internal.state = VolumeInfo.STATE_MOUNTED;
834 internal.path = Environment.getDataDirectory().getAbsolutePath();
835 mVolumes.put(internal.id, internal);
836 }
837
Jeff Sharkey8924e872015-11-30 12:52:10 -0700838 private void initIfReadyAndConnected() {
839 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
840 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700841 if (mSystemReady && mDaemonConnected
842 && !StorageManager.isNativeFileBasedEncryptionEnabled()) {
843 // When booting a device without native support, make sure that our
844 // user directories are locked or unlocked based on the current
845 // emulation status.
846 final boolean initLocked = StorageManager.isEmulatedFileBasedEncryptionEnabled();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000847 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700848 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700849 for (UserInfo user : users) {
850 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700851 if (initLocked) {
852 mCryptConnector.execute("cryptfs", "lock_user_key", user.id);
853 } else {
854 mCryptConnector.execute("cryptfs", "unlock_user_key", user.id,
Paul Crowleyd94ab732016-02-15 06:44:51 +0000855 user.serialNumber, "!", "!");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700856 }
Jeff Sharkey8924e872015-11-30 12:52:10 -0700857 } catch (NativeDaemonConnectorException e) {
858 Slog.w(TAG, "Failed to init vold", e);
859 }
860 }
861 }
862 }
863
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800864 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700865 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
866 + ", mDaemonConnected=" + mDaemonConnected);
867 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800868 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700869 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700870
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700871 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800872 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700873 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700874
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800875 mDisks.clear();
876 mVolumes.clear();
877
878 addInternalVolumeLocked();
879 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700880
Jeff Sharkey48877892015-03-18 11:27:19 -0700881 try {
882 mConnector.execute("volume", "reset");
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700883
884 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700885 for (UserInfo user : users) {
886 mConnector.execute("volume", "user_added", user.id, user.serialNumber);
887 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700888 for (int userId : systemUnlockedUsers) {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700889 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700890 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700891 } catch (NativeDaemonConnectorException e) {
892 Slog.w(TAG, "Failed to reset vold", e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700893 }
894 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700895 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700896
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700897 private void onUnlockUser(int userId) {
898 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700899
900 // We purposefully block here to make sure that user-specific
901 // staging area is ready so it's ready for zygote-forked apps to
902 // bind mount against.
903 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700904 mConnector.execute("volume", "user_started", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700905 } catch (NativeDaemonConnectorException ignored) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700906 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700907
908 // Record user as started so newly mounted volumes kick off events
909 // correctly, then synthesize events for any already-mounted volumes.
910 synchronized (mVolumes) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700911 for (int i = 0; i < mVolumes.size(); i++) {
912 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700913 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700914 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700915 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700916
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700917 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
918 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700919 }
920 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700921 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700922 }
923 }
924
925 private void onCleanupUser(int userId) {
926 Slog.d(TAG, "onCleanupUser " + userId);
927
928 try {
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700929 mConnector.execute("volume", "user_stopped", userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700930 } catch (NativeDaemonConnectorException ignored) {
931 }
932
933 synchronized (mVolumes) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700934 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700935 }
936 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700937
Christopher Tated417d622013-08-19 16:14:25 -0700938 void runIdleMaintenance(Runnable callback) {
939 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
940 }
941
Christopher Tate7265abe2014-11-21 13:54:45 -0800942 // Binder entry point for kicking off an immediate fstrim
943 @Override
944 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700945 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -0800946 runIdleMaintenance(null);
947 }
948
949 @Override
950 public long lastMaintenance() {
951 return mLastMaintenance;
952 }
953
San Mehat4270e1e2010-01-29 05:32:19 -0800954 /**
San Mehat4270e1e2010-01-29 05:32:19 -0800955 * Callback from NativeDaemonConnector
956 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700957 @Override
San Mehat4270e1e2010-01-29 05:32:19 -0800958 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700959 mDaemonConnected = true;
960 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
961 }
962
963 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700964 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800965 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -0700966
San Mehat4270e1e2010-01-29 05:32:19 -0800967 /*
Jeff Sharkey48877892015-03-18 11:27:19 -0700968 * Now that we've done our initialization, release
969 * the hounds!
San Mehat4270e1e2010-01-29 05:32:19 -0800970 */
Jeff Sharkey48877892015-03-18 11:27:19 -0700971 mConnectedSignal.countDown();
Paul Lawrence1c62cbb2015-06-03 14:14:52 -0700972 if (mConnectedSignal.getCount() != 0) {
973 // More daemons need to connect
974 return;
975 }
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400976
Jeff Sharkey48877892015-03-18 11:27:19 -0700977 // On an encrypted device we can't see system properties yet, so pull
978 // the system locale out of the mount service.
979 if ("".equals(SystemProperties.get("vold.encrypt_progress"))) {
980 copyLocaleFromMountService();
981 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700982
Jeff Sharkey48877892015-03-18 11:27:19 -0700983 // Let package manager load internal ASECs.
984 mPms.scanAvailableAsecs();
Mike Lockwood7fa24aa2011-03-23 14:52:34 -0400985
Jeff Sharkey48877892015-03-18 11:27:19 -0700986 // Notify people waiting for ASECs to be scanned that it's done.
987 mAsecsScanned.countDown();
San Mehat4270e1e2010-01-29 05:32:19 -0800988 }
989
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700990 private void copyLocaleFromMountService() {
991 String systemLocale;
992 try {
993 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
994 } catch (RemoteException e) {
995 return;
996 }
997 if (TextUtils.isEmpty(systemLocale)) {
998 return;
999 }
1000
1001 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1002 Locale locale = Locale.forLanguageTag(systemLocale);
1003 Configuration config = new Configuration();
1004 config.setLocale(locale);
1005 try {
1006 ActivityManagerNative.getDefault().updateConfiguration(config);
1007 } catch (RemoteException e) {
1008 Slog.e(TAG, "Error setting system locale from mount service", e);
1009 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001010
1011 // Temporary workaround for http://b/17945169.
1012 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001013 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001014 }
1015
San Mehat4270e1e2010-01-29 05:32:19 -08001016 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001017 * Callback from NativeDaemonConnector
1018 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001019 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001020 public boolean onCheckHoldWakeLock(int code) {
1021 return false;
1022 }
1023
1024 /**
1025 * Callback from NativeDaemonConnector
1026 */
Jeff Sharkey48877892015-03-18 11:27:19 -07001027 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001028 public boolean onEvent(int code, String raw, String[] cooked) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001029 synchronized (mLock) {
1030 return onEventLocked(code, raw, cooked);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08001031 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001032 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001033
Jeff Sharkey48877892015-03-18 11:27:19 -07001034 private boolean onEventLocked(int code, String raw, String[] cooked) {
1035 switch (code) {
1036 case VoldResponseCode.DISK_CREATED: {
1037 if (cooked.length != 3) break;
1038 final String id = cooked[1];
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001039 int flags = Integer.parseInt(cooked[2]);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001040 if (SystemProperties.getBoolean(StorageManager.PROP_FORCE_ADOPTABLE, false)
1041 || mForceAdoptable) {
Jeff Sharkey74acbbb2015-04-21 12:14:03 -07001042 flags |= DiskInfo.FLAG_ADOPTABLE;
1043 }
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001044 mDisks.put(id, new DiskInfo(id, flags));
Jeff Sharkey48877892015-03-18 11:27:19 -07001045 break;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07001046 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001047 case VoldResponseCode.DISK_SIZE_CHANGED: {
1048 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001049 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001050 if (disk != null) {
1051 disk.size = Long.parseLong(cooked[2]);
San Mehat4270e1e2010-01-29 05:32:19 -08001052 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001053 break;
1054 }
1055 case VoldResponseCode.DISK_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001056 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001057 if (disk != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001058 final StringBuilder builder = new StringBuilder();
1059 for (int i = 2; i < cooked.length; i++) {
1060 builder.append(cooked[i]).append(' ');
1061 }
1062 disk.label = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001063 }
1064 break;
1065 }
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001066 case VoldResponseCode.DISK_SCANNED: {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001067 if (cooked.length != 2) break;
1068 final DiskInfo disk = mDisks.get(cooked[1]);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001069 if (disk != null) {
1070 onDiskScannedLocked(disk);
1071 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -07001072 break;
1073 }
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001074 case VoldResponseCode.DISK_SYS_PATH_CHANGED: {
1075 if (cooked.length != 3) break;
1076 final DiskInfo disk = mDisks.get(cooked[1]);
1077 if (disk != null) {
1078 disk.sysPath = cooked[2];
1079 }
1080 break;
1081 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001082 case VoldResponseCode.DISK_DESTROYED: {
1083 if (cooked.length != 2) break;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07001084 final DiskInfo disk = mDisks.remove(cooked[1]);
1085 if (disk != null) {
1086 mCallbacks.notifyDiskDestroyed(disk);
1087 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001088 break;
1089 }
San Mehat4270e1e2010-01-29 05:32:19 -08001090
Jeff Sharkey48877892015-03-18 11:27:19 -07001091 case VoldResponseCode.VOLUME_CREATED: {
Jeff Sharkey48877892015-03-18 11:27:19 -07001092 final String id = cooked[1];
1093 final int type = Integer.parseInt(cooked[2]);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001094 final String diskId = TextUtils.nullIfEmpty(cooked[3]);
1095 final String partGuid = TextUtils.nullIfEmpty(cooked[4]);
1096
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001097 final DiskInfo disk = mDisks.get(diskId);
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07001098 final VolumeInfo vol = new VolumeInfo(id, type, disk, partGuid);
Jeff Sharkey48877892015-03-18 11:27:19 -07001099 mVolumes.put(id, vol);
1100 onVolumeCreatedLocked(vol);
1101 break;
1102 }
1103 case VoldResponseCode.VOLUME_STATE_CHANGED: {
1104 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001105 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001106 if (vol != null) {
1107 final int oldState = vol.state;
1108 final int newState = Integer.parseInt(cooked[2]);
1109 vol.state = newState;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001110 onVolumeStateChangedLocked(vol, oldState, newState);
Jeff Sharkey48877892015-03-18 11:27:19 -07001111 }
1112 break;
1113 }
1114 case VoldResponseCode.VOLUME_FS_TYPE_CHANGED: {
1115 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001116 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001117 if (vol != null) {
1118 vol.fsType = cooked[2];
1119 }
1120 break;
1121 }
1122 case VoldResponseCode.VOLUME_FS_UUID_CHANGED: {
1123 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001124 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001125 if (vol != null) {
1126 vol.fsUuid = cooked[2];
1127 }
1128 break;
1129 }
1130 case VoldResponseCode.VOLUME_FS_LABEL_CHANGED: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001131 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001132 if (vol != null) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07001133 final StringBuilder builder = new StringBuilder();
1134 for (int i = 2; i < cooked.length; i++) {
1135 builder.append(cooked[i]).append(' ');
1136 }
1137 vol.fsLabel = builder.toString().trim();
Jeff Sharkey48877892015-03-18 11:27:19 -07001138 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001139 // TODO: notify listeners that label changed
Jeff Sharkey48877892015-03-18 11:27:19 -07001140 break;
1141 }
1142 case VoldResponseCode.VOLUME_PATH_CHANGED: {
1143 if (cooked.length != 3) break;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001144 final VolumeInfo vol = mVolumes.get(cooked[1]);
Jeff Sharkey48877892015-03-18 11:27:19 -07001145 if (vol != null) {
1146 vol.path = cooked[2];
1147 }
1148 break;
1149 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001150 case VoldResponseCode.VOLUME_INTERNAL_PATH_CHANGED: {
1151 if (cooked.length != 3) break;
1152 final VolumeInfo vol = mVolumes.get(cooked[1]);
1153 if (vol != null) {
1154 vol.internalPath = cooked[2];
1155 }
1156 break;
1157 }
Jeff Sharkey48877892015-03-18 11:27:19 -07001158 case VoldResponseCode.VOLUME_DESTROYED: {
1159 if (cooked.length != 2) break;
1160 mVolumes.remove(cooked[1]);
1161 break;
1162 }
San Mehat4270e1e2010-01-29 05:32:19 -08001163
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001164 case VoldResponseCode.MOVE_STATUS: {
1165 final int status = Integer.parseInt(cooked[1]);
1166 onMoveStatusLocked(status);
1167 break;
1168 }
Jeff Sharkey9756d752015-05-14 21:07:42 -07001169 case VoldResponseCode.BENCHMARK_RESULT: {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001170 if (cooked.length != 7) break;
1171 final String path = cooked[1];
1172 final String ident = cooked[2];
1173 final long create = Long.parseLong(cooked[3]);
1174 final long drop = Long.parseLong(cooked[4]);
1175 final long run = Long.parseLong(cooked[5]);
1176 final long destroy = Long.parseLong(cooked[6]);
1177
Jeff Sharkey9756d752015-05-14 21:07:42 -07001178 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001179 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1180 + " " + ident + " " + create + " " + run + " " + destroy);
1181
1182 final VolumeRecord rec = findRecordForPath(path);
1183 if (rec != null) {
1184 rec.lastBenchMillis = System.currentTimeMillis();
1185 writeSettingsLocked();
1186 }
1187
1188 break;
1189 }
1190 case VoldResponseCode.TRIM_RESULT: {
1191 if (cooked.length != 4) break;
1192 final String path = cooked[1];
1193 final long bytes = Long.parseLong(cooked[2]);
1194 final long time = Long.parseLong(cooked[3]);
1195
1196 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1197 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path)
1198 + " " + bytes + " " + time);
1199
1200 final VolumeRecord rec = findRecordForPath(path);
1201 if (rec != null) {
1202 rec.lastTrimMillis = System.currentTimeMillis();
1203 writeSettingsLocked();
1204 }
1205
Jeff Sharkey9756d752015-05-14 21:07:42 -07001206 break;
1207 }
1208
Jeff Sharkey48877892015-03-18 11:27:19 -07001209 default: {
1210 Slog.d(TAG, "Unhandled vold event " + code);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001211 }
San Mehat4270e1e2010-01-29 05:32:19 -08001212 }
1213
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001214 return true;
San Mehat4270e1e2010-01-29 05:32:19 -08001215 }
1216
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001217 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001218 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001219 for (int i = 0; i < mVolumes.size(); i++) {
1220 final VolumeInfo vol = mVolumes.valueAt(i);
1221 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001222 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001223 }
1224 }
1225
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001226 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
1227 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1228 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1229 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001230 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001231
1232 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1233 if (latch != null) {
1234 latch.countDown();
1235 }
1236
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001237 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001238 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001239 }
1240
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001241 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001242 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1243 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1244 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1245
1246 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1247 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1248 Slog.v(TAG, "Found primary storage at " + vol);
1249 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1250 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1251 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1252
1253 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1254 Slog.v(TAG, "Found primary storage at " + vol);
1255 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1256 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1257 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1258 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001259
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001260 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001261 // TODO: only look at first public partition
1262 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1263 && vol.disk.isDefaultPrimary()) {
1264 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001265 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1266 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001267 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001268
1269 // Adoptable public disks are visible to apps, since they meet
1270 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001271 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001272 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1273 }
1274
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07001275 vol.mountUserId = ActivityManager.getCurrentUser();
Jeff Sharkey48877892015-03-18 11:27:19 -07001276 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001277
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001278 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1279 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1280
San Mehat4270e1e2010-01-29 05:32:19 -08001281 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001282 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001283 }
1284 }
1285
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001286 private boolean isBroadcastWorthy(VolumeInfo vol) {
1287 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001288 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001289 case VolumeInfo.TYPE_PUBLIC:
1290 case VolumeInfo.TYPE_EMULATED:
1291 break;
1292 default:
1293 return false;
1294 }
1295
1296 switch (vol.getState()) {
1297 case VolumeInfo.STATE_MOUNTED:
1298 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1299 case VolumeInfo.STATE_EJECTING:
1300 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001301 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001302 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001303 break;
1304 default:
1305 return false;
1306 }
1307
1308 return true;
1309 }
1310
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001311 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001312 // Remember that we saw this volume so we're ready to accept user
1313 // metadata, or so we can annoy them when a private volume is ejected
1314 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001315 VolumeRecord rec = mRecords.get(vol.fsUuid);
1316 if (rec == null) {
1317 rec = new VolumeRecord(vol.type, vol.fsUuid);
1318 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001319 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001320 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1321 rec.nickname = vol.disk.getDescription();
1322 }
1323 mRecords.put(rec.fsUuid, rec);
1324 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001325 } else {
1326 // Handle upgrade case where we didn't store partition GUID
1327 if (TextUtils.isEmpty(rec.partGuid)) {
1328 rec.partGuid = vol.partGuid;
1329 writeSettingsLocked();
1330 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001331 }
1332 }
1333
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001334 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1335
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001336 // Do not broadcast before boot has completed to avoid launching the
1337 // processes that receive the intent unnecessarily.
1338 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001339 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001340 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1341 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001342 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001343 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001344 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001345 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001346
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001347 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1348 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001349
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001350 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1351 // Kick state changed event towards all started users. Any users
1352 // started after this point will trigger additional
1353 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001354 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001355 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001356 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001357 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001358
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001359 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1360 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001361 }
1362 }
1363 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001364
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001365 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001366 // TODO: this should eventually be handled by new ObbVolume state changes
1367 /*
1368 * Some OBBs might have been unmounted when this volume was
1369 * unmounted, so send a message to the handler to let it know to
1370 * remove those from the list of mounted OBBS.
1371 */
1372 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1373 OBB_FLUSH_MOUNT_STATE, vol.path));
1374 }
San Mehat4270e1e2010-01-29 05:32:19 -08001375 }
1376
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001377 private void onMoveStatusLocked(int status) {
1378 if (mMoveCallback == null) {
1379 Slog.w(TAG, "Odd, status but no move requested");
1380 return;
1381 }
1382
1383 // TODO: estimate remaining time
1384 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001385 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001386 } catch (RemoteException ignored) {
1387 }
1388
1389 // We've finished copying and we're about to clean up old data, so
1390 // remember that move was successful if we get rebooted
1391 if (status == MOVE_STATUS_COPY_FINISHED) {
1392 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1393
1394 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001395 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001396 }
1397
1398 if (PackageManager.isMoveStatusFinished(status)) {
1399 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1400
1401 mMoveCallback = null;
1402 mMoveTargetUuid = null;
1403 }
1404 }
1405
Jeff Sharkey48877892015-03-18 11:27:19 -07001406 private void enforcePermission(String perm) {
1407 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001408 }
1409
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001410 /**
1411 * Decide if volume is mountable per device policies.
1412 */
1413 private boolean isMountDisallowed(VolumeInfo vol) {
1414 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE) {
1415 final UserManager userManager = mContext.getSystemService(UserManager.class);
1416 return userManager.hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1417 Binder.getCallingUserHandle());
1418 } else {
1419 return false;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001420 }
1421 }
1422
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001423 private void enforceAdminUser() {
1424 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1425 final int callingUserId = UserHandle.getCallingUserId();
1426 boolean isAdmin;
1427 long token = Binder.clearCallingIdentity();
1428 try {
1429 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1430 } finally {
1431 Binder.restoreCallingIdentity(token);
1432 }
1433 if (!isAdmin) {
1434 throw new SecurityException("Only admin users can adopt sd cards");
1435 }
1436 }
1437
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001438 /**
San Mehat207e5382010-02-04 20:46:54 -08001439 * Constructs a new MountService instance
1440 *
1441 * @param context Binder context for this service
1442 */
1443 public MountService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001444 sSelf = this;
1445
San Mehat207e5382010-02-04 20:46:54 -08001446 mContext = context;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001447 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001448 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001449
San Mehat207e5382010-02-04 20:46:54 -08001450 // XXX: This will go away soon in favor of IMountServiceObserver
1451 mPms = (PackageManagerService) ServiceManager.getService("package");
1452
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001453 HandlerThread hthread = new HandlerThread(TAG);
1454 hthread.start();
1455 mHandler = new MountServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001456
Kenny Roota02b8b02010-08-05 16:14:17 -07001457 // Add OBB Action Handler to MountService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001458 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001459
Christopher Tate7265abe2014-11-21 13:54:45 -08001460 // Initialize the last-fstrim tracking if necessary
1461 File dataDir = Environment.getDataDirectory();
1462 File systemDir = new File(dataDir, "system");
1463 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1464 if (!mLastMaintenanceFile.exists()) {
1465 // Not setting mLastMaintenance here means that we will force an
1466 // fstrim during reboot following the OTA that installs this code.
1467 try {
1468 (new FileOutputStream(mLastMaintenanceFile)).close();
1469 } catch (IOException e) {
1470 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1471 }
1472 } else {
1473 mLastMaintenance = mLastMaintenanceFile.lastModified();
1474 }
1475
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001476 mSettingsFile = new AtomicFile(
Jeff Sharkey8212ae02016-02-10 14:46:43 -07001477 new File(Environment.getDataSystemDirectory(), "storage.xml"));
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001478
1479 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001480 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001481 }
1482
Svet Ganov6ee871e2015-07-10 14:29:33 -07001483 LocalServices.addService(MountServiceInternal.class, mMountServiceInternal);
1484
Marco Nelissenc34ebce2010-02-18 13:39:41 -08001485 /*
Kenny Root305bcbf2010-09-03 07:56:38 -07001486 * Create the connection to vold with a maximum queue of twice the
1487 * amount of containers we'd ever expect to have. This keeps an
1488 * "asec list" from blocking a thread repeatedly.
1489 */
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001490
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001491 mConnector = new NativeDaemonConnector(this, "vold", MAX_CONTAINERS * 2, VOLD_TAG, 25,
1492 null);
Jeff Sharkey48877892015-03-18 11:27:19 -07001493 mConnector.setDebug(true);
Jeff Sharkey8948c012015-11-03 12:33:54 -08001494 mConnector.setWarnIfHeld(mLock);
Kenny Root51a573c2012-05-17 13:30:28 -07001495
Kenny Root305bcbf2010-09-03 07:56:38 -07001496 Thread thread = new Thread(mConnector, VOLD_TAG);
San Mehat207e5382010-02-04 20:46:54 -08001497 thread.start();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07001498
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07001499 // Reuse parameters from first connector since they are tested and safe
1500 mCryptConnector = new NativeDaemonConnector(this, "cryptd",
1501 MAX_CONTAINERS * 2, CRYPTD_TAG, 25, null);
1502 mCryptConnector.setDebug(true);
1503
1504 Thread crypt_thread = new Thread(mCryptConnector, CRYPTD_TAG);
1505 crypt_thread.start();
1506
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001507 final IntentFilter userFilter = new IntentFilter();
1508 userFilter.addAction(Intent.ACTION_USER_ADDED);
1509 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1510 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1511
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001512 synchronized (mLock) {
1513 addInternalVolumeLocked();
1514 }
Amith Yamasania7892482015-08-07 11:09:05 -07001515
Kenny Root07714d42011-08-17 17:49:28 -07001516 // Add ourself to the Watchdog monitors if enabled.
1517 if (WATCHDOG_ENABLE) {
1518 Watchdog.getInstance().addMonitor(this);
1519 }
San Mehat207e5382010-02-04 20:46:54 -08001520 }
1521
Jeff Sharkey56e62932015-03-21 20:41:00 -07001522 private void systemReady() {
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001523 mSystemReady = true;
1524 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1525 }
1526
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001527 private void bootCompleted() {
1528 mBootCompleted = true;
1529 }
1530
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001531 private String getDefaultPrimaryStorageUuid() {
1532 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1533 return StorageManager.UUID_PRIMARY_PHYSICAL;
1534 } else {
1535 return StorageManager.UUID_PRIVATE_INTERNAL;
1536 }
1537 }
1538
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001539 private void readSettingsLocked() {
1540 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001541 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001542 mForceAdoptable = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001543
1544 FileInputStream fis = null;
1545 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001546 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001547 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001548 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001549
1550 int type;
1551 while ((type = in.next()) != END_DOCUMENT) {
1552 if (type == START_TAG) {
1553 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001554 if (TAG_VOLUMES.equals(tag)) {
1555 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001556 final boolean primaryPhysical = SystemProperties.getBoolean(
1557 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1558 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1559 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1560 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001561 mPrimaryStorageUuid = readStringAttribute(in,
1562 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001563 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001564 mForceAdoptable = readBooleanAttribute(in, ATTR_FORCE_ADOPTABLE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001565
1566 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001567 final VolumeRecord rec = readVolumeRecord(in);
1568 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001569 }
1570 }
1571 }
1572 } catch (FileNotFoundException e) {
1573 // Missing metadata is okay, probably first boot
1574 } catch (IOException e) {
1575 Slog.wtf(TAG, "Failed reading metadata", e);
1576 } catch (XmlPullParserException e) {
1577 Slog.wtf(TAG, "Failed reading metadata", e);
1578 } finally {
1579 IoUtils.closeQuietly(fis);
1580 }
1581 }
1582
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001583 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001584 FileOutputStream fos = null;
1585 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001586 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001587
1588 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001589 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001590 out.startDocument(null, true);
1591 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001592 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001593 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001594 writeBooleanAttribute(out, ATTR_FORCE_ADOPTABLE, mForceAdoptable);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001595 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001596 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001597 final VolumeRecord rec = mRecords.valueAt(i);
1598 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001599 }
1600 out.endTag(null, TAG_VOLUMES);
1601 out.endDocument();
1602
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001603 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001604 } catch (IOException e) {
1605 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001606 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001607 }
1608 }
1609 }
1610
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001611 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1612 final int type = readIntAttribute(in, ATTR_TYPE);
1613 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1614 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001615 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001616 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1617 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001618 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1619 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1620 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001621 return meta;
1622 }
1623
1624 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1625 out.startTag(null, TAG_VOLUME);
1626 writeIntAttribute(out, ATTR_TYPE, rec.type);
1627 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001628 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001629 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1630 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001631 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1632 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1633 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001634 out.endTag(null, TAG_VOLUME);
1635 }
1636
San Mehat207e5382010-02-04 20:46:54 -08001637 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001638 * Exposed API calls below here
1639 */
1640
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001641 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001642 public void registerListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001643 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001644 }
1645
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001646 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001647 public void unregisterListener(IMountServiceListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001648 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001649 }
1650
Jeff Sharkey48877892015-03-18 11:27:19 -07001651 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08001652 public void shutdown(final IMountShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001653 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001654
San Mehata5078592010-03-25 09:36:54 -07001655 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001656 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001657 }
1658
Jeff Sharkey48877892015-03-18 11:27:19 -07001659 @Override
San Mehatb1043402010-02-05 08:26:50 -08001660 public boolean isUsbMassStorageConnected() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001661 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001662 }
1663
Jeff Sharkey48877892015-03-18 11:27:19 -07001664 @Override
Suchi Amalapurapu0eec21d2010-02-25 17:07:14 -08001665 public void setUsbMassStorageEnabled(boolean enable) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001666 throw new UnsupportedOperationException();
San Mehatb1043402010-02-05 08:26:50 -08001667 }
1668
Jeff Sharkey48877892015-03-18 11:27:19 -07001669 @Override
San Mehatb1043402010-02-05 08:26:50 -08001670 public boolean isUsbMassStorageEnabled() {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001671 throw new UnsupportedOperationException();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
Jason parks9ed98bc2011-01-17 09:58:35 -06001673
Jeff Sharkey48877892015-03-18 11:27:19 -07001674 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001675 public String getVolumeState(String mountPoint) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001676 throw new UnsupportedOperationException();
San Mehat7fd0fee2009-12-17 07:12:23 -08001677 }
1678
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001679 @Override
Kenny Roote1ff2142010-10-12 11:20:01 -07001680 public boolean isExternalStorageEmulated() {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001681 throw new UnsupportedOperationException();
Kenny Roote1ff2142010-10-12 11:20:01 -07001682 }
1683
Jeff Sharkey48877892015-03-18 11:27:19 -07001684 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001685 public int mountVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001686 mount(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001687 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689
Jeff Sharkey48877892015-03-18 11:27:19 -07001690 @Override
Ben Komalo13c71972011-09-07 16:35:56 -07001691 public void unmountVolume(String path, boolean force, boolean removeEncryption) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001692 unmount(findVolumeIdForPathOrThrow(path));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
Jeff Sharkey48877892015-03-18 11:27:19 -07001695 @Override
San Mehat4270e1e2010-01-29 05:32:19 -08001696 public int formatVolume(String path) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001697 format(findVolumeIdForPathOrThrow(path));
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001698 return 0;
1699 }
1700
1701 @Override
1702 public void mount(String volId) {
1703 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1704 waitForReady();
1705
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001706 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001707 if (isMountDisallowed(vol)) {
1708 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001709 }
1710 try {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001711 mConnector.execute("volume", "mount", vol.id, vol.mountFlags, vol.mountUserId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001712 } catch (NativeDaemonConnectorException e) {
1713 throw e.rethrowAsParcelableException();
1714 }
1715 }
1716
1717 @Override
1718 public void unmount(String volId) {
1719 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1720 waitForReady();
1721
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001722 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001723
1724 // TODO: expand PMS to know about multiple volumes
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001725 if (vol.isPrimaryPhysical()) {
1726 final long ident = Binder.clearCallingIdentity();
1727 try {
1728 synchronized (mUnmountLock) {
1729 mUnmountSignal = new CountDownLatch(1);
1730 mPms.updateExternalMediaStatus(false, true);
1731 waitForLatch(mUnmountSignal, "mUnmountSignal");
1732 mUnmountSignal = null;
1733 }
1734 } finally {
1735 Binder.restoreCallingIdentity(ident);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001736 }
1737 }
1738
1739 try {
1740 mConnector.execute("volume", "unmount", vol.id);
1741 } catch (NativeDaemonConnectorException e) {
1742 throw e.rethrowAsParcelableException();
1743 }
1744 }
1745
1746 @Override
1747 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001748 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat207e5382010-02-04 20:46:54 -08001749 waitForReady();
San Mehat5b77dab2010-01-26 13:28:50 -08001750
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001751 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001752 try {
Jeff Sharkey4e83cc92015-05-27 14:38:39 -07001753 mConnector.execute("volume", "format", vol.id, "auto");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001754 } catch (NativeDaemonConnectorException e) {
1755 throw e.rethrowAsParcelableException();
Jeff Sharkey48877892015-03-18 11:27:19 -07001756 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001757 }
1758
1759 @Override
Jeff Sharkey9756d752015-05-14 21:07:42 -07001760 public long benchmark(String volId) {
1761 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1762 waitForReady();
1763
1764 try {
Jeff Sharkey14cbe522015-07-08 14:06:37 -07001765 // TODO: make benchmark async so we don't block other commands
1766 final NativeDaemonEvent res = mConnector.execute(3 * DateUtils.MINUTE_IN_MILLIS,
1767 "volume", "benchmark", volId);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001768 return Long.parseLong(res.getMessage());
Todd Kennedy8101ee62015-06-23 13:35:28 -07001769 } catch (NativeDaemonTimeoutException e) {
1770 return Long.MAX_VALUE;
Jeff Sharkey9756d752015-05-14 21:07:42 -07001771 } catch (NativeDaemonConnectorException e) {
1772 throw e.rethrowAsParcelableException();
1773 }
1774 }
1775
1776 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001777 public void partitionPublic(String diskId) {
1778 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
1779 waitForReady();
1780
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001781 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001782 try {
1783 mConnector.execute("volume", "partition", diskId, "public");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001784 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001785 } catch (NativeDaemonConnectorException e) {
1786 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001787 } catch (TimeoutException e) {
1788 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001789 }
1790 }
1791
1792 @Override
1793 public void partitionPrivate(String diskId) {
1794 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001795 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001796 waitForReady();
1797
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001798 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001799 try {
1800 mConnector.execute("volume", "partition", diskId, "private");
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001801 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001802 } catch (NativeDaemonConnectorException e) {
1803 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001804 } catch (TimeoutException e) {
1805 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001806 }
1807 }
1808
1809 @Override
1810 public void partitionMixed(String diskId, int ratio) {
1811 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001812 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001813 waitForReady();
1814
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001815 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001816 try {
1817 mConnector.execute("volume", "partition", diskId, "mixed", ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001818 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001819 } catch (NativeDaemonConnectorException e) {
1820 throw e.rethrowAsParcelableException();
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001821 } catch (TimeoutException e) {
1822 throw new IllegalStateException(e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825
Jeff Sharkey48877892015-03-18 11:27:19 -07001826 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001827 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001828 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1829 waitForReady();
1830
Jeff Sharkey50a05452015-04-29 11:24:52 -07001831 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001832 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001833 final VolumeRecord rec = mRecords.get(fsUuid);
1834 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07001835 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001836 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001837 }
1838 }
1839
1840 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001841 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001842 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1843 waitForReady();
1844
Jeff Sharkey50a05452015-04-29 11:24:52 -07001845 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001846 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001847 final VolumeRecord rec = mRecords.get(fsUuid);
1848 rec.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001849 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001850 writeSettingsLocked();
1851 }
1852 }
1853
1854 @Override
1855 public void forgetVolume(String fsUuid) {
1856 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1857 waitForReady();
1858
Jeff Sharkey50a05452015-04-29 11:24:52 -07001859 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001860
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001861 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001862 final VolumeRecord rec = mRecords.remove(fsUuid);
1863 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001864 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001865 }
1866 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07001867
1868 // If this had been primary storage, revert back to internal and
1869 // reset vold so we bind into new volume into place.
1870 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001871 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001872 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001873 }
1874
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001875 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001876 }
1877 }
1878
Jeff Sharkey7d2af542015-05-12 15:27:15 -07001879 @Override
1880 public void forgetAllVolumes() {
1881 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1882 waitForReady();
1883
Jeff Sharkey50a05452015-04-29 11:24:52 -07001884 synchronized (mLock) {
1885 for (int i = 0; i < mRecords.size(); i++) {
1886 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001887 final VolumeRecord rec = mRecords.valueAt(i);
1888 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001889 mHandler.obtainMessage(H_PARTITION_FORGET, rec.partGuid).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001890 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001891 mCallbacks.notifyVolumeForgotten(fsUuid);
1892 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07001893 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001894
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001895 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
1896 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
1897 }
1898
1899 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001900 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07001901 }
1902 }
1903
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001904 private void forgetPartition(String partGuid) {
1905 try {
1906 mConnector.execute("volume", "forget_partition", partGuid);
1907 } catch (NativeDaemonConnectorException e) {
1908 Slog.w(TAG, "Failed to forget key for " + partGuid + ": " + e);
1909 }
1910 }
1911
Svet Ganov6ee871e2015-07-10 14:29:33 -07001912 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07001913 waitForReady();
1914
Svet Ganov6ee871e2015-07-10 14:29:33 -07001915 String modeName = "none";
1916 switch (mode) {
1917 case Zygote.MOUNT_EXTERNAL_DEFAULT: {
1918 modeName = "default";
1919 } break;
1920
1921 case Zygote.MOUNT_EXTERNAL_READ: {
1922 modeName = "read";
1923 } break;
1924
1925 case Zygote.MOUNT_EXTERNAL_WRITE: {
1926 modeName = "write";
1927 } break;
Jeff Sharkey9527b222015-06-24 15:24:48 -07001928 }
1929
1930 try {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001931 mConnector.execute("volume", "remount_uid", uid, modeName);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001932 } catch (NativeDaemonConnectorException e) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001933 Slog.w(TAG, "Failed to remount UID " + uid + " as " + modeName + ": " + e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07001934 }
1935 }
1936
1937 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001938 public void setDebugFlags(int flags, int mask) {
1939 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1940 waitForReady();
1941
Jeff Sharkeyba512352015-11-12 20:17:45 -08001942 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001943 if (StorageManager.isNativeFileBasedEncryptionEnabled()) {
1944 throw new IllegalStateException(
1945 "Emulation not available on device with native FBE");
1946 }
1947
Jeff Sharkey1176e512016-02-29 17:01:26 -07001948 final long token = Binder.clearCallingIdentity();
1949 try {
1950 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
1951 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001952
Jeff Sharkey1176e512016-02-29 17:01:26 -07001953 // Perform hard reboot to kick policy into place
1954 mContext.getSystemService(PowerManager.class).reboot(null);
1955 } finally {
1956 Binder.restoreCallingIdentity(token);
1957 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08001958 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001959
Jeff Sharkeyba512352015-11-12 20:17:45 -08001960 if ((mask & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0) {
1961 synchronized (mLock) {
1962 mForceAdoptable = (flags & StorageManager.DEBUG_FORCE_ADOPTABLE) != 0;
1963
1964 writeSettingsLocked();
1965 mHandler.obtainMessage(H_RESET).sendToTarget();
1966 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07001967 }
1968 }
1969
1970 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001971 public String getPrimaryStorageUuid() {
1972 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1973 waitForReady();
1974
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001975 synchronized (mLock) {
1976 return mPrimaryStorageUuid;
1977 }
1978 }
1979
1980 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001981 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
1982 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
1983 waitForReady();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001984
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001985 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001986 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
1987 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001988 }
1989
1990 if (mMoveCallback != null) {
1991 throw new IllegalStateException("Move already in progress");
1992 }
1993 mMoveCallback = callback;
1994 mMoveTargetUuid = volumeUuid;
1995
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001996 // When moving to/from primary physical volume, we probably just nuked
1997 // the current storage location, so we have nothing to move.
1998 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1999 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
2000 Slog.d(TAG, "Skipping move to/from primary physical");
2001 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
2002 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002003 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002004
2005 } else {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002006 final VolumeInfo from = findStorageForUuid(mPrimaryStorageUuid);
2007 final VolumeInfo to = findStorageForUuid(volumeUuid);
2008
2009 if (from == null) {
2010 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2011 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2012 return;
2013 } else if (to == null) {
2014 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2015 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2016 return;
2017 }
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002018
2019 try {
2020 mConnector.execute("volume", "move_storage", from.id, to.id);
2021 } catch (NativeDaemonConnectorException e) {
2022 throw e.rethrowAsParcelableException();
2023 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002024 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002025 }
2026 }
2027
2028 @Override
Mike Lockwoodecedfdc2011-06-08 15:11:59 -07002029 public int[] getStorageUsers(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002030 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
San Mehatc1b4ce92010-02-16 17:13:03 -08002031 waitForReady();
2032 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002033 final String[] r = NativeDaemonEvent.filterMessageList(
2034 mConnector.executeForList("storage", "users", path),
2035 VoldResponseCode.StorageUsersListResult);
2036
San Mehatc1b4ce92010-02-16 17:13:03 -08002037 // FMT: <pid> <process name>
2038 int[] data = new int[r.length];
2039 for (int i = 0; i < r.length; i++) {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002040 String[] tok = r[i].split(" ");
San Mehatc1b4ce92010-02-16 17:13:03 -08002041 try {
2042 data[i] = Integer.parseInt(tok[0]);
2043 } catch (NumberFormatException nfe) {
San Mehata5078592010-03-25 09:36:54 -07002044 Slog.e(TAG, String.format("Error parsing pid %s", tok[0]));
San Mehatc1b4ce92010-02-16 17:13:03 -08002045 return new int[0];
2046 }
2047 }
2048 return data;
2049 } catch (NativeDaemonConnectorException e) {
San Mehata5078592010-03-25 09:36:54 -07002050 Slog.e(TAG, "Failed to retrieve storage users list", e);
San Mehatc1b4ce92010-02-16 17:13:03 -08002051 return new int[0];
2052 }
2053 }
2054
San Mehatb1043402010-02-05 08:26:50 -08002055 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002056 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002057 for (int i = 0; i < mVolumes.size(); i++) {
2058 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002059 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002060 // Cool beans, we have a mounted primary volume
2061 return;
2062 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002063 }
San Mehatb1043402010-02-05 08:26:50 -08002064 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002065
2066 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002067 }
2068
San Mehat4270e1e2010-01-29 05:32:19 -08002069 public String[] getSecureContainerList() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002070 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002071 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002072 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002073
San Mehat4270e1e2010-01-29 05:32:19 -08002074 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002075 return NativeDaemonEvent.filterMessageList(
2076 mConnector.executeForList("asec", "list"), VoldResponseCode.AsecListResult);
San Mehat4270e1e2010-01-29 05:32:19 -08002077 } catch (NativeDaemonConnectorException e) {
2078 return new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
San Mehat36972292010-01-06 11:06:32 -08002081
Kenny Root6dceb882012-04-12 14:23:49 -07002082 public int createSecureContainer(String id, int sizeMb, String fstype, String key,
2083 int ownerUid, boolean external) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002084 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehat207e5382010-02-04 20:46:54 -08002085 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002086 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002087
San Mehatb1043402010-02-05 08:26:50 -08002088 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002089 try {
Jeff Sharkey56cd6462013-06-07 15:09:15 -07002090 mConnector.execute("asec", "create", id, sizeMb, fstype, new SensitiveArg(key),
2091 ownerUid, external ? "1" : "0");
San Mehat4270e1e2010-01-29 05:32:19 -08002092 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002093 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002094 }
San Mehata181b212010-02-11 06:50:20 -08002095
2096 if (rc == StorageResultCode.OperationSucceeded) {
2097 synchronized (mAsecMountSet) {
2098 mAsecMountSet.add(id);
2099 }
2100 }
San Mehat4270e1e2010-01-29 05:32:19 -08002101 return rc;
San Mehat36972292010-01-06 11:06:32 -08002102 }
2103
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002104 @Override
2105 public int resizeSecureContainer(String id, int sizeMb, String key) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002106 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002107 waitForReady();
2108 warnOnNotMounted();
2109
2110 int rc = StorageResultCode.OperationSucceeded;
2111 try {
2112 mConnector.execute("asec", "resize", id, sizeMb, new SensitiveArg(key));
2113 } catch (NativeDaemonConnectorException e) {
2114 rc = StorageResultCode.OperationFailedInternalError;
2115 }
2116 return rc;
2117 }
2118
San Mehat4270e1e2010-01-29 05:32:19 -08002119 public int finalizeSecureContainer(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002120 enforcePermission(android.Manifest.permission.ASEC_CREATE);
San Mehatb1043402010-02-05 08:26:50 -08002121 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002122
San Mehatb1043402010-02-05 08:26:50 -08002123 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002124 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002125 mConnector.execute("asec", "finalize", id);
San Mehata181b212010-02-11 06:50:20 -08002126 /*
2127 * Finalization does a remount, so no need
2128 * to update mAsecMountSet
2129 */
San Mehat4270e1e2010-01-29 05:32:19 -08002130 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002131 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002132 }
San Mehat4270e1e2010-01-29 05:32:19 -08002133 return rc;
San Mehat36972292010-01-06 11:06:32 -08002134 }
2135
Kenny Root6dceb882012-04-12 14:23:49 -07002136 public int fixPermissionsSecureContainer(String id, int gid, String filename) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002137 enforcePermission(android.Manifest.permission.ASEC_CREATE);
Kenny Root6dceb882012-04-12 14:23:49 -07002138 warnOnNotMounted();
2139
2140 int rc = StorageResultCode.OperationSucceeded;
2141 try {
2142 mConnector.execute("asec", "fixperms", id, gid, filename);
2143 /*
2144 * Fix permissions does a remount, so no need to update
2145 * mAsecMountSet
2146 */
2147 } catch (NativeDaemonConnectorException e) {
2148 rc = StorageResultCode.OperationFailedInternalError;
2149 }
2150 return rc;
2151 }
2152
San Mehatd9709982010-02-18 11:43:03 -08002153 public int destroySecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002154 enforcePermission(android.Manifest.permission.ASEC_DESTROY);
San Mehat207e5382010-02-04 20:46:54 -08002155 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002156 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002157
Kenny Rootaa485402010-09-14 14:49:41 -07002158 /*
2159 * Force a GC to make sure AssetManagers in other threads of the
2160 * system_server are cleaned up. We have to do this since AssetManager
2161 * instances are kept as a WeakReference and it's possible we have files
2162 * open on the external storage.
2163 */
2164 Runtime.getRuntime().gc();
2165
San Mehatb1043402010-02-05 08:26:50 -08002166 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002167 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002168 final Command cmd = new Command("asec", "destroy", id);
2169 if (force) {
2170 cmd.appendArg("force");
2171 }
2172 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002173 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002174 int code = e.getCode();
2175 if (code == VoldResponseCode.OpFailedStorageBusy) {
2176 rc = StorageResultCode.OperationFailedStorageBusy;
2177 } else {
2178 rc = StorageResultCode.OperationFailedInternalError;
2179 }
San Mehat02735bc2010-01-26 15:18:08 -08002180 }
San Mehata181b212010-02-11 06:50:20 -08002181
2182 if (rc == StorageResultCode.OperationSucceeded) {
2183 synchronized (mAsecMountSet) {
2184 if (mAsecMountSet.contains(id)) {
2185 mAsecMountSet.remove(id);
2186 }
2187 }
2188 }
2189
San Mehat4270e1e2010-01-29 05:32:19 -08002190 return rc;
San Mehat36972292010-01-06 11:06:32 -08002191 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002192
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002193 public int mountSecureContainer(String id, String key, int ownerUid, boolean readOnly) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002194 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002195 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002196 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002197
San Mehata181b212010-02-11 06:50:20 -08002198 synchronized (mAsecMountSet) {
2199 if (mAsecMountSet.contains(id)) {
2200 return StorageResultCode.OperationFailedStorageMounted;
2201 }
2202 }
2203
San Mehatb1043402010-02-05 08:26:50 -08002204 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002205 try {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07002206 mConnector.execute("asec", "mount", id, new SensitiveArg(key), ownerUid,
2207 readOnly ? "ro" : "rw");
San Mehat4270e1e2010-01-29 05:32:19 -08002208 } catch (NativeDaemonConnectorException e) {
Kenny Rootf0304622010-03-19 19:20:42 -07002209 int code = e.getCode();
2210 if (code != VoldResponseCode.OpFailedStorageBusy) {
2211 rc = StorageResultCode.OperationFailedInternalError;
2212 }
San Mehat02735bc2010-01-26 15:18:08 -08002213 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002214
2215 if (rc == StorageResultCode.OperationSucceeded) {
2216 synchronized (mAsecMountSet) {
2217 mAsecMountSet.add(id);
2218 }
2219 }
San Mehat4270e1e2010-01-29 05:32:19 -08002220 return rc;
San Mehat36972292010-01-06 11:06:32 -08002221 }
2222
San Mehatd9709982010-02-18 11:43:03 -08002223 public int unmountSecureContainer(String id, boolean force) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002224 enforcePermission(android.Manifest.permission.ASEC_MOUNT_UNMOUNT);
San Mehat207e5382010-02-04 20:46:54 -08002225 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002226 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002227
San Mehat6cdd9c02010-02-09 14:45:20 -08002228 synchronized (mAsecMountSet) {
2229 if (!mAsecMountSet.contains(id)) {
San Mehata181b212010-02-11 06:50:20 -08002230 return StorageResultCode.OperationFailedStorageNotMounted;
San Mehat6cdd9c02010-02-09 14:45:20 -08002231 }
2232 }
2233
Kenny Rootaa485402010-09-14 14:49:41 -07002234 /*
2235 * Force a GC to make sure AssetManagers in other threads of the
2236 * system_server are cleaned up. We have to do this since AssetManager
2237 * instances are kept as a WeakReference and it's possible we have files
2238 * open on the external storage.
2239 */
2240 Runtime.getRuntime().gc();
2241
San Mehatb1043402010-02-05 08:26:50 -08002242 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002243 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002244 final Command cmd = new Command("asec", "unmount", id);
2245 if (force) {
2246 cmd.appendArg("force");
2247 }
2248 mConnector.execute(cmd);
San Mehat4270e1e2010-01-29 05:32:19 -08002249 } catch (NativeDaemonConnectorException e) {
San Mehatd9709982010-02-18 11:43:03 -08002250 int code = e.getCode();
2251 if (code == VoldResponseCode.OpFailedStorageBusy) {
2252 rc = StorageResultCode.OperationFailedStorageBusy;
2253 } else {
2254 rc = StorageResultCode.OperationFailedInternalError;
2255 }
San Mehat02735bc2010-01-26 15:18:08 -08002256 }
San Mehat6cdd9c02010-02-09 14:45:20 -08002257
2258 if (rc == StorageResultCode.OperationSucceeded) {
2259 synchronized (mAsecMountSet) {
2260 mAsecMountSet.remove(id);
2261 }
2262 }
San Mehat4270e1e2010-01-29 05:32:19 -08002263 return rc;
San Mehat9dba7092010-01-18 06:47:41 -08002264 }
2265
San Mehat6cdd9c02010-02-09 14:45:20 -08002266 public boolean isSecureContainerMounted(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002267 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat6cdd9c02010-02-09 14:45:20 -08002268 waitForReady();
2269 warnOnNotMounted();
2270
2271 synchronized (mAsecMountSet) {
2272 return mAsecMountSet.contains(id);
2273 }
2274 }
2275
San Mehat4270e1e2010-01-29 05:32:19 -08002276 public int renameSecureContainer(String oldId, String newId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002277 enforcePermission(android.Manifest.permission.ASEC_RENAME);
San Mehat207e5382010-02-04 20:46:54 -08002278 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002279 warnOnNotMounted();
San Mehat4270e1e2010-01-29 05:32:19 -08002280
San Mehata181b212010-02-11 06:50:20 -08002281 synchronized (mAsecMountSet) {
San Mehat85451ee2010-02-24 08:54:18 -08002282 /*
Jason parks9ed98bc2011-01-17 09:58:35 -06002283 * Because a mounted container has active internal state which cannot be
San Mehat85451ee2010-02-24 08:54:18 -08002284 * changed while active, we must ensure both ids are not currently mounted.
2285 */
2286 if (mAsecMountSet.contains(oldId) || mAsecMountSet.contains(newId)) {
San Mehata181b212010-02-11 06:50:20 -08002287 return StorageResultCode.OperationFailedStorageMounted;
2288 }
2289 }
2290
San Mehatb1043402010-02-05 08:26:50 -08002291 int rc = StorageResultCode.OperationSucceeded;
San Mehat4270e1e2010-01-29 05:32:19 -08002292 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002293 mConnector.execute("asec", "rename", oldId, newId);
San Mehat4270e1e2010-01-29 05:32:19 -08002294 } catch (NativeDaemonConnectorException e) {
San Mehatb1043402010-02-05 08:26:50 -08002295 rc = StorageResultCode.OperationFailedInternalError;
San Mehat02735bc2010-01-26 15:18:08 -08002296 }
San Mehata181b212010-02-11 06:50:20 -08002297
San Mehat4270e1e2010-01-29 05:32:19 -08002298 return rc;
San Mehat45f61042010-01-23 08:12:43 -08002299 }
2300
San Mehat4270e1e2010-01-29 05:32:19 -08002301 public String getSecureContainerPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002302 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
San Mehat207e5382010-02-04 20:46:54 -08002303 waitForReady();
San Mehatb1043402010-02-05 08:26:50 -08002304 warnOnNotMounted();
San Mehatf919cd022010-02-04 15:10:38 -08002305
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002306 final NativeDaemonEvent event;
San Mehat2d66cef2010-03-23 11:12:52 -07002307 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002308 event = mConnector.execute("asec", "path", id);
2309 event.checkCode(VoldResponseCode.AsecPathResult);
2310 return event.getMessage();
San Mehat2d66cef2010-03-23 11:12:52 -07002311 } catch (NativeDaemonConnectorException e) {
2312 int code = e.getCode();
2313 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Fredrik Helmera20c8ef2011-02-09 16:16:10 +01002314 Slog.i(TAG, String.format("Container '%s' not found", id));
2315 return null;
San Mehat22dd86e2010-01-12 12:21:18 -08002316 } else {
San Mehat2d66cef2010-03-23 11:12:52 -07002317 throw new IllegalStateException(String.format("Unexpected response code %d", code));
San Mehat22dd86e2010-01-12 12:21:18 -08002318 }
2319 }
San Mehat22dd86e2010-01-12 12:21:18 -08002320 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002321
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002322 public String getSecureContainerFilesystemPath(String id) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002323 enforcePermission(android.Manifest.permission.ASEC_ACCESS);
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002324 waitForReady();
2325 warnOnNotMounted();
2326
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002327 final NativeDaemonEvent event;
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002328 try {
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002329 event = mConnector.execute("asec", "fspath", id);
2330 event.checkCode(VoldResponseCode.AsecPathResult);
2331 return event.getMessage();
Dianne Hackborn292f8bc2011-06-27 16:27:41 -07002332 } catch (NativeDaemonConnectorException e) {
2333 int code = e.getCode();
2334 if (code == VoldResponseCode.OpFailedStorageNotFound) {
2335 Slog.i(TAG, String.format("Container '%s' not found", id));
2336 return null;
2337 } else {
2338 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2339 }
2340 }
2341 }
2342
Jeff Sharkey48877892015-03-18 11:27:19 -07002343 @Override
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002344 public void finishMediaUpdate() {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002345 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Rubin Xucd7a0142015-04-17 23:45:27 +01002346 throw new SecurityException("no permission to call finishMediaUpdate()");
2347 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002348 if (mUnmountSignal != null) {
2349 mUnmountSignal.countDown();
2350 } else {
2351 Slog.w(TAG, "Odd, nobody asked to unmount?");
2352 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07002353 }
Kenny Root02c87302010-07-01 08:10:18 -07002354
Kenny Roota02b8b02010-08-05 16:14:17 -07002355 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2356 if (callerUid == android.os.Process.SYSTEM_UID) {
2357 return true;
2358 }
2359
Kenny Root02c87302010-07-01 08:10:18 -07002360 if (packageName == null) {
2361 return false;
2362 }
2363
Jeff Sharkeycd654482016-01-08 17:42:11 -07002364 final int packageUid = mPms.getPackageUid(packageName,
2365 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002366
2367 if (DEBUG_OBB) {
2368 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2369 packageUid + ", callerUid = " + callerUid);
2370 }
2371
2372 return callerUid == packageUid;
2373 }
2374
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002375 public String getMountedObbPath(String rawPath) {
2376 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002377
Kenny Root02c87302010-07-01 08:10:18 -07002378 waitForReady();
2379 warnOnNotMounted();
2380
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002381 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002382 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002383 state = mObbPathToStateMap.get(rawPath);
2384 }
2385 if (state == null) {
2386 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2387 return null;
2388 }
2389
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002390 final NativeDaemonEvent event;
Kenny Root02c87302010-07-01 08:10:18 -07002391 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07002392 event = mConnector.execute("obb", "path", state.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002393 event.checkCode(VoldResponseCode.AsecPathResult);
2394 return event.getMessage();
Kenny Root02c87302010-07-01 08:10:18 -07002395 } catch (NativeDaemonConnectorException e) {
2396 int code = e.getCode();
2397 if (code == VoldResponseCode.OpFailedStorageNotFound) {
Kenny Roota02b8b02010-08-05 16:14:17 -07002398 return null;
Kenny Root02c87302010-07-01 08:10:18 -07002399 } else {
2400 throw new IllegalStateException(String.format("Unexpected response code %d", code));
2401 }
2402 }
2403 }
2404
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002405 @Override
2406 public boolean isObbMounted(String rawPath) {
2407 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002408 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002409 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002410 }
Kenny Root02c87302010-07-01 08:10:18 -07002411 }
2412
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002413 @Override
2414 public void mountObb(
2415 String rawPath, String canonicalPath, String key, IObbActionListener token, int nonce) {
2416 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2417 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2418 Preconditions.checkNotNull(token, "token cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002419
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002420 final int callingUid = Binder.getCallingUid();
2421 final ObbState obbState = new ObbState(rawPath, canonicalPath, callingUid, token, nonce);
2422 final ObbAction action = new MountObbAction(obbState, key, callingUid);
Kenny Roota02b8b02010-08-05 16:14:17 -07002423 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2424
2425 if (DEBUG_OBB)
2426 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002427 }
2428
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002429 @Override
2430 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2431 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2432
2433 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002434 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002435 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002436 }
2437
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002438 if (existingState != null) {
2439 // TODO: separate state object from request data
2440 final int callingUid = Binder.getCallingUid();
2441 final ObbState newState = new ObbState(
2442 rawPath, existingState.canonicalPath, callingUid, token, nonce);
2443 final ObbAction action = new UnmountObbAction(newState, force);
2444 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002445
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002446 if (DEBUG_OBB)
2447 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2448 } else {
2449 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2450 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002451 }
2452
Ben Komalo444eca22011-09-01 15:17:44 -07002453 @Override
2454 public int getEncryptionState() {
2455 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2456 "no permission to access the crypt keeper");
2457
2458 waitForReady();
2459
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002460 final NativeDaemonEvent event;
Ben Komalo444eca22011-09-01 15:17:44 -07002461 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002462 event = mCryptConnector.execute("cryptfs", "cryptocomplete");
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002463 return Integer.parseInt(event.getMessage());
Ben Komalo444eca22011-09-01 15:17:44 -07002464 } catch (NumberFormatException e) {
2465 // Bad result - unexpected.
2466 Slog.w(TAG, "Unable to parse result from cryptfs cryptocomplete");
2467 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2468 } catch (NativeDaemonConnectorException e) {
2469 // Something bad happened.
2470 Slog.w(TAG, "Error in communicating with cryptfs in validating");
2471 return ENCRYPTION_STATE_ERROR_UNKNOWN;
2472 }
2473 }
2474
2475 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002476 public int decryptStorage(String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002477 if (TextUtils.isEmpty(password)) {
2478 throw new IllegalArgumentException("password cannot be empty");
Jason parks5af0b912010-11-29 09:05:25 -06002479 }
2480
Jason parks8888c592011-01-20 22:46:41 -06002481 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2482 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002483
2484 waitForReady();
2485
2486 if (DEBUG_EVENTS) {
2487 Slog.i(TAG, "decrypting storage...");
2488 }
2489
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002490 final NativeDaemonEvent event;
Jason parks5af0b912010-11-29 09:05:25 -06002491 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002492 event = mCryptConnector.execute("cryptfs", "checkpw", new SensitiveArg(password));
Jason parks9ed98bc2011-01-17 09:58:35 -06002493
Fredrik Roubertda6aedf2011-12-20 17:34:43 +01002494 final int code = Integer.parseInt(event.getMessage());
Jason parks9ed98bc2011-01-17 09:58:35 -06002495 if (code == 0) {
2496 // Decrypt was successful. Post a delayed message before restarting in order
2497 // to let the UI to clear itself
2498 mHandler.postDelayed(new Runnable() {
2499 public void run() {
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002500 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002501 mCryptConnector.execute("cryptfs", "restart");
Jeff Sharkey31c6e482011-11-18 17:09:01 -08002502 } catch (NativeDaemonConnectorException e) {
2503 Slog.e(TAG, "problem executing in background", e);
2504 }
Jason parks9ed98bc2011-01-17 09:58:35 -06002505 }
Jason parksf7b3cd42011-01-27 09:28:25 -06002506 }, 1000); // 1 second
Jason parks9ed98bc2011-01-17 09:58:35 -06002507 }
2508
2509 return code;
Jason parks5af0b912010-11-29 09:05:25 -06002510 } catch (NativeDaemonConnectorException e) {
2511 // Decryption failed
2512 return e.getCode();
2513 }
Jason parks5af0b912010-11-29 09:05:25 -06002514 }
2515
Paul Lawrence46791e72014-04-03 09:10:26 -07002516 public int encryptStorage(int type, String password) {
2517 if (TextUtils.isEmpty(password) && type != StorageManager.CRYPT_TYPE_DEFAULT) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002518 throw new IllegalArgumentException("password cannot be empty");
Jason parks56aa5322011-01-07 09:01:15 -06002519 }
2520
Jason parks8888c592011-01-20 22:46:41 -06002521 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2522 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002523
2524 waitForReady();
2525
2526 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002527 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002528 }
2529
2530 try {
Paul Lawrence5096d9e2015-09-09 13:05:45 -07002531 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2532 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2533 CRYPTO_TYPES[type]);
2534 } else {
2535 mCryptConnector.execute("cryptfs", "enablecrypto", "inplace",
2536 CRYPTO_TYPES[type], new SensitiveArg(password));
2537 }
Jason parks56aa5322011-01-07 09:01:15 -06002538 } catch (NativeDaemonConnectorException e) {
2539 // Encryption failed
2540 return e.getCode();
2541 }
2542
2543 return 0;
2544 }
2545
Paul Lawrence8e397362014-01-27 15:22:30 -08002546 /** Set the password for encrypting the master key.
2547 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2548 * @param password The password to set.
2549 */
2550 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002551 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2552 "no permission to access the crypt keeper");
2553
2554 waitForReady();
2555
2556 if (DEBUG_EVENTS) {
2557 Slog.i(TAG, "changing encryption password...");
2558 }
2559
2560 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002561 NativeDaemonEvent event = mCryptConnector.execute("cryptfs", "changepw", CRYPTO_TYPES[type],
Paul Lawrence05487612015-06-09 13:35:38 -07002562 new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002563 return Integer.parseInt(event.getMessage());
Jason parksf7b3cd42011-01-27 09:28:25 -06002564 } catch (NativeDaemonConnectorException e) {
2565 // Encryption failed
2566 return e.getCode();
2567 }
2568 }
2569
Christopher Tate32418be2011-10-10 13:51:12 -07002570 /**
2571 * Validate a user-supplied password string with cryptfs
2572 */
2573 @Override
2574 public int verifyEncryptionPassword(String password) throws RemoteException {
2575 // Only the system process is permitted to validate passwords
2576 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2577 throw new SecurityException("no permission to access the crypt keeper");
2578 }
2579
2580 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2581 "no permission to access the crypt keeper");
2582
2583 if (TextUtils.isEmpty(password)) {
2584 throw new IllegalArgumentException("password cannot be empty");
2585 }
2586
2587 waitForReady();
2588
2589 if (DEBUG_EVENTS) {
2590 Slog.i(TAG, "validating encryption password...");
2591 }
2592
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002593 final NativeDaemonEvent event;
Christopher Tate32418be2011-10-10 13:51:12 -07002594 try {
Paul Lawrence05487612015-06-09 13:35:38 -07002595 event = mCryptConnector.execute("cryptfs", "verifypw", new SensitiveArg(password));
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08002596 Slog.i(TAG, "cryptfs verifypw => " + event.getMessage());
2597 return Integer.parseInt(event.getMessage());
Christopher Tate32418be2011-10-10 13:51:12 -07002598 } catch (NativeDaemonConnectorException e) {
2599 // Encryption failed
2600 return e.getCode();
2601 }
2602 }
2603
Paul Lawrence8e397362014-01-27 15:22:30 -08002604 /**
2605 * Get the type of encryption used to encrypt the master key.
2606 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2607 */
2608 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002609 public int getPasswordType() {
Paul Lawrence8e397362014-01-27 15:22:30 -08002610
2611 waitForReady();
2612
2613 final NativeDaemonEvent event;
2614 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002615 event = mCryptConnector.execute("cryptfs", "getpwtype");
Paul Lawrence8e397362014-01-27 15:22:30 -08002616 for (int i = 0; i < CRYPTO_TYPES.length; ++i) {
2617 if (CRYPTO_TYPES[i].equals(event.getMessage()))
2618 return i;
2619 }
2620
2621 throw new IllegalStateException("unexpected return from cryptfs");
2622 } catch (NativeDaemonConnectorException e) {
2623 throw e.rethrowAsParcelableException();
2624 }
2625 }
2626
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002627 /**
2628 * Set a field in the crypto header.
2629 * @param field field to set
2630 * @param contents contents to set in field
2631 */
2632 @Override
2633 public void setField(String field, String contents) throws RemoteException {
2634
2635 waitForReady();
2636
2637 final NativeDaemonEvent event;
2638 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002639 event = mCryptConnector.execute("cryptfs", "setfield", field, contents);
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002640 } catch (NativeDaemonConnectorException e) {
2641 throw e.rethrowAsParcelableException();
2642 }
2643 }
2644
2645 /**
2646 * Gets a field from the crypto header.
2647 * @param field field to get
2648 * @return contents of field
2649 */
2650 @Override
2651 public String getField(String field) throws RemoteException {
2652
2653 waitForReady();
2654
2655 final NativeDaemonEvent event;
2656 try {
2657 final String[] contents = NativeDaemonEvent.filterMessageList(
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002658 mCryptConnector.executeForList("cryptfs", "getfield", field),
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002659 VoldResponseCode.CryptfsGetfieldResult);
2660 String result = new String();
2661 for (String content : contents) {
2662 result += content;
2663 }
2664 return result;
2665 } catch (NativeDaemonConnectorException e) {
2666 throw e.rethrowAsParcelableException();
2667 }
2668 }
2669
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002670 /**
2671 * Is userdata convertible to file based encryption?
2672 * @return non zero for convertible
2673 */
2674 @Override
2675 public boolean isConvertibleToFBE() throws RemoteException {
2676
2677 waitForReady();
2678
2679 final NativeDaemonEvent event;
2680 try {
2681 event = mCryptConnector.execute("cryptfs", "isConvertibleToFBE");
2682 return Integer.parseInt(event.getMessage()) != 0;
2683 } catch (NativeDaemonConnectorException e) {
2684 throw e.rethrowAsParcelableException();
2685 }
2686 }
2687
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002688 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002689 public String getPassword() throws RemoteException {
Rubin Xucd7a0142015-04-17 23:45:27 +01002690 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE,
2691 "only keyguard can retrieve password");
Paul Lawrence945490c2014-03-27 16:37:28 +00002692 if (!isReady()) {
2693 return new String();
2694 }
2695
2696 final NativeDaemonEvent event;
2697 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002698 event = mCryptConnector.execute("cryptfs", "getpw");
Paul Lawrence24063b52015-01-06 13:11:23 -08002699 if ("-1".equals(event.getMessage())) {
2700 // -1 equals no password
2701 return null;
2702 }
Paul Lawrence05487612015-06-09 13:35:38 -07002703 return event.getMessage();
Paul Lawrence945490c2014-03-27 16:37:28 +00002704 } catch (NativeDaemonConnectorException e) {
2705 throw e.rethrowAsParcelableException();
Paul Lawrence24063b52015-01-06 13:11:23 -08002706 } catch (IllegalArgumentException e) {
2707 Slog.e(TAG, "Invalid response to getPassword");
2708 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002709 }
2710 }
2711
2712 @Override
2713 public void clearPassword() throws RemoteException {
2714 if (!isReady()) {
2715 return;
2716 }
2717
2718 final NativeDaemonEvent event;
2719 try {
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07002720 event = mCryptConnector.execute("cryptfs", "clearpw");
Paul Lawrence945490c2014-03-27 16:37:28 +00002721 } catch (NativeDaemonConnectorException e) {
2722 throw e.rethrowAsParcelableException();
2723 }
2724 }
2725
2726 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002727 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002728 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002729 waitForReady();
2730
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002731 try {
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002732 mCryptConnector.execute("cryptfs", "create_user_key", userId, serialNumber,
2733 ephemeral ? 1 : 0);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002734 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002735 throw e.rethrowAsParcelableException();
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002736 }
2737 }
2738
Paul Crowley7ec733f2015-05-19 12:42:00 +01002739 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002740 public void destroyUserKey(int userId) {
2741 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002742 waitForReady();
2743
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002744 try {
2745 mCryptConnector.execute("cryptfs", "destroy_user_key", userId);
2746 } catch (NativeDaemonConnectorException e) {
2747 throw e.rethrowAsParcelableException();
2748 }
2749 }
2750
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002751 private SensitiveArg encodeBytes(byte[] bytes) {
2752 if (ArrayUtils.isEmpty(bytes)) {
2753 return new SensitiveArg("!");
2754 } else {
2755 return new SensitiveArg(HexDump.toHexString(bytes));
2756 }
2757 }
2758
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002759 @Override
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002760 public void changeUserKey(int userId, int serialNumber,
2761 byte[] token, byte[] oldSecret, byte[] newSecret) {
2762 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2763 waitForReady();
2764
2765 try {
2766 mCryptConnector.execute("cryptfs", "change_user_key", userId, serialNumber,
2767 encodeBytes(token), encodeBytes(oldSecret), encodeBytes(newSecret));
2768 } catch (NativeDaemonConnectorException e) {
2769 throw e.rethrowAsParcelableException();
2770 }
2771 }
2772
2773 @Override
2774 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002775 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2776 waitForReady();
2777
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002778 // When a user has secure lock screen, require a challenge token to
2779 // actually unlock. This check is mostly in place for emulation mode.
2780 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(token)) {
2781 throw new IllegalStateException("Token required to unlock secure user " + userId);
2782 }
2783
Paul Crowley7ec733f2015-05-19 12:42:00 +01002784 try {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002785 mCryptConnector.execute("cryptfs", "unlock_user_key", userId, serialNumber,
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002786 encodeBytes(token), encodeBytes(secret));
Paul Crowley7ec733f2015-05-19 12:42:00 +01002787 } catch (NativeDaemonConnectorException e) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002788 throw e.rethrowAsParcelableException();
2789 }
2790
2791 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002792 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002793 }
2794 }
2795
2796 @Override
2797 public void lockUserKey(int userId) {
2798 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2799 waitForReady();
2800
2801 try {
2802 mCryptConnector.execute("cryptfs", "lock_user_key", userId);
2803 } catch (NativeDaemonConnectorException e) {
2804 throw e.rethrowAsParcelableException();
2805 }
2806
2807 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002808 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002809 }
2810 }
2811
2812 @Override
2813 public boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyba512352015-11-12 20:17:45 -08002814 if (StorageManager.isFileBasedEncryptionEnabled()) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002815 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002816 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002817 }
2818 } else {
2819 return true;
2820 }
2821 }
2822
2823 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002824 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002825 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
2826 waitForReady();
2827
2828 try {
2829 mCryptConnector.execute("cryptfs", "prepare_user_storage", escapeNull(volumeUuid),
Jeff Sharkey47f71082016-02-01 17:03:54 -07002830 userId, serialNumber, flags);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002831 } catch (NativeDaemonConnectorException e) {
2832 throw e.rethrowAsParcelableException();
Paul Crowley7ec733f2015-05-19 12:42:00 +01002833 }
2834 }
2835
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002836 @Override
Daichi Hirono91e3b502015-12-16 09:24:16 +09002837 public ParcelFileDescriptor mountAppFuse(final String name) throws RemoteException {
Daichi Hironobee50c02015-12-14 11:00:54 +09002838 try {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002839 final int uid = Binder.getCallingUid();
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002840 final int pid = Binder.getCallingPid();
Daichi Hironobee50c02015-12-14 11:00:54 +09002841 final NativeDaemonEvent event =
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002842 mConnector.execute("appfuse", "mount", uid, pid, name);
Daichi Hironobee50c02015-12-14 11:00:54 +09002843 if (event.getFileDescriptors() == null) {
Daichi Hirono91e3b502015-12-16 09:24:16 +09002844 throw new RemoteException("AppFuse FD from vold is null.");
Daichi Hironobee50c02015-12-14 11:00:54 +09002845 }
Daichi Hirono91e3b502015-12-16 09:24:16 +09002846 return ParcelFileDescriptor.fromFd(
2847 event.getFileDescriptors()[0],
2848 mHandler,
2849 new ParcelFileDescriptor.OnCloseListener() {
2850 @Override
2851 public void onClose(IOException e) {
2852 try {
2853 final NativeDaemonEvent event = mConnector.execute(
Daichi Hironofd7d57e2016-01-29 14:30:58 +09002854 "appfuse", "unmount", uid, pid, name);
Daichi Hirono91e3b502015-12-16 09:24:16 +09002855 } catch (NativeDaemonConnectorException unmountException) {
2856 Log.e(TAG, "Failed to unmount appfuse.");
2857 }
2858 }
2859 });
Daichi Hironobee50c02015-12-14 11:00:54 +09002860 } catch (NativeDaemonConnectorException e) {
2861 throw e.rethrowAsParcelableException();
Daichi Hirono91e3b502015-12-16 09:24:16 +09002862 } catch (IOException e) {
2863 throw new RemoteException(e.getMessage());
Daichi Hironobee50c02015-12-14 11:00:54 +09002864 }
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002865 }
2866
2867 @Override
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002868 public int mkdirs(String callingPkg, String appPath) {
2869 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2870 final UserEnvironment userEnv = new UserEnvironment(userId);
2871
2872 // Validate that reported package name belongs to caller
2873 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2874 Context.APP_OPS_SERVICE);
2875 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2876
Jeff Sharkey48877892015-03-18 11:27:19 -07002877 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002878 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002879 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002880 } catch (IOException e) {
2881 Slog.e(TAG, "Failed to resolve " + appPath + ": " + e);
2882 return -1;
2883 }
2884
2885 // Try translating the app path into a vold path, but require that it
2886 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07002887 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
2888 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
2889 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
2890 appPath = appFile.getAbsolutePath();
2891 if (!appPath.endsWith("/")) {
2892 appPath = appPath + "/";
2893 }
2894
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002895 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002896 mConnector.execute("volume", "mkdirs", appPath);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002897 return 0;
2898 } catch (NativeDaemonConnectorException e) {
2899 return e.getCode();
2900 }
2901 }
2902
Jeff Sharkey48877892015-03-18 11:27:19 -07002903 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002904 }
2905
2906 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07002907 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002908 final int userId = UserHandle.getUserId(uid);
Jeff Sharkey46349872015-07-28 10:49:47 -07002909 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
2910
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002911 boolean reportUnmounted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -07002912 boolean foundPrimary = false;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002913
Svetoslav38c3dbb2015-07-14 11:27:06 -07002914 final long identity = Binder.clearCallingIdentity();
2915 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002916 if (!mMountServiceInternal.hasExternalStorage(uid, packageName)) {
2917 reportUnmounted = true;
2918 }
2919 if (!isUserKeyUnlocked(userId)) {
2920 reportUnmounted = true;
2921 }
Svetoslav38c3dbb2015-07-14 11:27:06 -07002922 } finally {
2923 Binder.restoreCallingIdentity(identity);
2924 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07002925
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002926 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07002927 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002928 for (int i = 0; i < mVolumes.size(); i++) {
2929 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -07002930 if (forWrite ? vol.isVisibleForWrite(userId) : vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07002931 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
2932 reportUnmounted);
Jeff Sharkey48877892015-03-18 11:27:19 -07002933 if (vol.isPrimary()) {
2934 res.add(0, userVol);
2935 foundPrimary = true;
2936 } else {
2937 res.add(userVol);
2938 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002939 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002940 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002941 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002942
2943 if (!foundPrimary) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002944 Log.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07002945
2946 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002947 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07002948
2949 final String id = "stub_primary";
2950 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002951 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07002952 final boolean primary = true;
2953 final boolean removable = primaryPhysical;
2954 final boolean emulated = !primaryPhysical;
2955 final long mtpReserveSize = 0L;
2956 final boolean allowMassStorage = false;
2957 final long maxFileSize = 0L;
2958 final UserHandle owner = new UserHandle(userId);
2959 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07002960 final String state = Environment.MEDIA_REMOVED;
2961
Jeff Sharkey5af1835d2015-07-07 17:26:59 -07002962 res.add(0, new StorageVolume(id, StorageVolume.STORAGE_ID_INVALID, path,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002963 description, primary, removable, emulated, mtpReserveSize,
2964 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07002965 }
2966
2967 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07002968 }
2969
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002970 @Override
2971 public DiskInfo[] getDisks() {
2972 synchronized (mLock) {
2973 final DiskInfo[] res = new DiskInfo[mDisks.size()];
2974 for (int i = 0; i < mDisks.size(); i++) {
2975 res[i] = mDisks.valueAt(i);
2976 }
2977 return res;
2978 }
2979 }
2980
2981 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002982 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002983 synchronized (mLock) {
2984 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
2985 for (int i = 0; i < mVolumes.size(); i++) {
2986 res[i] = mVolumes.valueAt(i);
2987 }
2988 return res;
2989 }
2990 }
2991
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002992 @Override
2993 public VolumeRecord[] getVolumeRecords(int flags) {
2994 synchronized (mLock) {
2995 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
2996 for (int i = 0; i < mRecords.size(); i++) {
2997 res[i] = mRecords.valueAt(i);
2998 }
2999 return res;
3000 }
3001 }
3002
Kenny Rootaf9d6672010-10-08 09:21:39 -07003003 private void addObbStateLocked(ObbState obbState) throws RemoteException {
3004 final IBinder binder = obbState.getBinder();
3005 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003006
Kenny Rootaf9d6672010-10-08 09:21:39 -07003007 if (obbStates == null) {
3008 obbStates = new ArrayList<ObbState>();
3009 mObbMounts.put(binder, obbStates);
3010 } else {
3011 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003012 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003013 throw new IllegalStateException("Attempt to add ObbState twice. "
3014 + "This indicates an error in the MountService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003015 }
3016 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003017 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003018
3019 obbStates.add(obbState);
3020 try {
3021 obbState.link();
3022 } catch (RemoteException e) {
3023 /*
3024 * The binder died before we could link it, so clean up our state
3025 * and return failure.
3026 */
3027 obbStates.remove(obbState);
3028 if (obbStates.isEmpty()) {
3029 mObbMounts.remove(binder);
3030 }
3031
3032 // Rethrow the error so mountObb can get it
3033 throw e;
3034 }
3035
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003036 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003037 }
3038
Kenny Rootaf9d6672010-10-08 09:21:39 -07003039 private void removeObbStateLocked(ObbState obbState) {
3040 final IBinder binder = obbState.getBinder();
3041 final List<ObbState> obbStates = mObbMounts.get(binder);
3042 if (obbStates != null) {
3043 if (obbStates.remove(obbState)) {
3044 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003045 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003046 if (obbStates.isEmpty()) {
3047 mObbMounts.remove(binder);
3048 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003049 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003050
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003051 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003052 }
3053
Kenny Roota02b8b02010-08-05 16:14:17 -07003054 private class ObbActionHandler extends Handler {
3055 private boolean mBound = false;
Kenny Root480afe72010-10-07 10:17:50 -07003056 private final List<ObbAction> mActions = new LinkedList<ObbAction>();
Kenny Roota02b8b02010-08-05 16:14:17 -07003057
3058 ObbActionHandler(Looper l) {
3059 super(l);
3060 }
3061
3062 @Override
3063 public void handleMessage(Message msg) {
3064 switch (msg.what) {
3065 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003066 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003067
3068 if (DEBUG_OBB)
3069 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3070
3071 // If a bind was already initiated we don't really
3072 // need to do anything. The pending install
3073 // will be processed later on.
3074 if (!mBound) {
3075 // If this is the only one pending we might
3076 // have to bind to the service again.
3077 if (!connectToService()) {
3078 Slog.e(TAG, "Failed to bind to media container service");
3079 action.handleError();
3080 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003081 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003082 }
Kenny Root735de3b2010-09-30 14:11:39 -07003083
Kenny Root735de3b2010-09-30 14:11:39 -07003084 mActions.add(action);
Kenny Roota02b8b02010-08-05 16:14:17 -07003085 break;
3086 }
3087 case OBB_MCS_BOUND: {
3088 if (DEBUG_OBB)
3089 Slog.i(TAG, "OBB_MCS_BOUND");
3090 if (msg.obj != null) {
3091 mContainerService = (IMediaContainerService) msg.obj;
3092 }
3093 if (mContainerService == null) {
3094 // Something seriously wrong. Bail out
3095 Slog.e(TAG, "Cannot bind to media container service");
3096 for (ObbAction action : mActions) {
3097 // Indicate service bind error
3098 action.handleError();
3099 }
3100 mActions.clear();
3101 } else if (mActions.size() > 0) {
Kenny Root480afe72010-10-07 10:17:50 -07003102 final ObbAction action = mActions.get(0);
Kenny Roota02b8b02010-08-05 16:14:17 -07003103 if (action != null) {
3104 action.execute(this);
3105 }
3106 } else {
3107 // Should never happen ideally.
3108 Slog.w(TAG, "Empty queue");
3109 }
3110 break;
3111 }
3112 case OBB_MCS_RECONNECT: {
3113 if (DEBUG_OBB)
3114 Slog.i(TAG, "OBB_MCS_RECONNECT");
3115 if (mActions.size() > 0) {
3116 if (mBound) {
3117 disconnectService();
3118 }
3119 if (!connectToService()) {
3120 Slog.e(TAG, "Failed to bind to media container service");
3121 for (ObbAction action : mActions) {
3122 // Indicate service bind error
3123 action.handleError();
3124 }
3125 mActions.clear();
3126 }
3127 }
3128 break;
3129 }
3130 case OBB_MCS_UNBIND: {
3131 if (DEBUG_OBB)
3132 Slog.i(TAG, "OBB_MCS_UNBIND");
3133
3134 // Delete pending install
3135 if (mActions.size() > 0) {
3136 mActions.remove(0);
3137 }
3138 if (mActions.size() == 0) {
3139 if (mBound) {
3140 disconnectService();
3141 }
3142 } else {
3143 // There are more pending requests in queue.
3144 // Just post MCS_BOUND message to trigger processing
3145 // of next pending install.
3146 mObbActionHandler.sendEmptyMessage(OBB_MCS_BOUND);
3147 }
3148 break;
3149 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003150 case OBB_FLUSH_MOUNT_STATE: {
3151 final String path = (String) msg.obj;
3152
3153 if (DEBUG_OBB)
3154 Slog.i(TAG, "Flushing all OBB state for path " + path);
3155
3156 synchronized (mObbMounts) {
3157 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3158
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003159 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003160 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003161 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003162
3163 /*
3164 * If this entry's source file is in the volume path
3165 * that got unmounted, remove it because it's no
3166 * longer valid.
3167 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003168 if (state.canonicalPath.startsWith(path)) {
3169 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003170 }
3171 }
3172
3173 for (final ObbState obbState : obbStatesToRemove) {
3174 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003175 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003176
3177 removeObbStateLocked(obbState);
3178
3179 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003180 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003181 OnObbStateChangeListener.UNMOUNTED);
3182 } catch (RemoteException e) {
3183 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003184 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003185 }
3186 }
3187 }
3188 break;
3189 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003190 }
3191 }
3192
3193 private boolean connectToService() {
3194 if (DEBUG_OBB)
3195 Slog.i(TAG, "Trying to bind to DefaultContainerService");
3196
3197 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Jeff Sharkey6dce4962015-07-03 18:08:41 -07003198 if (mContext.bindServiceAsUser(service, mDefContainerConn, Context.BIND_AUTO_CREATE,
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003199 UserHandle.SYSTEM)) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003200 mBound = true;
3201 return true;
3202 }
3203 return false;
3204 }
3205
3206 private void disconnectService() {
3207 mContainerService = null;
3208 mBound = false;
3209 mContext.unbindService(mDefContainerConn);
3210 }
3211 }
3212
3213 abstract class ObbAction {
3214 private static final int MAX_RETRIES = 3;
3215 private int mRetries;
3216
3217 ObbState mObbState;
3218
3219 ObbAction(ObbState obbState) {
3220 mObbState = obbState;
3221 }
3222
3223 public void execute(ObbActionHandler handler) {
3224 try {
3225 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003226 Slog.i(TAG, "Starting to execute action: " + toString());
Kenny Roota02b8b02010-08-05 16:14:17 -07003227 mRetries++;
3228 if (mRetries > MAX_RETRIES) {
3229 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Kenny Root480afe72010-10-07 10:17:50 -07003230 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003231 handleError();
Kenny Roota02b8b02010-08-05 16:14:17 -07003232 } else {
3233 handleExecute();
3234 if (DEBUG_OBB)
3235 Slog.i(TAG, "Posting install MCS_UNBIND");
3236 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
3237 }
3238 } catch (RemoteException e) {
3239 if (DEBUG_OBB)
3240 Slog.i(TAG, "Posting install MCS_RECONNECT");
3241 mObbActionHandler.sendEmptyMessage(OBB_MCS_RECONNECT);
3242 } catch (Exception e) {
3243 if (DEBUG_OBB)
3244 Slog.d(TAG, "Error handling OBB action", e);
3245 handleError();
Kenny Root17eb6fb2010-10-06 15:02:52 -07003246 mObbActionHandler.sendEmptyMessage(OBB_MCS_UNBIND);
Kenny Roota02b8b02010-08-05 16:14:17 -07003247 }
3248 }
3249
Kenny Root05105f72010-09-22 17:29:43 -07003250 abstract void handleExecute() throws RemoteException, IOException;
Kenny Roota02b8b02010-08-05 16:14:17 -07003251 abstract void handleError();
Kenny Root38cf8862010-09-26 14:18:51 -07003252
3253 protected ObbInfo getObbInfo() throws IOException {
3254 ObbInfo obbInfo;
3255 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003256 obbInfo = mContainerService.getObbInfo(mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003257 } catch (RemoteException e) {
3258 Slog.d(TAG, "Couldn't call DefaultContainerService to fetch OBB info for "
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003259 + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003260 obbInfo = null;
3261 }
3262 if (obbInfo == null) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003263 throw new IOException("Couldn't read OBB file: " + mObbState.canonicalPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003264 }
3265 return obbInfo;
3266 }
3267
Kenny Rootaf9d6672010-10-08 09:21:39 -07003268 protected void sendNewStatusOrIgnore(int status) {
3269 if (mObbState == null || mObbState.token == null) {
3270 return;
3271 }
3272
Kenny Root38cf8862010-09-26 14:18:51 -07003273 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003274 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003275 } catch (RemoteException e) {
3276 Slog.w(TAG, "MountServiceListener went away while calling onObbStateChanged");
3277 }
3278 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003279 }
3280
3281 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003282 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003283 private final int mCallingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003284
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003285 MountObbAction(ObbState obbState, String key, int callingUid) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003286 super(obbState);
3287 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003288 mCallingUid = callingUid;
Kenny Roota02b8b02010-08-05 16:14:17 -07003289 }
3290
Jason parks5af0b912010-11-29 09:05:25 -06003291 @Override
Kenny Root735de3b2010-09-30 14:11:39 -07003292 public void handleExecute() throws IOException, RemoteException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003293 waitForReady();
3294 warnOnNotMounted();
3295
Kenny Root38cf8862010-09-26 14:18:51 -07003296 final ObbInfo obbInfo = getObbInfo();
3297
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003298 if (!isUidOwnerOfPackageOrSystem(obbInfo.packageName, mCallingUid)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003299 Slog.w(TAG, "Denied attempt to mount OBB " + obbInfo.filename
3300 + " which is owned by " + obbInfo.packageName);
3301 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3302 return;
Kenny Roota02b8b02010-08-05 16:14:17 -07003303 }
3304
Kenny Rootaf9d6672010-10-08 09:21:39 -07003305 final boolean isMounted;
3306 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003307 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003308 }
3309 if (isMounted) {
3310 Slog.w(TAG, "Attempt to mount OBB which is already mounted: " + obbInfo.filename);
3311 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_ALREADY_MOUNTED);
3312 return;
3313 }
3314
Kenny Rootaf9d6672010-10-08 09:21:39 -07003315 final String hashedKey;
3316 if (mKey == null) {
3317 hashedKey = "none";
3318 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003319 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003320 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3321
3322 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), obbInfo.salt,
3323 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3324 SecretKey key = factory.generateSecret(ks);
3325 BigInteger bi = new BigInteger(key.getEncoded());
3326 hashedKey = bi.toString(16);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003327 } catch (NoSuchAlgorithmException e) {
Kenny Root3b1abba2010-10-13 15:00:07 -07003328 Slog.e(TAG, "Could not load PBKDF2 algorithm", e);
3329 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
3330 return;
3331 } catch (InvalidKeySpecException e) {
3332 Slog.e(TAG, "Invalid key spec when loading PBKDF2 algorithm", e);
3333 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root38cf8862010-09-26 14:18:51 -07003334 return;
3335 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003336 }
Kenny Root38cf8862010-09-26 14:18:51 -07003337
Kenny Rootaf9d6672010-10-08 09:21:39 -07003338 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003339 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003340 mConnector.execute("obb", "mount", mObbState.canonicalPath, new SensitiveArg(hashedKey),
Jeff Sharkey56cd6462013-06-07 15:09:15 -07003341 mObbState.ownerGid);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003342 } catch (NativeDaemonConnectorException e) {
3343 int code = e.getCode();
3344 if (code != VoldResponseCode.OpFailedStorageBusy) {
3345 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003346 }
3347 }
3348
Kenny Rootaf9d6672010-10-08 09:21:39 -07003349 if (rc == StorageResultCode.OperationSucceeded) {
3350 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003351 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003352
3353 synchronized (mObbMounts) {
3354 addObbStateLocked(mObbState);
3355 }
3356
3357 sendNewStatusOrIgnore(OnObbStateChangeListener.MOUNTED);
Kenny Root02c87302010-07-01 08:10:18 -07003358 } else {
Kenny Root05105f72010-09-22 17:29:43 -07003359 Slog.e(TAG, "Couldn't mount OBB file: " + rc);
Kenny Roota02b8b02010-08-05 16:14:17 -07003360
Kenny Rootaf9d6672010-10-08 09:21:39 -07003361 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT);
Kenny Root02c87302010-07-01 08:10:18 -07003362 }
3363 }
3364
Jason parks5af0b912010-11-29 09:05:25 -06003365 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003366 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003367 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Root02c87302010-07-01 08:10:18 -07003368 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003369
3370 @Override
3371 public String toString() {
3372 StringBuilder sb = new StringBuilder();
3373 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003374 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003375 sb.append('}');
3376 return sb.toString();
3377 }
3378 }
3379
3380 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003381 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003382
3383 UnmountObbAction(ObbState obbState, boolean force) {
3384 super(obbState);
3385 mForceUnmount = force;
3386 }
3387
Jason parks5af0b912010-11-29 09:05:25 -06003388 @Override
Kenny Root38cf8862010-09-26 14:18:51 -07003389 public void handleExecute() throws IOException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003390 waitForReady();
3391 warnOnNotMounted();
3392
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003393 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003394 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003395 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003396 }
Kenny Root38cf8862010-09-26 14:18:51 -07003397
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003398 if (existingState == null) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003399 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_NOT_MOUNTED);
3400 return;
3401 }
3402
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003403 if (existingState.ownerGid != mObbState.ownerGid) {
3404 Slog.w(TAG, "Permission denied attempting to unmount OBB " + existingState.rawPath
3405 + " (owned by GID " + existingState.ownerGid + ")");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003406 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_PERMISSION_DENIED);
3407 return;
3408 }
3409
Kenny Rootaf9d6672010-10-08 09:21:39 -07003410 int rc = StorageResultCode.OperationSucceeded;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003411 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003412 final Command cmd = new Command("obb", "unmount", mObbState.canonicalPath);
Jeff Sharkeydd519fa2011-12-02 14:11:21 -08003413 if (mForceUnmount) {
3414 cmd.appendArg("force");
3415 }
3416 mConnector.execute(cmd);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003417 } catch (NativeDaemonConnectorException e) {
3418 int code = e.getCode();
3419 if (code == VoldResponseCode.OpFailedStorageBusy) {
3420 rc = StorageResultCode.OperationFailedStorageBusy;
3421 } else if (code == VoldResponseCode.OpFailedStorageNotFound) {
3422 // If it's not mounted then we've already won.
3423 rc = StorageResultCode.OperationSucceeded;
3424 } else {
3425 rc = StorageResultCode.OperationFailedInternalError;
Kenny Roota02b8b02010-08-05 16:14:17 -07003426 }
3427 }
3428
Kenny Rootaf9d6672010-10-08 09:21:39 -07003429 if (rc == StorageResultCode.OperationSucceeded) {
3430 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003431 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003432 }
3433
Kenny Rootaf9d6672010-10-08 09:21:39 -07003434 sendNewStatusOrIgnore(OnObbStateChangeListener.UNMOUNTED);
Kenny Roota02b8b02010-08-05 16:14:17 -07003435 } else {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003436 Slog.w(TAG, "Could not unmount OBB: " + existingState);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003437 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT);
Kenny Roota02b8b02010-08-05 16:14:17 -07003438 }
3439 }
3440
Jason parks5af0b912010-11-29 09:05:25 -06003441 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003442 public void handleError() {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003443 sendNewStatusOrIgnore(OnObbStateChangeListener.ERROR_INTERNAL);
Kenny Roota02b8b02010-08-05 16:14:17 -07003444 }
3445
3446 @Override
3447 public String toString() {
3448 StringBuilder sb = new StringBuilder();
3449 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003450 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003451 sb.append(",force=");
3452 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003453 sb.append('}');
3454 return sb.toString();
3455 }
Kenny Root02c87302010-07-01 08:10:18 -07003456 }
Kenny Root38cf8862010-09-26 14:18:51 -07003457
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003458 private static class Callbacks extends Handler {
3459 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3460 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003461 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3462 private static final int MSG_VOLUME_FORGOTTEN = 4;
3463 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003464 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003465
3466 private final RemoteCallbackList<IMountServiceListener>
3467 mCallbacks = new RemoteCallbackList<>();
3468
3469 public Callbacks(Looper looper) {
3470 super(looper);
3471 }
3472
3473 public void register(IMountServiceListener callback) {
3474 mCallbacks.register(callback);
3475 }
3476
3477 public void unregister(IMountServiceListener callback) {
3478 mCallbacks.unregister(callback);
3479 }
3480
3481 @Override
3482 public void handleMessage(Message msg) {
3483 final SomeArgs args = (SomeArgs) msg.obj;
3484 final int n = mCallbacks.beginBroadcast();
3485 for (int i = 0; i < n; i++) {
3486 final IMountServiceListener callback = mCallbacks.getBroadcastItem(i);
3487 try {
3488 invokeCallback(callback, msg.what, args);
3489 } catch (RemoteException ignored) {
3490 }
3491 }
3492 mCallbacks.finishBroadcast();
3493 args.recycle();
3494 }
3495
3496 private void invokeCallback(IMountServiceListener callback, int what, SomeArgs args)
3497 throws RemoteException {
3498 switch (what) {
3499 case MSG_STORAGE_STATE_CHANGED: {
3500 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3501 (String) args.arg3);
3502 break;
3503 }
3504 case MSG_VOLUME_STATE_CHANGED: {
3505 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3506 break;
3507 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003508 case MSG_VOLUME_RECORD_CHANGED: {
3509 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3510 break;
3511 }
3512 case MSG_VOLUME_FORGOTTEN: {
3513 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003514 break;
3515 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003516 case MSG_DISK_SCANNED: {
3517 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003518 break;
3519 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003520 case MSG_DISK_DESTROYED: {
3521 callback.onDiskDestroyed((DiskInfo) args.arg1);
3522 break;
3523 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003524 }
3525 }
3526
3527 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3528 final SomeArgs args = SomeArgs.obtain();
3529 args.arg1 = path;
3530 args.arg2 = oldState;
3531 args.arg3 = newState;
3532 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3533 }
3534
3535 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3536 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003537 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003538 args.argi2 = oldState;
3539 args.argi3 = newState;
3540 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3541 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003542
Jeff Sharkey50a05452015-04-29 11:24:52 -07003543 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3544 final SomeArgs args = SomeArgs.obtain();
3545 args.arg1 = rec.clone();
3546 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3547 }
3548
3549 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003550 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003551 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003552 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003553 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003554
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003555 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003556 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003557 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003558 args.argi2 = volumeCount;
3559 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003560 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003561
3562 private void notifyDiskDestroyed(DiskInfo disk) {
3563 final SomeArgs args = SomeArgs.obtain();
3564 args.arg1 = disk.clone();
3565 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3566 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003567 }
3568
Kenny Root38cf8862010-09-26 14:18:51 -07003569 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003570 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
3571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
3572
3573 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003574 synchronized (mLock) {
3575 pw.println("Disks:");
3576 pw.increaseIndent();
3577 for (int i = 0; i < mDisks.size(); i++) {
3578 final DiskInfo disk = mDisks.valueAt(i);
3579 disk.dump(pw);
3580 }
3581 pw.decreaseIndent();
3582
3583 pw.println();
3584 pw.println("Volumes:");
3585 pw.increaseIndent();
3586 for (int i = 0; i < mVolumes.size(); i++) {
3587 final VolumeInfo vol = mVolumes.valueAt(i);
3588 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3589 vol.dump(pw);
3590 }
3591 pw.decreaseIndent();
3592
3593 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003594 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003595 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003596 for (int i = 0; i < mRecords.size(); i++) {
3597 final VolumeRecord note = mRecords.valueAt(i);
3598 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003599 }
3600 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003601
3602 pw.println();
3603 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07003604 pw.println("Force adoptable: " + mForceAdoptable);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08003605 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003606 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3607 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003608 }
Kenny Root38cf8862010-09-26 14:18:51 -07003609
Kenny Root38cf8862010-09-26 14:18:51 -07003610 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003611 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003612 pw.println("mObbMounts:");
3613 pw.increaseIndent();
3614 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3615 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003616 while (binders.hasNext()) {
3617 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003618 pw.println(e.getKey() + ":");
3619 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003620 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003621 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003622 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003623 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003624 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003625 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003626 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003627
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003628 pw.println();
3629 pw.println("mObbPathToStateMap:");
3630 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003631 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3632 while (maps.hasNext()) {
3633 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003634 pw.print(e.getKey());
3635 pw.print(" -> ");
3636 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003637 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003638 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003639 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003640
Robert Greenwalt470fd722012-01-18 12:51:15 -08003641 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003642 pw.println("mConnector:");
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003643 pw.increaseIndent();
Robert Greenwalt470fd722012-01-18 12:51:15 -08003644 mConnector.dump(fd, pw, args);
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003645 pw.decreaseIndent();
Christopher Tate7265abe2014-11-21 13:54:45 -08003646
Christopher Tate7265abe2014-11-21 13:54:45 -08003647 pw.println();
Jeff Sharkey5b0e5202015-12-18 17:18:09 -07003648 pw.println("mCryptConnector:");
3649 pw.increaseIndent();
3650 mCryptConnector.dump(fd, pw, args);
3651 pw.decreaseIndent();
3652
3653 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003654 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003655 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003658 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003659 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003660 public void monitor() {
3661 if (mConnector != null) {
3662 mConnector.monitor();
3663 }
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003664 if (mCryptConnector != null) {
3665 mCryptConnector.monitor();
3666 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003667 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003668
3669 private final class MountServiceInternalImpl extends MountServiceInternal {
3670 // Not guarded by a lock.
3671 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3672 new CopyOnWriteArrayList<>();
3673
3674 @Override
3675 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3676 // No locking - CopyOnWriteArrayList
3677 mPolicies.add(policy);
3678 }
3679
3680 @Override
3681 public void onExternalStoragePolicyChanged(int uid, String packageName) {
3682 final int mountMode = getExternalStorageMountMode(uid, packageName);
3683 remountUidExternalStorage(uid, mountMode);
3684 }
3685
3686 @Override
3687 public int getExternalStorageMountMode(int uid, String packageName) {
3688 // No locking - CopyOnWriteArrayList
3689 int mountMode = Integer.MAX_VALUE;
3690 for (ExternalStorageMountPolicy policy : mPolicies) {
3691 final int policyMode = policy.getMountMode(uid, packageName);
3692 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3693 return Zygote.MOUNT_EXTERNAL_NONE;
3694 }
3695 mountMode = Math.min(mountMode, policyMode);
3696 }
3697 if (mountMode == Integer.MAX_VALUE) {
3698 return Zygote.MOUNT_EXTERNAL_NONE;
3699 }
3700 return mountMode;
3701 }
3702
3703 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003704 // No need to check for system uid. This avoids a deadlock between
3705 // PackageManagerService and AppOpsService.
3706 if (uid == Process.SYSTEM_UID) {
3707 return true;
3708 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003709 // No locking - CopyOnWriteArrayList
3710 for (ExternalStorageMountPolicy policy : mPolicies) {
3711 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
3712 if (!policyHasStorage) {
3713 return false;
3714 }
3715 }
3716 return true;
3717 }
3718 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003719}