blob: 8fea3a4d150d99e97e3b6e39933168d298331ae2 [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
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -080019import static android.Manifest.permission.INSTALL_PACKAGES;
20import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
21import static android.app.AppOpsManager.MODE_ALLOWED;
Jeff Sharkey11697f52018-12-13 10:14:42 -070022import static android.app.AppOpsManager.OP_LEGACY_STORAGE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -080023import static android.app.AppOpsManager.OP_REQUEST_INSTALL_PACKAGES;
Jeff Sharkey11697f52018-12-13 10:14:42 -070024import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
25import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
26import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -080027import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey39466322018-12-05 19:19:52 -070028import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
Jeff Sharkey0095a822018-02-15 13:06:53 -070029import static android.os.storage.OnObbStateChangeListener.ERROR_ALREADY_MOUNTED;
30import static android.os.storage.OnObbStateChangeListener.ERROR_COULD_NOT_MOUNT;
31import static android.os.storage.OnObbStateChangeListener.ERROR_COULD_NOT_UNMOUNT;
32import static android.os.storage.OnObbStateChangeListener.ERROR_INTERNAL;
33import static android.os.storage.OnObbStateChangeListener.ERROR_NOT_MOUNTED;
34import static android.os.storage.OnObbStateChangeListener.ERROR_PERMISSION_DENIED;
35import static android.os.storage.OnObbStateChangeListener.MOUNTED;
36import static android.os.storage.OnObbStateChangeListener.UNMOUNTED;
Jeff Sharkey5790af02018-08-13 17:42:54 -060037
Jeff Sharkey11697f52018-12-13 10:14:42 -070038import static com.android.internal.util.XmlUtils.readBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070039import static com.android.internal.util.XmlUtils.readIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070040import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070041import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkey11697f52018-12-13 10:14:42 -070042import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070043import static com.android.internal.util.XmlUtils.writeIntAttribute;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -070044import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070045import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey5790af02018-08-13 17:42:54 -060046
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -070047import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
48import static org.xmlpull.v1.XmlPullParser.START_TAG;
49
Jason parks8888c592011-01-20 22:46:41 -060050import android.Manifest;
Jeff Sharkeyef10ee02015-07-05 14:17:27 -070051import android.annotation.Nullable;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -070052import android.app.ActivityManager;
Sudheer Shanka87915d62018-11-06 10:57:35 -080053import android.app.ActivityManagerInternal;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -070054import android.app.AppOpsManager;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070055import android.app.IActivityManager;
Jeff Sharkey9765e442017-12-14 22:15:14 -070056import android.app.KeyguardManager;
Pavel Grafovce72ef02018-01-10 17:14:11 +000057import android.app.admin.SecurityLog;
Jeff Sharkey9bed0702017-01-23 20:37:05 -070058import android.app.usage.StorageStatsManager;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070059import android.content.BroadcastReceiver;
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -070060import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.Context;
62import android.content.Intent;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070063import android.content.IntentFilter;
Sudheer Shanka0a541a52018-07-31 13:21:11 -070064import android.content.pm.ApplicationInfo;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -080065import android.content.pm.IPackageManager;
Jeff Sharkey275e3e42015-04-24 16:10:32 -070066import android.content.pm.IPackageMoveObserver;
Jeff Sharkey11697f52018-12-13 10:14:42 -070067import android.content.pm.PackageInfo;
Jeff Sharkey275e3e42015-04-24 16:10:32 -070068import android.content.pm.PackageManager;
Sudheer Shanka0a541a52018-07-31 13:21:11 -070069import android.content.pm.PackageManagerInternal;
Jeff Sharkey14cbe522015-07-08 14:06:37 -070070import android.content.pm.ProviderInfo;
Jeff Sharkeybcd262d2015-06-10 09:41:17 -070071import android.content.pm.UserInfo;
Elliott Hughesf839b4f2014-09-26 12:30:47 -070072import android.content.res.Configuration;
Kenny Root02c87302010-07-01 08:10:18 -070073import android.content.res.ObbInfo;
Daniel Colascione766b6322018-01-08 19:10:36 -080074import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.net.Uri;
Kenny Root02c87302010-07-01 08:10:18 -070076import android.os.Binder;
Jeff Sharkey4c099d02015-05-15 13:45:00 -070077import android.os.DropBoxManager;
Kenny Roota02b8b02010-08-05 16:14:17 -070078import android.os.Environment;
Jeff Sharkeyb049e212012-09-07 23:16:01 -070079import android.os.Environment.UserEnvironment;
Jeff Sharkey48877892015-03-18 11:27:19 -070080import android.os.FileUtils;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080081import android.os.Handler;
Dianne Hackbornefa92b22013-05-03 14:11:43 -070082import android.os.HandlerThread;
Kenny Roota02b8b02010-08-05 16:14:17 -070083import android.os.IBinder;
Jin Qian12690d52017-10-13 18:17:04 -070084import android.os.IStoraged;
Jeff Sharkey1019de92017-09-06 13:47:03 -060085import android.os.IVold;
Jeff Sharkey8058fe62017-09-13 11:50:33 -060086import android.os.IVoldListener;
Jeff Sharkeyb302c542017-09-15 12:57:59 -060087import android.os.IVoldTaskListener;
Daniel Sandler5f27ef42010-03-16 15:42:02 -040088import android.os.Looper;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -080089import android.os.Message;
Daichi Hirono9e8d9e22015-11-13 14:37:00 +090090import android.os.ParcelFileDescriptor;
Jeff Sharkey500ce9e2017-02-12 02:39:24 -070091import android.os.ParcelableException;
Jeff Sharkeyb302c542017-09-15 12:57:59 -060092import android.os.PersistableBundle;
Jeff Sharkeyce14cd02015-12-07 15:35:42 -070093import android.os.PowerManager;
Jeff Sharkey9527b222015-06-24 15:24:48 -070094import android.os.Process;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -070095import android.os.RemoteCallbackList;
San Mehat4270e1e2010-01-29 05:32:19 -080096import android.os.RemoteException;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -080097import android.os.ServiceManager;
Paul Crowleyfc0b5192018-07-02 13:58:10 -070098import android.os.ServiceSpecificException;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -070099import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700101import android.os.UserHandle;
Emily Bernier92aa5a22014-07-07 10:11:48 -0400102import android.os.UserManager;
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700103import android.os.UserManagerInternal;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700104import android.os.storage.DiskInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -0700105import android.os.storage.IObbActionListener;
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -0700106import android.os.storage.IStorageEventListener;
Sudheer Shanka2250d562016-11-07 15:41:02 -0800107import android.os.storage.IStorageManager;
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -0700108import android.os.storage.IStorageShutdownObserver;
Kenny Rootaf9d6672010-10-08 09:21:39 -0700109import android.os.storage.OnObbStateChangeListener;
Paul Lawrence46791e72014-04-03 09:10:26 -0700110import android.os.storage.StorageManager;
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -0700111import android.os.storage.StorageManagerInternal;
Mike Lockwood2f6a3882011-05-09 19:08:06 -0700112import android.os.storage.StorageVolume;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700113import android.os.storage.VolumeInfo;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700114import android.os.storage.VolumeRecord;
Jeff Sharkey5d0c55c2019-01-24 14:32:31 -0700115import android.provider.DeviceConfig;
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700116import android.provider.MediaStore;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700117import android.provider.Settings;
Inseob Kimc1246e62018-11-08 13:13:54 +0900118import android.sysprop.VoldProperties;
Jason parksf7b3cd42011-01-27 09:28:25 -0600119import android.text.TextUtils;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700120import android.text.format.DateUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700121import android.util.ArrayMap;
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700122import android.util.ArraySet;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700123import android.util.AtomicFile;
Jeff Sharkey9f2dc052018-01-07 16:47:31 -0700124import android.util.DataUnit;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700125import android.util.Log;
Felipe Leme281389a2016-10-10 17:12:20 -0700126import android.util.Pair;
San Mehata5078592010-03-25 09:36:54 -0700127import android.util.Slog;
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700128import android.util.SparseArray;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700129import android.util.TimeUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700130import android.util.Xml;
Jeff Sharkey48877892015-03-18 11:27:19 -0700131
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800132import com.android.internal.annotations.GuardedBy;
Sudheer Shankaff971bc2018-12-13 17:39:59 -0800133import com.android.internal.app.IAppOpsCallback;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800134import com.android.internal.app.IAppOpsService;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900135import com.android.internal.os.AppFuseMount;
Jeff Sharkey1019de92017-09-06 13:47:03 -0600136import com.android.internal.os.BackgroundThread;
Daichi Hirono812c95d2017-02-08 16:20:20 +0900137import com.android.internal.os.FuseUnavailableMountException;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700138import com.android.internal.os.SomeArgs;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700139import com.android.internal.os.Zygote;
Jeff Sharkey48877892015-03-18 11:27:19 -0700140import com.android.internal.util.ArrayUtils;
Jeff Sharkey11697f52018-12-13 10:14:42 -0700141import com.android.internal.util.CollectionUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600142import com.android.internal.util.DumpUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700143import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800144import com.android.internal.util.HexDump;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700145import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700146import com.android.internal.util.Preconditions;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700147import com.android.internal.widget.LockPatternUtils;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900148import com.android.server.storage.AppFuseBridge;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700149import com.android.server.wm.ActivityTaskManagerInternal;
150import com.android.server.wm.ActivityTaskManagerInternal.ScreenObserver;
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700151
Jeff Sharkey5790af02018-08-13 17:42:54 -0600152import libcore.io.IoUtils;
153import libcore.util.EmptyArray;
154
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700155import org.xmlpull.v1.XmlPullParser;
156import org.xmlpull.v1.XmlPullParserException;
157import org.xmlpull.v1.XmlSerializer;
158
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700159import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -0700160import java.io.FileDescriptor;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700161import java.io.FileInputStream;
162import java.io.FileNotFoundException;
Christopher Tate7265abe2014-11-21 13:54:45 -0800163import java.io.FileOutputStream;
Kenny Root05105f72010-09-22 17:29:43 -0700164import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -0700165import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -0700166import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -0800167import java.nio.charset.StandardCharsets;
Jeff Sharkey0095a822018-02-15 13:06:53 -0700168import java.security.GeneralSecurityException;
Kenny Root3b1abba2010-10-13 15:00:07 -0700169import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -0800170import java.util.ArrayList;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800171import java.util.Arrays;
Kenny Roota02b8b02010-08-05 16:14:17 -0700172import java.util.HashMap;
Kenny Root38cf8862010-09-26 14:18:51 -0700173import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -0700174import java.util.LinkedList;
175import java.util.List;
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700176import java.util.Locale;
Kenny Roota02b8b02010-08-05 16:14:17 -0700177import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -0700178import java.util.Map.Entry;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700179import java.util.Objects;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700180import java.util.concurrent.CopyOnWriteArrayList;
Kenny Root51a573c2012-05-17 13:30:28 -0700181import java.util.concurrent.CountDownLatch;
182import java.util.concurrent.TimeUnit;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700183import java.util.concurrent.TimeoutException;
Jeff Sharkey5790af02018-08-13 17:42:54 -0600184import java.util.regex.Matcher;
185import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Kenny Root3b1abba2010-10-13 15:00:07 -0700187import javax.crypto.SecretKey;
188import javax.crypto.SecretKeyFactory;
189import javax.crypto.spec.PBEKeySpec;
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191/**
Jeff Sharkey48877892015-03-18 11:27:19 -0700192 * Service responsible for various storage media. Connects to {@code vold} to
193 * watch for and manage dynamically added storage, such as SD cards and USB mass
194 * storage. Also decides how storage should be presented to users on the device.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 */
Jeff Sharkey9765e442017-12-14 22:15:14 -0700196class StorageManagerService extends IStorageManager.Stub
197 implements Watchdog.Monitor, ScreenObserver {
Jason parks5af0b912010-11-29 09:05:25 -0600198
Christopher Tated417d622013-08-19 16:14:25 -0700199 // Static direct instance pointer for the tightly-coupled idle service to use
Sudheer Shanka2250d562016-11-07 15:41:02 -0800200 static StorageManagerService sSelf = null;
Christopher Tated417d622013-08-19 16:14:25 -0700201
Daniel Colascione766b6322018-01-08 19:10:36 -0800202 /* Read during boot to decide whether to enable zram when available */
203 private static final String ZRAM_ENABLED_PROPERTY =
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700204 "persist.sys.zram_enabled";
205
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700206 private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage();
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700207
Jeff Sharkey36274992019-02-27 12:09:57 -0700208 private static final boolean ENABLE_LEGACY_GREYLIST = SystemProperties
209 .getBoolean(StorageManager.PROP_LEGACY_GREYLIST, true);
210
Jeff Sharkey56e62932015-03-21 20:41:00 -0700211 public static class Lifecycle extends SystemService {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800212 private StorageManagerService mStorageManagerService;
Jeff Sharkey56e62932015-03-21 20:41:00 -0700213
214 public Lifecycle(Context context) {
215 super(context);
216 }
217
218 @Override
219 public void onStart() {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800220 mStorageManagerService = new StorageManagerService(getContext());
221 publishBinderService("mount", mStorageManagerService);
222 mStorageManagerService.start();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700223 }
224
225 @Override
226 public void onBootPhase(int phase) {
Jeff Sharkey11697f52018-12-13 10:14:42 -0700227 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
228 mStorageManagerService.servicesReady();
229 } else if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800230 mStorageManagerService.systemReady();
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900231 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800232 mStorageManagerService.bootCompleted();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700233 }
234 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700235
236 @Override
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600237 public void onSwitchUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800238 mStorageManagerService.mCurrentUserId = userHandle;
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600239 }
240
241 @Override
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700242 public void onUnlockUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800243 mStorageManagerService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700244 }
245
246 @Override
247 public void onCleanupUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800248 mStorageManagerService.onCleanupUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700249 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700250 }
251
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800252 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800253 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700254
Jeff Sharkeyc3c72872018-06-06 15:35:53 -0600255 /**
256 * We now talk to vold over Binder, and it has its own internal lock to
257 * serialize certain calls. All long-running operations have been migrated
258 * to be async with callbacks, so we want watchdog to fire if vold wedges.
259 */
260 private static final boolean WATCHDOG_ENABLE = true;
Kenny Root07714d42011-08-17 17:49:28 -0700261
Jeff Sharkey00455bf2016-11-04 14:45:24 -0600262 /**
263 * Our goal is for all Android devices to be usable as development devices,
264 * which includes the new Direct Boot mode added in N. For devices that
265 * don't have native FBE support, we offer an emulation mode for developer
266 * testing purposes, but if it's prohibitively difficult to support this
267 * mode, it can be disabled for specific products using this flag.
268 */
269 private static final boolean EMULATE_FBE_SUPPORTED = true;
270
Sudheer Shanka2250d562016-11-07 15:41:02 -0800271 private static final String TAG = "StorageManagerService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700272
Jeff Sharkey9756d752015-05-14 21:07:42 -0700273 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700274 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700276 /** Magic value sent by MoveTask.cpp */
277 private static final int MOVE_STATUS_COPY_FINISHED = 82;
278
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700279 private static final int VERSION_INIT = 1;
280 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700281 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700282
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700283 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700284 private static final String ATTR_VERSION = "version";
285 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey11697f52018-12-13 10:14:42 -0700286 private static final String ATTR_ISOLATED_STORAGE = "isolatedStorage";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700287 private static final String TAG_VOLUME = "volume";
288 private static final String ATTR_TYPE = "type";
289 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700290 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700291 private static final String ATTR_NICKNAME = "nickname";
292 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700293 private static final String ATTR_CREATED_MILLIS = "createdMillis";
294 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
295 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700296
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700297 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700298
Jeff Sharkey48877892015-03-18 11:27:19 -0700299 /**
300 * <em>Never</em> hold the lock while performing downcalls into vold, since
301 * unsolicited events can suddenly appear to update data structures.
302 */
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600303 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_STORAGE);
Jeff Sharkey48877892015-03-18 11:27:19 -0700304
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700305 /**
306 * Similar to {@link #mLock}, never hold this lock while performing downcalls into vold.
307 * Also, never hold this while calling into PackageManagerService since it is used in callbacks
308 * from PackageManagerService.
309 *
310 * If both {@link #mLock} and this lock need to be held, {@link #mLock} should be acquired
311 * before this.
312 *
313 * Use -PL suffix for methods that need to called with this lock held.
314 */
315 private final Object mPackagesLock = new Object();
316
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700317 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700318 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700319 private int[] mLocalUnlockedUsers = EmptyArray.INT;
320 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800321 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700322 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700323
324 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700325 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700326 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700327 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700328 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700329 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700330
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700331 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700332 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700333 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700334 @GuardedBy("mLock")
335 private String mPrimaryStorageUuid;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700336
Jeff Sharkey11697f52018-12-13 10:14:42 -0700337 /** Flag indicating isolated storage state of last boot */
338 @GuardedBy("mLock")
339 private boolean mLastIsolatedStorage = false;
340
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700341 /** Map from disk ID to latches */
342 @GuardedBy("mLock")
343 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
344
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700345 @GuardedBy("mLock")
346 private IPackageMoveObserver mMoveCallback;
347 @GuardedBy("mLock")
348 private String mMoveTargetUuid;
349
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700350 @GuardedBy("mPackagesLock")
351 private final SparseArray<ArraySet<String>> mPackages = new SparseArray<>();
352
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600353 private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
354
Daichi Hirono9fb00182016-11-08 14:12:17 +0900355 /** Holding lock for AppFuse business */
356 private final Object mAppFuseLock = new Object();
357
358 @GuardedBy("mAppFuseLock")
359 private int mNextAppFuseName = 0;
360
361 @GuardedBy("mAppFuseLock")
Daichi Hironoe56740d2017-02-02 13:56:45 +0900362 private AppFuseBridge mAppFuseBridge = null;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900363
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700364 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700365 synchronized (mLock) {
366 final VolumeInfo vol = mVolumes.get(id);
367 if (vol != null) {
368 return vol;
369 }
370 }
371 throw new IllegalArgumentException("No volume found for ID " + id);
372 }
373
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700374 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700375 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700376 for (int i = 0; i < mVolumes.size(); i++) {
377 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700378 if (vol.path != null && path.startsWith(vol.path)) {
379 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700380 }
381 }
382 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700383 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700384 }
385
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700386 private VolumeRecord findRecordForPath(String path) {
387 synchronized (mLock) {
388 for (int i = 0; i < mVolumes.size(); i++) {
389 final VolumeInfo vol = mVolumes.valueAt(i);
390 if (vol.path != null && path.startsWith(vol.path)) {
391 return mRecords.get(vol.fsUuid);
392 }
393 }
394 }
395 return null;
396 }
397
398 private String scrubPath(String path) {
399 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
400 return "internal";
401 }
402 final VolumeRecord rec = findRecordForPath(path);
403 if (rec == null || rec.createdMillis == 0) {
404 return "unknown";
405 } else {
406 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
407 / DateUtils.WEEK_IN_MILLIS) + "w";
408 }
409 }
410
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700411 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700412 final StorageManager storage = mContext.getSystemService(StorageManager.class);
413 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700414 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700415 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
416 return storage.getPrimaryPhysicalVolume();
417 } else {
418 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
419 }
420 }
421
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700422 private boolean shouldBenchmark() {
423 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
424 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700425 if (benchInterval == -1) {
426 return false;
427 } else if (benchInterval == 0) {
428 return true;
429 }
430
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700431 synchronized (mLock) {
432 for (int i = 0; i < mVolumes.size(); i++) {
433 final VolumeInfo vol = mVolumes.valueAt(i);
434 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700435 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700436 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
437 if (benchAge >= benchInterval) {
438 return true;
439 }
440 }
441 }
442 return false;
443 }
444 }
445
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700446 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
447 synchronized (mLock) {
448 CountDownLatch latch = mDiskScanLatches.get(diskId);
449 if (latch == null) {
450 latch = new CountDownLatch(1);
451 mDiskScanLatches.put(diskId, latch);
452 }
453 return latch;
454 }
455 }
456
Paul Lawrence8e397362014-01-27 15:22:30 -0800457 /** List of crypto types.
458 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
459 * corresponding commands in CommandListener.cpp */
460 public static final String[] CRYPTO_TYPES
461 = { "password", "default", "pattern", "pin" };
462
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700463 private final Context mContext;
Jeff Sharkey5d0c55c2019-01-24 14:32:31 -0700464 private final ContentResolver mResolver;
Jeff Sharkeycd575992016-03-29 14:12:49 -0600465
Jeff Sharkey1019de92017-09-06 13:47:03 -0600466 private volatile IVold mVold;
Jin Qian12690d52017-10-13 18:17:04 -0700467 private volatile IStoraged mStoraged;
Jeff Sharkey1019de92017-09-06 13:47:03 -0600468
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700469 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900470 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700471 private volatile boolean mDaemonConnected = false;
Jeff Sharkey9765e442017-12-14 22:15:14 -0700472 private volatile boolean mSecureKeyguardShowing = true;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700473
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700474 private PackageManagerInternal mPmInternal;
Jeff Sharkey5790af02018-08-13 17:42:54 -0600475 private UserManagerInternal mUmInternal;
Sudheer Shanka87915d62018-11-06 10:57:35 -0800476 private ActivityManagerInternal mAmInternal;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700477
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800478 private IPackageManager mIPackageManager;
479 private IAppOpsService mIAppOpsService;
480
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700481 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700482 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700483
San Mehat6cdd9c02010-02-09 14:45:20 -0800484 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700485 * The size of the crypto algorithm key in bits for OBB files. Currently
486 * Twofish is used which takes 128-bit keys.
487 */
488 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
489
490 /**
491 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
492 * 1024 is reasonably secure and not too slow.
493 */
494 private static final int PBKDF2_HASH_ROUNDS = 1024;
495
496 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700497 * Mounted OBB tracking information. Used to track the current state of all
498 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700499 */
Kenny Root735de3b2010-09-30 14:11:39 -0700500 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700501
502 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700503 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
504
Svet Ganov6ee871e2015-07-10 14:29:33 -0700505 // Not guarded by a lock.
Sudheer Shanka2250d562016-11-07 15:41:02 -0800506 private final StorageManagerInternalImpl mStorageManagerInternal
507 = new StorageManagerInternalImpl();
Svet Ganov6ee871e2015-07-10 14:29:33 -0700508
Kenny Roota02b8b02010-08-05 16:14:17 -0700509 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700510 public ObbState(String rawPath, String canonicalPath, int callingUid,
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600511 IObbActionListener token, int nonce, String volId) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700512 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700513 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700514 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700515 this.token = token;
516 this.nonce = nonce;
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600517 this.volId = volId;
Kenny Roota02b8b02010-08-05 16:14:17 -0700518 }
519
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700520 final String rawPath;
521 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700522
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700523 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700524
Kenny Rootaf9d6672010-10-08 09:21:39 -0700525 // Token of remote Binder caller
526 final IObbActionListener token;
527
528 // Identifier to pass back to the token
529 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700530
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600531 String volId;
532
Kenny Root735de3b2010-09-30 14:11:39 -0700533 public IBinder getBinder() {
534 return token.asBinder();
535 }
536
Kenny Roota02b8b02010-08-05 16:14:17 -0700537 @Override
538 public void binderDied() {
539 ObbAction action = new UnmountObbAction(this, true);
540 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700541 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700542
Kenny Root5919ac62010-10-05 09:49:40 -0700543 public void link() throws RemoteException {
544 getBinder().linkToDeath(this, 0);
545 }
546
547 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700548 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700549 }
Kenny Root38cf8862010-09-26 14:18:51 -0700550
551 @Override
552 public String toString() {
553 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700554 sb.append("rawPath=").append(rawPath);
555 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700556 sb.append(",ownerGid=").append(ownerGid);
557 sb.append(",token=").append(token);
558 sb.append(",binder=").append(getBinder());
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600559 sb.append(",volId=").append(volId);
Kenny Root38cf8862010-09-26 14:18:51 -0700560 sb.append('}');
561 return sb.toString();
562 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700563 }
564
565 // OBB Action Handler
566 final private ObbActionHandler mObbActionHandler;
567
568 // OBB action handler messages
569 private static final int OBB_RUN_ACTION = 1;
Sudheer Shanka25469aa2018-08-27 15:50:23 -0700570 private static final int OBB_FLUSH_MOUNT_STATE = 2;
Kenny Root02c87302010-07-01 08:10:18 -0700571
Christopher Tate7265abe2014-11-21 13:54:45 -0800572 // Last fstrim operation tracking
573 private static final String LAST_FSTRIM_FILE = "last-fstrim";
574 private final File mLastMaintenanceFile;
575 private long mLastMaintenance;
576
Kenny Root02c87302010-07-01 08:10:18 -0700577 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700578 private static final int H_SYSTEM_READY = 1;
579 private static final int H_DAEMON_CONNECTED = 2;
580 private static final int H_SHUTDOWN = 3;
581 private static final int H_FSTRIM = 4;
582 private static final int H_VOLUME_MOUNT = 5;
583 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700584 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700585 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800586 private static final int H_PARTITION_FORGET = 9;
587 private static final int H_RESET = 10;
Jin Qiana85b9912017-10-17 15:48:18 -0700588 private static final int H_RUN_IDLE_MAINT = 11;
589 private static final int H_ABORT_IDLE_MAINT = 12;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800590
Sudheer Shanka2250d562016-11-07 15:41:02 -0800591 class StorageManagerServiceHandler extends Handler {
592 public StorageManagerServiceHandler(Looper looper) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700593 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400594 }
595
Jason parks5af0b912010-11-29 09:05:25 -0600596 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800597 public void handleMessage(Message msg) {
598 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700599 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700600 handleSystemReady();
601 break;
602 }
603 case H_DAEMON_CONNECTED: {
604 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700605 break;
606 }
Christopher Tated417d622013-08-19 16:14:25 -0700607 case H_FSTRIM: {
Christopher Tated417d622013-08-19 16:14:25 -0700608 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800609
610 // Remember when we kicked it off
611 try {
612 mLastMaintenance = System.currentTimeMillis();
613 mLastMaintenanceFile.setLastModified(mLastMaintenance);
614 } catch (Exception e) {
615 Slog.e(TAG, "Unable to record last fstrim!");
616 }
617
Jeff Sharkeyb302c542017-09-15 12:57:59 -0600618 // TODO: Reintroduce shouldBenchmark() test
Jeff Sharkey7e19f532017-11-06 13:54:11 -0700619 fstrim(0, null);
Christopher Tate7265abe2014-11-21 13:54:45 -0800620
Christopher Tated417d622013-08-19 16:14:25 -0700621 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700622 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700623 Runnable callback = (Runnable) msg.obj;
624 if (callback != null) {
625 callback.run();
626 }
627 break;
628 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700629 case H_SHUTDOWN: {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800630 final IStorageShutdownObserver obs = (IStorageShutdownObserver) msg.obj;
Jeff Sharkey48877892015-03-18 11:27:19 -0700631 boolean success = false;
632 try {
Jeff Sharkey54402792017-09-15 16:05:19 -0600633 mVold.shutdown();
634 success = true;
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600635 } catch (Exception e) {
636 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -0700637 }
638 if (obs != null) {
639 try {
640 obs.onShutDownComplete(success ? 0 : -1);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600641 } catch (Exception ignored) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700642 }
643 }
644 break;
645 }
646 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700647 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700648 if (isMountDisallowed(vol)) {
649 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
650 break;
651 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700652 mount(vol);
Jeff Sharkey48877892015-03-18 11:27:19 -0700653 break;
654 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700655 case H_VOLUME_UNMOUNT: {
656 final VolumeInfo vol = (VolumeInfo) msg.obj;
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700657 unmount(vol);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700658 break;
659 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700660 case H_VOLUME_BROADCAST: {
661 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700662 final String envState = userVol.getState();
663 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700664 + userVol.getOwner());
665
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700666 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700667 if (action != null) {
668 final Intent intent = new Intent(action,
669 Uri.fromFile(userVol.getPathFile()));
670 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
Jeff Sharkey082f83b2017-03-26 14:34:47 -0600671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
672 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkey48877892015-03-18 11:27:19 -0700673 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
674 }
675 break;
676 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700677 case H_INTERNAL_BROADCAST: {
678 // Internal broadcasts aimed at system components, not for
679 // third-party apps.
680 final Intent intent = (Intent) msg.obj;
681 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
682 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800683 break;
684 }
685 case H_PARTITION_FORGET: {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -0600686 final VolumeRecord rec = (VolumeRecord) msg.obj;
687 forgetPartition(rec.partGuid, rec.fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800688 break;
689 }
690 case H_RESET: {
691 resetIfReadyAndConnected();
692 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700693 }
Jin Qiana85b9912017-10-17 15:48:18 -0700694 case H_RUN_IDLE_MAINT: {
695 Slog.i(TAG, "Running idle maintenance");
696 runIdleMaint((Runnable)msg.obj);
697 break;
698 }
699 case H_ABORT_IDLE_MAINT: {
700 Slog.i(TAG, "Aborting idle maintenance");
701 abortIdleMaint((Runnable)msg.obj);
702 break;
703 }
704
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800705 }
706 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700707 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700708
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700709 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800710
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700711 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
712 @Override
713 public void onReceive(Context context, Intent intent) {
714 final String action = intent.getAction();
715 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700716 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700717
718 try {
719 if (Intent.ACTION_USER_ADDED.equals(action)) {
720 final UserManager um = mContext.getSystemService(UserManager.class);
721 final int userSerialNumber = um.getUserSerialNumber(userId);
Jeff Sharkey54402792017-09-15 16:05:19 -0600722 mVold.onUserAdded(userId, userSerialNumber);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700723 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700724 synchronized (mVolumes) {
725 final int size = mVolumes.size();
726 for (int i = 0; i < size; i++) {
727 final VolumeInfo vol = mVolumes.valueAt(i);
728 if (vol.mountUserId == userId) {
729 vol.mountUserId = UserHandle.USER_NULL;
730 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
731 }
732 }
733 }
Jeff Sharkey54402792017-09-15 16:05:19 -0600734 mVold.onUserRemoved(userId);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700735 }
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600736 } catch (Exception e) {
737 Slog.wtf(TAG, e);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700738 }
739 }
740 };
741
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700742 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
743 throws TimeoutException {
744 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700745 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700746 try {
747 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800748 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700749 } else {
750 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700751 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800752 }
Kenny Root51a573c2012-05-17 13:30:28 -0700753 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700754 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800755 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700756 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
757 throw new TimeoutException("Thread " + Thread.currentThread().getName()
758 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
759 }
San Mehat207e5382010-02-04 20:46:54 -0800760 }
San Mehat1f6301e2010-01-07 22:40:27 -0800761 }
Kenny Root02c87302010-07-01 08:10:18 -0700762
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700763 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700764 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800765 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700766
Jeff Sharkey48877892015-03-18 11:27:19 -0700767 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700768 MountServiceIdler.scheduleIdlePass(mContext);
Daniel Colascione766b6322018-01-08 19:10:36 -0800769
770 // Toggle zram-enable system property in response to settings
771 mContext.getContentResolver().registerContentObserver(
772 Settings.Global.getUriFor(Settings.Global.ZRAM_ENABLED),
773 false /*notifyForDescendants*/,
774 new ContentObserver(null /* current thread */) {
775 @Override
776 public void onChange(boolean selfChange) {
777 refreshZramSettings();
778 }
779 });
780 refreshZramSettings();
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700781
Srinivas Paladuguc8261752019-01-09 10:54:52 -0800782 // Schedule zram writeback unless zram is disabled by persist.sys.zram_enabled
783 String zramPropValue = SystemProperties.get(ZRAM_ENABLED_PROPERTY);
784 if (!zramPropValue.equals("0")
785 && mContext.getResources().getBoolean(
786 com.android.internal.R.bool.config_zramWriteback)) {
787 ZramWriteback.scheduleZramWriteback(mContext);
788 }
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700789 // Toggle isolated-enable system property in response to settings
790 mContext.getContentResolver().registerContentObserver(
791 Settings.Global.getUriFor(Settings.Global.ISOLATED_STORAGE_REMOTE),
792 false /*notifyForDescendants*/,
793 new ContentObserver(null /* current thread */) {
794 @Override
795 public void onChange(boolean selfChange) {
796 refreshIsolatedStorageSettings();
797 }
798 });
Jeff Sharkey5d0c55c2019-01-24 14:32:31 -0700799 // For now, simply clone property when it changes
800 DeviceConfig.addOnPropertyChangedListener(DeviceConfig.Storage.NAMESPACE,
801 mContext.getMainExecutor(), (namespace, name, value) -> {
Jeff Sharkey8b499a02019-01-28 13:31:50 -0700802 refreshIsolatedStorageSettings();
Jeff Sharkey5d0c55c2019-01-24 14:32:31 -0700803 });
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700804 refreshIsolatedStorageSettings();
Daniel Colascione766b6322018-01-08 19:10:36 -0800805 }
806
807 /**
808 * Update the zram_enabled system property (which init reads to
809 * decide whether to enable zram) to reflect the zram_enabled
810 * preference (which we can change for experimentation purposes).
811 */
812 private void refreshZramSettings() {
813 String propertyValue = SystemProperties.get(ZRAM_ENABLED_PROPERTY);
814 if ("".equals(propertyValue)) {
815 return; // System doesn't have zram toggling support
816 }
817 String desiredPropertyValue =
818 Settings.Global.getInt(mContext.getContentResolver(),
819 Settings.Global.ZRAM_ENABLED,
820 1) != 0
821 ? "1" : "0";
822 if (!desiredPropertyValue.equals(propertyValue)) {
823 // Avoid redundant disk writes by setting only if we're
824 // changing the property value. There's no race: we're the
825 // sole writer.
826 SystemProperties.set(ZRAM_ENABLED_PROPERTY, desiredPropertyValue);
Srinivas Paladuguc8261752019-01-09 10:54:52 -0800827 // Schedule writeback only if zram is being enabled.
828 if (desiredPropertyValue.equals("1")
829 && mContext.getResources().getBoolean(
830 com.android.internal.R.bool.config_zramWriteback)) {
831 ZramWriteback.scheduleZramWriteback(mContext);
832 }
Daniel Colascione766b6322018-01-08 19:10:36 -0800833 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700834 }
835
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700836 private void refreshIsolatedStorageSettings() {
Jeff Sharkey8b499a02019-01-28 13:31:50 -0700837 // Always copy value from newer DeviceConfig location
838 Settings.Global.putString(mResolver,
839 Settings.Global.ISOLATED_STORAGE_REMOTE,
840 DeviceConfig.getProperty(DeviceConfig.Storage.NAMESPACE,
841 DeviceConfig.Storage.ISOLATED_STORAGE_ENABLED));
842
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700843 final int local = Settings.Global.getInt(mContext.getContentResolver(),
844 Settings.Global.ISOLATED_STORAGE_LOCAL, 0);
845 final int remote = Settings.Global.getInt(mContext.getContentResolver(),
846 Settings.Global.ISOLATED_STORAGE_REMOTE, 0);
847
848 // Walk down precedence chain; we prefer local settings first, then
849 // remote settings, before finally falling back to hard-coded default.
850 final boolean res;
851 if (local == -1) {
852 res = false;
853 } else if (local == 1) {
854 res = true;
855 } else if (remote == -1) {
856 res = false;
857 } else if (remote == 1) {
858 res = true;
859 } else {
Jeff Sharkey06376802019-02-11 12:20:02 -0700860 res = true;
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700861 }
862
863 Slog.d(TAG, "Isolated storage local flag " + local + " and remote flag "
864 + remote + " resolved to " + res);
865 SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE, Boolean.toString(res));
866 }
867
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700868 /**
869 * MediaProvider has a ton of code that makes assumptions about storage
870 * paths never changing, so we outright kill them to pick up new state.
871 */
872 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700873 private void killMediaProvider(List<UserInfo> users) {
874 if (users == null) return;
875
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700876 final long token = Binder.clearCallingIdentity();
877 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700878 for (UserInfo user : users) {
879 // System user does not have media provider, so skip.
880 if (user.isSystemOnly()) continue;
881
Jeff Sharkey5790af02018-08-13 17:42:54 -0600882 final ProviderInfo provider = mPmInternal.resolveContentProvider(
883 MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600884 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
885 user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700886 if (provider != null) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800887 final IActivityManager am = ActivityManager.getService();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700888 try {
Jeff Sharkey85f449e2016-06-23 09:26:00 -0600889 am.killApplication(provider.applicationInfo.packageName,
890 UserHandle.getAppId(provider.applicationInfo.uid),
891 UserHandle.USER_ALL, "vold reset");
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700892 // We only need to run this once. It will kill all users' media processes.
893 break;
894 } catch (RemoteException e) {
895 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700896 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700897 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700898 } finally {
899 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700900 }
901 }
902
Andreas Gampea36dc622018-02-05 17:19:22 -0800903 @GuardedBy("mLock")
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800904 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700905 // Create a stub volume that represents internal storage
906 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
907 VolumeInfo.TYPE_PRIVATE, null, null);
908 internal.state = VolumeInfo.STATE_MOUNTED;
909 internal.path = Environment.getDataDirectory().getAbsolutePath();
910 mVolumes.put(internal.id, internal);
911 }
912
Jeff Sharkey8924e872015-11-30 12:52:10 -0700913 private void initIfReadyAndConnected() {
914 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
915 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700916 if (mSystemReady && mDaemonConnected
Paul Lawrence20be5d62016-02-26 13:51:17 -0800917 && !StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700918 // When booting a device without native support, make sure that our
919 // user directories are locked or unlocked based on the current
920 // emulation status.
Paul Lawrence20be5d62016-02-26 13:51:17 -0800921 final boolean initLocked = StorageManager.isFileEncryptedEmulatedOnly();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000922 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700923 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700924 for (UserInfo user : users) {
925 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700926 if (initLocked) {
Jeff Sharkey54402792017-09-15 16:05:19 -0600927 mVold.lockUserKey(user.id);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700928 } else {
Jeff Sharkey54402792017-09-15 16:05:19 -0600929 mVold.unlockUserKey(user.id, user.serialNumber, encodeBytes(null),
930 encodeBytes(null));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700931 }
Jeff Sharkey43e12112017-09-12 16:31:45 -0600932 } catch (Exception e) {
933 Slog.wtf(TAG, e);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700934 }
935 }
936 }
937 }
938
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800939 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700940 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
941 + ", mDaemonConnected=" + mDaemonConnected);
942 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800943 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700944 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700945
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700946 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800947 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700948 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700949
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800950 mDisks.clear();
951 mVolumes.clear();
952
953 addInternalVolumeLocked();
954 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700955
Jeff Sharkey48877892015-03-18 11:27:19 -0700956 try {
Jeff Sharkey54402792017-09-15 16:05:19 -0600957 mVold.reset();
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700958
959 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700960 for (UserInfo user : users) {
Jeff Sharkey54402792017-09-15 16:05:19 -0600961 mVold.onUserAdded(user.id, user.serialNumber);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700962 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700963 for (int userId : systemUnlockedUsers) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -0700964 sendUserStartedCallback(userId);
Jin Qian12690d52017-10-13 18:17:04 -0700965 mStoraged.onUserStarted(userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700966 }
Jeff Sharkey9765e442017-12-14 22:15:14 -0700967 mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
Risanaec0ee72018-10-31 10:10:12 +0900968 mStorageManagerInternal.onReset(mVold);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600969 } catch (Exception e) {
970 Slog.wtf(TAG, e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700971 }
972 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700973 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700974
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700975 private void onUnlockUser(int userId) {
976 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700977
978 // We purposefully block here to make sure that user-specific
979 // staging area is ready so it's ready for zygote-forked apps to
980 // bind mount against.
981 try {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -0700982 sendUserStartedCallback(userId);
Jin Qian12690d52017-10-13 18:17:04 -0700983 mStoraged.onUserStarted(userId);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600984 } catch (Exception e) {
985 Slog.wtf(TAG, e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700986 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700987
988 // Record user as started so newly mounted volumes kick off events
989 // correctly, then synthesize events for any already-mounted volumes.
yuanhuihuiefd1f122016-07-13 21:21:03 +0800990 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700991 for (int i = 0; i < mVolumes.size(); i++) {
992 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700993 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700994 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700995 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700996
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700997 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
998 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700999 }
1000 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001001 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -07001002 }
1003 }
1004
1005 private void onCleanupUser(int userId) {
1006 Slog.d(TAG, "onCleanupUser " + userId);
1007
1008 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001009 mVold.onUserStopped(userId);
Jin Qian12690d52017-10-13 18:17:04 -07001010 mStoraged.onUserStopped(userId);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001011 } catch (Exception e) {
1012 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -07001013 }
1014
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07001015 synchronized (mPackagesLock) {
1016 mPackages.delete(userId);
1017 }
1018
yuanhuihuiefd1f122016-07-13 21:21:03 +08001019 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001020 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -07001021 }
1022 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001023
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07001024 private void sendUserStartedCallback(int userId) throws Exception {
1025 if (!ENABLE_ISOLATED_STORAGE) {
1026 mVold.onUserStarted(userId, EmptyArray.STRING, EmptyArray.INT, EmptyArray.STRING);
1027 }
1028
1029 final String[] packages;
1030 final int[] appIds;
1031 final String[] sandboxIds;
1032 final SparseArray<String> sharedUserIds = mPmInternal.getAppsWithSharedUserIds();
1033 final List<ApplicationInfo> appInfos =
1034 mContext.getPackageManager().getInstalledApplicationsAsUser(
1035 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1036 synchronized (mPackagesLock) {
1037 final ArraySet<String> userPackages = new ArraySet<>();
1038 final ArrayMap<String, Integer> packageToAppId = new ArrayMap<>();
1039 for (int i = appInfos.size() - 1; i >= 0; --i) {
1040 final ApplicationInfo appInfo = appInfos.get(i);
1041 if (appInfo.isInstantApp()) {
1042 continue;
1043 }
1044 userPackages.add(appInfo.packageName);
1045 packageToAppId.put(appInfo.packageName, UserHandle.getAppId(appInfo.uid));
1046 }
1047 mPackages.put(userId, userPackages);
1048
1049 packages = new String[userPackages.size()];
1050 appIds = new int[userPackages.size()];
1051 sandboxIds = new String[userPackages.size()];
1052 for (int i = userPackages.size() - 1; i >= 0; --i) {
1053 packages[i] = userPackages.valueAt(i);
1054 appIds[i] = packageToAppId.get(packages[i]);
1055 sandboxIds[i] = getSandboxId(packages[i], sharedUserIds.get(appIds[i]));
1056 }
1057 }
1058 mVold.onUserStarted(userId, packages, appIds, sandboxIds);
1059 }
1060
Jeff Sharkey9765e442017-12-14 22:15:14 -07001061 @Override
1062 public void onAwakeStateChanged(boolean isAwake) {
1063 // Ignored
1064 }
1065
1066 @Override
1067 public void onKeyguardStateChanged(boolean isShowing) {
1068 // Push down current secure keyguard status so that we ignore malicious
1069 // USB devices while locked.
1070 mSecureKeyguardShowing = isShowing
1071 && mContext.getSystemService(KeyguardManager.class).isDeviceSecure();
1072 try {
1073 mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
1074 } catch (Exception e) {
1075 Slog.wtf(TAG, e);
1076 }
1077 }
1078
Christopher Tated417d622013-08-19 16:14:25 -07001079 void runIdleMaintenance(Runnable callback) {
1080 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
1081 }
1082
Christopher Tate7265abe2014-11-21 13:54:45 -08001083 // Binder entry point for kicking off an immediate fstrim
1084 @Override
1085 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -07001086 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -08001087 runIdleMaintenance(null);
1088 }
1089
1090 @Override
1091 public long lastMaintenance() {
1092 return mLastMaintenance;
1093 }
1094
San Mehat4270e1e2010-01-29 05:32:19 -08001095 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -07001096 mDaemonConnected = true;
1097 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
1098 }
1099
1100 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -07001101 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001102 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -07001103
Jeff Sharkey48877892015-03-18 11:27:19 -07001104 // On an encrypted device we can't see system properties yet, so pull
1105 // the system locale out of the mount service.
Inseob Kimc1246e62018-11-08 13:13:54 +09001106 if ("".equals(VoldProperties.encrypt_progress().orElse(""))) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001107 copyLocaleFromMountService();
1108 }
San Mehat4270e1e2010-01-29 05:32:19 -08001109 }
1110
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001111 private void copyLocaleFromMountService() {
1112 String systemLocale;
1113 try {
1114 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
1115 } catch (RemoteException e) {
1116 return;
1117 }
1118 if (TextUtils.isEmpty(systemLocale)) {
1119 return;
1120 }
1121
1122 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1123 Locale locale = Locale.forLanguageTag(systemLocale);
1124 Configuration config = new Configuration();
1125 config.setLocale(locale);
1126 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001127 ActivityManager.getService().updatePersistentConfiguration(config);
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001128 } catch (RemoteException e) {
1129 Slog.e(TAG, "Error setting system locale from mount service", e);
1130 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001131
1132 // Temporary workaround for http://b/17945169.
1133 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001134 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001135 }
1136
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001137 private final IVoldListener mListener = new IVoldListener.Stub() {
1138 @Override
1139 public void onDiskCreated(String diskId, int flags) {
1140 synchronized (mLock) {
Jeff Sharkey901c0422018-04-20 13:11:20 -06001141 final String value = SystemProperties.get(StorageManager.PROP_ADOPTABLE);
1142 switch (value) {
1143 case "force_on":
1144 flags |= DiskInfo.FLAG_ADOPTABLE;
1145 break;
1146 case "force_off":
1147 flags &= ~DiskInfo.FLAG_ADOPTABLE;
1148 break;
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001149 }
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001150 mDisks.put(diskId, new DiskInfo(diskId, flags));
1151 }
1152 }
1153
1154 @Override
1155 public void onDiskScanned(String diskId) {
1156 synchronized (mLock) {
1157 final DiskInfo disk = mDisks.get(diskId);
1158 if (disk != null) {
1159 onDiskScannedLocked(disk);
1160 }
1161 }
1162 }
1163
1164 @Override
1165 public void onDiskMetadataChanged(String diskId, long sizeBytes, String label,
1166 String sysPath) {
1167 synchronized (mLock) {
1168 final DiskInfo disk = mDisks.get(diskId);
1169 if (disk != null) {
1170 disk.size = sizeBytes;
1171 disk.label = label;
1172 disk.sysPath = sysPath;
1173 }
1174 }
1175 }
1176
1177 @Override
1178 public void onDiskDestroyed(String diskId) {
1179 synchronized (mLock) {
1180 final DiskInfo disk = mDisks.remove(diskId);
1181 if (disk != null) {
1182 mCallbacks.notifyDiskDestroyed(disk);
1183 }
1184 }
1185 }
1186
1187 @Override
1188 public void onVolumeCreated(String volId, int type, String diskId, String partGuid) {
1189 synchronized (mLock) {
1190 final DiskInfo disk = mDisks.get(diskId);
1191 final VolumeInfo vol = new VolumeInfo(volId, type, disk, partGuid);
1192 mVolumes.put(volId, vol);
1193 onVolumeCreatedLocked(vol);
1194 }
1195 }
1196
1197 @Override
1198 public void onVolumeStateChanged(String volId, int state) {
1199 synchronized (mLock) {
1200 final VolumeInfo vol = mVolumes.get(volId);
1201 if (vol != null) {
1202 final int oldState = vol.state;
1203 final int newState = state;
1204 vol.state = newState;
1205 onVolumeStateChangedLocked(vol, oldState, newState);
1206 }
1207 }
1208 }
1209
1210 @Override
1211 public void onVolumeMetadataChanged(String volId, String fsType, String fsUuid,
1212 String fsLabel) {
1213 synchronized (mLock) {
1214 final VolumeInfo vol = mVolumes.get(volId);
1215 if (vol != null) {
1216 vol.fsType = fsType;
1217 vol.fsUuid = fsUuid;
1218 vol.fsLabel = fsLabel;
1219 }
1220 }
1221 }
1222
1223 @Override
1224 public void onVolumePathChanged(String volId, String path) {
1225 synchronized (mLock) {
1226 final VolumeInfo vol = mVolumes.get(volId);
1227 if (vol != null) {
1228 vol.path = path;
1229 }
1230 }
1231 }
1232
1233 @Override
1234 public void onVolumeInternalPathChanged(String volId, String internalPath) {
1235 synchronized (mLock) {
1236 final VolumeInfo vol = mVolumes.get(volId);
1237 if (vol != null) {
1238 vol.internalPath = internalPath;
1239 }
1240 }
1241 }
1242
1243 @Override
1244 public void onVolumeDestroyed(String volId) {
1245 synchronized (mLock) {
1246 mVolumes.remove(volId);
1247 }
1248 }
1249 };
1250
Andreas Gampea36dc622018-02-05 17:19:22 -08001251 @GuardedBy("mLock")
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001252 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001253 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001254 for (int i = 0; i < mVolumes.size(); i++) {
1255 final VolumeInfo vol = mVolumes.valueAt(i);
1256 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001257 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001258 }
1259 }
1260
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001261 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001262 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1263 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001264 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1265 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001266 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001267
1268 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1269 if (latch != null) {
1270 latch.countDown();
1271 }
1272
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001273 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001274 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001275 }
1276
Andreas Gampea36dc622018-02-05 17:19:22 -08001277 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001278 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey5790af02018-08-13 17:42:54 -06001279 if (mPmInternal.isOnlyCoreApps()) {
Jeff Sharkey6855c482016-03-31 14:34:38 -06001280 Slog.d(TAG, "System booted in core-only mode; ignoring volume " + vol.getId());
1281 return;
1282 }
1283
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001284 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1285 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1286 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1287
1288 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1289 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1290 Slog.v(TAG, "Found primary storage at " + vol);
1291 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1292 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1293 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1294
1295 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1296 Slog.v(TAG, "Found primary storage at " + vol);
1297 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1298 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1299 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1300 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001301
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001302 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001303 // TODO: only look at first public partition
1304 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1305 && vol.disk.isDefaultPrimary()) {
1306 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001307 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1308 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001309 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001310
1311 // Adoptable public disks are visible to apps, since they meet
1312 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001313 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001314 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1315 }
1316
Jeff Sharkeyab15c392016-05-05 11:45:01 -06001317 vol.mountUserId = mCurrentUserId;
Jeff Sharkey48877892015-03-18 11:27:19 -07001318 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001319
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001320 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1321 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1322
Risan05c41e62018-10-29 08:57:43 +09001323 } else if (vol.type == VolumeInfo.TYPE_STUB) {
1324 vol.mountUserId = mCurrentUserId;
1325 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001326 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001327 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001328 }
1329 }
1330
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001331 private boolean isBroadcastWorthy(VolumeInfo vol) {
1332 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001333 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001334 case VolumeInfo.TYPE_PUBLIC:
1335 case VolumeInfo.TYPE_EMULATED:
Risan05c41e62018-10-29 08:57:43 +09001336 case VolumeInfo.TYPE_STUB:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001337 break;
1338 default:
1339 return false;
1340 }
1341
1342 switch (vol.getState()) {
1343 case VolumeInfo.STATE_MOUNTED:
1344 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1345 case VolumeInfo.STATE_EJECTING:
1346 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001347 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001348 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001349 break;
1350 default:
1351 return false;
1352 }
1353
1354 return true;
1355 }
1356
Andreas Gampea36dc622018-02-05 17:19:22 -08001357 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001358 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001359 // Remember that we saw this volume so we're ready to accept user
1360 // metadata, or so we can annoy them when a private volume is ejected
1361 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001362 VolumeRecord rec = mRecords.get(vol.fsUuid);
1363 if (rec == null) {
1364 rec = new VolumeRecord(vol.type, vol.fsUuid);
1365 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001366 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001367 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1368 rec.nickname = vol.disk.getDescription();
1369 }
1370 mRecords.put(rec.fsUuid, rec);
1371 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001372 } else {
1373 // Handle upgrade case where we didn't store partition GUID
1374 if (TextUtils.isEmpty(rec.partGuid)) {
1375 rec.partGuid = vol.partGuid;
1376 writeSettingsLocked();
1377 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001378 }
1379 }
1380
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001381 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1382
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001383 // Do not broadcast before boot has completed to avoid launching the
1384 // processes that receive the intent unnecessarily.
1385 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001386 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001387 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1388 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001389 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001390 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1391 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001392 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001393 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001394
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001395 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1396 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001397
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001398 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1399 // Kick state changed event towards all started users. Any users
1400 // started after this point will trigger additional
1401 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001402 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001403 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001404 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001405 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001406
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001407 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1408 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001409 }
1410 }
1411 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001412
Risan05c41e62018-10-29 08:57:43 +09001413 if ((vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_STUB)
1414 && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001415 // TODO: this should eventually be handled by new ObbVolume state changes
1416 /*
1417 * Some OBBs might have been unmounted when this volume was
1418 * unmounted, so send a message to the handler to let it know to
1419 * remove those from the list of mounted OBBS.
1420 */
1421 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1422 OBB_FLUSH_MOUNT_STATE, vol.path));
1423 }
Pavel Grafovce72ef02018-01-10 17:14:11 +00001424 maybeLogMediaMount(vol, newState);
1425 }
1426
1427 private void maybeLogMediaMount(VolumeInfo vol, int newState) {
1428 if (!SecurityLog.isLoggingEnabled()) {
1429 return;
1430 }
1431
1432 final DiskInfo disk = vol.getDisk();
1433 if (disk == null || (disk.flags & (DiskInfo.FLAG_SD | DiskInfo.FLAG_USB)) == 0) {
1434 return;
1435 }
1436
1437 // Sometimes there is a newline character.
1438 final String label = disk.label != null ? disk.label.trim() : "";
1439
1440 if (newState == VolumeInfo.STATE_MOUNTED
1441 || newState == VolumeInfo.STATE_MOUNTED_READ_ONLY) {
1442 SecurityLog.writeEvent(SecurityLog.TAG_MEDIA_MOUNT, vol.path, label);
1443 } else if (newState == VolumeInfo.STATE_UNMOUNTED
1444 || newState == VolumeInfo.STATE_BAD_REMOVAL) {
1445 SecurityLog.writeEvent(SecurityLog.TAG_MEDIA_UNMOUNT, vol.path, label);
1446 }
San Mehat4270e1e2010-01-29 05:32:19 -08001447 }
1448
Andreas Gampea36dc622018-02-05 17:19:22 -08001449 @GuardedBy("mLock")
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001450 private void onMoveStatusLocked(int status) {
1451 if (mMoveCallback == null) {
1452 Slog.w(TAG, "Odd, status but no move requested");
1453 return;
1454 }
1455
1456 // TODO: estimate remaining time
1457 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001458 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001459 } catch (RemoteException ignored) {
1460 }
1461
1462 // We've finished copying and we're about to clean up old data, so
1463 // remember that move was successful if we get rebooted
1464 if (status == MOVE_STATUS_COPY_FINISHED) {
1465 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1466
1467 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001468 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001469 }
1470
1471 if (PackageManager.isMoveStatusFinished(status)) {
1472 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1473
1474 mMoveCallback = null;
1475 mMoveTargetUuid = null;
1476 }
1477 }
1478
Jeff Sharkey48877892015-03-18 11:27:19 -07001479 private void enforcePermission(String perm) {
1480 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001481 }
1482
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001483 /**
1484 * Decide if volume is mountable per device policies.
1485 */
1486 private boolean isMountDisallowed(VolumeInfo vol) {
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001487 UserManager userManager = mContext.getSystemService(UserManager.class);
1488
1489 boolean isUsbRestricted = false;
1490 if (vol.disk != null && vol.disk.isUsb()) {
1491 isUsbRestricted = userManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER,
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001492 Binder.getCallingUserHandle());
Emily Bernier92aa5a22014-07-07 10:11:48 -04001493 }
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001494
1495 boolean isTypeRestricted = false;
Risan05c41e62018-10-29 08:57:43 +09001496 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE
1497 || vol.type == VolumeInfo.TYPE_STUB) {
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001498 isTypeRestricted = userManager
1499 .hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1500 Binder.getCallingUserHandle());
1501 }
1502
1503 return isUsbRestricted || isTypeRestricted;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001504 }
1505
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001506 private void enforceAdminUser() {
1507 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1508 final int callingUserId = UserHandle.getCallingUserId();
1509 boolean isAdmin;
1510 long token = Binder.clearCallingIdentity();
1511 try {
1512 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1513 } finally {
1514 Binder.restoreCallingIdentity(token);
1515 }
1516 if (!isAdmin) {
1517 throw new SecurityException("Only admin users can adopt sd cards");
1518 }
1519 }
1520
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001521 /**
Sudheer Shanka2250d562016-11-07 15:41:02 -08001522 * Constructs a new StorageManagerService instance
San Mehat207e5382010-02-04 20:46:54 -08001523 *
1524 * @param context Binder context for this service
1525 */
Sudheer Shanka2250d562016-11-07 15:41:02 -08001526 public StorageManagerService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001527 sSelf = this;
1528
Jeff Sharkey342b4bf2018-12-18 11:12:40 -07001529 // Snapshot feature flag used for this boot
1530 SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT, Boolean.toString(
Jeff Sharkey06376802019-02-11 12:20:02 -07001531 SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, true)));
Jeff Sharkey342b4bf2018-12-18 11:12:40 -07001532
San Mehat207e5382010-02-04 20:46:54 -08001533 mContext = context;
Jeff Sharkey5d0c55c2019-01-24 14:32:31 -07001534 mResolver = mContext.getContentResolver();
1535
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001536 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001537 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001538
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001539 HandlerThread hthread = new HandlerThread(TAG);
1540 hthread.start();
Sudheer Shanka2250d562016-11-07 15:41:02 -08001541 mHandler = new StorageManagerServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001542
Sudheer Shanka2250d562016-11-07 15:41:02 -08001543 // Add OBB Action Handler to StorageManagerService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001544 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001545
Christopher Tate7265abe2014-11-21 13:54:45 -08001546 // Initialize the last-fstrim tracking if necessary
1547 File dataDir = Environment.getDataDirectory();
1548 File systemDir = new File(dataDir, "system");
1549 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1550 if (!mLastMaintenanceFile.exists()) {
1551 // Not setting mLastMaintenance here means that we will force an
1552 // fstrim during reboot following the OTA that installs this code.
1553 try {
1554 (new FileOutputStream(mLastMaintenanceFile)).close();
1555 } catch (IOException e) {
1556 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1557 }
1558 } else {
1559 mLastMaintenance = mLastMaintenanceFile.lastModified();
1560 }
1561
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001562 mSettingsFile = new AtomicFile(
Dianne Hackborne17b4452018-01-10 13:15:40 -08001563 new File(Environment.getDataSystemDirectory(), "storage.xml"), "storage-settings");
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001564
1565 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001566 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001567 }
1568
Sudheer Shanka2250d562016-11-07 15:41:02 -08001569 LocalServices.addService(StorageManagerInternal.class, mStorageManagerInternal);
Svet Ganov6ee871e2015-07-10 14:29:33 -07001570
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001571 final IntentFilter userFilter = new IntentFilter();
1572 userFilter.addAction(Intent.ACTION_USER_ADDED);
1573 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1574 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1575
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001576 synchronized (mLock) {
1577 addInternalVolumeLocked();
1578 }
Amith Yamasania7892482015-08-07 11:09:05 -07001579
Kenny Root07714d42011-08-17 17:49:28 -07001580 // Add ourself to the Watchdog monitors if enabled.
1581 if (WATCHDOG_ENABLE) {
1582 Watchdog.getInstance().addMonitor(this);
1583 }
San Mehat207e5382010-02-04 20:46:54 -08001584 }
1585
Jeff Sharkeycd575992016-03-29 14:12:49 -06001586 private void start() {
Jeff Sharkey1019de92017-09-06 13:47:03 -06001587 connect();
Jeff Sharkeycd575992016-03-29 14:12:49 -06001588 }
1589
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001590 private static String getSandboxId(String packageName, String sharedUserId) {
Sudheer Shankad68bd602018-11-13 17:43:39 -08001591 return sharedUserId == null
1592 ? packageName : StorageManager.SHARED_SANDBOX_PREFIX + sharedUserId;
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001593 }
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001594
Jeff Sharkey1019de92017-09-06 13:47:03 -06001595 private void connect() {
Jin Qian12690d52017-10-13 18:17:04 -07001596 IBinder binder = ServiceManager.getService("storaged");
1597 if (binder != null) {
1598 try {
1599 binder.linkToDeath(new DeathRecipient() {
1600 @Override
1601 public void binderDied() {
1602 Slog.w(TAG, "storaged died; reconnecting");
1603 mStoraged = null;
1604 connect();
1605 }
1606 }, 0);
1607 } catch (RemoteException e) {
1608 binder = null;
1609 }
1610 }
1611
1612 if (binder != null) {
1613 mStoraged = IStoraged.Stub.asInterface(binder);
1614 } else {
1615 Slog.w(TAG, "storaged not found; trying again");
1616 }
1617
1618 binder = ServiceManager.getService("vold");
Jeff Sharkey1019de92017-09-06 13:47:03 -06001619 if (binder != null) {
1620 try {
1621 binder.linkToDeath(new DeathRecipient() {
1622 @Override
1623 public void binderDied() {
1624 Slog.w(TAG, "vold died; reconnecting");
Jin Qian12690d52017-10-13 18:17:04 -07001625 mVold = null;
Jeff Sharkey1019de92017-09-06 13:47:03 -06001626 connect();
1627 }
1628 }, 0);
1629 } catch (RemoteException e) {
1630 binder = null;
1631 }
1632 }
1633
1634 if (binder != null) {
1635 mVold = IVold.Stub.asInterface(binder);
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001636 try {
1637 mVold.setListener(mListener);
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001638 } catch (RemoteException e) {
Jin Qian12690d52017-10-13 18:17:04 -07001639 mVold = null;
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001640 Slog.w(TAG, "vold listener rejected; trying again", e);
1641 }
Jeff Sharkey1019de92017-09-06 13:47:03 -06001642 } else {
1643 Slog.w(TAG, "vold not found; trying again");
Jeff Sharkey1019de92017-09-06 13:47:03 -06001644 }
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001645
Jin Qian12690d52017-10-13 18:17:04 -07001646 if (mStoraged == null || mVold == null) {
1647 BackgroundThread.getHandler().postDelayed(() -> {
1648 connect();
1649 }, DateUtils.SECOND_IN_MILLIS);
1650 } else {
1651 onDaemonConnected();
1652 }
Jeff Sharkey1019de92017-09-06 13:47:03 -06001653 }
1654
Jeff Sharkey11697f52018-12-13 10:14:42 -07001655 private void servicesReady() {
Sudheer Shankaff585072019-01-29 23:19:45 -08001656 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
1657 mUmInternal = LocalServices.getService(UserManagerInternal.class);
1658 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
1659
1660 mIPackageManager = IPackageManager.Stub.asInterface(
1661 ServiceManager.getService("package"));
1662 mIAppOpsService = IAppOpsService.Stub.asInterface(
1663 ServiceManager.getService(Context.APP_OPS_SERVICE));
1664 try {
1665 mIAppOpsService.startWatchingMode(OP_REQUEST_INSTALL_PACKAGES, null, mAppOpsCallback);
1666 } catch (RemoteException e) {
1667 }
1668
Jeff Sharkey11697f52018-12-13 10:14:42 -07001669 synchronized (mLock) {
1670 final boolean thisIsolatedStorage = StorageManager.hasIsolatedStorage();
1671 if (mLastIsolatedStorage == thisIsolatedStorage) {
1672 // Nothing changed since last boot; keep rolling forward
1673 return;
1674 } else if (thisIsolatedStorage) {
1675 // This boot enables isolated storage; apply legacy behavior
1676 applyLegacyStorage();
1677 }
1678
1679 // Always remember the new state we just booted with
1680 writeSettingsLocked();
1681 }
1682 }
1683
1684 /**
1685 * If we're enabling isolated storage, we need to remember which existing
1686 * apps have already been using shared storage, and grant them legacy access
1687 * to keep them running smoothly.
1688 */
1689 private void applyLegacyStorage() {
1690 final AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1691 final UserManagerInternal um = LocalServices.getService(UserManagerInternal.class);
1692 for (int userId : um.getUserIds()) {
1693 final PackageManager pm;
1694 try {
1695 pm = mContext.createPackageContextAsUser(mContext.getPackageName(),
1696 0, UserHandle.of(userId)).getPackageManager();
1697 } catch (PackageManager.NameNotFoundException e) {
1698 throw new RuntimeException(e);
1699 }
1700
1701 final List<PackageInfo> pkgs = pm.getPackagesHoldingPermissions(new String[] {
1702 android.Manifest.permission.READ_EXTERNAL_STORAGE,
1703 android.Manifest.permission.WRITE_EXTERNAL_STORAGE
1704 }, MATCH_UNINSTALLED_PACKAGES | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
1705 for (PackageInfo pkg : pkgs) {
1706 final int uid = pkg.applicationInfo.uid;
1707 final String packageName = pkg.applicationInfo.packageName;
1708
1709 final long lastAccess = getLastAccessTime(appOps, uid, packageName, new int[] {
1710 AppOpsManager.OP_READ_EXTERNAL_STORAGE,
1711 AppOpsManager.OP_WRITE_EXTERNAL_STORAGE,
1712 });
1713
1714 Log.d(TAG, "Found " + uid + " " + packageName
1715 + " with granted storage access, last accessed " + lastAccess);
1716 if (lastAccess > 0) {
1717 appOps.setMode(AppOpsManager.OP_LEGACY_STORAGE,
1718 uid, packageName, AppOpsManager.MODE_ALLOWED);
1719 }
1720 }
1721 }
1722 }
1723
1724 private static long getLastAccessTime(AppOpsManager manager,
1725 int uid, String packageName, int[] ops) {
1726 long maxTime = 0;
1727 final List<AppOpsManager.PackageOps> pkgs = manager.getOpsForPackage(uid, packageName, ops);
Eugene Susla04d021c2018-12-17 14:49:59 -08001728 for (AppOpsManager.PackageOps pkg : CollectionUtils.emptyIfNull(pkgs)) {
1729 for (AppOpsManager.OpEntry op : CollectionUtils.emptyIfNull(pkg.getOps())) {
Jeff Sharkey11697f52018-12-13 10:14:42 -07001730 maxTime = Math.max(maxTime, op.getLastAccessTime());
1731 }
1732 }
1733 return maxTime;
1734 }
1735
Jeff Sharkey56e62932015-03-21 20:41:00 -07001736 private void systemReady() {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001737 LocalServices.getService(ActivityTaskManagerInternal.class)
Jeff Sharkey9765e442017-12-14 22:15:14 -07001738 .registerScreenObserver(this);
1739
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001740 mSystemReady = true;
1741 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1742 }
1743
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001744 private void bootCompleted() {
1745 mBootCompleted = true;
1746 }
1747
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001748 private String getDefaultPrimaryStorageUuid() {
1749 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1750 return StorageManager.UUID_PRIMARY_PHYSICAL;
1751 } else {
1752 return StorageManager.UUID_PRIVATE_INTERNAL;
1753 }
1754 }
1755
Andreas Gampea36dc622018-02-05 17:19:22 -08001756 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001757 private void readSettingsLocked() {
1758 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001759 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey11697f52018-12-13 10:14:42 -07001760 mLastIsolatedStorage = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001761
1762 FileInputStream fis = null;
1763 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001764 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001765 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001766 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001767
1768 int type;
1769 while ((type = in.next()) != END_DOCUMENT) {
1770 if (type == START_TAG) {
1771 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001772 if (TAG_VOLUMES.equals(tag)) {
1773 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001774 final boolean primaryPhysical = SystemProperties.getBoolean(
1775 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1776 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1777 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1778 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001779 mPrimaryStorageUuid = readStringAttribute(in,
1780 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001781 }
Jeff Sharkey11697f52018-12-13 10:14:42 -07001782 mLastIsolatedStorage = readBooleanAttribute(in,
1783 ATTR_ISOLATED_STORAGE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001784
1785 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001786 final VolumeRecord rec = readVolumeRecord(in);
1787 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001788 }
1789 }
1790 }
1791 } catch (FileNotFoundException e) {
1792 // Missing metadata is okay, probably first boot
1793 } catch (IOException e) {
1794 Slog.wtf(TAG, "Failed reading metadata", e);
1795 } catch (XmlPullParserException e) {
1796 Slog.wtf(TAG, "Failed reading metadata", e);
1797 } finally {
1798 IoUtils.closeQuietly(fis);
1799 }
1800 }
1801
Andreas Gampea36dc622018-02-05 17:19:22 -08001802 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001803 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001804 FileOutputStream fos = null;
1805 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001806 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001807
1808 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001809 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001810 out.startDocument(null, true);
1811 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001812 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001813 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey11697f52018-12-13 10:14:42 -07001814 writeBooleanAttribute(out, ATTR_ISOLATED_STORAGE, StorageManager.hasIsolatedStorage());
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001815 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001816 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001817 final VolumeRecord rec = mRecords.valueAt(i);
1818 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001819 }
1820 out.endTag(null, TAG_VOLUMES);
1821 out.endDocument();
1822
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001823 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001824 } catch (IOException e) {
1825 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001826 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001827 }
1828 }
1829 }
1830
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001831 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1832 final int type = readIntAttribute(in, ATTR_TYPE);
1833 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1834 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001835 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001836 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1837 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001838 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1839 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1840 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001841 return meta;
1842 }
1843
1844 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1845 out.startTag(null, TAG_VOLUME);
1846 writeIntAttribute(out, ATTR_TYPE, rec.type);
1847 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001848 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001849 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1850 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001851 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1852 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1853 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001854 out.endTag(null, TAG_VOLUME);
1855 }
1856
San Mehat207e5382010-02-04 20:46:54 -08001857 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001858 * Exposed API calls below here
1859 */
1860
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001861 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001862 public void registerListener(IStorageEventListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001863 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001864 }
1865
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001866 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001867 public void unregisterListener(IStorageEventListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001868 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001869 }
1870
Jeff Sharkey48877892015-03-18 11:27:19 -07001871 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001872 public void shutdown(final IStorageShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001873 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001874
San Mehata5078592010-03-25 09:36:54 -07001875 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001876 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001877 }
1878
Jeff Sharkey48877892015-03-18 11:27:19 -07001879 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001880 public void mount(String volId) {
1881 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001882
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001883 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001884 if (isMountDisallowed(vol)) {
1885 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001886 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001887 mount(vol);
1888 }
1889
1890 private void mount(VolumeInfo vol) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001891 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001892 mVold.mount(vol.id, vol.mountFlags, vol.mountUserId);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001893 } catch (Exception e) {
1894 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001895 }
1896 }
1897
1898 @Override
1899 public void unmount(String volId) {
1900 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001901
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001902 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001903 unmount(vol);
1904 }
1905
1906 private void unmount(VolumeInfo vol) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001907 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001908 mVold.unmount(vol.id);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001909 } catch (Exception e) {
1910 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001911 }
1912 }
1913
1914 @Override
1915 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001916 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat5b77dab2010-01-26 13:28:50 -08001917
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001918 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001919 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001920 mVold.format(vol.id, "auto");
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001921 } catch (Exception e) {
1922 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -07001923 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001924 }
1925
1926 @Override
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001927 public void benchmark(String volId, IVoldTaskListener listener) {
Jeff Sharkey9756d752015-05-14 21:07:42 -07001928 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001929
1930 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001931 mVold.benchmark(volId, new IVoldTaskListener.Stub() {
1932 @Override
1933 public void onStatus(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001934 dispatchOnStatus(listener, status, extras);
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001935 }
1936
1937 @Override
1938 public void onFinished(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001939 dispatchOnFinished(listener, status, extras);
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001940
1941 final String path = extras.getString("path");
1942 final String ident = extras.getString("ident");
1943 final long create = extras.getLong("create");
1944 final long run = extras.getLong("run");
1945 final long destroy = extras.getLong("destroy");
1946
1947 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1948 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1949 + " " + ident + " " + create + " " + run + " " + destroy);
1950
1951 synchronized (mLock) {
1952 final VolumeRecord rec = findRecordForPath(path);
1953 if (rec != null) {
1954 rec.lastBenchMillis = System.currentTimeMillis();
1955 writeSettingsLocked();
1956 }
1957 }
1958 }
1959 });
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001960 } catch (RemoteException e) {
1961 throw e.rethrowAsRuntimeException();
Jeff Sharkey9756d752015-05-14 21:07:42 -07001962 }
1963 }
1964
1965 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001966 public void partitionPublic(String diskId) {
1967 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001968
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001969 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001970 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001971 mVold.partition(diskId, IVold.PARTITION_TYPE_PUBLIC, -1);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001972 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001973 } catch (Exception e) {
1974 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001975 }
1976 }
1977
1978 @Override
1979 public void partitionPrivate(String diskId) {
1980 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001981 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001982
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001983 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001984 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001985 mVold.partition(diskId, IVold.PARTITION_TYPE_PRIVATE, -1);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001986 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001987 } catch (Exception e) {
1988 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001989 }
1990 }
1991
1992 @Override
1993 public void partitionMixed(String diskId, int ratio) {
1994 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001995 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001996
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001997 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001998 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001999 mVold.partition(diskId, IVold.PARTITION_TYPE_MIXED, ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07002000 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002001 } catch (Exception e) {
2002 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07002003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005
Jeff Sharkey48877892015-03-18 11:27:19 -07002006 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002007 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002008 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002009
Jeff Sharkey50a05452015-04-29 11:24:52 -07002010 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002011 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002012 final VolumeRecord rec = mRecords.get(fsUuid);
2013 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07002014 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002015 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002016 }
2017 }
2018
2019 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002020 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002021 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002022
Jeff Sharkey50a05452015-04-29 11:24:52 -07002023 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002024 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002025 final VolumeRecord rec = mRecords.get(fsUuid);
2026 rec.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07002027 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002028 writeSettingsLocked();
2029 }
2030 }
2031
2032 @Override
2033 public void forgetVolume(String fsUuid) {
2034 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002035
Jeff Sharkey50a05452015-04-29 11:24:52 -07002036 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002037
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002038 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002039 final VolumeRecord rec = mRecords.remove(fsUuid);
2040 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002041 mHandler.obtainMessage(H_PARTITION_FORGET, rec).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002042 }
2043 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07002044
2045 // If this had been primary storage, revert back to internal and
2046 // reset vold so we bind into new volume into place.
2047 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002048 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002049 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002050 }
2051
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002052 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002053 }
2054 }
2055
Jeff Sharkey7d2af542015-05-12 15:27:15 -07002056 @Override
2057 public void forgetAllVolumes() {
2058 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7d2af542015-05-12 15:27:15 -07002059
Jeff Sharkey50a05452015-04-29 11:24:52 -07002060 synchronized (mLock) {
2061 for (int i = 0; i < mRecords.size(); i++) {
2062 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002063 final VolumeRecord rec = mRecords.valueAt(i);
2064 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002065 mHandler.obtainMessage(H_PARTITION_FORGET, rec).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002066 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07002067 mCallbacks.notifyVolumeForgotten(fsUuid);
2068 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07002069 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002070
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002071 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
2072 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
2073 }
2074
2075 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002076 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002077 }
2078 }
2079
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002080 private void forgetPartition(String partGuid, String fsUuid) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002081 try {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002082 mVold.forgetPartition(partGuid, fsUuid);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002083 } catch (Exception e) {
2084 Slog.wtf(TAG, e);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002085 }
2086 }
2087
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002088 @Override
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002089 public void fstrim(int flags, IVoldTaskListener listener) {
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002090 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002091
2092 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002093 mVold.fstrim(flags, new IVoldTaskListener.Stub() {
2094 @Override
2095 public void onStatus(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002096 dispatchOnStatus(listener, status, extras);
2097
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002098 // Ignore trim failures
2099 if (status != 0) return;
2100
2101 final String path = extras.getString("path");
2102 final long bytes = extras.getLong("bytes");
2103 final long time = extras.getLong("time");
2104
2105 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
2106 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path) + " " + bytes + " " + time);
2107
2108 synchronized (mLock) {
2109 final VolumeRecord rec = findRecordForPath(path);
2110 if (rec != null) {
2111 rec.lastTrimMillis = System.currentTimeMillis();
2112 writeSettingsLocked();
2113 }
2114 }
2115 }
2116
2117 @Override
2118 public void onFinished(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002119 dispatchOnFinished(listener, status, extras);
2120
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002121 // TODO: benchmark when desired
2122 }
2123 });
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002124 } catch (RemoteException e) {
2125 throw e.rethrowAsRuntimeException();
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002126 }
2127 }
2128
Jin Qiana85b9912017-10-17 15:48:18 -07002129 void runIdleMaint(Runnable callback) {
2130 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
2131
2132 try {
2133 mVold.runIdleMaint(new IVoldTaskListener.Stub() {
2134 @Override
2135 public void onStatus(int status, PersistableBundle extras) {
2136 // Not currently used
2137 }
2138 @Override
2139 public void onFinished(int status, PersistableBundle extras) {
2140 if (callback != null) {
2141 BackgroundThread.getHandler().post(callback);
2142 }
2143 }
2144 });
2145 } catch (Exception e) {
2146 Slog.wtf(TAG, e);
2147 }
2148 }
2149
2150 @Override
2151 public void runIdleMaintenance() {
2152 runIdleMaint(null);
2153 }
2154
2155 void abortIdleMaint(Runnable callback) {
2156 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
2157
2158 try {
2159 mVold.abortIdleMaint(new IVoldTaskListener.Stub() {
2160 @Override
2161 public void onStatus(int status, PersistableBundle extras) {
2162 // Not currently used
2163 }
2164 @Override
2165 public void onFinished(int status, PersistableBundle extras) {
2166 if (callback != null) {
2167 BackgroundThread.getHandler().post(callback);
2168 }
2169 }
2170 });
2171 } catch (Exception e) {
2172 Slog.wtf(TAG, e);
2173 }
2174 }
2175
2176 @Override
2177 public void abortIdleMaintenance() {
2178 abortIdleMaint(null);
2179 }
2180
Svet Ganov6ee871e2015-07-10 14:29:33 -07002181 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002182 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002183 mVold.remountUid(uid, mode);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002184 } catch (Exception e) {
2185 Slog.wtf(TAG, e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07002186 }
2187 }
2188
2189 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002190 public void setDebugFlags(int flags, int mask) {
2191 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002192
Jeff Sharkeyba512352015-11-12 20:17:45 -08002193 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Jeff Sharkey00455bf2016-11-04 14:45:24 -06002194 if (!EMULATE_FBE_SUPPORTED) {
2195 throw new IllegalStateException(
2196 "Emulation not supported on this device");
2197 }
Paul Lawrence20be5d62016-02-26 13:51:17 -08002198 if (StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002199 throw new IllegalStateException(
Jeff Sharkey00455bf2016-11-04 14:45:24 -06002200 "Emulation not supported on device with native FBE");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002201 }
Jeff Sharkey5a785162016-03-21 13:02:06 -06002202 if (mLockPatternUtils.isCredentialRequiredToDecrypt(false)) {
2203 throw new IllegalStateException(
2204 "Emulation requires disabling 'Secure start-up' in Settings > Security");
2205 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002206
Jeff Sharkey1176e512016-02-29 17:01:26 -07002207 final long token = Binder.clearCallingIdentity();
2208 try {
2209 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
2210 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002211
Jeff Sharkey1176e512016-02-29 17:01:26 -07002212 // Perform hard reboot to kick policy into place
2213 mContext.getSystemService(PowerManager.class).reboot(null);
2214 } finally {
2215 Binder.restoreCallingIdentity(token);
2216 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08002217 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002218
Jeff Sharkey901c0422018-04-20 13:11:20 -06002219 if ((mask & (StorageManager.DEBUG_ADOPTABLE_FORCE_ON
2220 | StorageManager.DEBUG_ADOPTABLE_FORCE_OFF)) != 0) {
2221 final String value;
2222 if ((flags & StorageManager.DEBUG_ADOPTABLE_FORCE_ON) != 0) {
2223 value = "force_on";
2224 } else if ((flags & StorageManager.DEBUG_ADOPTABLE_FORCE_OFF) != 0) {
2225 value = "force_off";
2226 } else {
2227 value = "";
2228 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08002229
Jeff Sharkey901c0422018-04-20 13:11:20 -06002230 final long token = Binder.clearCallingIdentity();
2231 try {
2232 SystemProperties.set(StorageManager.PROP_ADOPTABLE, value);
2233
2234 // Reset storage to kick new setting into place
Jeff Sharkeyba512352015-11-12 20:17:45 -08002235 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey901c0422018-04-20 13:11:20 -06002236 } finally {
2237 Binder.restoreCallingIdentity(token);
Jeff Sharkeyba512352015-11-12 20:17:45 -08002238 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002239 }
Jeff Sharkey33dd1562016-04-07 11:05:33 -06002240
2241 if ((mask & (StorageManager.DEBUG_SDCARDFS_FORCE_ON
2242 | StorageManager.DEBUG_SDCARDFS_FORCE_OFF)) != 0) {
2243 final String value;
2244 if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_ON) != 0) {
2245 value = "force_on";
2246 } else if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_OFF) != 0) {
2247 value = "force_off";
2248 } else {
2249 value = "";
2250 }
2251
2252 final long token = Binder.clearCallingIdentity();
2253 try {
2254 SystemProperties.set(StorageManager.PROP_SDCARDFS, value);
2255
2256 // Reset storage to kick new setting into place
2257 mHandler.obtainMessage(H_RESET).sendToTarget();
2258 } finally {
2259 Binder.restoreCallingIdentity(token);
2260 }
2261 }
Jeff Sharkeye53e2d92017-03-25 23:14:06 -06002262
2263 if ((mask & StorageManager.DEBUG_VIRTUAL_DISK) != 0) {
2264 final boolean enabled = (flags & StorageManager.DEBUG_VIRTUAL_DISK) != 0;
2265
2266 final long token = Binder.clearCallingIdentity();
2267 try {
2268 SystemProperties.set(StorageManager.PROP_VIRTUAL_DISK, Boolean.toString(enabled));
2269
2270 // Reset storage to kick new setting into place
2271 mHandler.obtainMessage(H_RESET).sendToTarget();
2272 } finally {
2273 Binder.restoreCallingIdentity(token);
2274 }
2275 }
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002276
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07002277 if ((mask & (StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_ON
2278 | StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_OFF)) != 0) {
2279 final int value;
2280 if ((flags & StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_ON) != 0) {
2281 value = 1;
2282 } else if ((flags & StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_OFF) != 0) {
2283 value = -1;
2284 } else {
2285 value = 0;
2286 }
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002287
2288 final long token = Binder.clearCallingIdentity();
2289 try {
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07002290 Settings.Global.putInt(mContext.getContentResolver(),
2291 Settings.Global.ISOLATED_STORAGE_LOCAL, value);
2292 refreshIsolatedStorageSettings();
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002293
2294 // Perform hard reboot to kick policy into place
Jeff Sharkey36274992019-02-27 12:09:57 -07002295 mHandler.post(() -> {
2296 mContext.getSystemService(PowerManager.class).reboot(null);
2297 });
2298 } finally {
2299 Binder.restoreCallingIdentity(token);
2300 }
2301 }
2302
2303 if ((mask & StorageManager.DEBUG_LEGACY_GREYLIST) != 0) {
2304 final boolean enabled = (flags & StorageManager.DEBUG_LEGACY_GREYLIST) != 0;
2305
2306 final long token = Binder.clearCallingIdentity();
2307 try {
2308 SystemProperties.set(StorageManager.PROP_LEGACY_GREYLIST,
2309 Boolean.toString(enabled));
2310
2311 // Perform hard reboot to kick policy into place
2312 mHandler.post(() -> {
2313 mContext.getSystemService(PowerManager.class).reboot(null);
2314 });
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002315 } finally {
2316 Binder.restoreCallingIdentity(token);
2317 }
2318 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002319 }
2320
2321 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002322 public String getPrimaryStorageUuid() {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002323 synchronized (mLock) {
2324 return mPrimaryStorageUuid;
2325 }
2326 }
2327
2328 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002329 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
2330 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002331
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002332 final VolumeInfo from;
2333 final VolumeInfo to;
2334
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002335 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002336 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
2337 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002338 }
2339
2340 if (mMoveCallback != null) {
2341 throw new IllegalStateException("Move already in progress");
2342 }
2343 mMoveCallback = callback;
2344 mMoveTargetUuid = volumeUuid;
2345
Jeff Sharkeya65e6492017-06-21 13:45:11 -06002346 // We need all the users unlocked to move their primary storage
2347 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
2348 for (UserInfo user : users) {
2349 if (StorageManager.isFileEncryptedNativeOrEmulated()
2350 && !isUserKeyUnlocked(user.id)) {
2351 Slog.w(TAG, "Failing move due to locked user " + user.id);
2352 onMoveStatusLocked(PackageManager.MOVE_FAILED_LOCKED_USER);
2353 return;
2354 }
2355 }
2356
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002357 // When moving to/from primary physical volume, we probably just nuked
2358 // the current storage location, so we have nothing to move.
2359 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
2360 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
2361 Slog.d(TAG, "Skipping move to/from primary physical");
2362 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
2363 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002364 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002365 return;
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002366
2367 } else {
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002368 from = findStorageForUuid(mPrimaryStorageUuid);
2369 to = findStorageForUuid(volumeUuid);
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002370
2371 if (from == null) {
2372 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2373 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2374 return;
2375 } else if (to == null) {
2376 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2377 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2378 return;
2379 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002380 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002381 }
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002382
2383 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002384 mVold.moveStorage(from.id, to.id, new IVoldTaskListener.Stub() {
2385 @Override
2386 public void onStatus(int status, PersistableBundle extras) {
2387 synchronized (mLock) {
2388 onMoveStatusLocked(status);
2389 }
2390 }
2391
2392 @Override
2393 public void onFinished(int status, PersistableBundle extras) {
2394 // Not currently used
2395 }
2396 });
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002397 } catch (Exception e) {
2398 Slog.wtf(TAG, e);
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002399 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002400 }
2401
San Mehatb1043402010-02-05 08:26:50 -08002402 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002403 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002404 for (int i = 0; i < mVolumes.size(); i++) {
2405 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002406 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002407 // Cool beans, we have a mounted primary volume
2408 return;
2409 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002410 }
San Mehatb1043402010-02-05 08:26:50 -08002411 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002412
2413 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002414 }
2415
Kenny Roota02b8b02010-08-05 16:14:17 -07002416 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2417 if (callerUid == android.os.Process.SYSTEM_UID) {
2418 return true;
2419 }
2420
Kenny Root02c87302010-07-01 08:10:18 -07002421 if (packageName == null) {
2422 return false;
2423 }
2424
Jeff Sharkey5790af02018-08-13 17:42:54 -06002425 final int packageUid = mPmInternal.getPackageUid(packageName,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002426 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002427
2428 if (DEBUG_OBB) {
2429 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2430 packageUid + ", callerUid = " + callerUid);
2431 }
2432
2433 return callerUid == packageUid;
2434 }
2435
Jeff Sharkey54402792017-09-15 16:05:19 -06002436 @Override
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002437 public String getMountedObbPath(String rawPath) {
2438 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002439
Kenny Root02c87302010-07-01 08:10:18 -07002440 warnOnNotMounted();
2441
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002442 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002443 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002444 state = mObbPathToStateMap.get(rawPath);
2445 }
2446 if (state == null) {
2447 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2448 return null;
2449 }
2450
Jeff Sharkey54402792017-09-15 16:05:19 -06002451 return findVolumeByIdOrThrow(state.volId).getPath().getAbsolutePath();
Kenny Root02c87302010-07-01 08:10:18 -07002452 }
2453
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002454 @Override
2455 public boolean isObbMounted(String rawPath) {
2456 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002457 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002458 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002459 }
Kenny Root02c87302010-07-01 08:10:18 -07002460 }
2461
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002462 @Override
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002463 public void mountObb(String rawPath, String canonicalPath, String key,
2464 IObbActionListener token, int nonce, ObbInfo obbInfo) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002465 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2466 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2467 Preconditions.checkNotNull(token, "token cannot be null");
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002468 Preconditions.checkNotNull(obbInfo, "obbIfno cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002469
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002470 final int callingUid = Binder.getCallingUid();
Jeff Sharkey41cd6812017-09-11 10:32:17 -06002471 final ObbState obbState = new ObbState(rawPath, canonicalPath,
2472 callingUid, token, nonce, null);
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002473 final ObbAction action = new MountObbAction(obbState, key, callingUid, obbInfo);
Kenny Roota02b8b02010-08-05 16:14:17 -07002474 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2475
2476 if (DEBUG_OBB)
2477 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002478 }
2479
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002480 @Override
2481 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2482 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2483
2484 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002485 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002486 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002487 }
2488
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002489 if (existingState != null) {
2490 // TODO: separate state object from request data
2491 final int callingUid = Binder.getCallingUid();
Jeff Sharkey41cd6812017-09-11 10:32:17 -06002492 final ObbState newState = new ObbState(rawPath, existingState.canonicalPath,
2493 callingUid, token, nonce, existingState.volId);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002494 final ObbAction action = new UnmountObbAction(newState, force);
2495 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002496
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002497 if (DEBUG_OBB)
2498 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2499 } else {
2500 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2501 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002502 }
2503
Ben Komalo444eca22011-09-01 15:17:44 -07002504 @Override
2505 public int getEncryptionState() {
2506 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2507 "no permission to access the crypt keeper");
2508
Ben Komalo444eca22011-09-01 15:17:44 -07002509 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002510 return mVold.fdeComplete();
2511 } catch (Exception e) {
2512 Slog.wtf(TAG, e);
Sudheer Shankaf7341142016-10-18 17:15:18 -07002513 return StorageManager.ENCRYPTION_STATE_ERROR_UNKNOWN;
Ben Komalo444eca22011-09-01 15:17:44 -07002514 }
2515 }
2516
2517 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002518 public int decryptStorage(String password) {
Jason parks8888c592011-01-20 22:46:41 -06002519 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2520 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002521
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002522 if (TextUtils.isEmpty(password)) {
2523 throw new IllegalArgumentException("password cannot be empty");
2524 }
2525
Jason parks5af0b912010-11-29 09:05:25 -06002526 if (DEBUG_EVENTS) {
2527 Slog.i(TAG, "decrypting storage...");
2528 }
2529
2530 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002531 mVold.fdeCheckPassword(password);
2532 mHandler.postDelayed(() -> {
2533 try {
2534 mVold.fdeRestart();
2535 } catch (Exception e) {
2536 Slog.wtf(TAG, e);
2537 }
2538 }, DateUtils.SECOND_IN_MILLIS);
2539 return 0;
Paul Crowleyfc0b5192018-07-02 13:58:10 -07002540 } catch (ServiceSpecificException e) {
2541 Slog.e(TAG, "fdeCheckPassword failed", e);
2542 return e.errorCode;
Jeff Sharkey54402792017-09-15 16:05:19 -06002543 } catch (Exception e) {
2544 Slog.wtf(TAG, e);
2545 return StorageManager.ENCRYPTION_STATE_ERROR_UNKNOWN;
Jason parks5af0b912010-11-29 09:05:25 -06002546 }
Jason parks5af0b912010-11-29 09:05:25 -06002547 }
2548
Jeff Sharkey54402792017-09-15 16:05:19 -06002549 @Override
Paul Lawrence46791e72014-04-03 09:10:26 -07002550 public int encryptStorage(int type, String password) {
Jason parks8888c592011-01-20 22:46:41 -06002551 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2552 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002553
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002554 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2555 password = "";
2556 } else if (TextUtils.isEmpty(password)) {
2557 throw new IllegalArgumentException("password cannot be empty");
2558 }
2559
Jason parks56aa5322011-01-07 09:01:15 -06002560 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002561 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002562 }
2563
2564 try {
Paul Lawrence89a0ae42017-12-22 10:11:10 -08002565 mVold.fdeEnable(type, password, 0);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002566 } catch (Exception e) {
2567 Slog.wtf(TAG, e);
2568 return -1;
Jason parks56aa5322011-01-07 09:01:15 -06002569 }
2570
2571 return 0;
2572 }
2573
Paul Lawrence8e397362014-01-27 15:22:30 -08002574 /** Set the password for encrypting the master key.
2575 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2576 * @param password The password to set.
2577 */
Jeff Sharkey54402792017-09-15 16:05:19 -06002578 @Override
Paul Lawrence8e397362014-01-27 15:22:30 -08002579 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002580 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2581 "no permission to access the crypt keeper");
2582
Jeff Sharkeyae266462017-11-27 13:32:24 -07002583 if (StorageManager.isFileEncryptedNativeOnly()) {
2584 // Not supported on FBE devices
2585 return -1;
2586 }
2587
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002588 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2589 password = "";
2590 } else if (TextUtils.isEmpty(password)) {
2591 throw new IllegalArgumentException("password cannot be empty");
2592 }
2593
Jason parksf7b3cd42011-01-27 09:28:25 -06002594 if (DEBUG_EVENTS) {
2595 Slog.i(TAG, "changing encryption password...");
2596 }
2597
2598 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002599 mVold.fdeChangePassword(type, password);
2600 return 0;
2601 } catch (Exception e) {
2602 Slog.wtf(TAG, e);
2603 return -1;
Jason parksf7b3cd42011-01-27 09:28:25 -06002604 }
2605 }
2606
Christopher Tate32418be2011-10-10 13:51:12 -07002607 /**
2608 * Validate a user-supplied password string with cryptfs
2609 */
2610 @Override
2611 public int verifyEncryptionPassword(String password) throws RemoteException {
2612 // Only the system process is permitted to validate passwords
2613 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2614 throw new SecurityException("no permission to access the crypt keeper");
2615 }
2616
2617 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2618 "no permission to access the crypt keeper");
2619
2620 if (TextUtils.isEmpty(password)) {
2621 throw new IllegalArgumentException("password cannot be empty");
2622 }
2623
Christopher Tate32418be2011-10-10 13:51:12 -07002624 if (DEBUG_EVENTS) {
2625 Slog.i(TAG, "validating encryption password...");
2626 }
2627
2628 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002629 mVold.fdeVerifyPassword(password);
2630 return 0;
2631 } catch (Exception e) {
2632 Slog.wtf(TAG, e);
2633 return -1;
Christopher Tate32418be2011-10-10 13:51:12 -07002634 }
2635 }
2636
Paul Lawrence8e397362014-01-27 15:22:30 -08002637 /**
2638 * Get the type of encryption used to encrypt the master key.
2639 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2640 */
2641 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002642 public int getPasswordType() {
Paul Lawrence76a40572017-03-15 11:08:04 -07002643 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence9de713d2016-05-02 22:45:33 +00002644 "no permission to access the crypt keeper");
2645
Paul Lawrence8e397362014-01-27 15:22:30 -08002646 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002647 return mVold.fdeGetPasswordType();
2648 } catch (Exception e) {
2649 Slog.wtf(TAG, e);
2650 return -1;
Paul Lawrence8e397362014-01-27 15:22:30 -08002651 }
2652 }
2653
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002654 /**
2655 * Set a field in the crypto header.
2656 * @param field field to set
2657 * @param contents contents to set in field
2658 */
2659 @Override
2660 public void setField(String field, String contents) throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002661 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002662 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002663
Jeff Sharkeyae266462017-11-27 13:32:24 -07002664 if (StorageManager.isFileEncryptedNativeOnly()) {
2665 // Not supported on FBE devices
2666 return;
2667 }
2668
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002669 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002670 mVold.fdeSetField(field, contents);
2671 return;
2672 } catch (Exception e) {
2673 Slog.wtf(TAG, e);
2674 return;
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002675 }
2676 }
2677
2678 /**
2679 * Gets a field from the crypto header.
2680 * @param field field to get
2681 * @return contents of field
2682 */
2683 @Override
2684 public String getField(String field) throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002685 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002686 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002687
Jeff Sharkeyae266462017-11-27 13:32:24 -07002688 if (StorageManager.isFileEncryptedNativeOnly()) {
2689 // Not supported on FBE devices
2690 return null;
2691 }
2692
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002693 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002694 return mVold.fdeGetField(field);
2695 } catch (Exception e) {
2696 Slog.wtf(TAG, e);
2697 return null;
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002698 }
2699 }
2700
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002701 /**
2702 * Is userdata convertible to file based encryption?
2703 * @return non zero for convertible
2704 */
2705 @Override
2706 public boolean isConvertibleToFBE() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002707 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002708 "no permission to access the crypt keeper");
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002709
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002710 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002711 return mVold.isConvertibleToFbe();
2712 } catch (Exception e) {
2713 Slog.wtf(TAG, e);
2714 return false;
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002715 }
2716 }
2717
Daniel Rosenberge129e5c2018-11-07 19:25:55 -08002718 /**
2719 * Signal that checkpointing partitions should commit changes
2720 */
2721 @Override
2722 public void commitChanges() throws RemoteException {
2723 // Only the system process is permitted to commit checkpoints
2724 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2725 throw new SecurityException("no permission to commit checkpoint changes");
2726 }
2727
2728 mVold.commitChanges();
2729 }
2730
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002731 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002732 public String getPassword() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002733 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Rubin Xucd7a0142015-04-17 23:45:27 +01002734 "only keyguard can retrieve password");
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002735
Paul Lawrence945490c2014-03-27 16:37:28 +00002736 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002737 return mVold.fdeGetPassword();
2738 } catch (Exception e) {
2739 Slog.wtf(TAG, e);
Paul Lawrence24063b52015-01-06 13:11:23 -08002740 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002741 }
2742 }
2743
2744 @Override
2745 public void clearPassword() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002746 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002747 "only keyguard can clear password");
2748
Paul Lawrence945490c2014-03-27 16:37:28 +00002749 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002750 mVold.fdeClearPassword();
2751 return;
2752 } catch (Exception e) {
2753 Slog.wtf(TAG, e);
2754 return;
Paul Lawrence945490c2014-03-27 16:37:28 +00002755 }
2756 }
2757
2758 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002759 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002760 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002761
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002762 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002763 mVold.createUserKey(userId, serialNumber, ephemeral);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002764 } catch (Exception e) {
2765 Slog.wtf(TAG, e);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002766 }
2767 }
2768
Paul Crowley7ec733f2015-05-19 12:42:00 +01002769 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002770 public void destroyUserKey(int userId) {
2771 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002772
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002773 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002774 mVold.destroyUserKey(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002775 } catch (Exception e) {
2776 Slog.wtf(TAG, e);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002777 }
2778 }
2779
Jeff Sharkey43e12112017-09-12 16:31:45 -06002780 private String encodeBytes(byte[] bytes) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002781 if (ArrayUtils.isEmpty(bytes)) {
Jeff Sharkey43e12112017-09-12 16:31:45 -06002782 return "!";
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002783 } else {
Jeff Sharkey43e12112017-09-12 16:31:45 -06002784 return HexDump.toHexString(bytes);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002785 }
2786 }
2787
Paul Crowleycc701552016-05-17 14:18:49 -07002788 /*
2789 * Add this token/secret pair to the set of ways we can recover a disk encryption key.
2790 * Changing the token/secret for a disk encryption key is done in two phases: first, adding
2791 * a new token/secret pair with this call, then delting all other pairs with
2792 * fixateNewestUserKeyAuth. This allows other places where a credential is used, such as
2793 * Gatekeeper, to be updated between the two calls.
2794 */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002795 @Override
Paul Crowleycc701552016-05-17 14:18:49 -07002796 public void addUserKeyAuth(int userId, int serialNumber, byte[] token, byte[] secret) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002797 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002798
2799 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002800 mVold.addUserKeyAuth(userId, serialNumber, encodeBytes(token), encodeBytes(secret));
Jeff Sharkey43e12112017-09-12 16:31:45 -06002801 } catch (Exception e) {
2802 Slog.wtf(TAG, e);
Paul Crowleycc701552016-05-17 14:18:49 -07002803 }
2804 }
2805
2806 /*
2807 * Delete all disk encryption token/secret pairs except the most recently added one
2808 */
2809 @Override
2810 public void fixateNewestUserKeyAuth(int userId) {
2811 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleycc701552016-05-17 14:18:49 -07002812
2813 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002814 mVold.fixateNewestUserKeyAuth(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002815 } catch (Exception e) {
2816 Slog.wtf(TAG, e);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002817 }
2818 }
2819
2820 @Override
2821 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Sudheer Shanka03b20ec2019-02-21 15:11:00 -08002822 Slog.d(TAG, "unlockUserKey: " + userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002823 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002824
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002825 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002826 // When a user has secure lock screen, require secret to actually unlock.
2827 // This check is mostly in place for emulation mode.
2828 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(secret)) {
2829 throw new IllegalStateException("Secret required to unlock secure user " + userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002830 }
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002831
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002832 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002833 mVold.unlockUserKey(userId, serialNumber, encodeBytes(token),
2834 encodeBytes(secret));
Jeff Sharkey43e12112017-09-12 16:31:45 -06002835 } catch (Exception e) {
2836 Slog.wtf(TAG, e);
2837 return;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002838 }
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002839 }
2840
2841 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002842 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002843 }
2844 }
2845
2846 @Override
2847 public void lockUserKey(int userId) {
2848 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002849
2850 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002851 mVold.lockUserKey(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002852 } catch (Exception e) {
2853 Slog.wtf(TAG, e);
2854 return;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002855 }
2856
2857 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002858 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002859 }
2860 }
2861
2862 @Override
2863 public boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002864 synchronized (mLock) {
2865 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002866 }
2867 }
2868
2869 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002870 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002871 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002872
2873 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002874 mVold.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002875 } catch (Exception e) {
2876 Slog.wtf(TAG, e);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002877 }
2878 }
2879
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002880 @Override
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002881 public void destroyUserStorage(String volumeUuid, int userId, int flags) {
2882 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002883
2884 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002885 mVold.destroyUserStorage(volumeUuid, userId, flags);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002886 } catch (Exception e) {
2887 Slog.wtf(TAG, e);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002888 }
2889 }
2890
Daichi Hironoe56740d2017-02-02 13:56:45 +09002891 class AppFuseMountScope extends AppFuseBridge.MountScope {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002892 boolean opened = false;
2893
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002894 public AppFuseMountScope(int uid, int mountId) {
2895 super(uid, mountId);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002896 }
2897
2898 @Override
2899 public ParcelFileDescriptor open() throws NativeDaemonConnectorException {
Jeff Sharkey54402792017-09-15 16:05:19 -06002900 try {
2901 return new ParcelFileDescriptor(
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002902 mVold.mountAppFuse(uid, mountId));
Jeff Sharkey54402792017-09-15 16:05:19 -06002903 } catch (Exception e) {
2904 throw new NativeDaemonConnectorException("Failed to mount", e);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002905 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002906 }
2907
2908 @Override
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002909 public ParcelFileDescriptor openFile(int mountId, int fileId, int flags)
2910 throws NativeDaemonConnectorException {
2911 try {
2912 return new ParcelFileDescriptor(
2913 mVold.openAppFuseFile(uid, mountId, fileId, flags));
2914 } catch (Exception e) {
2915 throw new NativeDaemonConnectorException("Failed to open", e);
2916 }
2917 }
2918
2919 @Override
Daichi Hironoe56740d2017-02-02 13:56:45 +09002920 public void close() throws Exception {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002921 if (opened) {
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002922 mVold.unmountAppFuse(uid, mountId);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002923 opened = false;
2924 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002925 }
2926 }
2927
2928 @Override
Daichi Hirono812c95d2017-02-08 16:20:20 +09002929 public @Nullable AppFuseMount mountProxyFileDescriptorBridge() {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002930 Slog.v(TAG, "mountProxyFileDescriptorBridge");
Daichi Hirono9fb00182016-11-08 14:12:17 +09002931 final int uid = Binder.getCallingUid();
Daichi Hirono9fb00182016-11-08 14:12:17 +09002932
Daichi Hironoe56740d2017-02-02 13:56:45 +09002933 while (true) {
2934 synchronized (mAppFuseLock) {
2935 boolean newlyCreated = false;
2936 if (mAppFuseBridge == null) {
2937 mAppFuseBridge = new AppFuseBridge();
2938 new Thread(mAppFuseBridge, AppFuseBridge.TAG).start();
2939 newlyCreated = true;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002940 }
Daichi Hironoe56740d2017-02-02 13:56:45 +09002941 try {
2942 final int name = mNextAppFuseName++;
2943 try {
2944 return new AppFuseMount(
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002945 name, mAppFuseBridge.addBridge(new AppFuseMountScope(uid, name)));
Daichi Hirono812c95d2017-02-08 16:20:20 +09002946 } catch (FuseUnavailableMountException e) {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002947 if (newlyCreated) {
2948 // If newly created bridge fails, it's a real error.
Daichi Hirono812c95d2017-02-08 16:20:20 +09002949 Slog.e(TAG, "", e);
2950 return null;
Daichi Hironoe56740d2017-02-02 13:56:45 +09002951 }
2952 // It seems the thread of mAppFuseBridge has already been terminated.
2953 mAppFuseBridge = null;
2954 }
2955 } catch (NativeDaemonConnectorException e) {
2956 throw e.rethrowAsParcelableException();
2957 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002958 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002959 }
2960 }
2961
2962 @Override
Daichi Hirono812c95d2017-02-08 16:20:20 +09002963 public @Nullable ParcelFileDescriptor openProxyFileDescriptor(
2964 int mountId, int fileId, int mode) {
2965 Slog.v(TAG, "mountProxyFileDescriptor");
Jeff Sharkey39466322018-12-05 19:19:52 -07002966
2967 // We only support a narrow set of incoming mode flags
Jeff Sharkey3b1c2542018-12-13 15:01:38 -07002968 mode &= MODE_READ_WRITE;
Jeff Sharkey39466322018-12-05 19:19:52 -07002969
Daichi Hirono9fb00182016-11-08 14:12:17 +09002970 try {
2971 synchronized (mAppFuseLock) {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002972 if (mAppFuseBridge == null) {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002973 Slog.e(TAG, "FuseBridge has not been created");
2974 return null;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002975 }
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002976 return mAppFuseBridge.openFile(mountId, fileId, mode);
Daichi Hirono9fb00182016-11-08 14:12:17 +09002977 }
Daichi Hirono812c95d2017-02-08 16:20:20 +09002978 } catch (FuseUnavailableMountException | InterruptedException error) {
2979 Slog.v(TAG, "The mount point has already been invalid", error);
2980 return null;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002981 }
2982 }
2983
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002984 @Override
Jeff Sharkeyae266462017-11-27 13:32:24 -07002985 public void mkdirs(String callingPkg, String appPath) {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002986 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2987 final UserEnvironment userEnv = new UserEnvironment(userId);
Farid Zare Seisanac094512018-04-02 15:06:13 -07002988 final String propertyName = "sys.user." + userId + ".ce_available";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002989
Jeff Sharkey196c7552018-03-26 15:56:50 -06002990 // Ignore requests to create directories while storage is locked
Farid Zare Seisanac094512018-04-02 15:06:13 -07002991 if (!isUserKeyUnlocked(userId)) {
2992 throw new IllegalStateException("Failed to prepare " + appPath);
2993 }
2994
2995 // Ignore requests to create directories if CE storage is not available
Farid Zare Seisan7f6b8122018-03-30 11:19:10 -07002996 if ((userId == UserHandle.USER_SYSTEM)
2997 && !SystemProperties.getBoolean(propertyName, false)) {
Farid Zare Seisanac094512018-04-02 15:06:13 -07002998 throw new IllegalStateException("Failed to prepare " + appPath);
2999 }
Jeff Sharkey196c7552018-03-26 15:56:50 -06003000
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003001 // Validate that reported package name belongs to caller
3002 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
3003 Context.APP_OPS_SERVICE);
3004 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
3005
Jeff Sharkey48877892015-03-18 11:27:19 -07003006 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003007 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07003008 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003009 } catch (IOException e) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07003010 throw new IllegalStateException("Failed to resolve " + appPath + ": " + e);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003011 }
3012
3013 // Try translating the app path into a vold path, but require that it
3014 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07003015 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
3016 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
3017 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
3018 appPath = appFile.getAbsolutePath();
3019 if (!appPath.endsWith("/")) {
3020 appPath = appPath + "/";
3021 }
3022
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003023 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06003024 mVold.mkdirs(appPath);
Jeff Sharkey27a108c2017-11-30 17:11:40 -07003025 return;
Jeff Sharkeyace874b2017-09-07 15:27:33 -06003026 } catch (Exception e) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07003027 throw new IllegalStateException("Failed to prepare " + appPath + ": " + e);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003028 }
3029 }
3030
Jeff Sharkey48877892015-03-18 11:27:19 -07003031 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07003032 }
3033
3034 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07003035 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003036 final int userId = UserHandle.getUserId(uid);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003037
Jeff Sharkey46349872015-07-28 10:49:47 -07003038 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003039 final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0;
3040 final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0;
Jeff Sharkey46349872015-07-28 10:49:47 -07003041
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003042 final boolean userKeyUnlocked;
3043 final boolean storagePermission;
3044 final long token = Binder.clearCallingIdentity();
Svetoslav38c3dbb2015-07-14 11:27:06 -07003045 try {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003046 userKeyUnlocked = isUserKeyUnlocked(userId);
Sudheer Shanka2250d562016-11-07 15:41:02 -08003047 storagePermission = mStorageManagerInternal.hasExternalStorage(uid, packageName);
Svetoslav38c3dbb2015-07-14 11:27:06 -07003048 } finally {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003049 Binder.restoreCallingIdentity(token);
Svetoslav38c3dbb2015-07-14 11:27:06 -07003050 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003051
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003052 boolean foundPrimary = false;
3053
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003054 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07003055 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003056 for (int i = 0; i < mVolumes.size(); i++) {
3057 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003058 switch (vol.getType()) {
3059 case VolumeInfo.TYPE_PUBLIC:
Risan05c41e62018-10-29 08:57:43 +09003060 case VolumeInfo.TYPE_STUB:
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003061 case VolumeInfo.TYPE_EMULATED:
3062 break;
3063 default:
3064 continue;
3065 }
3066
3067 boolean match = false;
3068 if (forWrite) {
3069 match = vol.isVisibleForWrite(userId);
3070 } else {
Felipe Leme123a0e72016-06-10 11:09:11 -07003071 match = vol.isVisibleForRead(userId)
3072 || (includeInvisible && vol.getPath() != null);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003073 }
3074 if (!match) continue;
3075
3076 boolean reportUnmounted = false;
3077 if ((vol.getType() == VolumeInfo.TYPE_EMULATED) && !userKeyUnlocked) {
3078 reportUnmounted = true;
3079 } else if (!storagePermission && !realState) {
3080 reportUnmounted = true;
3081 }
3082
3083 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
3084 reportUnmounted);
3085 if (vol.isPrimary()) {
3086 res.add(0, userVol);
3087 foundPrimary = true;
3088 } else {
3089 res.add(userVol);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07003090 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003091 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003092 }
Jeff Sharkey48877892015-03-18 11:27:19 -07003093
3094 if (!foundPrimary) {
Jeff Sharkey11697f52018-12-13 10:14:42 -07003095 Slog.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07003096
3097 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003098 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07003099
3100 final String id = "stub_primary";
3101 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003102 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07003103 final boolean primary = true;
3104 final boolean removable = primaryPhysical;
3105 final boolean emulated = !primaryPhysical;
Jeff Sharkey48877892015-03-18 11:27:19 -07003106 final boolean allowMassStorage = false;
3107 final long maxFileSize = 0L;
3108 final UserHandle owner = new UserHandle(userId);
3109 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07003110 final String state = Environment.MEDIA_REMOVED;
3111
Jerry Zhang71938e12018-05-10 18:28:29 -07003112 res.add(0, new StorageVolume(id, path, path,
Jerry Zhangf9c5c252017-08-16 18:07:51 -07003113 description, primary, removable, emulated,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003114 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07003115 }
3116
3117 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003118 }
3119
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003120 @Override
3121 public DiskInfo[] getDisks() {
3122 synchronized (mLock) {
3123 final DiskInfo[] res = new DiskInfo[mDisks.size()];
3124 for (int i = 0; i < mDisks.size(); i++) {
3125 res[i] = mDisks.valueAt(i);
3126 }
3127 return res;
3128 }
3129 }
3130
3131 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003132 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003133 synchronized (mLock) {
3134 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
3135 for (int i = 0; i < mVolumes.size(); i++) {
3136 res[i] = mVolumes.valueAt(i);
3137 }
3138 return res;
3139 }
3140 }
3141
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003142 @Override
3143 public VolumeRecord[] getVolumeRecords(int flags) {
3144 synchronized (mLock) {
3145 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
3146 for (int i = 0; i < mRecords.size(); i++) {
3147 res[i] = mRecords.valueAt(i);
3148 }
3149 return res;
3150 }
3151 }
3152
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003153 @Override
3154 public long getCacheQuotaBytes(String volumeUuid, int uid) {
3155 if (uid != Binder.getCallingUid()) {
3156 mContext.enforceCallingPermission(android.Manifest.permission.STORAGE_INTERNAL, TAG);
3157 }
Daniel Nishi80fdb012017-03-09 14:30:07 -08003158 final long token = Binder.clearCallingIdentity();
3159 final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
3160 try {
3161 return stats.getCacheQuotaBytes(volumeUuid, uid);
3162 } finally {
3163 Binder.restoreCallingIdentity(token);
3164 }
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003165 }
3166
3167 @Override
3168 public long getCacheSizeBytes(String volumeUuid, int uid) {
3169 if (uid != Binder.getCallingUid()) {
3170 mContext.enforceCallingPermission(android.Manifest.permission.STORAGE_INTERNAL, TAG);
3171 }
3172 final long token = Binder.clearCallingIdentity();
3173 try {
3174 return mContext.getSystemService(StorageStatsManager.class)
3175 .queryStatsForUid(volumeUuid, uid).getCacheBytes();
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003176 } catch (IOException e) {
3177 throw new ParcelableException(e);
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003178 } finally {
3179 Binder.restoreCallingIdentity(token);
3180 }
3181 }
3182
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003183 private int adjustAllocateFlags(int flags, int callingUid, String callingPackage) {
3184 // Require permission to allocate aggressively
3185 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003186 mContext.enforceCallingOrSelfPermission(
3187 android.Manifest.permission.ALLOCATE_AGGRESSIVE, TAG);
3188 }
3189
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003190 // Apps normally can't directly defy reserved space
3191 flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED;
3192 flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
3193
3194 // However, if app is actively using the camera, then we're willing to
3195 // clear up to half of the reserved cache space, since the user might be
3196 // trying to capture an important memory.
3197 final AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
3198 final long token = Binder.clearCallingIdentity();
3199 try {
3200 if (appOps.isOperationActive(AppOpsManager.OP_CAMERA, callingUid, callingPackage)) {
3201 Slog.d(TAG, "UID " + callingUid + " is actively using camera;"
3202 + " letting them defy reserved cached data");
3203 flags |= StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
3204 }
3205 } finally {
3206 Binder.restoreCallingIdentity(token);
3207 }
3208
3209 return flags;
3210 }
3211
3212 @Override
3213 public long getAllocatableBytes(String volumeUuid, int flags, String callingPackage) {
3214 flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
3215
3216 final StorageManager storage = mContext.getSystemService(StorageManager.class);
3217 final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003218 final long token = Binder.clearCallingIdentity();
3219 try {
3220 // In general, apps can allocate as much space as they want, except
3221 // we never let them eat into either the minimum cache space or into
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003222 // the low disk warning space. To avoid user confusion, this logic
3223 // should be kept in sync with getFreeBytes().
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003224 final File path = storage.findPathForUuid(volumeUuid);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003225
3226 final long usable = path.getUsableSpace();
3227 final long lowReserved = storage.getStorageLowBytes(path);
3228 final long fullReserved = storage.getStorageFullBytes(path);
3229
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003230 if (stats.isQuotaSupported(volumeUuid)) {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003231 final long cacheTotal = stats.getCacheBytes(volumeUuid);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003232 final long cacheReserved = storage.getStorageCacheBytes(path, flags);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003233 final long cacheClearable = Math.max(0, cacheTotal - cacheReserved);
3234
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003235 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
3236 return Math.max(0, (usable + cacheClearable) - fullReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003237 } else {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003238 return Math.max(0, (usable + cacheClearable) - lowReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003239 }
3240 } else {
3241 // When we don't have fast quota information, we ignore cached
3242 // data and only consider unused bytes.
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003243 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003244 return Math.max(0, usable - fullReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003245 } else {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003246 return Math.max(0, usable - lowReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003247 }
3248 }
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003249 } catch (IOException e) {
3250 throw new ParcelableException(e);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003251 } finally {
3252 Binder.restoreCallingIdentity(token);
3253 }
Jeff Sharkey500ce9e2017-02-12 02:39:24 -07003254 }
3255
3256 @Override
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003257 public void allocateBytes(String volumeUuid, long bytes, int flags, String callingPackage) {
3258 flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003259
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003260 final long allocatableBytes = getAllocatableBytes(volumeUuid, flags, callingPackage);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003261 if (bytes > allocatableBytes) {
3262 throw new ParcelableException(new IOException("Failed to allocate " + bytes
3263 + " because only " + allocatableBytes + " allocatable"));
3264 }
3265
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003266 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003267 final long token = Binder.clearCallingIdentity();
3268 try {
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003269 // Free up enough disk space to satisfy both the requested allocation
3270 // and our low disk warning space.
3271 final File path = storage.findPathForUuid(volumeUuid);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003272 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
3273 bytes += storage.getStorageFullBytes(path);
3274 } else {
3275 bytes += storage.getStorageLowBytes(path);
3276 }
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003277
Jeff Sharkey5790af02018-08-13 17:42:54 -06003278 mPmInternal.freeStorage(volumeUuid, bytes, flags);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003279 } catch (IOException e) {
3280 throw new ParcelableException(e);
3281 } finally {
3282 Binder.restoreCallingIdentity(token);
Jeff Sharkey500ce9e2017-02-12 02:39:24 -07003283 }
3284 }
3285
Sudheer Shankaff971bc2018-12-13 17:39:59 -08003286 private IAppOpsCallback.Stub mAppOpsCallback = new IAppOpsCallback.Stub() {
3287 @Override
3288 public void opChanged(int op, int uid, String packageName) throws RemoteException {
3289 if (!ENABLE_ISOLATED_STORAGE) return;
3290
3291 remountUidExternalStorage(uid, getMountMode(uid, packageName));
3292 }
3293 };
3294
Jeff Sharkey5790af02018-08-13 17:42:54 -06003295 private static final Pattern PATTERN_TRANSLATE = Pattern.compile(
3296 "(?i)^(/storage/[^/]+/(?:[0-9]+/)?)(.*)");
3297
3298 @Override
Sudheer Shanka87915d62018-11-06 10:57:35 -08003299 public String translateAppToSystem(String path, int pid, int uid) {
3300 return translateInternal(path, pid, uid, true);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003301 }
3302
3303 @Override
Sudheer Shanka87915d62018-11-06 10:57:35 -08003304 public String translateSystemToApp(String path, int pid, int uid) {
3305 return translateInternal(path, pid, uid, false);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003306 }
3307
Sudheer Shanka87915d62018-11-06 10:57:35 -08003308 private String translateInternal(String path, int pid, int uid, boolean toSystem) {
Jeff Sharkey5790af02018-08-13 17:42:54 -06003309 if (!ENABLE_ISOLATED_STORAGE) return path;
3310
3311 if (path.contains("/../")) {
3312 throw new SecurityException("Shady looking path " + path);
3313 }
3314
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003315 final int mountMode = mAmInternal.getStorageMountMode(pid, uid);
Sudheer Shanka0b6da532019-01-09 12:06:51 -08003316 if (mountMode == Zygote.MOUNT_EXTERNAL_FULL
3317 || mountMode == Zygote.MOUNT_EXTERNAL_LEGACY) {
Sudheer Shanka87915d62018-11-06 10:57:35 -08003318 return path;
3319 }
Jeff Sharkey5790af02018-08-13 17:42:54 -06003320
3321 final Matcher m = PATTERN_TRANSLATE.matcher(path);
3322 if (m.matches()) {
3323 final String device = m.group(1);
3324 final String devicePath = m.group(2);
3325
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003326 if (mountMode == Zygote.MOUNT_EXTERNAL_INSTALLER
3327 && devicePath.startsWith("Android/obb/")) {
3328 return path;
3329 }
3330
Jeff Sharkey5790af02018-08-13 17:42:54 -06003331 // Does path belong to any packages belonging to this UID? If so,
3332 // they get to go straight through to legacy paths.
Sudheer Shanka87915d62018-11-06 10:57:35 -08003333 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(uid);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003334 for (String pkg : pkgs) {
3335 if (devicePath.startsWith("Android/data/" + pkg + "/") ||
3336 devicePath.startsWith("Android/media/" + pkg + "/") ||
3337 devicePath.startsWith("Android/obb/" + pkg + "/")) {
3338 return path;
3339 }
3340 }
3341
Sudheer Shanka87915d62018-11-06 10:57:35 -08003342 final String sharedUserId = mPmInternal.getSharedUserIdForPackage(pkgs[0]);
3343 final String sandboxId = getSandboxId(pkgs[0], sharedUserId);
3344
Jeff Sharkey5790af02018-08-13 17:42:54 -06003345 if (toSystem) {
3346 // Everything else goes into sandbox.
Sudheer Shanka31ad0a12018-10-20 20:59:00 -07003347 return device + "Android/sandbox/" + sandboxId + "/" + devicePath;
Jeff Sharkey5790af02018-08-13 17:42:54 -06003348 } else {
3349 // Does path belong to this sandbox? If so, leave sandbox.
Sudheer Shanka31ad0a12018-10-20 20:59:00 -07003350 final String sandboxPrefix = "Android/sandbox/" + sandboxId + "/";
Jeff Sharkey5790af02018-08-13 17:42:54 -06003351 if (devicePath.startsWith(sandboxPrefix)) {
3352 return device + devicePath.substring(sandboxPrefix.length());
3353 }
3354
3355 // Path isn't valid inside sandbox!
3356 throw new SecurityException(
3357 "Path " + path + " isn't valid inside sandbox " + sandboxId);
3358 }
3359 }
3360
3361 return path;
3362 }
3363
Kenny Rootaf9d6672010-10-08 09:21:39 -07003364 private void addObbStateLocked(ObbState obbState) throws RemoteException {
3365 final IBinder binder = obbState.getBinder();
3366 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003367
Kenny Rootaf9d6672010-10-08 09:21:39 -07003368 if (obbStates == null) {
3369 obbStates = new ArrayList<ObbState>();
3370 mObbMounts.put(binder, obbStates);
3371 } else {
3372 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003373 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003374 throw new IllegalStateException("Attempt to add ObbState twice. "
Sudheer Shanka2250d562016-11-07 15:41:02 -08003375 + "This indicates an error in the StorageManagerService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003376 }
3377 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003378 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003379
3380 obbStates.add(obbState);
3381 try {
3382 obbState.link();
3383 } catch (RemoteException e) {
3384 /*
3385 * The binder died before we could link it, so clean up our state
3386 * and return failure.
3387 */
3388 obbStates.remove(obbState);
3389 if (obbStates.isEmpty()) {
3390 mObbMounts.remove(binder);
3391 }
3392
3393 // Rethrow the error so mountObb can get it
3394 throw e;
3395 }
3396
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003397 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003398 }
3399
Kenny Rootaf9d6672010-10-08 09:21:39 -07003400 private void removeObbStateLocked(ObbState obbState) {
3401 final IBinder binder = obbState.getBinder();
3402 final List<ObbState> obbStates = mObbMounts.get(binder);
3403 if (obbStates != null) {
3404 if (obbStates.remove(obbState)) {
3405 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003406 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003407 if (obbStates.isEmpty()) {
3408 mObbMounts.remove(binder);
3409 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003410 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003411
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003412 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003413 }
3414
Kenny Roota02b8b02010-08-05 16:14:17 -07003415 private class ObbActionHandler extends Handler {
Kenny Roota02b8b02010-08-05 16:14:17 -07003416
3417 ObbActionHandler(Looper l) {
3418 super(l);
3419 }
3420
3421 @Override
3422 public void handleMessage(Message msg) {
3423 switch (msg.what) {
3424 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003425 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003426
3427 if (DEBUG_OBB)
3428 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3429
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003430 action.execute(this);
Kenny Roota02b8b02010-08-05 16:14:17 -07003431 break;
3432 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003433 case OBB_FLUSH_MOUNT_STATE: {
3434 final String path = (String) msg.obj;
3435
3436 if (DEBUG_OBB)
3437 Slog.i(TAG, "Flushing all OBB state for path " + path);
3438
3439 synchronized (mObbMounts) {
3440 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3441
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003442 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003443 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003444 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003445
3446 /*
3447 * If this entry's source file is in the volume path
3448 * that got unmounted, remove it because it's no
3449 * longer valid.
3450 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003451 if (state.canonicalPath.startsWith(path)) {
3452 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003453 }
3454 }
3455
3456 for (final ObbState obbState : obbStatesToRemove) {
3457 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003458 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003459
3460 removeObbStateLocked(obbState);
3461
3462 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003463 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003464 OnObbStateChangeListener.UNMOUNTED);
3465 } catch (RemoteException e) {
3466 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003467 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003468 }
3469 }
3470 }
3471 break;
3472 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003473 }
3474 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003475 }
3476
Jeff Sharkey0095a822018-02-15 13:06:53 -07003477 private static class ObbException extends Exception {
3478 public final int status;
3479
3480 public ObbException(int status, String message) {
3481 super(message);
3482 this.status = status;
3483 }
3484
3485 public ObbException(int status, Throwable cause) {
3486 super(cause.getMessage(), cause);
3487 this.status = status;
3488 }
3489 }
3490
Kenny Roota02b8b02010-08-05 16:14:17 -07003491 abstract class ObbAction {
Kenny Roota02b8b02010-08-05 16:14:17 -07003492
3493 ObbState mObbState;
3494
3495 ObbAction(ObbState obbState) {
3496 mObbState = obbState;
3497 }
3498
3499 public void execute(ObbActionHandler handler) {
3500 try {
3501 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003502 Slog.i(TAG, "Starting to execute action: " + toString());
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003503 handleExecute();
Jeff Sharkey0095a822018-02-15 13:06:53 -07003504 } catch (ObbException e) {
3505 notifyObbStateChange(e);
Kenny Roota02b8b02010-08-05 16:14:17 -07003506 }
3507 }
3508
Jeff Sharkey0095a822018-02-15 13:06:53 -07003509 abstract void handleExecute() throws ObbException;
Kenny Root38cf8862010-09-26 14:18:51 -07003510
Jeff Sharkey0095a822018-02-15 13:06:53 -07003511 protected void notifyObbStateChange(ObbException e) {
3512 Slog.w(TAG, e);
3513 notifyObbStateChange(e.status);
3514 }
3515
3516 protected void notifyObbStateChange(int status) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003517 if (mObbState == null || mObbState.token == null) {
3518 return;
3519 }
3520
Kenny Root38cf8862010-09-26 14:18:51 -07003521 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003522 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003523 } catch (RemoteException e) {
Sudheer Shanka2250d562016-11-07 15:41:02 -08003524 Slog.w(TAG, "StorageEventListener went away while calling onObbStateChanged");
Kenny Root38cf8862010-09-26 14:18:51 -07003525 }
3526 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003527 }
3528
3529 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003530 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003531 private final int mCallingUid;
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003532 private ObbInfo mObbInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -07003533
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003534 MountObbAction(ObbState obbState, String key, int callingUid, ObbInfo obbInfo) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003535 super(obbState);
3536 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003537 mCallingUid = callingUid;
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003538 mObbInfo = obbInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -07003539 }
3540
Jason parks5af0b912010-11-29 09:05:25 -06003541 @Override
Jeff Sharkey0095a822018-02-15 13:06:53 -07003542 public void handleExecute() throws ObbException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003543 warnOnNotMounted();
3544
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003545 if (!isUidOwnerOfPackageOrSystem(mObbInfo.packageName, mCallingUid)) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003546 throw new ObbException(ERROR_PERMISSION_DENIED, "Denied attempt to mount OBB "
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003547 + mObbInfo.filename + " which is owned by " + mObbInfo.packageName);
Kenny Roota02b8b02010-08-05 16:14:17 -07003548 }
3549
Kenny Rootaf9d6672010-10-08 09:21:39 -07003550 final boolean isMounted;
3551 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003552 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003553 }
3554 if (isMounted) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003555 throw new ObbException(ERROR_ALREADY_MOUNTED,
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003556 "Attempt to mount OBB which is already mounted: " + mObbInfo.filename);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003557 }
3558
Kenny Rootaf9d6672010-10-08 09:21:39 -07003559 final String hashedKey;
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003560 final String binderKey;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003561 if (mKey == null) {
3562 hashedKey = "none";
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003563 binderKey = "";
Kenny Rootaf9d6672010-10-08 09:21:39 -07003564 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003565 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003566 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3567
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003568 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), mObbInfo.salt,
Kenny Root3b1abba2010-10-13 15:00:07 -07003569 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3570 SecretKey key = factory.generateSecret(ks);
3571 BigInteger bi = new BigInteger(key.getEncoded());
3572 hashedKey = bi.toString(16);
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003573 binderKey = hashedKey;
Jeff Sharkey0095a822018-02-15 13:06:53 -07003574 } catch (GeneralSecurityException e) {
3575 throw new ObbException(ERROR_INTERNAL, e);
Kenny Root38cf8862010-09-26 14:18:51 -07003576 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003577 }
Kenny Root38cf8862010-09-26 14:18:51 -07003578
Kenny Rootaf9d6672010-10-08 09:21:39 -07003579 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06003580 mObbState.volId = mVold.createObb(mObbState.canonicalPath, binderKey,
3581 mObbState.ownerGid);
3582 mVold.mount(mObbState.volId, 0, -1);
Kenny Roota02b8b02010-08-05 16:14:17 -07003583
Kenny Rootaf9d6672010-10-08 09:21:39 -07003584 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003585 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003586
3587 synchronized (mObbMounts) {
3588 addObbStateLocked(mObbState);
3589 }
3590
Jeff Sharkey0095a822018-02-15 13:06:53 -07003591 notifyObbStateChange(MOUNTED);
3592 } catch (Exception e) {
3593 throw new ObbException(ERROR_COULD_NOT_MOUNT, e);
Kenny Root02c87302010-07-01 08:10:18 -07003594 }
3595 }
3596
Jason parks5af0b912010-11-29 09:05:25 -06003597 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003598 public String toString() {
3599 StringBuilder sb = new StringBuilder();
3600 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003601 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003602 sb.append('}');
3603 return sb.toString();
3604 }
3605 }
3606
3607 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003608 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003609
3610 UnmountObbAction(ObbState obbState, boolean force) {
3611 super(obbState);
3612 mForceUnmount = force;
3613 }
3614
Jason parks5af0b912010-11-29 09:05:25 -06003615 @Override
Jeff Sharkey0095a822018-02-15 13:06:53 -07003616 public void handleExecute() throws ObbException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003617 warnOnNotMounted();
3618
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003619 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003620 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003621 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003622 }
Kenny Root38cf8862010-09-26 14:18:51 -07003623
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003624 if (existingState == null) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003625 throw new ObbException(ERROR_NOT_MOUNTED, "Missing existingState");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003626 }
3627
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003628 if (existingState.ownerGid != mObbState.ownerGid) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003629 notifyObbStateChange(new ObbException(ERROR_PERMISSION_DENIED,
3630 "Permission denied to unmount OBB " + existingState.rawPath
3631 + " (owned by GID " + existingState.ownerGid + ")"));
Kenny Rootaf9d6672010-10-08 09:21:39 -07003632 return;
3633 }
3634
Kenny Rootaf9d6672010-10-08 09:21:39 -07003635 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06003636 mVold.unmount(mObbState.volId);
3637 mVold.destroyObb(mObbState.volId);
3638 mObbState.volId = null;
Kenny Roota02b8b02010-08-05 16:14:17 -07003639
Kenny Rootaf9d6672010-10-08 09:21:39 -07003640 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003641 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003642 }
3643
Jeff Sharkey0095a822018-02-15 13:06:53 -07003644 notifyObbStateChange(UNMOUNTED);
3645 } catch (Exception e) {
3646 throw new ObbException(ERROR_COULD_NOT_UNMOUNT, e);
Kenny Roota02b8b02010-08-05 16:14:17 -07003647 }
3648 }
3649
Jason parks5af0b912010-11-29 09:05:25 -06003650 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003651 public String toString() {
3652 StringBuilder sb = new StringBuilder();
3653 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003654 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003655 sb.append(",force=");
3656 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003657 sb.append('}');
3658 return sb.toString();
3659 }
Kenny Root02c87302010-07-01 08:10:18 -07003660 }
Kenny Root38cf8862010-09-26 14:18:51 -07003661
Jeff Sharkey7e19f532017-11-06 13:54:11 -07003662 private void dispatchOnStatus(IVoldTaskListener listener, int status,
3663 PersistableBundle extras) {
3664 if (listener != null) {
3665 try {
3666 listener.onStatus(status, extras);
3667 } catch (RemoteException ignored) {
3668 }
3669 }
3670 }
3671
3672 private void dispatchOnFinished(IVoldTaskListener listener, int status,
3673 PersistableBundle extras) {
3674 if (listener != null) {
3675 try {
3676 listener.onFinished(status, extras);
3677 } catch (RemoteException ignored) {
3678 }
3679 }
3680 }
3681
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003682 private int getMountMode(int uid, String packageName) {
3683 try {
3684 if (Process.isIsolated(uid)) {
3685 return Zygote.MOUNT_EXTERNAL_NONE;
3686 }
3687 if (mIPackageManager.checkUidPermission(WRITE_MEDIA_STORAGE, uid)
3688 == PERMISSION_GRANTED) {
3689 return Zygote.MOUNT_EXTERNAL_FULL;
Jeff Sharkey11697f52018-12-13 10:14:42 -07003690 } else if (mIAppOpsService.checkOperation(OP_LEGACY_STORAGE, uid,
3691 packageName) == MODE_ALLOWED) {
Sudheer Shanka0b6da532019-01-09 12:06:51 -08003692 return Zygote.MOUNT_EXTERNAL_LEGACY;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003693 } else if (mIPackageManager.checkUidPermission(INSTALL_PACKAGES, uid)
3694 == PERMISSION_GRANTED || mIAppOpsService.checkOperation(
3695 OP_REQUEST_INSTALL_PACKAGES, uid, packageName) == MODE_ALLOWED) {
3696 return Zygote.MOUNT_EXTERNAL_INSTALLER;
Sudheer Shanka0f26cbd2019-01-18 18:25:38 -08003697 } else if (mPmInternal.isInstantApp(packageName, UserHandle.getUserId(uid))) {
3698 return Zygote.MOUNT_EXTERNAL_NONE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003699 } else {
Jeff Sharkey36274992019-02-27 12:09:57 -07003700 if (ENABLE_LEGACY_GREYLIST) {
3701 // STOPSHIP: remove this temporary workaround once developers
3702 // fix bugs where they're opening _data paths in native code
3703 switch (packageName) {
3704 case "com.facebook.katana": // b/123996076
3705 case "jp.naver.line.android": // b/124767356
3706 case "com.mxtech.videoplayer.ad": // b/124531483
3707 return Zygote.MOUNT_EXTERNAL_LEGACY;
3708 }
Jeff Sharkey0ebbd462019-02-19 23:45:57 -07003709 }
Jeff Sharkey36274992019-02-27 12:09:57 -07003710 return Zygote.MOUNT_EXTERNAL_WRITE;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003711 }
3712 } catch (RemoteException e) {
3713 // Should not happen
3714 }
3715 return Zygote.MOUNT_EXTERNAL_NONE;
3716 }
3717
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003718 private static class Callbacks extends Handler {
3719 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3720 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003721 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3722 private static final int MSG_VOLUME_FORGOTTEN = 4;
3723 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003724 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003725
Sudheer Shanka2250d562016-11-07 15:41:02 -08003726 private final RemoteCallbackList<IStorageEventListener>
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003727 mCallbacks = new RemoteCallbackList<>();
3728
3729 public Callbacks(Looper looper) {
3730 super(looper);
3731 }
3732
Sudheer Shanka2250d562016-11-07 15:41:02 -08003733 public void register(IStorageEventListener callback) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003734 mCallbacks.register(callback);
3735 }
3736
Sudheer Shanka2250d562016-11-07 15:41:02 -08003737 public void unregister(IStorageEventListener callback) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003738 mCallbacks.unregister(callback);
3739 }
3740
3741 @Override
3742 public void handleMessage(Message msg) {
3743 final SomeArgs args = (SomeArgs) msg.obj;
3744 final int n = mCallbacks.beginBroadcast();
3745 for (int i = 0; i < n; i++) {
Sudheer Shanka2250d562016-11-07 15:41:02 -08003746 final IStorageEventListener callback = mCallbacks.getBroadcastItem(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003747 try {
3748 invokeCallback(callback, msg.what, args);
3749 } catch (RemoteException ignored) {
3750 }
3751 }
3752 mCallbacks.finishBroadcast();
3753 args.recycle();
3754 }
3755
Sudheer Shanka2250d562016-11-07 15:41:02 -08003756 private void invokeCallback(IStorageEventListener callback, int what, SomeArgs args)
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003757 throws RemoteException {
3758 switch (what) {
3759 case MSG_STORAGE_STATE_CHANGED: {
3760 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3761 (String) args.arg3);
3762 break;
3763 }
3764 case MSG_VOLUME_STATE_CHANGED: {
3765 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3766 break;
3767 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003768 case MSG_VOLUME_RECORD_CHANGED: {
3769 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3770 break;
3771 }
3772 case MSG_VOLUME_FORGOTTEN: {
3773 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003774 break;
3775 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003776 case MSG_DISK_SCANNED: {
3777 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003778 break;
3779 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003780 case MSG_DISK_DESTROYED: {
3781 callback.onDiskDestroyed((DiskInfo) args.arg1);
3782 break;
3783 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003784 }
3785 }
3786
3787 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3788 final SomeArgs args = SomeArgs.obtain();
3789 args.arg1 = path;
3790 args.arg2 = oldState;
3791 args.arg3 = newState;
3792 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3793 }
3794
3795 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3796 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003797 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003798 args.argi2 = oldState;
3799 args.argi3 = newState;
3800 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3801 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003802
Jeff Sharkey50a05452015-04-29 11:24:52 -07003803 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3804 final SomeArgs args = SomeArgs.obtain();
3805 args.arg1 = rec.clone();
3806 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3807 }
3808
3809 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003810 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003811 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003812 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003813 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003814
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003815 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003816 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003817 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003818 args.argi2 = volumeCount;
3819 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003820 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003821
3822 private void notifyDiskDestroyed(DiskInfo disk) {
3823 final SomeArgs args = SomeArgs.obtain();
3824 args.arg1 = disk.clone();
3825 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3826 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003827 }
3828
Kenny Root38cf8862010-09-26 14:18:51 -07003829 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003830 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003831 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003832
3833 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003834 synchronized (mLock) {
3835 pw.println("Disks:");
3836 pw.increaseIndent();
3837 for (int i = 0; i < mDisks.size(); i++) {
3838 final DiskInfo disk = mDisks.valueAt(i);
3839 disk.dump(pw);
3840 }
3841 pw.decreaseIndent();
3842
3843 pw.println();
3844 pw.println("Volumes:");
3845 pw.increaseIndent();
3846 for (int i = 0; i < mVolumes.size(); i++) {
3847 final VolumeInfo vol = mVolumes.valueAt(i);
3848 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3849 vol.dump(pw);
3850 }
3851 pw.decreaseIndent();
3852
3853 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003854 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003855 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003856 for (int i = 0; i < mRecords.size(); i++) {
3857 final VolumeRecord note = mRecords.valueAt(i);
3858 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003859 }
3860 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003861
3862 pw.println();
3863 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003864
3865 pw.println();
Felipe Leme281389a2016-10-10 17:12:20 -07003866 final Pair<String, Long> pair = StorageManager.getPrimaryStoragePathAndSize();
3867 if (pair == null) {
3868 pw.println("Internal storage total size: N/A");
3869 } else {
3870 pw.print("Internal storage (");
3871 pw.print(pair.first);
3872 pw.print(") total size: ");
3873 pw.print(pair.second);
3874 pw.print(" (");
Jeff Sharkey9f2dc052018-01-07 16:47:31 -07003875 pw.print(DataUnit.MEBIBYTES.toBytes(pair.second));
3876 pw.println(" MiB)");
Felipe Leme281389a2016-10-10 17:12:20 -07003877 }
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003878
3879 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003880 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3881 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003882
3883 final ContentResolver cr = mContext.getContentResolver();
3884 pw.println();
3885 pw.println("Isolated storage, local feature flag: "
3886 + Settings.Global.getInt(cr, Settings.Global.ISOLATED_STORAGE_LOCAL, 0));
3887 pw.println("Isolated storage, remote feature flag: "
3888 + Settings.Global.getInt(cr, Settings.Global.ISOLATED_STORAGE_REMOTE, 0));
3889 pw.println("Isolated storage, resolved: " + StorageManager.hasIsolatedStorage());
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003890 }
Kenny Root38cf8862010-09-26 14:18:51 -07003891
Kenny Root38cf8862010-09-26 14:18:51 -07003892 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003893 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003894 pw.println("mObbMounts:");
3895 pw.increaseIndent();
3896 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3897 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003898 while (binders.hasNext()) {
3899 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003900 pw.println(e.getKey() + ":");
3901 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003902 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003903 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003904 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003905 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003906 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003907 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003908 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003909
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003910 pw.println();
3911 pw.println("mObbPathToStateMap:");
3912 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003913 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3914 while (maps.hasNext()) {
3915 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003916 pw.print(e.getKey());
3917 pw.print(" -> ");
3918 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003919 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003920 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003921 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003922
Robert Greenwalt470fd722012-01-18 12:51:15 -08003923 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003924 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003925 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003928 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003929 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003930 public void monitor() {
Jeff Sharkey54402792017-09-15 16:05:19 -06003931 try {
3932 mVold.monitor();
3933 } catch (Exception e) {
3934 Slog.wtf(TAG, e);
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003935 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003936 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003937
Sudheer Shanka2250d562016-11-07 15:41:02 -08003938 private final class StorageManagerInternalImpl extends StorageManagerInternal {
Svet Ganov6ee871e2015-07-10 14:29:33 -07003939 // Not guarded by a lock.
3940 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3941 new CopyOnWriteArrayList<>();
3942
Risanaec0ee72018-10-31 10:10:12 +09003943 @GuardedBy("mResetListeners")
3944 private final List<StorageManagerInternal.ResetListener> mResetListeners =
3945 new ArrayList<>();
3946
Svet Ganov6ee871e2015-07-10 14:29:33 -07003947 @Override
3948 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3949 // No locking - CopyOnWriteArrayList
3950 mPolicies.add(policy);
3951 }
3952
3953 @Override
3954 public void onExternalStoragePolicyChanged(int uid, String packageName) {
Sudheer Shanka0a541a52018-07-31 13:21:11 -07003955 // No runtime storage permissions in isolated storage world, so nothing to do here.
Jeff Sharkeyc58fdf32018-08-15 18:49:34 -06003956 if (ENABLE_ISOLATED_STORAGE) return;
Svet Ganov6ee871e2015-07-10 14:29:33 -07003957 final int mountMode = getExternalStorageMountMode(uid, packageName);
3958 remountUidExternalStorage(uid, mountMode);
3959 }
3960
3961 @Override
3962 public int getExternalStorageMountMode(int uid, String packageName) {
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003963 if (ENABLE_ISOLATED_STORAGE) {
3964 return getMountMode(uid, packageName);
3965 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003966 // No locking - CopyOnWriteArrayList
3967 int mountMode = Integer.MAX_VALUE;
3968 for (ExternalStorageMountPolicy policy : mPolicies) {
3969 final int policyMode = policy.getMountMode(uid, packageName);
3970 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3971 return Zygote.MOUNT_EXTERNAL_NONE;
3972 }
3973 mountMode = Math.min(mountMode, policyMode);
3974 }
3975 if (mountMode == Integer.MAX_VALUE) {
3976 return Zygote.MOUNT_EXTERNAL_NONE;
3977 }
3978 return mountMode;
3979 }
3980
Risanaec0ee72018-10-31 10:10:12 +09003981 @Override
3982 public void addResetListener(StorageManagerInternal.ResetListener listener) {
3983 synchronized (mResetListeners) {
3984 mResetListeners.add(listener);
3985 }
3986 }
3987
3988 public void onReset(IVold vold) {
3989 synchronized (mResetListeners) {
3990 for (StorageManagerInternal.ResetListener listener : mResetListeners) {
3991 listener.onReset(vold);
3992 }
3993 }
3994 }
3995
Svet Ganov6ee871e2015-07-10 14:29:33 -07003996 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003997 // No need to check for system uid. This avoids a deadlock between
3998 // PackageManagerService and AppOpsService.
3999 if (uid == Process.SYSTEM_UID) {
4000 return true;
4001 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08004002 if (ENABLE_ISOLATED_STORAGE) {
4003 return getMountMode(uid, packageName) != Zygote.MOUNT_EXTERNAL_NONE;
4004 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07004005 // No locking - CopyOnWriteArrayList
4006 for (ExternalStorageMountPolicy policy : mPolicies) {
4007 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
4008 if (!policyHasStorage) {
4009 return false;
4010 }
4011 }
4012 return true;
4013 }
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004014
4015 @Override
Sudheer Shanka584b0682018-10-04 16:26:16 -07004016 public void prepareSandboxForApp(String packageName, int appId, String sharedUserId,
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004017 int userId) {
4018 final String sandboxId;
4019 synchronized (mPackagesLock) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004020 final ArraySet<String> userPackages = mPackages.get(userId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004021 // If userPackages is empty, it means the user is not started yet, so no need to
4022 // do anything now.
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004023 if (userPackages == null || userPackages.contains(packageName)) {
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004024 return;
4025 }
4026 userPackages.add(packageName);
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08004027 sandboxId = StorageManagerService.this.getSandboxId(packageName, sharedUserId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004028 }
4029
4030 try {
Sudheer Shanka584b0682018-10-04 16:26:16 -07004031 mVold.prepareSandboxForApp(packageName, appId, sandboxId, userId);
4032 } catch (Exception e) {
4033 Slog.wtf(TAG, e);
4034 }
4035 }
4036
4037 @Override
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004038 public void destroySandboxForApp(String packageName, String sharedUserId, int userId) {
Sudheer Shanka584b0682018-10-04 16:26:16 -07004039 if (!ENABLE_ISOLATED_STORAGE) {
4040 return;
4041 }
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08004042 final String sandboxId = StorageManagerService.this.getSandboxId(
4043 packageName, sharedUserId);
Sudheer Shanka584b0682018-10-04 16:26:16 -07004044 synchronized (mPackagesLock) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004045 final ArraySet<String> userPackages = mPackages.get(userId);
4046 // If the userPackages is null, it means the user is not started but we still
4047 // need to delete the sandbox data though.
4048 if (userPackages != null) {
4049 userPackages.remove(packageName);
Sudheer Shanka584b0682018-10-04 16:26:16 -07004050 }
4051 }
4052 try {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004053 mVold.destroySandboxForApp(packageName, sandboxId, userId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004054 } catch (Exception e) {
4055 Slog.wtf(TAG, e);
4056 }
4057 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07004058
4059 @Override
Sudheer Shanka03fd40b2019-02-06 12:39:14 -08004060 public String getSandboxId(String packageName) {
4061 return StorageManagerService.this.getSandboxId(packageName,
4062 mPmInternal.getSharedUserIdForPackage(packageName));
4063 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07004064 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07004065}