blob: 9f8eeb3a067c81b99acb980264ae2874bc51641e [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 Sharkey14cbe522015-07-08 14:06:37 -0700115import android.provider.MediaStore;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700116import android.provider.Settings;
Inseob Kimc1246e62018-11-08 13:13:54 +0900117import android.sysprop.VoldProperties;
Jason parksf7b3cd42011-01-27 09:28:25 -0600118import android.text.TextUtils;
Jeff Sharkey1783f142015-04-17 10:52:51 -0700119import android.text.format.DateUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700120import android.util.ArrayMap;
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700121import android.util.ArraySet;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700122import android.util.AtomicFile;
Jeff Sharkey9f2dc052018-01-07 16:47:31 -0700123import android.util.DataUnit;
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700124import android.util.Log;
Felipe Leme281389a2016-10-10 17:12:20 -0700125import android.util.Pair;
San Mehata5078592010-03-25 09:36:54 -0700126import android.util.Slog;
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700127import android.util.SparseArray;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700128import android.util.TimeUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700129import android.util.Xml;
Jeff Sharkey48877892015-03-18 11:27:19 -0700130
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800131import com.android.internal.annotations.GuardedBy;
Sudheer Shankaff971bc2018-12-13 17:39:59 -0800132import com.android.internal.app.IAppOpsCallback;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800133import com.android.internal.app.IAppOpsService;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900134import com.android.internal.os.AppFuseMount;
Jeff Sharkey1019de92017-09-06 13:47:03 -0600135import com.android.internal.os.BackgroundThread;
Daichi Hirono812c95d2017-02-08 16:20:20 +0900136import com.android.internal.os.FuseUnavailableMountException;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700137import com.android.internal.os.SomeArgs;
Jeff Sharkey9527b222015-06-24 15:24:48 -0700138import com.android.internal.os.Zygote;
Jeff Sharkey48877892015-03-18 11:27:19 -0700139import com.android.internal.util.ArrayUtils;
Jeff Sharkey11697f52018-12-13 10:14:42 -0700140import com.android.internal.util.CollectionUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600141import com.android.internal.util.DumpUtils;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700142import com.android.internal.util.FastXmlSerializer;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800143import com.android.internal.util.HexDump;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -0700144import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700145import com.android.internal.util.Preconditions;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700146import com.android.internal.widget.LockPatternUtils;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900147import com.android.server.storage.AppFuseBridge;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700148import com.android.server.wm.ActivityTaskManagerInternal;
149import com.android.server.wm.ActivityTaskManagerInternal.ScreenObserver;
Jeff Sharkey5217cac2015-12-20 15:34:01 -0700150
Jeff Sharkey5790af02018-08-13 17:42:54 -0600151import libcore.io.IoUtils;
152import libcore.util.EmptyArray;
153
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700154import org.xmlpull.v1.XmlPullParser;
155import org.xmlpull.v1.XmlPullParserException;
156import org.xmlpull.v1.XmlSerializer;
157
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700158import java.io.File;
Kenny Root38cf8862010-09-26 14:18:51 -0700159import java.io.FileDescriptor;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700160import java.io.FileInputStream;
161import java.io.FileNotFoundException;
Christopher Tate7265abe2014-11-21 13:54:45 -0800162import java.io.FileOutputStream;
Kenny Root05105f72010-09-22 17:29:43 -0700163import java.io.IOException;
Kenny Root38cf8862010-09-26 14:18:51 -0700164import java.io.PrintWriter;
Kenny Root3b1abba2010-10-13 15:00:07 -0700165import java.math.BigInteger;
Paul Lawrence8e397362014-01-27 15:22:30 -0800166import java.nio.charset.StandardCharsets;
Jeff Sharkey0095a822018-02-15 13:06:53 -0700167import java.security.GeneralSecurityException;
Kenny Root3b1abba2010-10-13 15:00:07 -0700168import java.security.spec.KeySpec;
San Mehat22dd86e2010-01-12 12:21:18 -0800169import java.util.ArrayList;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800170import java.util.Arrays;
Kenny Roota02b8b02010-08-05 16:14:17 -0700171import java.util.HashMap;
Kenny Root38cf8862010-09-26 14:18:51 -0700172import java.util.Iterator;
Kenny Roota02b8b02010-08-05 16:14:17 -0700173import java.util.LinkedList;
174import java.util.List;
Elliott Hughesf839b4f2014-09-26 12:30:47 -0700175import java.util.Locale;
Kenny Roota02b8b02010-08-05 16:14:17 -0700176import java.util.Map;
Kenny Root38cf8862010-09-26 14:18:51 -0700177import java.util.Map.Entry;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700178import java.util.Objects;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700179import java.util.concurrent.CopyOnWriteArrayList;
Kenny Root51a573c2012-05-17 13:30:28 -0700180import java.util.concurrent.CountDownLatch;
181import java.util.concurrent.TimeUnit;
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700182import java.util.concurrent.TimeoutException;
Jeff Sharkey5790af02018-08-13 17:42:54 -0600183import java.util.regex.Matcher;
184import java.util.regex.Pattern;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Kenny Root3b1abba2010-10-13 15:00:07 -0700186import javax.crypto.SecretKey;
187import javax.crypto.SecretKeyFactory;
188import javax.crypto.spec.PBEKeySpec;
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190/**
Jeff Sharkey48877892015-03-18 11:27:19 -0700191 * Service responsible for various storage media. Connects to {@code vold} to
192 * watch for and manage dynamically added storage, such as SD cards and USB mass
193 * storage. Also decides how storage should be presented to users on the device.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 */
Jeff Sharkey9765e442017-12-14 22:15:14 -0700195class StorageManagerService extends IStorageManager.Stub
196 implements Watchdog.Monitor, ScreenObserver {
Jason parks5af0b912010-11-29 09:05:25 -0600197
Christopher Tated417d622013-08-19 16:14:25 -0700198 // Static direct instance pointer for the tightly-coupled idle service to use
Sudheer Shanka2250d562016-11-07 15:41:02 -0800199 static StorageManagerService sSelf = null;
Christopher Tated417d622013-08-19 16:14:25 -0700200
Daniel Colascione766b6322018-01-08 19:10:36 -0800201 /* Read during boot to decide whether to enable zram when available */
202 private static final String ZRAM_ENABLED_PROPERTY =
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700203 "persist.sys.zram_enabled";
204
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700205 private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage();
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700206
Jeff Sharkey56e62932015-03-21 20:41:00 -0700207 public static class Lifecycle extends SystemService {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800208 private StorageManagerService mStorageManagerService;
Jeff Sharkey56e62932015-03-21 20:41:00 -0700209
210 public Lifecycle(Context context) {
211 super(context);
212 }
213
214 @Override
215 public void onStart() {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800216 mStorageManagerService = new StorageManagerService(getContext());
217 publishBinderService("mount", mStorageManagerService);
218 mStorageManagerService.start();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700219 }
220
221 @Override
222 public void onBootPhase(int phase) {
Jeff Sharkey11697f52018-12-13 10:14:42 -0700223 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
224 mStorageManagerService.servicesReady();
225 } else if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800226 mStorageManagerService.systemReady();
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900227 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800228 mStorageManagerService.bootCompleted();
Jeff Sharkey56e62932015-03-21 20:41:00 -0700229 }
230 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700231
232 @Override
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600233 public void onSwitchUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800234 mStorageManagerService.mCurrentUserId = userHandle;
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600235 }
236
237 @Override
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700238 public void onUnlockUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800239 mStorageManagerService.onUnlockUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700240 }
241
242 @Override
243 public void onCleanupUser(int userHandle) {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800244 mStorageManagerService.onCleanupUser(userHandle);
Jeff Sharkey48877892015-03-18 11:27:19 -0700245 }
Jeff Sharkey56e62932015-03-21 20:41:00 -0700246 }
247
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800248 private static final boolean DEBUG_EVENTS = false;
Kenny Rootb7db2722011-01-25 16:39:35 -0800249 private static final boolean DEBUG_OBB = false;
Kenny Root02c87302010-07-01 08:10:18 -0700250
Jeff Sharkeyc3c72872018-06-06 15:35:53 -0600251 /**
252 * We now talk to vold over Binder, and it has its own internal lock to
253 * serialize certain calls. All long-running operations have been migrated
254 * to be async with callbacks, so we want watchdog to fire if vold wedges.
255 */
256 private static final boolean WATCHDOG_ENABLE = true;
Kenny Root07714d42011-08-17 17:49:28 -0700257
Jeff Sharkey00455bf2016-11-04 14:45:24 -0600258 /**
259 * Our goal is for all Android devices to be usable as development devices,
260 * which includes the new Direct Boot mode added in N. For devices that
261 * don't have native FBE support, we offer an emulation mode for developer
262 * testing purposes, but if it's prohibitively difficult to support this
263 * mode, it can be disabled for specific products using this flag.
264 */
265 private static final boolean EMULATE_FBE_SUPPORTED = true;
266
Sudheer Shanka2250d562016-11-07 15:41:02 -0800267 private static final String TAG = "StorageManagerService";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700268
Jeff Sharkey9756d752015-05-14 21:07:42 -0700269 private static final String TAG_STORAGE_BENCHMARK = "storage_benchmark";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700270 private static final String TAG_STORAGE_TRIM = "storage_trim";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700272 /** Magic value sent by MoveTask.cpp */
273 private static final int MOVE_STATUS_COPY_FINISHED = 82;
274
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700275 private static final int VERSION_INIT = 1;
276 private static final int VERSION_ADD_PRIMARY = 2;
Jeff Sharkeyfced5342015-05-10 14:53:34 -0700277 private static final int VERSION_FIX_PRIMARY = 3;
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700278
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700279 private static final String TAG_VOLUMES = "volumes";
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700280 private static final String ATTR_VERSION = "version";
281 private static final String ATTR_PRIMARY_STORAGE_UUID = "primaryStorageUuid";
Jeff Sharkey11697f52018-12-13 10:14:42 -0700282 private static final String ATTR_ISOLATED_STORAGE = "isolatedStorage";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700283 private static final String TAG_VOLUME = "volume";
284 private static final String ATTR_TYPE = "type";
285 private static final String ATTR_FS_UUID = "fsUuid";
Jeff Sharkey5cc0df22015-06-17 19:44:05 -0700286 private static final String ATTR_PART_GUID = "partGuid";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700287 private static final String ATTR_NICKNAME = "nickname";
288 private static final String ATTR_USER_FLAGS = "userFlags";
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700289 private static final String ATTR_CREATED_MILLIS = "createdMillis";
290 private static final String ATTR_LAST_TRIM_MILLIS = "lastTrimMillis";
291 private static final String ATTR_LAST_BENCH_MILLIS = "lastBenchMillis";
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700292
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700293 private final AtomicFile mSettingsFile;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700294
Jeff Sharkey48877892015-03-18 11:27:19 -0700295 /**
296 * <em>Never</em> hold the lock while performing downcalls into vold, since
297 * unsolicited events can suddenly appear to update data structures.
298 */
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600299 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_STORAGE);
Jeff Sharkey48877892015-03-18 11:27:19 -0700300
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700301 /**
302 * Similar to {@link #mLock}, never hold this lock while performing downcalls into vold.
303 * Also, never hold this while calling into PackageManagerService since it is used in callbacks
304 * from PackageManagerService.
305 *
306 * If both {@link #mLock} and this lock need to be held, {@link #mLock} should be acquired
307 * before this.
308 *
309 * Use -PL suffix for methods that need to called with this lock held.
310 */
311 private final Object mPackagesLock = new Object();
312
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700313 /** Set of users that we know are unlocked. */
Jeff Sharkey48877892015-03-18 11:27:19 -0700314 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700315 private int[] mLocalUnlockedUsers = EmptyArray.INT;
316 /** Set of users that system knows are unlocked. */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800317 @GuardedBy("mLock")
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700318 private int[] mSystemUnlockedUsers = EmptyArray.INT;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700319
320 /** Map from disk ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700321 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700322 private ArrayMap<String, DiskInfo> mDisks = new ArrayMap<>();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700323 /** Map from volume ID to disk */
Jeff Sharkey48877892015-03-18 11:27:19 -0700324 @GuardedBy("mLock")
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700325 private final ArrayMap<String, VolumeInfo> mVolumes = new ArrayMap<>();
Jeff Sharkey48877892015-03-18 11:27:19 -0700326
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700327 /** Map from UUID to record */
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700328 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -0700329 private ArrayMap<String, VolumeRecord> mRecords = new ArrayMap<>();
Jeff Sharkey620b32b2015-04-23 19:36:02 -0700330 @GuardedBy("mLock")
331 private String mPrimaryStorageUuid;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -0700332
Jeff Sharkey11697f52018-12-13 10:14:42 -0700333 /** Flag indicating isolated storage state of last boot */
334 @GuardedBy("mLock")
335 private boolean mLastIsolatedStorage = false;
336
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700337 /** Map from disk ID to latches */
338 @GuardedBy("mLock")
339 private ArrayMap<String, CountDownLatch> mDiskScanLatches = new ArrayMap<>();
340
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700341 @GuardedBy("mLock")
342 private IPackageMoveObserver mMoveCallback;
343 @GuardedBy("mLock")
344 private String mMoveTargetUuid;
345
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700346 @GuardedBy("mPackagesLock")
347 private final SparseArray<ArraySet<String>> mPackages = new SparseArray<>();
348
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700349 /**
350 * List of volumes visible to any user.
351 * TODO: may be have a map of userId -> volumes?
352 */
353 private final CopyOnWriteArrayList<VolumeInfo> mVisibleVols = new CopyOnWriteArrayList<>();
354
Jeff Sharkeyab15c392016-05-05 11:45:01 -0600355 private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
356
Daichi Hirono9fb00182016-11-08 14:12:17 +0900357 /** Holding lock for AppFuse business */
358 private final Object mAppFuseLock = new Object();
359
360 @GuardedBy("mAppFuseLock")
361 private int mNextAppFuseName = 0;
362
363 @GuardedBy("mAppFuseLock")
Daichi Hironoe56740d2017-02-02 13:56:45 +0900364 private AppFuseBridge mAppFuseBridge = null;
Daichi Hirono9fb00182016-11-08 14:12:17 +0900365
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700366 private VolumeInfo findVolumeByIdOrThrow(String id) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700367 synchronized (mLock) {
368 final VolumeInfo vol = mVolumes.get(id);
369 if (vol != null) {
370 return vol;
371 }
372 }
373 throw new IllegalArgumentException("No volume found for ID " + id);
374 }
375
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700376 private String findVolumeIdForPathOrThrow(String path) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700377 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700378 for (int i = 0; i < mVolumes.size(); i++) {
379 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700380 if (vol.path != null && path.startsWith(vol.path)) {
381 return vol.id;
Jeff Sharkey48877892015-03-18 11:27:19 -0700382 }
383 }
384 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700385 throw new IllegalArgumentException("No volume found for path " + path);
Jeff Sharkey48877892015-03-18 11:27:19 -0700386 }
387
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700388 private VolumeRecord findRecordForPath(String path) {
389 synchronized (mLock) {
390 for (int i = 0; i < mVolumes.size(); i++) {
391 final VolumeInfo vol = mVolumes.valueAt(i);
392 if (vol.path != null && path.startsWith(vol.path)) {
393 return mRecords.get(vol.fsUuid);
394 }
395 }
396 }
397 return null;
398 }
399
400 private String scrubPath(String path) {
401 if (path.startsWith(Environment.getDataDirectory().getAbsolutePath())) {
402 return "internal";
403 }
404 final VolumeRecord rec = findRecordForPath(path);
405 if (rec == null || rec.createdMillis == 0) {
406 return "unknown";
407 } else {
408 return "ext:" + (int) ((System.currentTimeMillis() - rec.createdMillis)
409 / DateUtils.WEEK_IN_MILLIS) + "w";
410 }
411 }
412
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700413 private @Nullable VolumeInfo findStorageForUuid(String volumeUuid) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700414 final StorageManager storage = mContext.getSystemService(StorageManager.class);
415 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
Jeff Sharkeyef10ee02015-07-05 14:17:27 -0700416 return storage.findVolumeById(VolumeInfo.ID_EMULATED_INTERNAL);
Jeff Sharkey275e3e42015-04-24 16:10:32 -0700417 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
418 return storage.getPrimaryPhysicalVolume();
419 } else {
420 return storage.findEmulatedForPrivate(storage.findVolumeByUuid(volumeUuid));
421 }
422 }
423
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700424 private boolean shouldBenchmark() {
425 final long benchInterval = Settings.Global.getLong(mContext.getContentResolver(),
426 Settings.Global.STORAGE_BENCHMARK_INTERVAL, DateUtils.WEEK_IN_MILLIS);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700427 if (benchInterval == -1) {
428 return false;
429 } else if (benchInterval == 0) {
430 return true;
431 }
432
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700433 synchronized (mLock) {
434 for (int i = 0; i < mVolumes.size(); i++) {
435 final VolumeInfo vol = mVolumes.valueAt(i);
436 final VolumeRecord rec = mRecords.get(vol.fsUuid);
Jeff Sharkeye83d8a92015-09-09 14:53:38 -0700437 if (vol.isMountedWritable() && rec != null) {
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700438 final long benchAge = System.currentTimeMillis() - rec.lastBenchMillis;
439 if (benchAge >= benchInterval) {
440 return true;
441 }
442 }
443 }
444 return false;
445 }
446 }
447
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700448 private CountDownLatch findOrCreateDiskScanLatch(String diskId) {
449 synchronized (mLock) {
450 CountDownLatch latch = mDiskScanLatches.get(diskId);
451 if (latch == null) {
452 latch = new CountDownLatch(1);
453 mDiskScanLatches.put(diskId, latch);
454 }
455 return latch;
456 }
457 }
458
Paul Lawrence8e397362014-01-27 15:22:30 -0800459 /** List of crypto types.
460 * These must match CRYPT_TYPE_XXX in cryptfs.h AND their
461 * corresponding commands in CommandListener.cpp */
462 public static final String[] CRYPTO_TYPES
463 = { "password", "default", "pattern", "pin" };
464
Brian Carlstrom7395a8a2014-04-28 22:11:01 -0700465 private final Context mContext;
Jeff Sharkeycd575992016-03-29 14:12:49 -0600466
Jeff Sharkey1019de92017-09-06 13:47:03 -0600467 private volatile IVold mVold;
Jin Qian12690d52017-10-13 18:17:04 -0700468 private volatile IStoraged mStoraged;
Jeff Sharkey1019de92017-09-06 13:47:03 -0600469
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700470 private volatile boolean mSystemReady = false;
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +0900471 private volatile boolean mBootCompleted = false;
Jeff Sharkey48877892015-03-18 11:27:19 -0700472 private volatile boolean mDaemonConnected = false;
Jeff Sharkey9765e442017-12-14 22:15:14 -0700473 private volatile boolean mSecureKeyguardShowing = true;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700474
Sudheer Shanka0a541a52018-07-31 13:21:11 -0700475 private PackageManagerInternal mPmInternal;
Jeff Sharkey5790af02018-08-13 17:42:54 -0600476 private UserManagerInternal mUmInternal;
Sudheer Shanka87915d62018-11-06 10:57:35 -0800477 private ActivityManagerInternal mAmInternal;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700478
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800479 private IPackageManager mIPackageManager;
480 private IAppOpsService mIAppOpsService;
481
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700482 private final Callbacks mCallbacks;
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -0700483 private final LockPatternUtils mLockPatternUtils;
Jeff Sharkey48877892015-03-18 11:27:19 -0700484
San Mehat6cdd9c02010-02-09 14:45:20 -0800485 /**
Kenny Root3b1abba2010-10-13 15:00:07 -0700486 * The size of the crypto algorithm key in bits for OBB files. Currently
487 * Twofish is used which takes 128-bit keys.
488 */
489 private static final int CRYPTO_ALGORITHM_KEY_SIZE = 128;
490
491 /**
492 * The number of times to run SHA1 in the PBKDF2 function for OBB files.
493 * 1024 is reasonably secure and not too slow.
494 */
495 private static final int PBKDF2_HASH_ROUNDS = 1024;
496
497 /**
Kenny Roota02b8b02010-08-05 16:14:17 -0700498 * Mounted OBB tracking information. Used to track the current state of all
499 * OBBs.
Kenny Root02c87302010-07-01 08:10:18 -0700500 */
Kenny Root735de3b2010-09-30 14:11:39 -0700501 final private Map<IBinder, List<ObbState>> mObbMounts = new HashMap<IBinder, List<ObbState>>();
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700502
503 /** Map from raw paths to {@link ObbState}. */
Kenny Roota02b8b02010-08-05 16:14:17 -0700504 final private Map<String, ObbState> mObbPathToStateMap = new HashMap<String, ObbState>();
505
Svet Ganov6ee871e2015-07-10 14:29:33 -0700506 // Not guarded by a lock.
Sudheer Shanka2250d562016-11-07 15:41:02 -0800507 private final StorageManagerInternalImpl mStorageManagerInternal
508 = new StorageManagerInternalImpl();
Svet Ganov6ee871e2015-07-10 14:29:33 -0700509
Kenny Roota02b8b02010-08-05 16:14:17 -0700510 class ObbState implements IBinder.DeathRecipient {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700511 public ObbState(String rawPath, String canonicalPath, int callingUid,
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600512 IObbActionListener token, int nonce, String volId) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700513 this.rawPath = rawPath;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700514 this.canonicalPath = canonicalPath;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700515 this.ownerGid = UserHandle.getSharedAppGid(callingUid);
Kenny Rootaf9d6672010-10-08 09:21:39 -0700516 this.token = token;
517 this.nonce = nonce;
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600518 this.volId = volId;
Kenny Roota02b8b02010-08-05 16:14:17 -0700519 }
520
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700521 final String rawPath;
522 final String canonicalPath;
Kenny Roota02b8b02010-08-05 16:14:17 -0700523
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700524 final int ownerGid;
Kenny Roota02b8b02010-08-05 16:14:17 -0700525
Kenny Rootaf9d6672010-10-08 09:21:39 -0700526 // Token of remote Binder caller
527 final IObbActionListener token;
528
529 // Identifier to pass back to the token
530 final int nonce;
Kenny Roota02b8b02010-08-05 16:14:17 -0700531
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600532 String volId;
533
Kenny Root735de3b2010-09-30 14:11:39 -0700534 public IBinder getBinder() {
535 return token.asBinder();
536 }
537
Kenny Roota02b8b02010-08-05 16:14:17 -0700538 @Override
539 public void binderDied() {
540 ObbAction action = new UnmountObbAction(this, true);
541 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root735de3b2010-09-30 14:11:39 -0700542 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700543
Kenny Root5919ac62010-10-05 09:49:40 -0700544 public void link() throws RemoteException {
545 getBinder().linkToDeath(this, 0);
546 }
547
548 public void unlink() {
Kenny Root735de3b2010-09-30 14:11:39 -0700549 getBinder().unlinkToDeath(this, 0);
Kenny Roota02b8b02010-08-05 16:14:17 -0700550 }
Kenny Root38cf8862010-09-26 14:18:51 -0700551
552 @Override
553 public String toString() {
554 StringBuilder sb = new StringBuilder("ObbState{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700555 sb.append("rawPath=").append(rawPath);
556 sb.append(",canonicalPath=").append(canonicalPath);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -0700557 sb.append(",ownerGid=").append(ownerGid);
558 sb.append(",token=").append(token);
559 sb.append(",binder=").append(getBinder());
Jeff Sharkey41cd6812017-09-11 10:32:17 -0600560 sb.append(",volId=").append(volId);
Kenny Root38cf8862010-09-26 14:18:51 -0700561 sb.append('}');
562 return sb.toString();
563 }
Kenny Roota02b8b02010-08-05 16:14:17 -0700564 }
565
566 // OBB Action Handler
567 final private ObbActionHandler mObbActionHandler;
568
569 // OBB action handler messages
570 private static final int OBB_RUN_ACTION = 1;
Sudheer Shanka25469aa2018-08-27 15:50:23 -0700571 private static final int OBB_FLUSH_MOUNT_STATE = 2;
Kenny Root02c87302010-07-01 08:10:18 -0700572
Christopher Tate7265abe2014-11-21 13:54:45 -0800573 // Last fstrim operation tracking
574 private static final String LAST_FSTRIM_FILE = "last-fstrim";
575 private final File mLastMaintenanceFile;
576 private long mLastMaintenance;
577
Kenny Root02c87302010-07-01 08:10:18 -0700578 // Handler messages
Jeff Sharkey48877892015-03-18 11:27:19 -0700579 private static final int H_SYSTEM_READY = 1;
580 private static final int H_DAEMON_CONNECTED = 2;
581 private static final int H_SHUTDOWN = 3;
582 private static final int H_FSTRIM = 4;
583 private static final int H_VOLUME_MOUNT = 5;
584 private static final int H_VOLUME_BROADCAST = 6;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700585 private static final int H_INTERNAL_BROADCAST = 7;
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700586 private static final int H_VOLUME_UNMOUNT = 8;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800587 private static final int H_PARTITION_FORGET = 9;
588 private static final int H_RESET = 10;
Jin Qiana85b9912017-10-17 15:48:18 -0700589 private static final int H_RUN_IDLE_MAINT = 11;
590 private static final int H_ABORT_IDLE_MAINT = 12;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -0800591
Sudheer Shanka2250d562016-11-07 15:41:02 -0800592 class StorageManagerServiceHandler extends Handler {
593 public StorageManagerServiceHandler(Looper looper) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700594 super(looper);
Daniel Sandler5f27ef42010-03-16 15:42:02 -0400595 }
596
Jason parks5af0b912010-11-29 09:05:25 -0600597 @Override
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800598 public void handleMessage(Message msg) {
599 switch (msg.what) {
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700600 case H_SYSTEM_READY: {
Jeff Sharkey48877892015-03-18 11:27:19 -0700601 handleSystemReady();
602 break;
603 }
604 case H_DAEMON_CONNECTED: {
605 handleDaemonConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700606 break;
607 }
Christopher Tated417d622013-08-19 16:14:25 -0700608 case H_FSTRIM: {
Christopher Tated417d622013-08-19 16:14:25 -0700609 Slog.i(TAG, "Running fstrim idle maintenance");
Christopher Tate7265abe2014-11-21 13:54:45 -0800610
611 // Remember when we kicked it off
612 try {
613 mLastMaintenance = System.currentTimeMillis();
614 mLastMaintenanceFile.setLastModified(mLastMaintenance);
615 } catch (Exception e) {
616 Slog.e(TAG, "Unable to record last fstrim!");
617 }
618
Jeff Sharkeyb302c542017-09-15 12:57:59 -0600619 // TODO: Reintroduce shouldBenchmark() test
Jeff Sharkey7e19f532017-11-06 13:54:11 -0700620 fstrim(0, null);
Christopher Tate7265abe2014-11-21 13:54:45 -0800621
Christopher Tated417d622013-08-19 16:14:25 -0700622 // invoke the completion callback, if any
Jeff Sharkeye8a4b662015-06-27 15:43:45 -0700623 // TODO: fstrim is non-blocking, so remove this useless callback
Christopher Tated417d622013-08-19 16:14:25 -0700624 Runnable callback = (Runnable) msg.obj;
625 if (callback != null) {
626 callback.run();
627 }
628 break;
629 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700630 case H_SHUTDOWN: {
Sudheer Shanka2250d562016-11-07 15:41:02 -0800631 final IStorageShutdownObserver obs = (IStorageShutdownObserver) msg.obj;
Jeff Sharkey48877892015-03-18 11:27:19 -0700632 boolean success = false;
633 try {
Jeff Sharkey54402792017-09-15 16:05:19 -0600634 mVold.shutdown();
635 success = true;
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600636 } catch (Exception e) {
637 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -0700638 }
639 if (obs != null) {
640 try {
641 obs.onShutDownComplete(success ? 0 : -1);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600642 } catch (Exception ignored) {
Jeff Sharkey48877892015-03-18 11:27:19 -0700643 }
644 }
645 break;
646 }
647 case H_VOLUME_MOUNT: {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700648 final VolumeInfo vol = (VolumeInfo) msg.obj;
Jeff Sharkey2e606d72015-07-27 14:19:54 -0700649 if (isMountDisallowed(vol)) {
650 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
651 break;
652 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700653 mount(vol);
Jeff Sharkey48877892015-03-18 11:27:19 -0700654 break;
655 }
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700656 case H_VOLUME_UNMOUNT: {
657 final VolumeInfo vol = (VolumeInfo) msg.obj;
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700658 unmount(vol);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700659 break;
660 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700661 case H_VOLUME_BROADCAST: {
662 final StorageVolume userVol = (StorageVolume) msg.obj;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700663 final String envState = userVol.getState();
664 Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
Jeff Sharkey48877892015-03-18 11:27:19 -0700665 + userVol.getOwner());
666
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700667 final String action = VolumeInfo.getBroadcastForEnvironment(envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700668 if (action != null) {
669 final Intent intent = new Intent(action,
670 Uri.fromFile(userVol.getPathFile()));
671 intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
Jeff Sharkey082f83b2017-03-26 14:34:47 -0600672 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
673 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkey48877892015-03-18 11:27:19 -0700674 mContext.sendBroadcastAsUser(intent, userVol.getOwner());
675 }
676 break;
677 }
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700678 case H_INTERNAL_BROADCAST: {
679 // Internal broadcasts aimed at system components, not for
680 // third-party apps.
681 final Intent intent = (Intent) msg.obj;
682 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
683 android.Manifest.permission.WRITE_MEDIA_STORAGE);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800684 break;
685 }
686 case H_PARTITION_FORGET: {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -0600687 final VolumeRecord rec = (VolumeRecord) msg.obj;
688 forgetPartition(rec.partGuid, rec.fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800689 break;
690 }
691 case H_RESET: {
692 resetIfReadyAndConnected();
693 break;
Jeff Sharkeyabc3e852015-08-03 14:41:13 -0700694 }
Jin Qiana85b9912017-10-17 15:48:18 -0700695 case H_RUN_IDLE_MAINT: {
696 Slog.i(TAG, "Running idle maintenance");
697 runIdleMaint((Runnable)msg.obj);
698 break;
699 }
700 case H_ABORT_IDLE_MAINT: {
701 Slog.i(TAG, "Aborting idle maintenance");
702 abortIdleMaint((Runnable)msg.obj);
703 break;
704 }
705
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800706 }
707 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700708 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700709
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700710 private final Handler mHandler;
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -0800711
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700712 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
713 @Override
714 public void onReceive(Context context, Intent intent) {
715 final String action = intent.getAction();
716 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700717 Preconditions.checkArgument(userId >= 0);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700718
719 try {
720 if (Intent.ACTION_USER_ADDED.equals(action)) {
721 final UserManager um = mContext.getSystemService(UserManager.class);
722 final int userSerialNumber = um.getUserSerialNumber(userId);
Jeff Sharkey54402792017-09-15 16:05:19 -0600723 mVold.onUserAdded(userId, userSerialNumber);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700724 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700725 synchronized (mVolumes) {
726 final int size = mVolumes.size();
727 for (int i = 0; i < size; i++) {
728 final VolumeInfo vol = mVolumes.valueAt(i);
729 if (vol.mountUserId == userId) {
730 vol.mountUserId = UserHandle.USER_NULL;
731 mHandler.obtainMessage(H_VOLUME_UNMOUNT, vol).sendToTarget();
732 }
733 }
734 }
Jeff Sharkey54402792017-09-15 16:05:19 -0600735 mVold.onUserRemoved(userId);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700736 }
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600737 } catch (Exception e) {
738 Slog.wtf(TAG, e);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700739 }
740 }
741 };
742
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700743 private void waitForLatch(CountDownLatch latch, String condition, long timeoutMillis)
744 throws TimeoutException {
745 final long startMillis = SystemClock.elapsedRealtime();
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700746 while (true) {
Kenny Root51a573c2012-05-17 13:30:28 -0700747 try {
748 if (latch.await(5000, TimeUnit.MILLISECONDS)) {
San Mehat207e5382010-02-04 20:46:54 -0800749 return;
Kenny Root51a573c2012-05-17 13:30:28 -0700750 } else {
751 Slog.w(TAG, "Thread " + Thread.currentThread().getName()
Jeff Sharkey48877892015-03-18 11:27:19 -0700752 + " still waiting for " + condition + "...");
San Mehat207e5382010-02-04 20:46:54 -0800753 }
Kenny Root51a573c2012-05-17 13:30:28 -0700754 } catch (InterruptedException e) {
Jeff Sharkeyeba260d2015-04-19 14:35:16 -0700755 Slog.w(TAG, "Interrupt while waiting for " + condition);
San Mehat207e5382010-02-04 20:46:54 -0800756 }
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -0700757 if (timeoutMillis > 0 && SystemClock.elapsedRealtime() > startMillis + timeoutMillis) {
758 throw new TimeoutException("Thread " + Thread.currentThread().getName()
759 + " gave up waiting for " + condition + " after " + timeoutMillis + "ms");
760 }
San Mehat207e5382010-02-04 20:46:54 -0800761 }
San Mehat1f6301e2010-01-07 22:40:27 -0800762 }
Kenny Root02c87302010-07-01 08:10:18 -0700763
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700764 private void handleSystemReady() {
Jeff Sharkey8924e872015-11-30 12:52:10 -0700765 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800766 resetIfReadyAndConnected();
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700767
Jeff Sharkey48877892015-03-18 11:27:19 -0700768 // Start scheduling nominally-daily fstrim operations
Christopher Tate115afda2014-06-06 19:06:26 -0700769 MountServiceIdler.scheduleIdlePass(mContext);
Daniel Colascione766b6322018-01-08 19:10:36 -0800770
771 // Toggle zram-enable system property in response to settings
772 mContext.getContentResolver().registerContentObserver(
773 Settings.Global.getUriFor(Settings.Global.ZRAM_ENABLED),
774 false /*notifyForDescendants*/,
775 new ContentObserver(null /* current thread */) {
776 @Override
777 public void onChange(boolean selfChange) {
778 refreshZramSettings();
779 }
780 });
781 refreshZramSettings();
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700782
783 // Toggle isolated-enable system property in response to settings
784 mContext.getContentResolver().registerContentObserver(
785 Settings.Global.getUriFor(Settings.Global.ISOLATED_STORAGE_REMOTE),
786 false /*notifyForDescendants*/,
787 new ContentObserver(null /* current thread */) {
788 @Override
789 public void onChange(boolean selfChange) {
790 refreshIsolatedStorageSettings();
791 }
792 });
793 refreshIsolatedStorageSettings();
Daniel Colascione766b6322018-01-08 19:10:36 -0800794 }
795
796 /**
797 * Update the zram_enabled system property (which init reads to
798 * decide whether to enable zram) to reflect the zram_enabled
799 * preference (which we can change for experimentation purposes).
800 */
801 private void refreshZramSettings() {
802 String propertyValue = SystemProperties.get(ZRAM_ENABLED_PROPERTY);
803 if ("".equals(propertyValue)) {
804 return; // System doesn't have zram toggling support
805 }
806 String desiredPropertyValue =
807 Settings.Global.getInt(mContext.getContentResolver(),
808 Settings.Global.ZRAM_ENABLED,
809 1) != 0
810 ? "1" : "0";
811 if (!desiredPropertyValue.equals(propertyValue)) {
812 // Avoid redundant disk writes by setting only if we're
813 // changing the property value. There's no race: we're the
814 // sole writer.
815 SystemProperties.set(ZRAM_ENABLED_PROPERTY, desiredPropertyValue);
816 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700817 }
818
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -0700819 private void refreshIsolatedStorageSettings() {
820 final int local = Settings.Global.getInt(mContext.getContentResolver(),
821 Settings.Global.ISOLATED_STORAGE_LOCAL, 0);
822 final int remote = Settings.Global.getInt(mContext.getContentResolver(),
823 Settings.Global.ISOLATED_STORAGE_REMOTE, 0);
824
825 // Walk down precedence chain; we prefer local settings first, then
826 // remote settings, before finally falling back to hard-coded default.
827 final boolean res;
828 if (local == -1) {
829 res = false;
830 } else if (local == 1) {
831 res = true;
832 } else if (remote == -1) {
833 res = false;
834 } else if (remote == 1) {
835 res = true;
836 } else {
837 res = false;
838 }
839
840 Slog.d(TAG, "Isolated storage local flag " + local + " and remote flag "
841 + remote + " resolved to " + res);
842 SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE, Boolean.toString(res));
843 }
844
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700845 /**
846 * MediaProvider has a ton of code that makes assumptions about storage
847 * paths never changing, so we outright kill them to pick up new state.
848 */
849 @Deprecated
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700850 private void killMediaProvider(List<UserInfo> users) {
851 if (users == null) return;
852
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700853 final long token = Binder.clearCallingIdentity();
854 try {
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700855 for (UserInfo user : users) {
856 // System user does not have media provider, so skip.
857 if (user.isSystemOnly()) continue;
858
Jeff Sharkey5790af02018-08-13 17:42:54 -0600859 final ProviderInfo provider = mPmInternal.resolveContentProvider(
860 MediaStore.AUTHORITY, PackageManager.MATCH_DIRECT_BOOT_AWARE
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600861 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
862 user.id);
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700863 if (provider != null) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800864 final IActivityManager am = ActivityManager.getService();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700865 try {
Jeff Sharkey85f449e2016-06-23 09:26:00 -0600866 am.killApplication(provider.applicationInfo.packageName,
867 UserHandle.getAppId(provider.applicationInfo.uid),
868 UserHandle.USER_ALL, "vold reset");
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700869 // We only need to run this once. It will kill all users' media processes.
870 break;
871 } catch (RemoteException e) {
872 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700873 }
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700874 }
Jeff Sharkeyb3cf9532015-07-17 15:12:39 -0700875 } finally {
876 Binder.restoreCallingIdentity(token);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700877 }
878 }
879
Andreas Gampea36dc622018-02-05 17:19:22 -0800880 @GuardedBy("mLock")
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800881 private void addInternalVolumeLocked() {
Amith Yamasania7892482015-08-07 11:09:05 -0700882 // Create a stub volume that represents internal storage
883 final VolumeInfo internal = new VolumeInfo(VolumeInfo.ID_PRIVATE_INTERNAL,
884 VolumeInfo.TYPE_PRIVATE, null, null);
885 internal.state = VolumeInfo.STATE_MOUNTED;
886 internal.path = Environment.getDataDirectory().getAbsolutePath();
887 mVolumes.put(internal.id, internal);
888 }
889
Jeff Sharkey8924e872015-11-30 12:52:10 -0700890 private void initIfReadyAndConnected() {
891 Slog.d(TAG, "Thinking about init, mSystemReady=" + mSystemReady
892 + ", mDaemonConnected=" + mDaemonConnected);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700893 if (mSystemReady && mDaemonConnected
Paul Lawrence20be5d62016-02-26 13:51:17 -0800894 && !StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700895 // When booting a device without native support, make sure that our
896 // user directories are locked or unlocked based on the current
897 // emulation status.
Paul Lawrence20be5d62016-02-26 13:51:17 -0800898 final boolean initLocked = StorageManager.isFileEncryptedEmulatedOnly();
Paul Crowleyd94ab732016-02-15 06:44:51 +0000899 Slog.d(TAG, "Setting up emulation state, initlocked=" + initLocked);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700900 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Jeff Sharkey8924e872015-11-30 12:52:10 -0700901 for (UserInfo user : users) {
902 try {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700903 if (initLocked) {
Jeff Sharkey54402792017-09-15 16:05:19 -0600904 mVold.lockUserKey(user.id);
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700905 } else {
Jeff Sharkey54402792017-09-15 16:05:19 -0600906 mVold.unlockUserKey(user.id, user.serialNumber, encodeBytes(null),
907 encodeBytes(null));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700908 }
Jeff Sharkey43e12112017-09-12 16:31:45 -0600909 } catch (Exception e) {
910 Slog.wtf(TAG, e);
Jeff Sharkey8924e872015-11-30 12:52:10 -0700911 }
912 }
913 }
914 }
915
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800916 private void resetIfReadyAndConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -0700917 Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
918 + ", mDaemonConnected=" + mDaemonConnected);
919 if (mSystemReady && mDaemonConnected) {
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800920 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
Xiaohui Chen621b3fc2015-10-02 14:41:42 -0700921 killMediaProvider(users);
Jeff Sharkey14cbe522015-07-08 14:06:37 -0700922
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700923 final int[] systemUnlockedUsers;
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800924 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700925 systemUnlockedUsers = mSystemUnlockedUsers;
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700926
Jeff Sharkey5a9bb742015-11-03 10:15:57 -0800927 mDisks.clear();
928 mVolumes.clear();
929
930 addInternalVolumeLocked();
931 }
Jeff Sharkey59d577a2015-04-11 21:27:21 -0700932
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700933 mVisibleVols.clear();
934
Jeff Sharkey48877892015-03-18 11:27:19 -0700935 try {
Jeff Sharkey54402792017-09-15 16:05:19 -0600936 mVold.reset();
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700937
938 // Tell vold about all existing and started users
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700939 for (UserInfo user : users) {
Jeff Sharkey54402792017-09-15 16:05:19 -0600940 mVold.onUserAdded(user.id, user.serialNumber);
Jeff Sharkeybcd262d2015-06-10 09:41:17 -0700941 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700942 for (int userId : systemUnlockedUsers) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -0700943 sendUserStartedCallback(userId);
Jin Qian12690d52017-10-13 18:17:04 -0700944 mStoraged.onUserStarted(userId);
Jeff Sharkey50a05452015-04-29 11:24:52 -0700945 }
Jeff Sharkey9765e442017-12-14 22:15:14 -0700946 mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
Risanaec0ee72018-10-31 10:10:12 +0900947 mStorageManagerInternal.onReset(mVold);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600948 } catch (Exception e) {
949 Slog.wtf(TAG, e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700950 }
951 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700952 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700953
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700954 private void onUnlockUser(int userId) {
955 Slog.d(TAG, "onUnlockUser " + userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700956
957 // We purposefully block here to make sure that user-specific
958 // staging area is ready so it's ready for zygote-forked apps to
959 // bind mount against.
960 try {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -0700961 sendUserStartedCallback(userId);
Jin Qian12690d52017-10-13 18:17:04 -0700962 mStoraged.onUserStarted(userId);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600963 } catch (Exception e) {
964 Slog.wtf(TAG, e);
Jeff Sharkeyb049e212012-09-07 23:16:01 -0700965 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700966
967 // Record user as started so newly mounted volumes kick off events
968 // correctly, then synthesize events for any already-mounted volumes.
yuanhuihuiefd1f122016-07-13 21:21:03 +0800969 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -0700970 for (int i = 0; i < mVolumes.size(); i++) {
971 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey46349872015-07-28 10:49:47 -0700972 if (vol.isVisibleForRead(userId) && vol.isMountedReadable()) {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700973 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey48877892015-03-18 11:27:19 -0700974 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -0700975
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700976 final String envState = VolumeInfo.getEnvironmentForState(vol.getState());
977 mCallbacks.notifyStorageStateChanged(userVol.getPath(), envState, envState);
Jeff Sharkey48877892015-03-18 11:27:19 -0700978 }
979 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700980 mSystemUnlockedUsers = ArrayUtils.appendInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -0700981 }
982 }
983
984 private void onCleanupUser(int userId) {
985 Slog.d(TAG, "onCleanupUser " + userId);
986
987 try {
Jeff Sharkey54402792017-09-15 16:05:19 -0600988 mVold.onUserStopped(userId);
Jin Qian12690d52017-10-13 18:17:04 -0700989 mStoraged.onUserStopped(userId);
Jeff Sharkeyace874b2017-09-07 15:27:33 -0600990 } catch (Exception e) {
991 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -0700992 }
993
Sudheer Shanka2ac25a92018-10-25 10:59:32 -0700994 synchronized (mPackagesLock) {
995 mPackages.delete(userId);
996 }
997
yuanhuihuiefd1f122016-07-13 21:21:03 +0800998 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -0700999 mSystemUnlockedUsers = ArrayUtils.removeInt(mSystemUnlockedUsers, userId);
Jeff Sharkey48877892015-03-18 11:27:19 -07001000 }
1001 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001002
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07001003 private void sendUserStartedCallback(int userId) throws Exception {
1004 if (!ENABLE_ISOLATED_STORAGE) {
1005 mVold.onUserStarted(userId, EmptyArray.STRING, EmptyArray.INT, EmptyArray.STRING);
1006 }
1007
1008 final String[] packages;
1009 final int[] appIds;
1010 final String[] sandboxIds;
1011 final SparseArray<String> sharedUserIds = mPmInternal.getAppsWithSharedUserIds();
1012 final List<ApplicationInfo> appInfos =
1013 mContext.getPackageManager().getInstalledApplicationsAsUser(
1014 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1015 synchronized (mPackagesLock) {
1016 final ArraySet<String> userPackages = new ArraySet<>();
1017 final ArrayMap<String, Integer> packageToAppId = new ArrayMap<>();
1018 for (int i = appInfos.size() - 1; i >= 0; --i) {
1019 final ApplicationInfo appInfo = appInfos.get(i);
1020 if (appInfo.isInstantApp()) {
1021 continue;
1022 }
1023 userPackages.add(appInfo.packageName);
1024 packageToAppId.put(appInfo.packageName, UserHandle.getAppId(appInfo.uid));
1025 }
1026 mPackages.put(userId, userPackages);
1027
1028 packages = new String[userPackages.size()];
1029 appIds = new int[userPackages.size()];
1030 sandboxIds = new String[userPackages.size()];
1031 for (int i = userPackages.size() - 1; i >= 0; --i) {
1032 packages[i] = userPackages.valueAt(i);
1033 appIds[i] = packageToAppId.get(packages[i]);
1034 sandboxIds[i] = getSandboxId(packages[i], sharedUserIds.get(appIds[i]));
1035 }
1036 }
1037 mVold.onUserStarted(userId, packages, appIds, sandboxIds);
1038 }
1039
Jeff Sharkey9765e442017-12-14 22:15:14 -07001040 @Override
1041 public void onAwakeStateChanged(boolean isAwake) {
1042 // Ignored
1043 }
1044
1045 @Override
1046 public void onKeyguardStateChanged(boolean isShowing) {
1047 // Push down current secure keyguard status so that we ignore malicious
1048 // USB devices while locked.
1049 mSecureKeyguardShowing = isShowing
1050 && mContext.getSystemService(KeyguardManager.class).isDeviceSecure();
1051 try {
1052 mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
1053 } catch (Exception e) {
1054 Slog.wtf(TAG, e);
1055 }
1056 }
1057
Christopher Tated417d622013-08-19 16:14:25 -07001058 void runIdleMaintenance(Runnable callback) {
1059 mHandler.sendMessage(mHandler.obtainMessage(H_FSTRIM, callback));
1060 }
1061
Christopher Tate7265abe2014-11-21 13:54:45 -08001062 // Binder entry point for kicking off an immediate fstrim
1063 @Override
1064 public void runMaintenance() {
Jeff Sharkey48877892015-03-18 11:27:19 -07001065 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Christopher Tate7265abe2014-11-21 13:54:45 -08001066 runIdleMaintenance(null);
1067 }
1068
1069 @Override
1070 public long lastMaintenance() {
1071 return mLastMaintenance;
1072 }
1073
San Mehat4270e1e2010-01-29 05:32:19 -08001074 public void onDaemonConnected() {
Jeff Sharkey48877892015-03-18 11:27:19 -07001075 mDaemonConnected = true;
1076 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
1077 }
1078
1079 private void handleDaemonConnected() {
Jeff Sharkey8924e872015-11-30 12:52:10 -07001080 initIfReadyAndConnected();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001081 resetIfReadyAndConnected();
Jeff Sharkey48877892015-03-18 11:27:19 -07001082
Jeff Sharkey48877892015-03-18 11:27:19 -07001083 // On an encrypted device we can't see system properties yet, so pull
1084 // the system locale out of the mount service.
Inseob Kimc1246e62018-11-08 13:13:54 +09001085 if ("".equals(VoldProperties.encrypt_progress().orElse(""))) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001086 copyLocaleFromMountService();
1087 }
San Mehat4270e1e2010-01-29 05:32:19 -08001088 }
1089
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001090 private void copyLocaleFromMountService() {
1091 String systemLocale;
1092 try {
1093 systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
1094 } catch (RemoteException e) {
1095 return;
1096 }
1097 if (TextUtils.isEmpty(systemLocale)) {
1098 return;
1099 }
1100
1101 Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
1102 Locale locale = Locale.forLanguageTag(systemLocale);
1103 Configuration config = new Configuration();
1104 config.setLocale(locale);
1105 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001106 ActivityManager.getService().updatePersistentConfiguration(config);
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001107 } catch (RemoteException e) {
1108 Slog.e(TAG, "Error setting system locale from mount service", e);
1109 }
Elliott Hughes9c33f282014-10-13 12:39:56 -07001110
1111 // Temporary workaround for http://b/17945169.
1112 Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
Narayan Kamathd30dbb82015-01-15 14:48:15 +00001113 SystemProperties.set("persist.sys.locale", locale.toLanguageTag());
Elliott Hughesf839b4f2014-09-26 12:30:47 -07001114 }
1115
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001116 private final IVoldListener mListener = new IVoldListener.Stub() {
1117 @Override
1118 public void onDiskCreated(String diskId, int flags) {
1119 synchronized (mLock) {
Jeff Sharkey901c0422018-04-20 13:11:20 -06001120 final String value = SystemProperties.get(StorageManager.PROP_ADOPTABLE);
1121 switch (value) {
1122 case "force_on":
1123 flags |= DiskInfo.FLAG_ADOPTABLE;
1124 break;
1125 case "force_off":
1126 flags &= ~DiskInfo.FLAG_ADOPTABLE;
1127 break;
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001128 }
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001129 mDisks.put(diskId, new DiskInfo(diskId, flags));
1130 }
1131 }
1132
1133 @Override
1134 public void onDiskScanned(String diskId) {
1135 synchronized (mLock) {
1136 final DiskInfo disk = mDisks.get(diskId);
1137 if (disk != null) {
1138 onDiskScannedLocked(disk);
1139 }
1140 }
1141 }
1142
1143 @Override
1144 public void onDiskMetadataChanged(String diskId, long sizeBytes, String label,
1145 String sysPath) {
1146 synchronized (mLock) {
1147 final DiskInfo disk = mDisks.get(diskId);
1148 if (disk != null) {
1149 disk.size = sizeBytes;
1150 disk.label = label;
1151 disk.sysPath = sysPath;
1152 }
1153 }
1154 }
1155
1156 @Override
1157 public void onDiskDestroyed(String diskId) {
1158 synchronized (mLock) {
1159 final DiskInfo disk = mDisks.remove(diskId);
1160 if (disk != null) {
1161 mCallbacks.notifyDiskDestroyed(disk);
1162 }
1163 }
1164 }
1165
1166 @Override
1167 public void onVolumeCreated(String volId, int type, String diskId, String partGuid) {
1168 synchronized (mLock) {
1169 final DiskInfo disk = mDisks.get(diskId);
1170 final VolumeInfo vol = new VolumeInfo(volId, type, disk, partGuid);
1171 mVolumes.put(volId, vol);
1172 onVolumeCreatedLocked(vol);
1173 }
1174 }
1175
1176 @Override
1177 public void onVolumeStateChanged(String volId, int state) {
1178 synchronized (mLock) {
1179 final VolumeInfo vol = mVolumes.get(volId);
1180 if (vol != null) {
1181 final int oldState = vol.state;
1182 final int newState = state;
1183 vol.state = newState;
1184 onVolumeStateChangedLocked(vol, oldState, newState);
1185 }
1186 }
1187 }
1188
1189 @Override
1190 public void onVolumeMetadataChanged(String volId, String fsType, String fsUuid,
1191 String fsLabel) {
1192 synchronized (mLock) {
1193 final VolumeInfo vol = mVolumes.get(volId);
1194 if (vol != null) {
1195 vol.fsType = fsType;
1196 vol.fsUuid = fsUuid;
1197 vol.fsLabel = fsLabel;
1198 }
1199 }
1200 }
1201
1202 @Override
1203 public void onVolumePathChanged(String volId, String path) {
1204 synchronized (mLock) {
1205 final VolumeInfo vol = mVolumes.get(volId);
1206 if (vol != null) {
1207 vol.path = path;
1208 }
1209 }
1210 }
1211
1212 @Override
1213 public void onVolumeInternalPathChanged(String volId, String internalPath) {
1214 synchronized (mLock) {
1215 final VolumeInfo vol = mVolumes.get(volId);
1216 if (vol != null) {
1217 vol.internalPath = internalPath;
1218 }
1219 }
1220 }
1221
1222 @Override
1223 public void onVolumeDestroyed(String volId) {
1224 synchronized (mLock) {
1225 mVolumes.remove(volId);
1226 }
1227 }
1228 };
1229
Andreas Gampea36dc622018-02-05 17:19:22 -08001230 @GuardedBy("mLock")
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001231 private void onDiskScannedLocked(DiskInfo disk) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001232 int volumeCount = 0;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001233 for (int i = 0; i < mVolumes.size(); i++) {
1234 final VolumeInfo vol = mVolumes.valueAt(i);
1235 if (Objects.equals(disk.id, vol.getDiskId())) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001236 volumeCount++;
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001237 }
1238 }
1239
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001240 final Intent intent = new Intent(DiskInfo.ACTION_DISK_SCANNED);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001241 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1242 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001243 intent.putExtra(DiskInfo.EXTRA_DISK_ID, disk.id);
1244 intent.putExtra(DiskInfo.EXTRA_VOLUME_COUNT, volumeCount);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001245 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001246
1247 final CountDownLatch latch = mDiskScanLatches.remove(disk.id);
1248 if (latch != null) {
1249 latch.countDown();
1250 }
1251
Jeff Sharkeyf5a6bd72015-05-19 14:42:38 -07001252 disk.volumeCount = volumeCount;
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001253 mCallbacks.notifyDiskScanned(disk, volumeCount);
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001254 }
1255
Andreas Gampea36dc622018-02-05 17:19:22 -08001256 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001257 private void onVolumeCreatedLocked(VolumeInfo vol) {
Jeff Sharkey5790af02018-08-13 17:42:54 -06001258 if (mPmInternal.isOnlyCoreApps()) {
Jeff Sharkey6855c482016-03-31 14:34:38 -06001259 Slog.d(TAG, "System booted in core-only mode; ignoring volume " + vol.getId());
1260 return;
1261 }
1262
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001263 if (vol.type == VolumeInfo.TYPE_EMULATED) {
1264 final StorageManager storage = mContext.getSystemService(StorageManager.class);
1265 final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
1266
1267 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)
1268 && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
1269 Slog.v(TAG, "Found primary storage at " + vol);
1270 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1271 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1272 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1273
1274 } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
1275 Slog.v(TAG, "Found primary storage at " + vol);
1276 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1277 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1278 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1279 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001280
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001281 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001282 // TODO: only look at first public partition
1283 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1284 && vol.disk.isDefaultPrimary()) {
1285 Slog.v(TAG, "Found primary storage at " + vol);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001286 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1287 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
San Mehat4270e1e2010-01-29 05:32:19 -08001288 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001289
1290 // Adoptable public disks are visible to apps, since they meet
1291 // public API requirement of being in a stable location.
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001292 if (vol.disk.isAdoptable()) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07001293 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
1294 }
1295
Jeff Sharkeyab15c392016-05-05 11:45:01 -06001296 vol.mountUserId = mCurrentUserId;
Jeff Sharkey48877892015-03-18 11:27:19 -07001297 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001298
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -07001299 } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1300 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
1301
Risan05c41e62018-10-29 08:57:43 +09001302 } else if (vol.type == VolumeInfo.TYPE_STUB) {
1303 vol.mountUserId = mCurrentUserId;
1304 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001305 } else {
Jeff Sharkey48877892015-03-18 11:27:19 -07001306 Slog.d(TAG, "Skipping automatic mounting of " + vol);
San Mehat4270e1e2010-01-29 05:32:19 -08001307 }
1308 }
1309
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001310 private boolean isBroadcastWorthy(VolumeInfo vol) {
1311 switch (vol.getType()) {
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001312 case VolumeInfo.TYPE_PRIVATE:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001313 case VolumeInfo.TYPE_PUBLIC:
1314 case VolumeInfo.TYPE_EMULATED:
Risan05c41e62018-10-29 08:57:43 +09001315 case VolumeInfo.TYPE_STUB:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001316 break;
1317 default:
1318 return false;
1319 }
1320
1321 switch (vol.getState()) {
1322 case VolumeInfo.STATE_MOUNTED:
1323 case VolumeInfo.STATE_MOUNTED_READ_ONLY:
1324 case VolumeInfo.STATE_EJECTING:
1325 case VolumeInfo.STATE_UNMOUNTED:
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001326 case VolumeInfo.STATE_UNMOUNTABLE:
Tony Mantlerf0d71052015-06-24 11:45:25 -07001327 case VolumeInfo.STATE_BAD_REMOVAL:
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001328 break;
1329 default:
1330 return false;
1331 }
1332
1333 return true;
1334 }
1335
Andreas Gampea36dc622018-02-05 17:19:22 -08001336 @GuardedBy("mLock")
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07001337 private void onVolumeStateChangedLocked(VolumeInfo vol, int oldState, int newState) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001338 // Remember that we saw this volume so we're ready to accept user
1339 // metadata, or so we can annoy them when a private volume is ejected
1340 if (vol.isMountedReadable() && !TextUtils.isEmpty(vol.fsUuid)) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001341 VolumeRecord rec = mRecords.get(vol.fsUuid);
1342 if (rec == null) {
1343 rec = new VolumeRecord(vol.type, vol.fsUuid);
1344 rec.partGuid = vol.partGuid;
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001345 rec.createdMillis = System.currentTimeMillis();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001346 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1347 rec.nickname = vol.disk.getDescription();
1348 }
1349 mRecords.put(rec.fsUuid, rec);
1350 writeSettingsLocked();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001351 } else {
1352 // Handle upgrade case where we didn't store partition GUID
1353 if (TextUtils.isEmpty(rec.partGuid)) {
1354 rec.partGuid = vol.partGuid;
1355 writeSettingsLocked();
1356 }
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001357 }
1358 }
1359
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001360 mCallbacks.notifyVolumeStateChanged(vol, oldState, newState);
1361
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001362 // Do not broadcast before boot has completed to avoid launching the
1363 // processes that receive the intent unnecessarily.
1364 if (mBootCompleted && isBroadcastWorthy(vol)) {
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001365 final Intent intent = new Intent(VolumeInfo.ACTION_VOLUME_STATE_CHANGED);
Jeff Sharkeyc7acac62015-06-12 16:16:56 -07001366 intent.putExtra(VolumeInfo.EXTRA_VOLUME_ID, vol.id);
1367 intent.putExtra(VolumeInfo.EXTRA_VOLUME_STATE, newState);
Tony Mantlerf0d71052015-06-24 11:45:25 -07001368 intent.putExtra(VolumeRecord.EXTRA_FS_UUID, vol.fsUuid);
Jeff Sharkey7732e1e2016-03-30 17:14:23 -06001369 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1370 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Jeff Sharkeyabc3e852015-08-03 14:41:13 -07001371 mHandler.obtainMessage(H_INTERNAL_BROADCAST, intent).sendToTarget();
Jeff Sharkeye6c04f92015-04-18 21:38:05 -07001372 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001373
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001374 final String oldStateEnv = VolumeInfo.getEnvironmentForState(oldState);
1375 final String newStateEnv = VolumeInfo.getEnvironmentForState(newState);
Emily Bernier92aa5a22014-07-07 10:11:48 -04001376
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001377 if (!Objects.equals(oldStateEnv, newStateEnv)) {
1378 // Kick state changed event towards all started users. Any users
1379 // started after this point will trigger additional
1380 // user-specific broadcasts.
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07001381 for (int userId : mSystemUnlockedUsers) {
Jeff Sharkey46349872015-07-28 10:49:47 -07001382 if (vol.isVisibleForRead(userId)) {
Svet Ganov6ee871e2015-07-10 14:29:33 -07001383 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, false);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001384 mHandler.obtainMessage(H_VOLUME_BROADCAST, userVol).sendToTarget();
Jeff Sharkey48877892015-03-18 11:27:19 -07001385
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001386 mCallbacks.notifyStorageStateChanged(userVol.getPath(), oldStateEnv,
1387 newStateEnv);
San Mehat4270e1e2010-01-29 05:32:19 -08001388 }
1389 }
1390 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001391
Risan05c41e62018-10-29 08:57:43 +09001392 if ((vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_STUB)
1393 && vol.state == VolumeInfo.STATE_EJECTING) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001394 // TODO: this should eventually be handled by new ObbVolume state changes
1395 /*
1396 * Some OBBs might have been unmounted when this volume was
1397 * unmounted, so send a message to the handler to let it know to
1398 * remove those from the list of mounted OBBS.
1399 */
1400 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(
1401 OBB_FLUSH_MOUNT_STATE, vol.path));
1402 }
Pavel Grafovce72ef02018-01-10 17:14:11 +00001403 maybeLogMediaMount(vol, newState);
1404 }
1405
1406 private void maybeLogMediaMount(VolumeInfo vol, int newState) {
1407 if (!SecurityLog.isLoggingEnabled()) {
1408 return;
1409 }
1410
1411 final DiskInfo disk = vol.getDisk();
1412 if (disk == null || (disk.flags & (DiskInfo.FLAG_SD | DiskInfo.FLAG_USB)) == 0) {
1413 return;
1414 }
1415
1416 // Sometimes there is a newline character.
1417 final String label = disk.label != null ? disk.label.trim() : "";
1418
1419 if (newState == VolumeInfo.STATE_MOUNTED
1420 || newState == VolumeInfo.STATE_MOUNTED_READ_ONLY) {
1421 SecurityLog.writeEvent(SecurityLog.TAG_MEDIA_MOUNT, vol.path, label);
1422 } else if (newState == VolumeInfo.STATE_UNMOUNTED
1423 || newState == VolumeInfo.STATE_BAD_REMOVAL) {
1424 SecurityLog.writeEvent(SecurityLog.TAG_MEDIA_UNMOUNT, vol.path, label);
1425 }
San Mehat4270e1e2010-01-29 05:32:19 -08001426 }
1427
Andreas Gampea36dc622018-02-05 17:19:22 -08001428 @GuardedBy("mLock")
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001429 private void onMoveStatusLocked(int status) {
1430 if (mMoveCallback == null) {
1431 Slog.w(TAG, "Odd, status but no move requested");
1432 return;
1433 }
1434
1435 // TODO: estimate remaining time
1436 try {
Jeff Sharkey50a05452015-04-29 11:24:52 -07001437 mMoveCallback.onStatusChanged(-1, status, -1);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001438 } catch (RemoteException ignored) {
1439 }
1440
1441 // We've finished copying and we're about to clean up old data, so
1442 // remember that move was successful if we get rebooted
1443 if (status == MOVE_STATUS_COPY_FINISHED) {
1444 Slog.d(TAG, "Move to " + mMoveTargetUuid + " copy phase finshed; persisting");
1445
1446 mPrimaryStorageUuid = mMoveTargetUuid;
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001447 writeSettingsLocked();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07001448 }
1449
1450 if (PackageManager.isMoveStatusFinished(status)) {
1451 Slog.d(TAG, "Move to " + mMoveTargetUuid + " finished with status " + status);
1452
1453 mMoveCallback = null;
1454 mMoveTargetUuid = null;
1455 }
1456 }
1457
Jeff Sharkey48877892015-03-18 11:27:19 -07001458 private void enforcePermission(String perm) {
1459 mContext.enforceCallingOrSelfPermission(perm, perm);
Mike Lockwooda5250c92011-05-23 13:44:04 -04001460 }
1461
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001462 /**
1463 * Decide if volume is mountable per device policies.
1464 */
1465 private boolean isMountDisallowed(VolumeInfo vol) {
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001466 UserManager userManager = mContext.getSystemService(UserManager.class);
1467
1468 boolean isUsbRestricted = false;
1469 if (vol.disk != null && vol.disk.isUsb()) {
1470 isUsbRestricted = userManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER,
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001471 Binder.getCallingUserHandle());
Emily Bernier92aa5a22014-07-07 10:11:48 -04001472 }
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001473
1474 boolean isTypeRestricted = false;
Risan05c41e62018-10-29 08:57:43 +09001475 if (vol.type == VolumeInfo.TYPE_PUBLIC || vol.type == VolumeInfo.TYPE_PRIVATE
1476 || vol.type == VolumeInfo.TYPE_STUB) {
Philip P. Moltmannec3cbb22016-09-14 13:24:52 -07001477 isTypeRestricted = userManager
1478 .hasUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1479 Binder.getCallingUserHandle());
1480 }
1481
1482 return isUsbRestricted || isTypeRestricted;
Emily Bernier92aa5a22014-07-07 10:11:48 -04001483 }
1484
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001485 private void enforceAdminUser() {
1486 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1487 final int callingUserId = UserHandle.getCallingUserId();
1488 boolean isAdmin;
1489 long token = Binder.clearCallingIdentity();
1490 try {
1491 isAdmin = um.getUserInfo(callingUserId).isAdmin();
1492 } finally {
1493 Binder.restoreCallingIdentity(token);
1494 }
1495 if (!isAdmin) {
1496 throw new SecurityException("Only admin users can adopt sd cards");
1497 }
1498 }
1499
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001500 /**
Sudheer Shanka2250d562016-11-07 15:41:02 -08001501 * Constructs a new StorageManagerService instance
San Mehat207e5382010-02-04 20:46:54 -08001502 *
1503 * @param context Binder context for this service
1504 */
Sudheer Shanka2250d562016-11-07 15:41:02 -08001505 public StorageManagerService(Context context) {
Christopher Tated417d622013-08-19 16:14:25 -07001506 sSelf = this;
1507
Jeff Sharkey342b4bf2018-12-18 11:12:40 -07001508 // Snapshot feature flag used for this boot
1509 SystemProperties.set(StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT, Boolean.toString(
1510 SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, false)));
1511
San Mehat207e5382010-02-04 20:46:54 -08001512 mContext = context;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001513 mCallbacks = new Callbacks(FgThread.get().getLooper());
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07001514 mLockPatternUtils = new LockPatternUtils(mContext);
San Mehat207e5382010-02-04 20:46:54 -08001515
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001516 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
Jeff Sharkey5790af02018-08-13 17:42:54 -06001517 mUmInternal = LocalServices.getService(UserManagerInternal.class);
Sudheer Shanka87915d62018-11-06 10:57:35 -08001518 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
San Mehat207e5382010-02-04 20:46:54 -08001519
Dianne Hackbornefa92b22013-05-03 14:11:43 -07001520 HandlerThread hthread = new HandlerThread(TAG);
1521 hthread.start();
Sudheer Shanka2250d562016-11-07 15:41:02 -08001522 mHandler = new StorageManagerServiceHandler(hthread.getLooper());
Daniel Sandler5f27ef42010-03-16 15:42:02 -04001523
Sudheer Shanka2250d562016-11-07 15:41:02 -08001524 // Add OBB Action Handler to StorageManagerService thread.
Dianne Hackborn8d044e82013-04-30 17:24:15 -07001525 mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
Kenny Roota02b8b02010-08-05 16:14:17 -07001526
Christopher Tate7265abe2014-11-21 13:54:45 -08001527 // Initialize the last-fstrim tracking if necessary
1528 File dataDir = Environment.getDataDirectory();
1529 File systemDir = new File(dataDir, "system");
1530 mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
1531 if (!mLastMaintenanceFile.exists()) {
1532 // Not setting mLastMaintenance here means that we will force an
1533 // fstrim during reboot following the OTA that installs this code.
1534 try {
1535 (new FileOutputStream(mLastMaintenanceFile)).close();
1536 } catch (IOException e) {
1537 Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
1538 }
1539 } else {
1540 mLastMaintenance = mLastMaintenanceFile.lastModified();
1541 }
1542
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001543 mSettingsFile = new AtomicFile(
Dianne Hackborne17b4452018-01-10 13:15:40 -08001544 new File(Environment.getDataSystemDirectory(), "storage.xml"), "storage-settings");
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001545
1546 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001547 readSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001548 }
1549
Sudheer Shanka2250d562016-11-07 15:41:02 -08001550 LocalServices.addService(StorageManagerInternal.class, mStorageManagerInternal);
Svet Ganov6ee871e2015-07-10 14:29:33 -07001551
Jeff Sharkeybcd262d2015-06-10 09:41:17 -07001552 final IntentFilter userFilter = new IntentFilter();
1553 userFilter.addAction(Intent.ACTION_USER_ADDED);
1554 userFilter.addAction(Intent.ACTION_USER_REMOVED);
1555 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
1556
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08001557 synchronized (mLock) {
1558 addInternalVolumeLocked();
1559 }
Amith Yamasania7892482015-08-07 11:09:05 -07001560
Kenny Root07714d42011-08-17 17:49:28 -07001561 // Add ourself to the Watchdog monitors if enabled.
1562 if (WATCHDOG_ENABLE) {
1563 Watchdog.getInstance().addMonitor(this);
1564 }
San Mehat207e5382010-02-04 20:46:54 -08001565 }
1566
Jeff Sharkeycd575992016-03-29 14:12:49 -06001567 private void start() {
Jeff Sharkey1019de92017-09-06 13:47:03 -06001568 connect();
Jeff Sharkeycd575992016-03-29 14:12:49 -06001569 }
1570
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001571 private static String getSandboxId(String packageName, String sharedUserId) {
Sudheer Shankad68bd602018-11-13 17:43:39 -08001572 return sharedUserId == null
1573 ? packageName : StorageManager.SHARED_SANDBOX_PREFIX + sharedUserId;
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001574 }
Sudheer Shanka0a541a52018-07-31 13:21:11 -07001575
Jeff Sharkey1019de92017-09-06 13:47:03 -06001576 private void connect() {
Jin Qian12690d52017-10-13 18:17:04 -07001577 IBinder binder = ServiceManager.getService("storaged");
1578 if (binder != null) {
1579 try {
1580 binder.linkToDeath(new DeathRecipient() {
1581 @Override
1582 public void binderDied() {
1583 Slog.w(TAG, "storaged died; reconnecting");
1584 mStoraged = null;
1585 connect();
1586 }
1587 }, 0);
1588 } catch (RemoteException e) {
1589 binder = null;
1590 }
1591 }
1592
1593 if (binder != null) {
1594 mStoraged = IStoraged.Stub.asInterface(binder);
1595 } else {
1596 Slog.w(TAG, "storaged not found; trying again");
1597 }
1598
1599 binder = ServiceManager.getService("vold");
Jeff Sharkey1019de92017-09-06 13:47:03 -06001600 if (binder != null) {
1601 try {
1602 binder.linkToDeath(new DeathRecipient() {
1603 @Override
1604 public void binderDied() {
1605 Slog.w(TAG, "vold died; reconnecting");
Jin Qian12690d52017-10-13 18:17:04 -07001606 mVold = null;
Jeff Sharkey1019de92017-09-06 13:47:03 -06001607 connect();
1608 }
1609 }, 0);
1610 } catch (RemoteException e) {
1611 binder = null;
1612 }
1613 }
1614
1615 if (binder != null) {
1616 mVold = IVold.Stub.asInterface(binder);
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001617 try {
1618 mVold.setListener(mListener);
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001619 } catch (RemoteException e) {
Jin Qian12690d52017-10-13 18:17:04 -07001620 mVold = null;
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001621 Slog.w(TAG, "vold listener rejected; trying again", e);
1622 }
Jeff Sharkey1019de92017-09-06 13:47:03 -06001623 } else {
1624 Slog.w(TAG, "vold not found; trying again");
Jeff Sharkey1019de92017-09-06 13:47:03 -06001625 }
Jeff Sharkey8058fe62017-09-13 11:50:33 -06001626
Jin Qian12690d52017-10-13 18:17:04 -07001627 if (mStoraged == null || mVold == null) {
1628 BackgroundThread.getHandler().postDelayed(() -> {
1629 connect();
1630 }, DateUtils.SECOND_IN_MILLIS);
1631 } else {
1632 onDaemonConnected();
1633 }
Jeff Sharkey1019de92017-09-06 13:47:03 -06001634 }
1635
Jeff Sharkey11697f52018-12-13 10:14:42 -07001636 private void servicesReady() {
1637 synchronized (mLock) {
1638 final boolean thisIsolatedStorage = StorageManager.hasIsolatedStorage();
1639 if (mLastIsolatedStorage == thisIsolatedStorage) {
1640 // Nothing changed since last boot; keep rolling forward
1641 return;
1642 } else if (thisIsolatedStorage) {
1643 // This boot enables isolated storage; apply legacy behavior
1644 applyLegacyStorage();
1645 }
1646
1647 // Always remember the new state we just booted with
1648 writeSettingsLocked();
1649 }
1650 }
1651
1652 /**
1653 * If we're enabling isolated storage, we need to remember which existing
1654 * apps have already been using shared storage, and grant them legacy access
1655 * to keep them running smoothly.
1656 */
1657 private void applyLegacyStorage() {
1658 final AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
1659 final UserManagerInternal um = LocalServices.getService(UserManagerInternal.class);
1660 for (int userId : um.getUserIds()) {
1661 final PackageManager pm;
1662 try {
1663 pm = mContext.createPackageContextAsUser(mContext.getPackageName(),
1664 0, UserHandle.of(userId)).getPackageManager();
1665 } catch (PackageManager.NameNotFoundException e) {
1666 throw new RuntimeException(e);
1667 }
1668
1669 final List<PackageInfo> pkgs = pm.getPackagesHoldingPermissions(new String[] {
1670 android.Manifest.permission.READ_EXTERNAL_STORAGE,
1671 android.Manifest.permission.WRITE_EXTERNAL_STORAGE
1672 }, MATCH_UNINSTALLED_PACKAGES | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
1673 for (PackageInfo pkg : pkgs) {
1674 final int uid = pkg.applicationInfo.uid;
1675 final String packageName = pkg.applicationInfo.packageName;
1676
1677 final long lastAccess = getLastAccessTime(appOps, uid, packageName, new int[] {
1678 AppOpsManager.OP_READ_EXTERNAL_STORAGE,
1679 AppOpsManager.OP_WRITE_EXTERNAL_STORAGE,
1680 });
1681
1682 Log.d(TAG, "Found " + uid + " " + packageName
1683 + " with granted storage access, last accessed " + lastAccess);
1684 if (lastAccess > 0) {
1685 appOps.setMode(AppOpsManager.OP_LEGACY_STORAGE,
1686 uid, packageName, AppOpsManager.MODE_ALLOWED);
1687 }
1688 }
1689 }
1690 }
1691
1692 private static long getLastAccessTime(AppOpsManager manager,
1693 int uid, String packageName, int[] ops) {
1694 long maxTime = 0;
1695 final List<AppOpsManager.PackageOps> pkgs = manager.getOpsForPackage(uid, packageName, ops);
1696 for (AppOpsManager.PackageOps pkg : CollectionUtils.defeatNullable(pkgs)) {
1697 for (AppOpsManager.OpEntry op : CollectionUtils.defeatNullable(pkg.getOps())) {
1698 maxTime = Math.max(maxTime, op.getLastAccessTime());
1699 }
1700 }
1701 return maxTime;
1702 }
1703
Jeff Sharkey56e62932015-03-21 20:41:00 -07001704 private void systemReady() {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001705 LocalServices.getService(ActivityTaskManagerInternal.class)
Jeff Sharkey9765e442017-12-14 22:15:14 -07001706 .registerScreenObserver(this);
1707
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001708 mSystemReady = true;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08001709 mIPackageManager = IPackageManager.Stub.asInterface(
1710 ServiceManager.getService("package"));
1711 mIAppOpsService = IAppOpsService.Stub.asInterface(
1712 ServiceManager.getService(Context.APP_OPS_SERVICE));
Sudheer Shankaff971bc2018-12-13 17:39:59 -08001713 try {
1714 mIAppOpsService.startWatchingMode(OP_REQUEST_INSTALL_PACKAGES, null, mAppOpsCallback);
1715 } catch (RemoteException e) {
1716 }
Jeff Sharkeyb049e212012-09-07 23:16:01 -07001717 mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
1718 }
1719
Yasuhiro Matsuda87a38b52015-07-24 22:10:16 +09001720 private void bootCompleted() {
1721 mBootCompleted = true;
1722 }
1723
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001724 private String getDefaultPrimaryStorageUuid() {
1725 if (SystemProperties.getBoolean(StorageManager.PROP_PRIMARY_PHYSICAL, false)) {
1726 return StorageManager.UUID_PRIMARY_PHYSICAL;
1727 } else {
1728 return StorageManager.UUID_PRIVATE_INTERNAL;
1729 }
1730 }
1731
Andreas Gampea36dc622018-02-05 17:19:22 -08001732 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001733 private void readSettingsLocked() {
1734 mRecords.clear();
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001735 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey11697f52018-12-13 10:14:42 -07001736 mLastIsolatedStorage = false;
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001737
1738 FileInputStream fis = null;
1739 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001740 fis = mSettingsFile.openRead();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001741 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001742 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001743
1744 int type;
1745 while ((type = in.next()) != END_DOCUMENT) {
1746 if (type == START_TAG) {
1747 final String tag = in.getName();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001748 if (TAG_VOLUMES.equals(tag)) {
1749 final int version = readIntAttribute(in, ATTR_VERSION, VERSION_INIT);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001750 final boolean primaryPhysical = SystemProperties.getBoolean(
1751 StorageManager.PROP_PRIMARY_PHYSICAL, false);
1752 final boolean validAttr = (version >= VERSION_FIX_PRIMARY)
1753 || (version >= VERSION_ADD_PRIMARY && !primaryPhysical);
1754 if (validAttr) {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001755 mPrimaryStorageUuid = readStringAttribute(in,
1756 ATTR_PRIMARY_STORAGE_UUID);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001757 }
Jeff Sharkey11697f52018-12-13 10:14:42 -07001758 mLastIsolatedStorage = readBooleanAttribute(in,
1759 ATTR_ISOLATED_STORAGE, false);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001760
1761 } else if (TAG_VOLUME.equals(tag)) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001762 final VolumeRecord rec = readVolumeRecord(in);
1763 mRecords.put(rec.fsUuid, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001764 }
1765 }
1766 }
1767 } catch (FileNotFoundException e) {
1768 // Missing metadata is okay, probably first boot
1769 } catch (IOException e) {
1770 Slog.wtf(TAG, "Failed reading metadata", e);
1771 } catch (XmlPullParserException e) {
1772 Slog.wtf(TAG, "Failed reading metadata", e);
1773 } finally {
1774 IoUtils.closeQuietly(fis);
1775 }
1776 }
1777
Andreas Gampea36dc622018-02-05 17:19:22 -08001778 @GuardedBy("mLock")
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001779 private void writeSettingsLocked() {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001780 FileOutputStream fos = null;
1781 try {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001782 fos = mSettingsFile.startWrite();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001783
1784 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001785 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001786 out.startDocument(null, true);
1787 out.startTag(null, TAG_VOLUMES);
Jeff Sharkeyfced5342015-05-10 14:53:34 -07001788 writeIntAttribute(out, ATTR_VERSION, VERSION_FIX_PRIMARY);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07001789 writeStringAttribute(out, ATTR_PRIMARY_STORAGE_UUID, mPrimaryStorageUuid);
Jeff Sharkey11697f52018-12-13 10:14:42 -07001790 writeBooleanAttribute(out, ATTR_ISOLATED_STORAGE, StorageManager.hasIsolatedStorage());
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001791 final int size = mRecords.size();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001792 for (int i = 0; i < size; i++) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001793 final VolumeRecord rec = mRecords.valueAt(i);
1794 writeVolumeRecord(out, rec);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001795 }
1796 out.endTag(null, TAG_VOLUMES);
1797 out.endDocument();
1798
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001799 mSettingsFile.finishWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001800 } catch (IOException e) {
1801 if (fos != null) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001802 mSettingsFile.failWrite(fos);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001803 }
1804 }
1805 }
1806
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001807 public static VolumeRecord readVolumeRecord(XmlPullParser in) throws IOException {
1808 final int type = readIntAttribute(in, ATTR_TYPE);
1809 final String fsUuid = readStringAttribute(in, ATTR_FS_UUID);
1810 final VolumeRecord meta = new VolumeRecord(type, fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001811 meta.partGuid = readStringAttribute(in, ATTR_PART_GUID);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001812 meta.nickname = readStringAttribute(in, ATTR_NICKNAME);
1813 meta.userFlags = readIntAttribute(in, ATTR_USER_FLAGS);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001814 meta.createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS);
1815 meta.lastTrimMillis = readLongAttribute(in, ATTR_LAST_TRIM_MILLIS);
1816 meta.lastBenchMillis = readLongAttribute(in, ATTR_LAST_BENCH_MILLIS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001817 return meta;
1818 }
1819
1820 public static void writeVolumeRecord(XmlSerializer out, VolumeRecord rec) throws IOException {
1821 out.startTag(null, TAG_VOLUME);
1822 writeIntAttribute(out, ATTR_TYPE, rec.type);
1823 writeStringAttribute(out, ATTR_FS_UUID, rec.fsUuid);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07001824 writeStringAttribute(out, ATTR_PART_GUID, rec.partGuid);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001825 writeStringAttribute(out, ATTR_NICKNAME, rec.nickname);
1826 writeIntAttribute(out, ATTR_USER_FLAGS, rec.userFlags);
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07001827 writeLongAttribute(out, ATTR_CREATED_MILLIS, rec.createdMillis);
1828 writeLongAttribute(out, ATTR_LAST_TRIM_MILLIS, rec.lastTrimMillis);
1829 writeLongAttribute(out, ATTR_LAST_BENCH_MILLIS, rec.lastBenchMillis);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001830 out.endTag(null, TAG_VOLUME);
1831 }
1832
San Mehat207e5382010-02-04 20:46:54 -08001833 /**
San Mehat4270e1e2010-01-29 05:32:19 -08001834 * Exposed API calls below here
1835 */
1836
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001837 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001838 public void registerListener(IStorageEventListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001839 mCallbacks.register(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001840 }
1841
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001842 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001843 public void unregisterListener(IStorageEventListener listener) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001844 mCallbacks.unregister(listener);
San Mehat4270e1e2010-01-29 05:32:19 -08001845 }
1846
Jeff Sharkey48877892015-03-18 11:27:19 -07001847 @Override
Sudheer Shanka2250d562016-11-07 15:41:02 -08001848 public void shutdown(final IStorageShutdownObserver observer) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001849 enforcePermission(android.Manifest.permission.SHUTDOWN);
San Mehat4270e1e2010-01-29 05:32:19 -08001850
San Mehata5078592010-03-25 09:36:54 -07001851 Slog.i(TAG, "Shutting down");
Jeff Sharkey48877892015-03-18 11:27:19 -07001852 mHandler.obtainMessage(H_SHUTDOWN, observer).sendToTarget();
San Mehat4270e1e2010-01-29 05:32:19 -08001853 }
1854
Jeff Sharkey48877892015-03-18 11:27:19 -07001855 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001856 public void mount(String volId) {
1857 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001858
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001859 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey2e606d72015-07-27 14:19:54 -07001860 if (isMountDisallowed(vol)) {
1861 throw new SecurityException("Mounting " + volId + " restricted by policy");
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001862 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001863 mount(vol);
1864 }
1865
1866 private void mount(VolumeInfo vol) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001867 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001868 mVold.mount(vol.id, vol.mountFlags, vol.mountUserId);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001869 if ((vol.mountFlags & VolumeInfo.MOUNT_FLAG_VISIBLE) != 0) {
1870 mVisibleVols.add(vol);
1871 }
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001872 } catch (Exception e) {
1873 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001874 }
1875 }
1876
1877 @Override
1878 public void unmount(String volId) {
1879 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001880
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001881 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001882 unmount(vol);
1883 }
1884
1885 private void unmount(VolumeInfo vol) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001886 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001887 mVold.unmount(vol.id);
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07001888 if ((vol.mountFlags & VolumeInfo.MOUNT_FLAG_VISIBLE) != 0) {
1889 mVisibleVols.remove(vol);
1890 }
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001891 } catch (Exception e) {
1892 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001893 }
1894 }
1895
1896 @Override
1897 public void format(String volId) {
Jeff Sharkey48877892015-03-18 11:27:19 -07001898 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
San Mehat5b77dab2010-01-26 13:28:50 -08001899
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07001900 final VolumeInfo vol = findVolumeByIdOrThrow(volId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001901 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001902 mVold.format(vol.id, "auto");
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001903 } catch (Exception e) {
1904 Slog.wtf(TAG, e);
Jeff Sharkey48877892015-03-18 11:27:19 -07001905 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001906 }
1907
1908 @Override
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001909 public void benchmark(String volId, IVoldTaskListener listener) {
Jeff Sharkey9756d752015-05-14 21:07:42 -07001910 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey9756d752015-05-14 21:07:42 -07001911
1912 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001913 mVold.benchmark(volId, new IVoldTaskListener.Stub() {
1914 @Override
1915 public void onStatus(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001916 dispatchOnStatus(listener, status, extras);
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001917 }
1918
1919 @Override
1920 public void onFinished(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001921 dispatchOnFinished(listener, status, extras);
Jeff Sharkeyb302c542017-09-15 12:57:59 -06001922
1923 final String path = extras.getString("path");
1924 final String ident = extras.getString("ident");
1925 final long create = extras.getLong("create");
1926 final long run = extras.getLong("run");
1927 final long destroy = extras.getLong("destroy");
1928
1929 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
1930 dropBox.addText(TAG_STORAGE_BENCHMARK, scrubPath(path)
1931 + " " + ident + " " + create + " " + run + " " + destroy);
1932
1933 synchronized (mLock) {
1934 final VolumeRecord rec = findRecordForPath(path);
1935 if (rec != null) {
1936 rec.lastBenchMillis = System.currentTimeMillis();
1937 writeSettingsLocked();
1938 }
1939 }
1940 }
1941 });
Jeff Sharkey7e19f532017-11-06 13:54:11 -07001942 } catch (RemoteException e) {
1943 throw e.rethrowAsRuntimeException();
Jeff Sharkey9756d752015-05-14 21:07:42 -07001944 }
1945 }
1946
1947 @Override
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001948 public void partitionPublic(String diskId) {
1949 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001950
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001951 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001952 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001953 mVold.partition(diskId, IVold.PARTITION_TYPE_PUBLIC, -1);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001954 waitForLatch(latch, "partitionPublic", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001955 } catch (Exception e) {
1956 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001957 }
1958 }
1959
1960 @Override
1961 public void partitionPrivate(String diskId) {
1962 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001963 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001964
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001965 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001966 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001967 mVold.partition(diskId, IVold.PARTITION_TYPE_PRIVATE, -1);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001968 waitForLatch(latch, "partitionPrivate", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001969 } catch (Exception e) {
1970 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001971 }
1972 }
1973
1974 @Override
1975 public void partitionMixed(String diskId, int ratio) {
1976 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Amith Yamasani462ac3a2015-06-30 14:21:01 -07001977 enforceAdminUser();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001978
Jeff Sharkeyeba260d2015-04-19 14:35:16 -07001979 final CountDownLatch latch = findOrCreateDiskScanLatch(diskId);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001980 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06001981 mVold.partition(diskId, IVold.PARTITION_TYPE_MIXED, ratio);
Jeff Sharkeyedcdaf62015-07-09 09:45:36 -07001982 waitForLatch(latch, "partitionMixed", 3 * DateUtils.MINUTE_IN_MILLIS);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06001983 } catch (Exception e) {
1984 Slog.wtf(TAG, e);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07001985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987
Jeff Sharkey48877892015-03-18 11:27:19 -07001988 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001989 public void setVolumeNickname(String fsUuid, String nickname) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001990 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001991
Jeff Sharkey50a05452015-04-29 11:24:52 -07001992 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001993 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001994 final VolumeRecord rec = mRecords.get(fsUuid);
1995 rec.nickname = nickname;
Jeff Sharkey50a05452015-04-29 11:24:52 -07001996 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07001997 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07001998 }
1999 }
2000
2001 @Override
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002002 public void setVolumeUserFlags(String fsUuid, int flags, int mask) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002003 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002004
Jeff Sharkey50a05452015-04-29 11:24:52 -07002005 Preconditions.checkNotNull(fsUuid);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002006 synchronized (mLock) {
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002007 final VolumeRecord rec = mRecords.get(fsUuid);
2008 rec.userFlags = (rec.userFlags & ~mask) | (flags & mask);
Jeff Sharkey50a05452015-04-29 11:24:52 -07002009 mCallbacks.notifyVolumeRecordChanged(rec);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002010 writeSettingsLocked();
2011 }
2012 }
2013
2014 @Override
2015 public void forgetVolume(String fsUuid) {
2016 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002017
Jeff Sharkey50a05452015-04-29 11:24:52 -07002018 Preconditions.checkNotNull(fsUuid);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002019
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002020 synchronized (mLock) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002021 final VolumeRecord rec = mRecords.remove(fsUuid);
2022 if (rec != null && !TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002023 mHandler.obtainMessage(H_PARTITION_FORGET, rec).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002024 }
2025 mCallbacks.notifyVolumeForgotten(fsUuid);
Jeff Sharkey50a05452015-04-29 11:24:52 -07002026
2027 // If this had been primary storage, revert back to internal and
2028 // reset vold so we bind into new volume into place.
2029 if (Objects.equals(mPrimaryStorageUuid, fsUuid)) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002030 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002031 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002032 }
2033
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07002034 writeSettingsLocked();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07002035 }
2036 }
2037
Jeff Sharkey7d2af542015-05-12 15:27:15 -07002038 @Override
2039 public void forgetAllVolumes() {
2040 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey7d2af542015-05-12 15:27:15 -07002041
Jeff Sharkey50a05452015-04-29 11:24:52 -07002042 synchronized (mLock) {
2043 for (int i = 0; i < mRecords.size(); i++) {
2044 final String fsUuid = mRecords.keyAt(i);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002045 final VolumeRecord rec = mRecords.valueAt(i);
2046 if (!TextUtils.isEmpty(rec.partGuid)) {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002047 mHandler.obtainMessage(H_PARTITION_FORGET, rec).sendToTarget();
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002048 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07002049 mCallbacks.notifyVolumeForgotten(fsUuid);
2050 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07002051 mRecords.clear();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002052
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002053 if (!Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid)) {
2054 mPrimaryStorageUuid = getDefaultPrimaryStorageUuid();
2055 }
2056
2057 writeSettingsLocked();
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002058 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey50a05452015-04-29 11:24:52 -07002059 }
2060 }
2061
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002062 private void forgetPartition(String partGuid, String fsUuid) {
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002063 try {
Jeff Sharkeydb4b6192017-10-24 11:08:50 -06002064 mVold.forgetPartition(partGuid, fsUuid);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002065 } catch (Exception e) {
2066 Slog.wtf(TAG, e);
Jeff Sharkey5cc0df22015-06-17 19:44:05 -07002067 }
2068 }
2069
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002070 @Override
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002071 public void fstrim(int flags, IVoldTaskListener listener) {
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002072 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002073
2074 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002075 mVold.fstrim(flags, new IVoldTaskListener.Stub() {
2076 @Override
2077 public void onStatus(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002078 dispatchOnStatus(listener, status, extras);
2079
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002080 // Ignore trim failures
2081 if (status != 0) return;
2082
2083 final String path = extras.getString("path");
2084 final long bytes = extras.getLong("bytes");
2085 final long time = extras.getLong("time");
2086
2087 final DropBoxManager dropBox = mContext.getSystemService(DropBoxManager.class);
2088 dropBox.addText(TAG_STORAGE_TRIM, scrubPath(path) + " " + bytes + " " + time);
2089
2090 synchronized (mLock) {
2091 final VolumeRecord rec = findRecordForPath(path);
2092 if (rec != null) {
2093 rec.lastTrimMillis = System.currentTimeMillis();
2094 writeSettingsLocked();
2095 }
2096 }
2097 }
2098
2099 @Override
2100 public void onFinished(int status, PersistableBundle extras) {
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002101 dispatchOnFinished(listener, status, extras);
2102
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002103 // TODO: benchmark when desired
2104 }
2105 });
Jeff Sharkey7e19f532017-11-06 13:54:11 -07002106 } catch (RemoteException e) {
2107 throw e.rethrowAsRuntimeException();
Jeff Sharkey31d0b702016-11-21 14:16:53 -07002108 }
2109 }
2110
Jin Qiana85b9912017-10-17 15:48:18 -07002111 void runIdleMaint(Runnable callback) {
2112 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
2113
2114 try {
2115 mVold.runIdleMaint(new IVoldTaskListener.Stub() {
2116 @Override
2117 public void onStatus(int status, PersistableBundle extras) {
2118 // Not currently used
2119 }
2120 @Override
2121 public void onFinished(int status, PersistableBundle extras) {
2122 if (callback != null) {
2123 BackgroundThread.getHandler().post(callback);
2124 }
2125 }
2126 });
2127 } catch (Exception e) {
2128 Slog.wtf(TAG, e);
2129 }
2130 }
2131
2132 @Override
2133 public void runIdleMaintenance() {
2134 runIdleMaint(null);
2135 }
2136
2137 void abortIdleMaint(Runnable callback) {
2138 enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
2139
2140 try {
2141 mVold.abortIdleMaint(new IVoldTaskListener.Stub() {
2142 @Override
2143 public void onStatus(int status, PersistableBundle extras) {
2144 // Not currently used
2145 }
2146 @Override
2147 public void onFinished(int status, PersistableBundle extras) {
2148 if (callback != null) {
2149 BackgroundThread.getHandler().post(callback);
2150 }
2151 }
2152 });
2153 } catch (Exception e) {
2154 Slog.wtf(TAG, e);
2155 }
2156 }
2157
2158 @Override
2159 public void abortIdleMaintenance() {
2160 abortIdleMaint(null);
2161 }
2162
Svet Ganov6ee871e2015-07-10 14:29:33 -07002163 private void remountUidExternalStorage(int uid, int mode) {
Jeff Sharkey9527b222015-06-24 15:24:48 -07002164 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002165 mVold.remountUid(uid, mode);
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002166 } catch (Exception e) {
2167 Slog.wtf(TAG, e);
Jeff Sharkey9527b222015-06-24 15:24:48 -07002168 }
2169 }
2170
2171 @Override
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002172 public void setDebugFlags(int flags, int mask) {
2173 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002174
Jeff Sharkeyba512352015-11-12 20:17:45 -08002175 if ((mask & StorageManager.DEBUG_EMULATE_FBE) != 0) {
Jeff Sharkey00455bf2016-11-04 14:45:24 -06002176 if (!EMULATE_FBE_SUPPORTED) {
2177 throw new IllegalStateException(
2178 "Emulation not supported on this device");
2179 }
Paul Lawrence20be5d62016-02-26 13:51:17 -08002180 if (StorageManager.isFileEncryptedNativeOnly()) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002181 throw new IllegalStateException(
Jeff Sharkey00455bf2016-11-04 14:45:24 -06002182 "Emulation not supported on device with native FBE");
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002183 }
Jeff Sharkey5a785162016-03-21 13:02:06 -06002184 if (mLockPatternUtils.isCredentialRequiredToDecrypt(false)) {
2185 throw new IllegalStateException(
2186 "Emulation requires disabling 'Secure start-up' in Settings > Security");
2187 }
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002188
Jeff Sharkey1176e512016-02-29 17:01:26 -07002189 final long token = Binder.clearCallingIdentity();
2190 try {
2191 final boolean emulateFbe = (flags & StorageManager.DEBUG_EMULATE_FBE) != 0;
2192 SystemProperties.set(StorageManager.PROP_EMULATE_FBE, Boolean.toString(emulateFbe));
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002193
Jeff Sharkey1176e512016-02-29 17:01:26 -07002194 // Perform hard reboot to kick policy into place
2195 mContext.getSystemService(PowerManager.class).reboot(null);
2196 } finally {
2197 Binder.restoreCallingIdentity(token);
2198 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08002199 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002200
Jeff Sharkey901c0422018-04-20 13:11:20 -06002201 if ((mask & (StorageManager.DEBUG_ADOPTABLE_FORCE_ON
2202 | StorageManager.DEBUG_ADOPTABLE_FORCE_OFF)) != 0) {
2203 final String value;
2204 if ((flags & StorageManager.DEBUG_ADOPTABLE_FORCE_ON) != 0) {
2205 value = "force_on";
2206 } else if ((flags & StorageManager.DEBUG_ADOPTABLE_FORCE_OFF) != 0) {
2207 value = "force_off";
2208 } else {
2209 value = "";
2210 }
Jeff Sharkeyba512352015-11-12 20:17:45 -08002211
Jeff Sharkey901c0422018-04-20 13:11:20 -06002212 final long token = Binder.clearCallingIdentity();
2213 try {
2214 SystemProperties.set(StorageManager.PROP_ADOPTABLE, value);
2215
2216 // Reset storage to kick new setting into place
Jeff Sharkeyba512352015-11-12 20:17:45 -08002217 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkey901c0422018-04-20 13:11:20 -06002218 } finally {
2219 Binder.restoreCallingIdentity(token);
Jeff Sharkeyba512352015-11-12 20:17:45 -08002220 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002221 }
Jeff Sharkey33dd1562016-04-07 11:05:33 -06002222
2223 if ((mask & (StorageManager.DEBUG_SDCARDFS_FORCE_ON
2224 | StorageManager.DEBUG_SDCARDFS_FORCE_OFF)) != 0) {
2225 final String value;
2226 if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_ON) != 0) {
2227 value = "force_on";
2228 } else if ((flags & StorageManager.DEBUG_SDCARDFS_FORCE_OFF) != 0) {
2229 value = "force_off";
2230 } else {
2231 value = "";
2232 }
2233
2234 final long token = Binder.clearCallingIdentity();
2235 try {
2236 SystemProperties.set(StorageManager.PROP_SDCARDFS, value);
2237
2238 // Reset storage to kick new setting into place
2239 mHandler.obtainMessage(H_RESET).sendToTarget();
2240 } finally {
2241 Binder.restoreCallingIdentity(token);
2242 }
2243 }
Jeff Sharkeye53e2d92017-03-25 23:14:06 -06002244
2245 if ((mask & StorageManager.DEBUG_VIRTUAL_DISK) != 0) {
2246 final boolean enabled = (flags & StorageManager.DEBUG_VIRTUAL_DISK) != 0;
2247
2248 final long token = Binder.clearCallingIdentity();
2249 try {
2250 SystemProperties.set(StorageManager.PROP_VIRTUAL_DISK, Boolean.toString(enabled));
2251
2252 // Reset storage to kick new setting into place
2253 mHandler.obtainMessage(H_RESET).sendToTarget();
2254 } finally {
2255 Binder.restoreCallingIdentity(token);
2256 }
2257 }
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002258
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07002259 if ((mask & (StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_ON
2260 | StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_OFF)) != 0) {
2261 final int value;
2262 if ((flags & StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_ON) != 0) {
2263 value = 1;
2264 } else if ((flags & StorageManager.DEBUG_ISOLATED_STORAGE_FORCE_OFF) != 0) {
2265 value = -1;
2266 } else {
2267 value = 0;
2268 }
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002269
2270 final long token = Binder.clearCallingIdentity();
2271 try {
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07002272 Settings.Global.putInt(mContext.getContentResolver(),
2273 Settings.Global.ISOLATED_STORAGE_LOCAL, value);
2274 refreshIsolatedStorageSettings();
Sudheer Shankabe0febe2018-11-07 18:24:37 -08002275
2276 // Perform hard reboot to kick policy into place
2277 mContext.getSystemService(PowerManager.class).reboot(null);
2278 } finally {
2279 Binder.restoreCallingIdentity(token);
2280 }
2281 }
Jeff Sharkey4c099d02015-05-15 13:45:00 -07002282 }
2283
2284 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002285 public String getPrimaryStorageUuid() {
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002286 synchronized (mLock) {
2287 return mPrimaryStorageUuid;
2288 }
2289 }
2290
2291 @Override
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002292 public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback) {
2293 enforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002294
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002295 final VolumeInfo from;
2296 final VolumeInfo to;
2297
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002298 synchronized (mLock) {
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002299 if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
2300 throw new IllegalArgumentException("Primary storage already at " + volumeUuid);
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002301 }
2302
2303 if (mMoveCallback != null) {
2304 throw new IllegalStateException("Move already in progress");
2305 }
2306 mMoveCallback = callback;
2307 mMoveTargetUuid = volumeUuid;
2308
Jeff Sharkeya65e6492017-06-21 13:45:11 -06002309 // We need all the users unlocked to move their primary storage
2310 final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
2311 for (UserInfo user : users) {
2312 if (StorageManager.isFileEncryptedNativeOrEmulated()
2313 && !isUserKeyUnlocked(user.id)) {
2314 Slog.w(TAG, "Failing move due to locked user " + user.id);
2315 onMoveStatusLocked(PackageManager.MOVE_FAILED_LOCKED_USER);
2316 return;
2317 }
2318 }
2319
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002320 // When moving to/from primary physical volume, we probably just nuked
2321 // the current storage location, so we have nothing to move.
2322 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
2323 || Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
2324 Slog.d(TAG, "Skipping move to/from primary physical");
2325 onMoveStatusLocked(MOVE_STATUS_COPY_FINISHED);
2326 onMoveStatusLocked(PackageManager.MOVE_SUCCEEDED);
Jeff Sharkey5a9bb742015-11-03 10:15:57 -08002327 mHandler.obtainMessage(H_RESET).sendToTarget();
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002328 return;
Jeff Sharkeyfced5342015-05-10 14:53:34 -07002329
2330 } else {
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002331 from = findStorageForUuid(mPrimaryStorageUuid);
2332 to = findStorageForUuid(volumeUuid);
Jeff Sharkeyef10ee02015-07-05 14:17:27 -07002333
2334 if (from == null) {
2335 Slog.w(TAG, "Failing move due to missing from volume " + mPrimaryStorageUuid);
2336 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2337 return;
2338 } else if (to == null) {
2339 Slog.w(TAG, "Failing move due to missing to volume " + volumeUuid);
2340 onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
2341 return;
2342 }
Jeff Sharkey275e3e42015-04-24 16:10:32 -07002343 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002344 }
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002345
2346 try {
Jeff Sharkeyb302c542017-09-15 12:57:59 -06002347 mVold.moveStorage(from.id, to.id, new IVoldTaskListener.Stub() {
2348 @Override
2349 public void onStatus(int status, PersistableBundle extras) {
2350 synchronized (mLock) {
2351 onMoveStatusLocked(status);
2352 }
2353 }
2354
2355 @Override
2356 public void onFinished(int status, PersistableBundle extras) {
2357 // Not currently used
2358 }
2359 });
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002360 } catch (Exception e) {
2361 Slog.wtf(TAG, e);
Jeff Sharkeya31460c2016-06-22 09:04:33 -06002362 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07002363 }
2364
San Mehatb1043402010-02-05 08:26:50 -08002365 private void warnOnNotMounted() {
Jeff Sharkey48877892015-03-18 11:27:19 -07002366 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07002367 for (int i = 0; i < mVolumes.size(); i++) {
2368 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07002369 if (vol.isPrimary() && vol.isMountedWritable()) {
Jeff Sharkey48877892015-03-18 11:27:19 -07002370 // Cool beans, we have a mounted primary volume
2371 return;
2372 }
Jeff Sharkey32ee8312012-09-30 13:21:31 -07002373 }
San Mehatb1043402010-02-05 08:26:50 -08002374 }
Jeff Sharkey48877892015-03-18 11:27:19 -07002375
2376 Slog.w(TAG, "No primary storage mounted!");
San Mehatb1043402010-02-05 08:26:50 -08002377 }
2378
Kenny Roota02b8b02010-08-05 16:14:17 -07002379 private boolean isUidOwnerOfPackageOrSystem(String packageName, int callerUid) {
2380 if (callerUid == android.os.Process.SYSTEM_UID) {
2381 return true;
2382 }
2383
Kenny Root02c87302010-07-01 08:10:18 -07002384 if (packageName == null) {
2385 return false;
2386 }
2387
Jeff Sharkey5790af02018-08-13 17:42:54 -06002388 final int packageUid = mPmInternal.getPackageUid(packageName,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002389 PackageManager.MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callerUid));
Kenny Root02c87302010-07-01 08:10:18 -07002390
2391 if (DEBUG_OBB) {
2392 Slog.d(TAG, "packageName = " + packageName + ", packageUid = " +
2393 packageUid + ", callerUid = " + callerUid);
2394 }
2395
2396 return callerUid == packageUid;
2397 }
2398
Jeff Sharkey54402792017-09-15 16:05:19 -06002399 @Override
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002400 public String getMountedObbPath(String rawPath) {
2401 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002402
Kenny Root02c87302010-07-01 08:10:18 -07002403 warnOnNotMounted();
2404
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002405 final ObbState state;
Rubin Xucd7a0142015-04-17 23:45:27 +01002406 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002407 state = mObbPathToStateMap.get(rawPath);
2408 }
2409 if (state == null) {
2410 Slog.w(TAG, "Failed to find OBB mounted at " + rawPath);
2411 return null;
2412 }
2413
Jeff Sharkey54402792017-09-15 16:05:19 -06002414 return findVolumeByIdOrThrow(state.volId).getPath().getAbsolutePath();
Kenny Root02c87302010-07-01 08:10:18 -07002415 }
2416
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002417 @Override
2418 public boolean isObbMounted(String rawPath) {
2419 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002420 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002421 return mObbPathToStateMap.containsKey(rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07002422 }
Kenny Root02c87302010-07-01 08:10:18 -07002423 }
2424
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002425 @Override
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002426 public void mountObb(String rawPath, String canonicalPath, String key,
2427 IObbActionListener token, int nonce, ObbInfo obbInfo) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002428 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2429 Preconditions.checkNotNull(canonicalPath, "canonicalPath cannot be null");
2430 Preconditions.checkNotNull(token, "token cannot be null");
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002431 Preconditions.checkNotNull(obbInfo, "obbIfno cannot be null");
Kenny Rootaf9d6672010-10-08 09:21:39 -07002432
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002433 final int callingUid = Binder.getCallingUid();
Jeff Sharkey41cd6812017-09-11 10:32:17 -06002434 final ObbState obbState = new ObbState(rawPath, canonicalPath,
2435 callingUid, token, nonce, null);
Sudheer Shanka25469aa2018-08-27 15:50:23 -07002436 final ObbAction action = new MountObbAction(obbState, key, callingUid, obbInfo);
Kenny Roota02b8b02010-08-05 16:14:17 -07002437 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
2438
2439 if (DEBUG_OBB)
2440 Slog.i(TAG, "Send to OBB handler: " + action.toString());
Kenny Root02c87302010-07-01 08:10:18 -07002441 }
2442
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002443 @Override
2444 public void unmountObb(String rawPath, boolean force, IObbActionListener token, int nonce) {
2445 Preconditions.checkNotNull(rawPath, "rawPath cannot be null");
2446
2447 final ObbState existingState;
Rubin Xucd7a0142015-04-17 23:45:27 +01002448 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002449 existingState = mObbPathToStateMap.get(rawPath);
Kenny Rootf1121dc2010-09-29 07:30:53 -07002450 }
2451
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002452 if (existingState != null) {
2453 // TODO: separate state object from request data
2454 final int callingUid = Binder.getCallingUid();
Jeff Sharkey41cd6812017-09-11 10:32:17 -06002455 final ObbState newState = new ObbState(rawPath, existingState.canonicalPath,
2456 callingUid, token, nonce, existingState.volId);
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002457 final ObbAction action = new UnmountObbAction(newState, force);
2458 mObbActionHandler.sendMessage(mObbActionHandler.obtainMessage(OBB_RUN_ACTION, action));
Kenny Root02c87302010-07-01 08:10:18 -07002459
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07002460 if (DEBUG_OBB)
2461 Slog.i(TAG, "Send to OBB handler: " + action.toString());
2462 } else {
2463 Slog.w(TAG, "Unknown OBB mount at " + rawPath);
2464 }
Kenny Roota02b8b02010-08-05 16:14:17 -07002465 }
2466
Ben Komalo444eca22011-09-01 15:17:44 -07002467 @Override
2468 public int getEncryptionState() {
2469 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2470 "no permission to access the crypt keeper");
2471
Ben Komalo444eca22011-09-01 15:17:44 -07002472 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002473 return mVold.fdeComplete();
2474 } catch (Exception e) {
2475 Slog.wtf(TAG, e);
Sudheer Shankaf7341142016-10-18 17:15:18 -07002476 return StorageManager.ENCRYPTION_STATE_ERROR_UNKNOWN;
Ben Komalo444eca22011-09-01 15:17:44 -07002477 }
2478 }
2479
2480 @Override
Jason parks5af0b912010-11-29 09:05:25 -06002481 public int decryptStorage(String password) {
Jason parks8888c592011-01-20 22:46:41 -06002482 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2483 "no permission to access the crypt keeper");
Jason parks5af0b912010-11-29 09:05:25 -06002484
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002485 if (TextUtils.isEmpty(password)) {
2486 throw new IllegalArgumentException("password cannot be empty");
2487 }
2488
Jason parks5af0b912010-11-29 09:05:25 -06002489 if (DEBUG_EVENTS) {
2490 Slog.i(TAG, "decrypting storage...");
2491 }
2492
2493 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002494 mVold.fdeCheckPassword(password);
2495 mHandler.postDelayed(() -> {
2496 try {
2497 mVold.fdeRestart();
2498 } catch (Exception e) {
2499 Slog.wtf(TAG, e);
2500 }
2501 }, DateUtils.SECOND_IN_MILLIS);
2502 return 0;
Paul Crowleyfc0b5192018-07-02 13:58:10 -07002503 } catch (ServiceSpecificException e) {
2504 Slog.e(TAG, "fdeCheckPassword failed", e);
2505 return e.errorCode;
Jeff Sharkey54402792017-09-15 16:05:19 -06002506 } catch (Exception e) {
2507 Slog.wtf(TAG, e);
2508 return StorageManager.ENCRYPTION_STATE_ERROR_UNKNOWN;
Jason parks5af0b912010-11-29 09:05:25 -06002509 }
Jason parks5af0b912010-11-29 09:05:25 -06002510 }
2511
Jeff Sharkey54402792017-09-15 16:05:19 -06002512 @Override
Paul Lawrence46791e72014-04-03 09:10:26 -07002513 public int encryptStorage(int type, String password) {
Jason parks8888c592011-01-20 22:46:41 -06002514 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2515 "no permission to access the crypt keeper");
Jason parks56aa5322011-01-07 09:01:15 -06002516
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002517 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2518 password = "";
2519 } else if (TextUtils.isEmpty(password)) {
2520 throw new IllegalArgumentException("password cannot be empty");
2521 }
2522
Jason parks56aa5322011-01-07 09:01:15 -06002523 if (DEBUG_EVENTS) {
Jason parks8888c592011-01-20 22:46:41 -06002524 Slog.i(TAG, "encrypting storage...");
Jason parks56aa5322011-01-07 09:01:15 -06002525 }
2526
2527 try {
Paul Lawrence89a0ae42017-12-22 10:11:10 -08002528 mVold.fdeEnable(type, password, 0);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002529 } catch (Exception e) {
2530 Slog.wtf(TAG, e);
2531 return -1;
Jason parks56aa5322011-01-07 09:01:15 -06002532 }
2533
2534 return 0;
2535 }
2536
Paul Lawrence8e397362014-01-27 15:22:30 -08002537 /** Set the password for encrypting the master key.
2538 * @param type One of the CRYPTO_TYPE_XXX consts defined in StorageManager.
2539 * @param password The password to set.
2540 */
Jeff Sharkey54402792017-09-15 16:05:19 -06002541 @Override
Paul Lawrence8e397362014-01-27 15:22:30 -08002542 public int changeEncryptionPassword(int type, String password) {
Jason parksf7b3cd42011-01-27 09:28:25 -06002543 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2544 "no permission to access the crypt keeper");
2545
Jeff Sharkeyae266462017-11-27 13:32:24 -07002546 if (StorageManager.isFileEncryptedNativeOnly()) {
2547 // Not supported on FBE devices
2548 return -1;
2549 }
2550
Jeff Sharkey8058fe62017-09-13 11:50:33 -06002551 if (type == StorageManager.CRYPT_TYPE_DEFAULT) {
2552 password = "";
2553 } else if (TextUtils.isEmpty(password)) {
2554 throw new IllegalArgumentException("password cannot be empty");
2555 }
2556
Jason parksf7b3cd42011-01-27 09:28:25 -06002557 if (DEBUG_EVENTS) {
2558 Slog.i(TAG, "changing encryption password...");
2559 }
2560
2561 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002562 mVold.fdeChangePassword(type, password);
2563 return 0;
2564 } catch (Exception e) {
2565 Slog.wtf(TAG, e);
2566 return -1;
Jason parksf7b3cd42011-01-27 09:28:25 -06002567 }
2568 }
2569
Christopher Tate32418be2011-10-10 13:51:12 -07002570 /**
2571 * Validate a user-supplied password string with cryptfs
2572 */
2573 @Override
2574 public int verifyEncryptionPassword(String password) throws RemoteException {
2575 // Only the system process is permitted to validate passwords
2576 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2577 throw new SecurityException("no permission to access the crypt keeper");
2578 }
2579
2580 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
2581 "no permission to access the crypt keeper");
2582
2583 if (TextUtils.isEmpty(password)) {
2584 throw new IllegalArgumentException("password cannot be empty");
2585 }
2586
Christopher Tate32418be2011-10-10 13:51:12 -07002587 if (DEBUG_EVENTS) {
2588 Slog.i(TAG, "validating encryption password...");
2589 }
2590
2591 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002592 mVold.fdeVerifyPassword(password);
2593 return 0;
2594 } catch (Exception e) {
2595 Slog.wtf(TAG, e);
2596 return -1;
Christopher Tate32418be2011-10-10 13:51:12 -07002597 }
2598 }
2599
Paul Lawrence8e397362014-01-27 15:22:30 -08002600 /**
2601 * Get the type of encryption used to encrypt the master key.
2602 * @return The type, one of the CRYPT_TYPE_XXX consts from StorageManager.
2603 */
2604 @Override
Svetoslav16e4a1a2014-09-29 18:16:20 -07002605 public int getPasswordType() {
Paul Lawrence76a40572017-03-15 11:08:04 -07002606 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence9de713d2016-05-02 22:45:33 +00002607 "no permission to access the crypt keeper");
2608
Paul Lawrence8e397362014-01-27 15:22:30 -08002609 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002610 return mVold.fdeGetPasswordType();
2611 } catch (Exception e) {
2612 Slog.wtf(TAG, e);
2613 return -1;
Paul Lawrence8e397362014-01-27 15:22:30 -08002614 }
2615 }
2616
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002617 /**
2618 * Set a field in the crypto header.
2619 * @param field field to set
2620 * @param contents contents to set in field
2621 */
2622 @Override
2623 public void setField(String field, String contents) throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002624 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002625 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002626
yusukes14a8b1f2018-07-23 17:34:42 -07002627 if (!StorageManager.isBlockEncrypted()) {
2628 // Only supported on FDE devices
Jeff Sharkeyae266462017-11-27 13:32:24 -07002629 return;
2630 }
2631
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002632 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002633 mVold.fdeSetField(field, contents);
2634 return;
2635 } catch (Exception e) {
2636 Slog.wtf(TAG, e);
2637 return;
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002638 }
2639 }
2640
2641 /**
2642 * Gets a field from the crypto header.
2643 * @param field field to get
2644 * @return contents of field
2645 */
2646 @Override
2647 public String getField(String field) throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002648 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002649 "no permission to access the crypt keeper");
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002650
yusukes14a8b1f2018-07-23 17:34:42 -07002651 if (!StorageManager.isBlockEncrypted()) {
2652 // Only supported on FDE devices
Jeff Sharkeyae266462017-11-27 13:32:24 -07002653 return null;
2654 }
2655
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002656 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002657 return mVold.fdeGetField(field);
2658 } catch (Exception e) {
2659 Slog.wtf(TAG, e);
2660 return null;
Paul Lawrencee51dcf92014-03-18 10:56:00 -07002661 }
2662 }
2663
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002664 /**
2665 * Is userdata convertible to file based encryption?
2666 * @return non zero for convertible
2667 */
2668 @Override
2669 public boolean isConvertibleToFBE() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002670 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002671 "no permission to access the crypt keeper");
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002672
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002673 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002674 return mVold.isConvertibleToFbe();
2675 } catch (Exception e) {
2676 Slog.wtf(TAG, e);
2677 return false;
Paul Lawrence3806d9c2015-10-29 10:30:46 -07002678 }
2679 }
2680
Daniel Rosenberge129e5c2018-11-07 19:25:55 -08002681 /**
2682 * Signal that checkpointing partitions should commit changes
2683 */
2684 @Override
2685 public void commitChanges() throws RemoteException {
2686 // Only the system process is permitted to commit checkpoints
2687 if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
2688 throw new SecurityException("no permission to commit checkpoint changes");
2689 }
2690
2691 mVold.commitChanges();
2692 }
2693
Jeff Sharkeyb049e212012-09-07 23:16:01 -07002694 @Override
Paul Lawrence945490c2014-03-27 16:37:28 +00002695 public String getPassword() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002696 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Rubin Xucd7a0142015-04-17 23:45:27 +01002697 "only keyguard can retrieve password");
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002698
Paul Lawrence945490c2014-03-27 16:37:28 +00002699 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002700 return mVold.fdeGetPassword();
2701 } catch (Exception e) {
2702 Slog.wtf(TAG, e);
Paul Lawrence24063b52015-01-06 13:11:23 -08002703 return null;
Paul Lawrence945490c2014-03-27 16:37:28 +00002704 }
2705 }
2706
2707 @Override
2708 public void clearPassword() throws RemoteException {
Paul Lawrence76a40572017-03-15 11:08:04 -07002709 mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
Paul Lawrence0bbd1082016-04-26 15:21:02 -07002710 "only keyguard can clear password");
2711
Paul Lawrence945490c2014-03-27 16:37:28 +00002712 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002713 mVold.fdeClearPassword();
2714 return;
2715 } catch (Exception e) {
2716 Slog.wtf(TAG, e);
2717 return;
Paul Lawrence945490c2014-03-27 16:37:28 +00002718 }
2719 }
2720
2721 @Override
Lenka Trochtovac4dd0212015-11-18 12:22:06 +01002722 public void createUserKey(int userId, int serialNumber, boolean ephemeral) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002723 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002724
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002725 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002726 mVold.createUserKey(userId, serialNumber, ephemeral);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002727 } catch (Exception e) {
2728 Slog.wtf(TAG, e);
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002729 }
2730 }
2731
Paul Crowley7ec733f2015-05-19 12:42:00 +01002732 @Override
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002733 public void destroyUserKey(int userId) {
2734 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002735
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002736 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002737 mVold.destroyUserKey(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002738 } catch (Exception e) {
2739 Slog.wtf(TAG, e);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002740 }
2741 }
2742
Jeff Sharkey43e12112017-09-12 16:31:45 -06002743 private String encodeBytes(byte[] bytes) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002744 if (ArrayUtils.isEmpty(bytes)) {
Jeff Sharkey43e12112017-09-12 16:31:45 -06002745 return "!";
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002746 } else {
Jeff Sharkey43e12112017-09-12 16:31:45 -06002747 return HexDump.toHexString(bytes);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002748 }
2749 }
2750
Paul Crowleycc701552016-05-17 14:18:49 -07002751 /*
2752 * Add this token/secret pair to the set of ways we can recover a disk encryption key.
2753 * Changing the token/secret for a disk encryption key is done in two phases: first, adding
2754 * a new token/secret pair with this call, then delting all other pairs with
2755 * fixateNewestUserKeyAuth. This allows other places where a credential is used, such as
2756 * Gatekeeper, to be updated between the two calls.
2757 */
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002758 @Override
Paul Crowleycc701552016-05-17 14:18:49 -07002759 public void addUserKeyAuth(int userId, int serialNumber, byte[] token, byte[] secret) {
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002760 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002761
2762 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002763 mVold.addUserKeyAuth(userId, serialNumber, encodeBytes(token), encodeBytes(secret));
Jeff Sharkey43e12112017-09-12 16:31:45 -06002764 } catch (Exception e) {
2765 Slog.wtf(TAG, e);
Paul Crowleycc701552016-05-17 14:18:49 -07002766 }
2767 }
2768
2769 /*
2770 * Delete all disk encryption token/secret pairs except the most recently added one
2771 */
2772 @Override
2773 public void fixateNewestUserKeyAuth(int userId) {
2774 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Paul Crowleycc701552016-05-17 14:18:49 -07002775
2776 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002777 mVold.fixateNewestUserKeyAuth(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002778 } catch (Exception e) {
2779 Slog.wtf(TAG, e);
Paul Crowleyfaeb3eb2016-02-08 15:58:29 +00002780 }
2781 }
2782
2783 @Override
2784 public void unlockUserKey(int userId, int serialNumber, byte[] token, byte[] secret) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002785 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002786
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002787 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
Rubin Xu3bf722a2016-12-15 16:07:38 +00002788 // When a user has secure lock screen, require secret to actually unlock.
2789 // This check is mostly in place for emulation mode.
2790 if (mLockPatternUtils.isSecure(userId) && ArrayUtils.isEmpty(secret)) {
2791 throw new IllegalStateException("Secret required to unlock secure user " + userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002792 }
Jeff Sharkeyb9fe5372015-12-03 15:23:08 -07002793
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002794 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002795 mVold.unlockUserKey(userId, serialNumber, encodeBytes(token),
2796 encodeBytes(secret));
Jeff Sharkey43e12112017-09-12 16:31:45 -06002797 } catch (Exception e) {
2798 Slog.wtf(TAG, e);
2799 return;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002800 }
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002801 }
2802
2803 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002804 mLocalUnlockedUsers = ArrayUtils.appendInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002805 }
2806 }
2807
2808 @Override
2809 public void lockUserKey(int userId) {
2810 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002811
2812 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002813 mVold.lockUserKey(userId);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002814 } catch (Exception e) {
2815 Slog.wtf(TAG, e);
2816 return;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002817 }
2818
2819 synchronized (mLock) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002820 mLocalUnlockedUsers = ArrayUtils.removeInt(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002821 }
2822 }
2823
2824 @Override
2825 public boolean isUserKeyUnlocked(int userId) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002826 synchronized (mLock) {
2827 return ArrayUtils.contains(mLocalUnlockedUsers, userId);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002828 }
2829 }
2830
2831 @Override
Jeff Sharkey47f71082016-02-01 17:03:54 -07002832 public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002833 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08002834
2835 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002836 mVold.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002837 } catch (Exception e) {
2838 Slog.wtf(TAG, e);
Paul Crowley7ec733f2015-05-19 12:42:00 +01002839 }
2840 }
2841
Paul Crowleybcf48ed2015-04-22 13:36:59 +01002842 @Override
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002843 public void destroyUserStorage(String volumeUuid, int userId, int flags) {
2844 enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002845
2846 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002847 mVold.destroyUserStorage(volumeUuid, userId, flags);
Jeff Sharkey43e12112017-09-12 16:31:45 -06002848 } catch (Exception e) {
2849 Slog.wtf(TAG, e);
Jeff Sharkeyfcf1e552016-04-14 20:44:58 -06002850 }
2851 }
2852
Daichi Hironoe56740d2017-02-02 13:56:45 +09002853 class AppFuseMountScope extends AppFuseBridge.MountScope {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002854 boolean opened = false;
2855
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002856 public AppFuseMountScope(int uid, int mountId) {
2857 super(uid, mountId);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002858 }
2859
2860 @Override
2861 public ParcelFileDescriptor open() throws NativeDaemonConnectorException {
Jeff Sharkey54402792017-09-15 16:05:19 -06002862 try {
2863 return new ParcelFileDescriptor(
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002864 mVold.mountAppFuse(uid, mountId));
Jeff Sharkey54402792017-09-15 16:05:19 -06002865 } catch (Exception e) {
2866 throw new NativeDaemonConnectorException("Failed to mount", e);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002867 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002868 }
2869
2870 @Override
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002871 public ParcelFileDescriptor openFile(int mountId, int fileId, int flags)
2872 throws NativeDaemonConnectorException {
2873 try {
2874 return new ParcelFileDescriptor(
2875 mVold.openAppFuseFile(uid, mountId, fileId, flags));
2876 } catch (Exception e) {
2877 throw new NativeDaemonConnectorException("Failed to open", e);
2878 }
2879 }
2880
2881 @Override
Daichi Hironoe56740d2017-02-02 13:56:45 +09002882 public void close() throws Exception {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002883 if (opened) {
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002884 mVold.unmountAppFuse(uid, mountId);
Daichi Hirono812c95d2017-02-08 16:20:20 +09002885 opened = false;
2886 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002887 }
2888 }
2889
2890 @Override
Daichi Hirono812c95d2017-02-08 16:20:20 +09002891 public @Nullable AppFuseMount mountProxyFileDescriptorBridge() {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002892 Slog.v(TAG, "mountProxyFileDescriptorBridge");
Daichi Hirono9fb00182016-11-08 14:12:17 +09002893 final int uid = Binder.getCallingUid();
Daichi Hirono9fb00182016-11-08 14:12:17 +09002894
Daichi Hironoe56740d2017-02-02 13:56:45 +09002895 while (true) {
2896 synchronized (mAppFuseLock) {
2897 boolean newlyCreated = false;
2898 if (mAppFuseBridge == null) {
2899 mAppFuseBridge = new AppFuseBridge();
2900 new Thread(mAppFuseBridge, AppFuseBridge.TAG).start();
2901 newlyCreated = true;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002902 }
Daichi Hironoe56740d2017-02-02 13:56:45 +09002903 try {
2904 final int name = mNextAppFuseName++;
2905 try {
2906 return new AppFuseMount(
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002907 name, mAppFuseBridge.addBridge(new AppFuseMountScope(uid, name)));
Daichi Hirono812c95d2017-02-08 16:20:20 +09002908 } catch (FuseUnavailableMountException e) {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002909 if (newlyCreated) {
2910 // If newly created bridge fails, it's a real error.
Daichi Hirono812c95d2017-02-08 16:20:20 +09002911 Slog.e(TAG, "", e);
2912 return null;
Daichi Hironoe56740d2017-02-02 13:56:45 +09002913 }
2914 // It seems the thread of mAppFuseBridge has already been terminated.
2915 mAppFuseBridge = null;
2916 }
2917 } catch (NativeDaemonConnectorException e) {
2918 throw e.rethrowAsParcelableException();
2919 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002920 }
Daichi Hirono9fb00182016-11-08 14:12:17 +09002921 }
2922 }
2923
2924 @Override
Daichi Hirono812c95d2017-02-08 16:20:20 +09002925 public @Nullable ParcelFileDescriptor openProxyFileDescriptor(
2926 int mountId, int fileId, int mode) {
2927 Slog.v(TAG, "mountProxyFileDescriptor");
Jeff Sharkey39466322018-12-05 19:19:52 -07002928
2929 // We only support a narrow set of incoming mode flags
Jeff Sharkey3b1c2542018-12-13 15:01:38 -07002930 mode &= MODE_READ_WRITE;
Jeff Sharkey39466322018-12-05 19:19:52 -07002931
Daichi Hirono9fb00182016-11-08 14:12:17 +09002932 try {
2933 synchronized (mAppFuseLock) {
Daichi Hironoe56740d2017-02-02 13:56:45 +09002934 if (mAppFuseBridge == null) {
Daichi Hirono812c95d2017-02-08 16:20:20 +09002935 Slog.e(TAG, "FuseBridge has not been created");
2936 return null;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002937 }
Ryo Hashimoto38bcbf02018-05-16 18:20:37 +09002938 return mAppFuseBridge.openFile(mountId, fileId, mode);
Daichi Hirono9fb00182016-11-08 14:12:17 +09002939 }
Daichi Hirono812c95d2017-02-08 16:20:20 +09002940 } catch (FuseUnavailableMountException | InterruptedException error) {
2941 Slog.v(TAG, "The mount point has already been invalid", error);
2942 return null;
Daichi Hirono9fb00182016-11-08 14:12:17 +09002943 }
2944 }
2945
Daichi Hirono9e8d9e22015-11-13 14:37:00 +09002946 @Override
Jeff Sharkeyae266462017-11-27 13:32:24 -07002947 public void mkdirs(String callingPkg, String appPath) {
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002948 final int userId = UserHandle.getUserId(Binder.getCallingUid());
2949 final UserEnvironment userEnv = new UserEnvironment(userId);
Farid Zare Seisanac094512018-04-02 15:06:13 -07002950 final String propertyName = "sys.user." + userId + ".ce_available";
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002951
Jeff Sharkey196c7552018-03-26 15:56:50 -06002952 // Ignore requests to create directories while storage is locked
Farid Zare Seisanac094512018-04-02 15:06:13 -07002953 if (!isUserKeyUnlocked(userId)) {
2954 throw new IllegalStateException("Failed to prepare " + appPath);
2955 }
2956
2957 // Ignore requests to create directories if CE storage is not available
Farid Zare Seisan7f6b8122018-03-30 11:19:10 -07002958 if ((userId == UserHandle.USER_SYSTEM)
2959 && !SystemProperties.getBoolean(propertyName, false)) {
Farid Zare Seisanac094512018-04-02 15:06:13 -07002960 throw new IllegalStateException("Failed to prepare " + appPath);
2961 }
Jeff Sharkey196c7552018-03-26 15:56:50 -06002962
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002963 // Validate that reported package name belongs to caller
2964 final AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(
2965 Context.APP_OPS_SERVICE);
2966 appOps.checkPackage(Binder.getCallingUid(), callingPkg);
2967
Jeff Sharkey48877892015-03-18 11:27:19 -07002968 File appFile = null;
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002969 try {
Jeff Sharkey48877892015-03-18 11:27:19 -07002970 appFile = new File(appPath).getCanonicalFile();
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002971 } catch (IOException e) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002972 throw new IllegalStateException("Failed to resolve " + appPath + ": " + e);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002973 }
2974
2975 // Try translating the app path into a vold path, but require that it
2976 // belong to the calling package.
Jeff Sharkey48877892015-03-18 11:27:19 -07002977 if (FileUtils.contains(userEnv.buildExternalStorageAppDataDirs(callingPkg), appFile) ||
2978 FileUtils.contains(userEnv.buildExternalStorageAppObbDirs(callingPkg), appFile) ||
2979 FileUtils.contains(userEnv.buildExternalStorageAppMediaDirs(callingPkg), appFile)) {
2980 appPath = appFile.getAbsolutePath();
2981 if (!appPath.endsWith("/")) {
2982 appPath = appPath + "/";
2983 }
2984
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002985 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06002986 mVold.mkdirs(appPath);
Jeff Sharkey27a108c2017-11-30 17:11:40 -07002987 return;
Jeff Sharkeyace874b2017-09-07 15:27:33 -06002988 } catch (Exception e) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002989 throw new IllegalStateException("Failed to prepare " + appPath + ": " + e);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002990 }
2991 }
2992
Jeff Sharkey48877892015-03-18 11:27:19 -07002993 throw new SecurityException("Invalid mkdirs path: " + appFile);
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002994 }
2995
2996 @Override
Jeff Sharkey46349872015-07-28 10:49:47 -07002997 public StorageVolume[] getVolumeList(int uid, String packageName, int flags) {
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07002998 final int userId = UserHandle.getUserId(uid);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06002999
Jeff Sharkey46349872015-07-28 10:49:47 -07003000 final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0;
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003001 final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0;
3002 final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0;
Jeff Sharkey46349872015-07-28 10:49:47 -07003003
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003004 final boolean userKeyUnlocked;
3005 final boolean storagePermission;
3006 final long token = Binder.clearCallingIdentity();
Svetoslav38c3dbb2015-07-14 11:27:06 -07003007 try {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003008 userKeyUnlocked = isUserKeyUnlocked(userId);
Sudheer Shanka2250d562016-11-07 15:41:02 -08003009 storagePermission = mStorageManagerInternal.hasExternalStorage(uid, packageName);
Svetoslav38c3dbb2015-07-14 11:27:06 -07003010 } finally {
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003011 Binder.restoreCallingIdentity(token);
Svetoslav38c3dbb2015-07-14 11:27:06 -07003012 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003013
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003014 boolean foundPrimary = false;
3015
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003016 final ArrayList<StorageVolume> res = new ArrayList<>();
Jeff Sharkey48877892015-03-18 11:27:19 -07003017 synchronized (mLock) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003018 for (int i = 0; i < mVolumes.size(); i++) {
3019 final VolumeInfo vol = mVolumes.valueAt(i);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003020 switch (vol.getType()) {
3021 case VolumeInfo.TYPE_PUBLIC:
Risan05c41e62018-10-29 08:57:43 +09003022 case VolumeInfo.TYPE_STUB:
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003023 case VolumeInfo.TYPE_EMULATED:
3024 break;
3025 default:
3026 continue;
3027 }
3028
3029 boolean match = false;
3030 if (forWrite) {
3031 match = vol.isVisibleForWrite(userId);
3032 } else {
Felipe Leme123a0e72016-06-10 11:09:11 -07003033 match = vol.isVisibleForRead(userId)
3034 || (includeInvisible && vol.getPath() != null);
Jeff Sharkeyc02bfae2016-03-27 15:06:53 -06003035 }
3036 if (!match) continue;
3037
3038 boolean reportUnmounted = false;
3039 if ((vol.getType() == VolumeInfo.TYPE_EMULATED) && !userKeyUnlocked) {
3040 reportUnmounted = true;
3041 } else if (!storagePermission && !realState) {
3042 reportUnmounted = true;
3043 }
3044
3045 final StorageVolume userVol = vol.buildStorageVolume(mContext, userId,
3046 reportUnmounted);
3047 if (vol.isPrimary()) {
3048 res.add(0, userVol);
3049 foundPrimary = true;
3050 } else {
3051 res.add(userVol);
Jeff Sharkeyb049e212012-09-07 23:16:01 -07003052 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003053 }
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003054 }
Jeff Sharkey48877892015-03-18 11:27:19 -07003055
3056 if (!foundPrimary) {
Jeff Sharkey11697f52018-12-13 10:14:42 -07003057 Slog.w(TAG, "No primary storage defined yet; hacking together a stub");
Jeff Sharkey48877892015-03-18 11:27:19 -07003058
3059 final boolean primaryPhysical = SystemProperties.getBoolean(
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003060 StorageManager.PROP_PRIMARY_PHYSICAL, false);
Jeff Sharkey48877892015-03-18 11:27:19 -07003061
3062 final String id = "stub_primary";
3063 final File path = Environment.getLegacyExternalStorageDirectory();
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003064 final String description = mContext.getString(android.R.string.unknownName);
Jeff Sharkey48877892015-03-18 11:27:19 -07003065 final boolean primary = true;
3066 final boolean removable = primaryPhysical;
3067 final boolean emulated = !primaryPhysical;
Jeff Sharkey48877892015-03-18 11:27:19 -07003068 final boolean allowMassStorage = false;
3069 final long maxFileSize = 0L;
3070 final UserHandle owner = new UserHandle(userId);
3071 final String uuid = null;
Jeff Sharkey48877892015-03-18 11:27:19 -07003072 final String state = Environment.MEDIA_REMOVED;
3073
Jerry Zhang71938e12018-05-10 18:28:29 -07003074 res.add(0, new StorageVolume(id, path, path,
Jerry Zhangf9c5c252017-08-16 18:07:51 -07003075 description, primary, removable, emulated,
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003076 allowMassStorage, maxFileSize, owner, uuid, state));
Jeff Sharkey48877892015-03-18 11:27:19 -07003077 }
3078
3079 return res.toArray(new StorageVolume[res.size()]);
Mike Lockwood8fa5f802011-03-24 08:12:30 -07003080 }
3081
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003082 @Override
3083 public DiskInfo[] getDisks() {
3084 synchronized (mLock) {
3085 final DiskInfo[] res = new DiskInfo[mDisks.size()];
3086 for (int i = 0; i < mDisks.size(); i++) {
3087 res[i] = mDisks.valueAt(i);
3088 }
3089 return res;
3090 }
3091 }
3092
3093 @Override
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003094 public VolumeInfo[] getVolumes(int flags) {
Jeff Sharkey1b8ef7e2015-04-03 17:14:45 -07003095 synchronized (mLock) {
3096 final VolumeInfo[] res = new VolumeInfo[mVolumes.size()];
3097 for (int i = 0; i < mVolumes.size(); i++) {
3098 res[i] = mVolumes.valueAt(i);
3099 }
3100 return res;
3101 }
3102 }
3103
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003104 @Override
3105 public VolumeRecord[] getVolumeRecords(int flags) {
3106 synchronized (mLock) {
3107 final VolumeRecord[] res = new VolumeRecord[mRecords.size()];
3108 for (int i = 0; i < mRecords.size(); i++) {
3109 res[i] = mRecords.valueAt(i);
3110 }
3111 return res;
3112 }
3113 }
3114
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003115 @Override
3116 public long getCacheQuotaBytes(String volumeUuid, int uid) {
3117 if (uid != Binder.getCallingUid()) {
3118 mContext.enforceCallingPermission(android.Manifest.permission.STORAGE_INTERNAL, TAG);
3119 }
Daniel Nishi80fdb012017-03-09 14:30:07 -08003120 final long token = Binder.clearCallingIdentity();
3121 final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
3122 try {
3123 return stats.getCacheQuotaBytes(volumeUuid, uid);
3124 } finally {
3125 Binder.restoreCallingIdentity(token);
3126 }
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003127 }
3128
3129 @Override
3130 public long getCacheSizeBytes(String volumeUuid, int uid) {
3131 if (uid != Binder.getCallingUid()) {
3132 mContext.enforceCallingPermission(android.Manifest.permission.STORAGE_INTERNAL, TAG);
3133 }
3134 final long token = Binder.clearCallingIdentity();
3135 try {
3136 return mContext.getSystemService(StorageStatsManager.class)
3137 .queryStatsForUid(volumeUuid, uid).getCacheBytes();
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003138 } catch (IOException e) {
3139 throw new ParcelableException(e);
Jeff Sharkey9bed0702017-01-23 20:37:05 -07003140 } finally {
3141 Binder.restoreCallingIdentity(token);
3142 }
3143 }
3144
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003145 private int adjustAllocateFlags(int flags, int callingUid, String callingPackage) {
3146 // Require permission to allocate aggressively
3147 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003148 mContext.enforceCallingOrSelfPermission(
3149 android.Manifest.permission.ALLOCATE_AGGRESSIVE, TAG);
3150 }
3151
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003152 // Apps normally can't directly defy reserved space
3153 flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_ALL_RESERVED;
3154 flags &= ~StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
3155
3156 // However, if app is actively using the camera, then we're willing to
3157 // clear up to half of the reserved cache space, since the user might be
3158 // trying to capture an important memory.
3159 final AppOpsManager appOps = mContext.getSystemService(AppOpsManager.class);
3160 final long token = Binder.clearCallingIdentity();
3161 try {
3162 if (appOps.isOperationActive(AppOpsManager.OP_CAMERA, callingUid, callingPackage)) {
3163 Slog.d(TAG, "UID " + callingUid + " is actively using camera;"
3164 + " letting them defy reserved cached data");
3165 flags |= StorageManager.FLAG_ALLOCATE_DEFY_HALF_RESERVED;
3166 }
3167 } finally {
3168 Binder.restoreCallingIdentity(token);
3169 }
3170
3171 return flags;
3172 }
3173
3174 @Override
3175 public long getAllocatableBytes(String volumeUuid, int flags, String callingPackage) {
3176 flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
3177
3178 final StorageManager storage = mContext.getSystemService(StorageManager.class);
3179 final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003180 final long token = Binder.clearCallingIdentity();
3181 try {
3182 // In general, apps can allocate as much space as they want, except
3183 // we never let them eat into either the minimum cache space or into
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003184 // the low disk warning space. To avoid user confusion, this logic
3185 // should be kept in sync with getFreeBytes().
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003186 final File path = storage.findPathForUuid(volumeUuid);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003187
3188 final long usable = path.getUsableSpace();
3189 final long lowReserved = storage.getStorageLowBytes(path);
3190 final long fullReserved = storage.getStorageFullBytes(path);
3191
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003192 if (stats.isQuotaSupported(volumeUuid)) {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003193 final long cacheTotal = stats.getCacheBytes(volumeUuid);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003194 final long cacheReserved = storage.getStorageCacheBytes(path, flags);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003195 final long cacheClearable = Math.max(0, cacheTotal - cacheReserved);
3196
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003197 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
3198 return Math.max(0, (usable + cacheClearable) - fullReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003199 } else {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003200 return Math.max(0, (usable + cacheClearable) - lowReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003201 }
3202 } else {
3203 // When we don't have fast quota information, we ignore cached
3204 // data and only consider unused bytes.
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003205 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003206 return Math.max(0, usable - fullReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003207 } else {
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003208 return Math.max(0, usable - lowReserved);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003209 }
3210 }
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003211 } catch (IOException e) {
3212 throw new ParcelableException(e);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003213 } finally {
3214 Binder.restoreCallingIdentity(token);
3215 }
Jeff Sharkey500ce9e2017-02-12 02:39:24 -07003216 }
3217
3218 @Override
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003219 public void allocateBytes(String volumeUuid, long bytes, int flags, String callingPackage) {
3220 flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003221
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003222 final long allocatableBytes = getAllocatableBytes(volumeUuid, flags, callingPackage);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003223 if (bytes > allocatableBytes) {
3224 throw new ParcelableException(new IOException("Failed to allocate " + bytes
3225 + " because only " + allocatableBytes + " allocatable"));
3226 }
3227
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003228 final StorageManager storage = mContext.getSystemService(StorageManager.class);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003229 final long token = Binder.clearCallingIdentity();
3230 try {
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003231 // Free up enough disk space to satisfy both the requested allocation
3232 // and our low disk warning space.
3233 final File path = storage.findPathForUuid(volumeUuid);
Jeff Sharkeyddff8072017-05-26 13:10:46 -06003234 if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
3235 bytes += storage.getStorageFullBytes(path);
3236 } else {
3237 bytes += storage.getStorageLowBytes(path);
3238 }
Jeff Sharkey789a8fc2017-04-16 13:18:35 -06003239
Jeff Sharkey5790af02018-08-13 17:42:54 -06003240 mPmInternal.freeStorage(volumeUuid, bytes, flags);
Jeff Sharkeyd5d5e922017-02-21 10:51:23 -07003241 } catch (IOException e) {
3242 throw new ParcelableException(e);
3243 } finally {
3244 Binder.restoreCallingIdentity(token);
Jeff Sharkey500ce9e2017-02-12 02:39:24 -07003245 }
3246 }
3247
Sudheer Shankaff971bc2018-12-13 17:39:59 -08003248 private IAppOpsCallback.Stub mAppOpsCallback = new IAppOpsCallback.Stub() {
3249 @Override
3250 public void opChanged(int op, int uid, String packageName) throws RemoteException {
3251 if (!ENABLE_ISOLATED_STORAGE) return;
3252
3253 remountUidExternalStorage(uid, getMountMode(uid, packageName));
3254 }
3255 };
3256
Jeff Sharkey5790af02018-08-13 17:42:54 -06003257 private static final Pattern PATTERN_TRANSLATE = Pattern.compile(
3258 "(?i)^(/storage/[^/]+/(?:[0-9]+/)?)(.*)");
3259
3260 @Override
Sudheer Shanka87915d62018-11-06 10:57:35 -08003261 public String translateAppToSystem(String path, int pid, int uid) {
3262 return translateInternal(path, pid, uid, true);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003263 }
3264
3265 @Override
Sudheer Shanka87915d62018-11-06 10:57:35 -08003266 public String translateSystemToApp(String path, int pid, int uid) {
3267 return translateInternal(path, pid, uid, false);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003268 }
3269
Sudheer Shanka87915d62018-11-06 10:57:35 -08003270 private String translateInternal(String path, int pid, int uid, boolean toSystem) {
Jeff Sharkey5790af02018-08-13 17:42:54 -06003271 if (!ENABLE_ISOLATED_STORAGE) return path;
3272
3273 if (path.contains("/../")) {
3274 throw new SecurityException("Shady looking path " + path);
3275 }
3276
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003277 final int mountMode = mAmInternal.getStorageMountMode(pid, uid);
3278 if (mountMode == Zygote.MOUNT_EXTERNAL_FULL) {
Sudheer Shanka87915d62018-11-06 10:57:35 -08003279 return path;
3280 }
Jeff Sharkey5790af02018-08-13 17:42:54 -06003281
3282 final Matcher m = PATTERN_TRANSLATE.matcher(path);
3283 if (m.matches()) {
3284 final String device = m.group(1);
3285 final String devicePath = m.group(2);
3286
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003287 if (mountMode == Zygote.MOUNT_EXTERNAL_INSTALLER
3288 && devicePath.startsWith("Android/obb/")) {
3289 return path;
3290 }
3291
Jeff Sharkey5790af02018-08-13 17:42:54 -06003292 // Does path belong to any packages belonging to this UID? If so,
3293 // they get to go straight through to legacy paths.
Sudheer Shanka87915d62018-11-06 10:57:35 -08003294 final String[] pkgs = mContext.getPackageManager().getPackagesForUid(uid);
Jeff Sharkey5790af02018-08-13 17:42:54 -06003295 for (String pkg : pkgs) {
3296 if (devicePath.startsWith("Android/data/" + pkg + "/") ||
3297 devicePath.startsWith("Android/media/" + pkg + "/") ||
3298 devicePath.startsWith("Android/obb/" + pkg + "/")) {
3299 return path;
3300 }
3301 }
3302
Sudheer Shanka87915d62018-11-06 10:57:35 -08003303 final String sharedUserId = mPmInternal.getSharedUserIdForPackage(pkgs[0]);
3304 final String sandboxId = getSandboxId(pkgs[0], sharedUserId);
3305
Jeff Sharkey5790af02018-08-13 17:42:54 -06003306 if (toSystem) {
3307 // Everything else goes into sandbox.
Sudheer Shanka31ad0a12018-10-20 20:59:00 -07003308 return device + "Android/sandbox/" + sandboxId + "/" + devicePath;
Jeff Sharkey5790af02018-08-13 17:42:54 -06003309 } else {
3310 // Does path belong to this sandbox? If so, leave sandbox.
Sudheer Shanka31ad0a12018-10-20 20:59:00 -07003311 final String sandboxPrefix = "Android/sandbox/" + sandboxId + "/";
Jeff Sharkey5790af02018-08-13 17:42:54 -06003312 if (devicePath.startsWith(sandboxPrefix)) {
3313 return device + devicePath.substring(sandboxPrefix.length());
3314 }
3315
3316 // Path isn't valid inside sandbox!
3317 throw new SecurityException(
3318 "Path " + path + " isn't valid inside sandbox " + sandboxId);
3319 }
3320 }
3321
3322 return path;
3323 }
3324
Kenny Rootaf9d6672010-10-08 09:21:39 -07003325 private void addObbStateLocked(ObbState obbState) throws RemoteException {
3326 final IBinder binder = obbState.getBinder();
3327 List<ObbState> obbStates = mObbMounts.get(binder);
Kenny Root5919ac62010-10-05 09:49:40 -07003328
Kenny Rootaf9d6672010-10-08 09:21:39 -07003329 if (obbStates == null) {
3330 obbStates = new ArrayList<ObbState>();
3331 mObbMounts.put(binder, obbStates);
3332 } else {
3333 for (final ObbState o : obbStates) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003334 if (o.rawPath.equals(obbState.rawPath)) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003335 throw new IllegalStateException("Attempt to add ObbState twice. "
Sudheer Shanka2250d562016-11-07 15:41:02 -08003336 + "This indicates an error in the StorageManagerService logic.");
Kenny Root5919ac62010-10-05 09:49:40 -07003337 }
3338 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003339 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003340
3341 obbStates.add(obbState);
3342 try {
3343 obbState.link();
3344 } catch (RemoteException e) {
3345 /*
3346 * The binder died before we could link it, so clean up our state
3347 * and return failure.
3348 */
3349 obbStates.remove(obbState);
3350 if (obbStates.isEmpty()) {
3351 mObbMounts.remove(binder);
3352 }
3353
3354 // Rethrow the error so mountObb can get it
3355 throw e;
3356 }
3357
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003358 mObbPathToStateMap.put(obbState.rawPath, obbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003359 }
3360
Kenny Rootaf9d6672010-10-08 09:21:39 -07003361 private void removeObbStateLocked(ObbState obbState) {
3362 final IBinder binder = obbState.getBinder();
3363 final List<ObbState> obbStates = mObbMounts.get(binder);
3364 if (obbStates != null) {
3365 if (obbStates.remove(obbState)) {
3366 obbState.unlink();
Kenny Root05105f72010-09-22 17:29:43 -07003367 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003368 if (obbStates.isEmpty()) {
3369 mObbMounts.remove(binder);
3370 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003371 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003372
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003373 mObbPathToStateMap.remove(obbState.rawPath);
Kenny Root38cf8862010-09-26 14:18:51 -07003374 }
3375
Kenny Roota02b8b02010-08-05 16:14:17 -07003376 private class ObbActionHandler extends Handler {
Kenny Roota02b8b02010-08-05 16:14:17 -07003377
3378 ObbActionHandler(Looper l) {
3379 super(l);
3380 }
3381
3382 @Override
3383 public void handleMessage(Message msg) {
3384 switch (msg.what) {
3385 case OBB_RUN_ACTION: {
Kenny Root480afe72010-10-07 10:17:50 -07003386 final ObbAction action = (ObbAction) msg.obj;
Kenny Roota02b8b02010-08-05 16:14:17 -07003387
3388 if (DEBUG_OBB)
3389 Slog.i(TAG, "OBB_RUN_ACTION: " + action.toString());
3390
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003391 action.execute(this);
Kenny Roota02b8b02010-08-05 16:14:17 -07003392 break;
3393 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003394 case OBB_FLUSH_MOUNT_STATE: {
3395 final String path = (String) msg.obj;
3396
3397 if (DEBUG_OBB)
3398 Slog.i(TAG, "Flushing all OBB state for path " + path);
3399
3400 synchronized (mObbMounts) {
3401 final List<ObbState> obbStatesToRemove = new LinkedList<ObbState>();
3402
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003403 final Iterator<ObbState> i = mObbPathToStateMap.values().iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003404 while (i.hasNext()) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003405 final ObbState state = i.next();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003406
3407 /*
3408 * If this entry's source file is in the volume path
3409 * that got unmounted, remove it because it's no
3410 * longer valid.
3411 */
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003412 if (state.canonicalPath.startsWith(path)) {
3413 obbStatesToRemove.add(state);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003414 }
3415 }
3416
3417 for (final ObbState obbState : obbStatesToRemove) {
3418 if (DEBUG_OBB)
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003419 Slog.i(TAG, "Removing state for " + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003420
3421 removeObbStateLocked(obbState);
3422
3423 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003424 obbState.token.onObbResult(obbState.rawPath, obbState.nonce,
Kenny Rootaf9d6672010-10-08 09:21:39 -07003425 OnObbStateChangeListener.UNMOUNTED);
3426 } catch (RemoteException e) {
3427 Slog.i(TAG, "Couldn't send unmount notification for OBB: "
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003428 + obbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003429 }
3430 }
3431 }
3432 break;
3433 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003434 }
3435 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003436 }
3437
Jeff Sharkey0095a822018-02-15 13:06:53 -07003438 private static class ObbException extends Exception {
3439 public final int status;
3440
3441 public ObbException(int status, String message) {
3442 super(message);
3443 this.status = status;
3444 }
3445
3446 public ObbException(int status, Throwable cause) {
3447 super(cause.getMessage(), cause);
3448 this.status = status;
3449 }
3450 }
3451
Kenny Roota02b8b02010-08-05 16:14:17 -07003452 abstract class ObbAction {
Kenny Roota02b8b02010-08-05 16:14:17 -07003453
3454 ObbState mObbState;
3455
3456 ObbAction(ObbState obbState) {
3457 mObbState = obbState;
3458 }
3459
3460 public void execute(ObbActionHandler handler) {
3461 try {
3462 if (DEBUG_OBB)
Ben Komalo444eca22011-09-01 15:17:44 -07003463 Slog.i(TAG, "Starting to execute action: " + toString());
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003464 handleExecute();
Jeff Sharkey0095a822018-02-15 13:06:53 -07003465 } catch (ObbException e) {
3466 notifyObbStateChange(e);
Kenny Roota02b8b02010-08-05 16:14:17 -07003467 }
3468 }
3469
Jeff Sharkey0095a822018-02-15 13:06:53 -07003470 abstract void handleExecute() throws ObbException;
Kenny Root38cf8862010-09-26 14:18:51 -07003471
Jeff Sharkey0095a822018-02-15 13:06:53 -07003472 protected void notifyObbStateChange(ObbException e) {
3473 Slog.w(TAG, e);
3474 notifyObbStateChange(e.status);
3475 }
3476
3477 protected void notifyObbStateChange(int status) {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003478 if (mObbState == null || mObbState.token == null) {
3479 return;
3480 }
3481
Kenny Root38cf8862010-09-26 14:18:51 -07003482 try {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003483 mObbState.token.onObbResult(mObbState.rawPath, mObbState.nonce, status);
Kenny Root38cf8862010-09-26 14:18:51 -07003484 } catch (RemoteException e) {
Sudheer Shanka2250d562016-11-07 15:41:02 -08003485 Slog.w(TAG, "StorageEventListener went away while calling onObbStateChanged");
Kenny Root38cf8862010-09-26 14:18:51 -07003486 }
3487 }
Kenny Roota02b8b02010-08-05 16:14:17 -07003488 }
3489
3490 class MountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003491 private final String mKey;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003492 private final int mCallingUid;
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003493 private ObbInfo mObbInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -07003494
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003495 MountObbAction(ObbState obbState, String key, int callingUid, ObbInfo obbInfo) {
Kenny Roota02b8b02010-08-05 16:14:17 -07003496 super(obbState);
3497 mKey = key;
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003498 mCallingUid = callingUid;
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003499 mObbInfo = obbInfo;
Kenny Roota02b8b02010-08-05 16:14:17 -07003500 }
3501
Jason parks5af0b912010-11-29 09:05:25 -06003502 @Override
Jeff Sharkey0095a822018-02-15 13:06:53 -07003503 public void handleExecute() throws ObbException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003504 warnOnNotMounted();
3505
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003506 if (!isUidOwnerOfPackageOrSystem(mObbInfo.packageName, mCallingUid)) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003507 throw new ObbException(ERROR_PERMISSION_DENIED, "Denied attempt to mount OBB "
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003508 + mObbInfo.filename + " which is owned by " + mObbInfo.packageName);
Kenny Roota02b8b02010-08-05 16:14:17 -07003509 }
3510
Kenny Rootaf9d6672010-10-08 09:21:39 -07003511 final boolean isMounted;
3512 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003513 isMounted = mObbPathToStateMap.containsKey(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003514 }
3515 if (isMounted) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003516 throw new ObbException(ERROR_ALREADY_MOUNTED,
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003517 "Attempt to mount OBB which is already mounted: " + mObbInfo.filename);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003518 }
3519
Kenny Rootaf9d6672010-10-08 09:21:39 -07003520 final String hashedKey;
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003521 final String binderKey;
Kenny Rootaf9d6672010-10-08 09:21:39 -07003522 if (mKey == null) {
3523 hashedKey = "none";
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003524 binderKey = "";
Kenny Rootaf9d6672010-10-08 09:21:39 -07003525 } else {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003526 try {
Kenny Root3b1abba2010-10-13 15:00:07 -07003527 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
3528
Sudheer Shanka25469aa2018-08-27 15:50:23 -07003529 KeySpec ks = new PBEKeySpec(mKey.toCharArray(), mObbInfo.salt,
Kenny Root3b1abba2010-10-13 15:00:07 -07003530 PBKDF2_HASH_ROUNDS, CRYPTO_ALGORITHM_KEY_SIZE);
3531 SecretKey key = factory.generateSecret(ks);
3532 BigInteger bi = new BigInteger(key.getEncoded());
3533 hashedKey = bi.toString(16);
Jeff Sharkey41cd6812017-09-11 10:32:17 -06003534 binderKey = hashedKey;
Jeff Sharkey0095a822018-02-15 13:06:53 -07003535 } catch (GeneralSecurityException e) {
3536 throw new ObbException(ERROR_INTERNAL, e);
Kenny Root38cf8862010-09-26 14:18:51 -07003537 }
Kenny Rootaf9d6672010-10-08 09:21:39 -07003538 }
Kenny Root38cf8862010-09-26 14:18:51 -07003539
Kenny Rootaf9d6672010-10-08 09:21:39 -07003540 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06003541 mObbState.volId = mVold.createObb(mObbState.canonicalPath, binderKey,
3542 mObbState.ownerGid);
3543 mVold.mount(mObbState.volId, 0, -1);
Kenny Roota02b8b02010-08-05 16:14:17 -07003544
Kenny Rootaf9d6672010-10-08 09:21:39 -07003545 if (DEBUG_OBB)
Xiaohui Chen621b3fc2015-10-02 14:41:42 -07003546 Slog.d(TAG, "Successfully mounted OBB " + mObbState.canonicalPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003547
3548 synchronized (mObbMounts) {
3549 addObbStateLocked(mObbState);
3550 }
3551
Jeff Sharkey0095a822018-02-15 13:06:53 -07003552 notifyObbStateChange(MOUNTED);
3553 } catch (Exception e) {
3554 throw new ObbException(ERROR_COULD_NOT_MOUNT, e);
Kenny Root02c87302010-07-01 08:10:18 -07003555 }
3556 }
3557
Jason parks5af0b912010-11-29 09:05:25 -06003558 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003559 public String toString() {
3560 StringBuilder sb = new StringBuilder();
3561 sb.append("MountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003562 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003563 sb.append('}');
3564 return sb.toString();
3565 }
3566 }
3567
3568 class UnmountObbAction extends ObbAction {
Ben Komalo444eca22011-09-01 15:17:44 -07003569 private final boolean mForceUnmount;
Kenny Roota02b8b02010-08-05 16:14:17 -07003570
3571 UnmountObbAction(ObbState obbState, boolean force) {
3572 super(obbState);
3573 mForceUnmount = force;
3574 }
3575
Jason parks5af0b912010-11-29 09:05:25 -06003576 @Override
Jeff Sharkey0095a822018-02-15 13:06:53 -07003577 public void handleExecute() throws ObbException {
Kenny Rootaf9d6672010-10-08 09:21:39 -07003578 warnOnNotMounted();
3579
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003580 final ObbState existingState;
Kenny Root38cf8862010-09-26 14:18:51 -07003581 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003582 existingState = mObbPathToStateMap.get(mObbState.rawPath);
Kenny Rootaf9d6672010-10-08 09:21:39 -07003583 }
Kenny Root38cf8862010-09-26 14:18:51 -07003584
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003585 if (existingState == null) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003586 throw new ObbException(ERROR_NOT_MOUNTED, "Missing existingState");
Kenny Rootaf9d6672010-10-08 09:21:39 -07003587 }
3588
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003589 if (existingState.ownerGid != mObbState.ownerGid) {
Jeff Sharkey0095a822018-02-15 13:06:53 -07003590 notifyObbStateChange(new ObbException(ERROR_PERMISSION_DENIED,
3591 "Permission denied to unmount OBB " + existingState.rawPath
3592 + " (owned by GID " + existingState.ownerGid + ")"));
Kenny Rootaf9d6672010-10-08 09:21:39 -07003593 return;
3594 }
3595
Kenny Rootaf9d6672010-10-08 09:21:39 -07003596 try {
Jeff Sharkey54402792017-09-15 16:05:19 -06003597 mVold.unmount(mObbState.volId);
3598 mVold.destroyObb(mObbState.volId);
3599 mObbState.volId = null;
Kenny Roota02b8b02010-08-05 16:14:17 -07003600
Kenny Rootaf9d6672010-10-08 09:21:39 -07003601 synchronized (mObbMounts) {
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003602 removeObbStateLocked(existingState);
Kenny Root38cf8862010-09-26 14:18:51 -07003603 }
3604
Jeff Sharkey0095a822018-02-15 13:06:53 -07003605 notifyObbStateChange(UNMOUNTED);
3606 } catch (Exception e) {
3607 throw new ObbException(ERROR_COULD_NOT_UNMOUNT, e);
Kenny Roota02b8b02010-08-05 16:14:17 -07003608 }
3609 }
3610
Jason parks5af0b912010-11-29 09:05:25 -06003611 @Override
Kenny Roota02b8b02010-08-05 16:14:17 -07003612 public String toString() {
3613 StringBuilder sb = new StringBuilder();
3614 sb.append("UnmountObbAction{");
Jeff Sharkey4fbbda42012-09-24 18:34:07 -07003615 sb.append(mObbState);
Kenny Roota02b8b02010-08-05 16:14:17 -07003616 sb.append(",force=");
3617 sb.append(mForceUnmount);
Kenny Roota02b8b02010-08-05 16:14:17 -07003618 sb.append('}');
3619 return sb.toString();
3620 }
Kenny Root02c87302010-07-01 08:10:18 -07003621 }
Kenny Root38cf8862010-09-26 14:18:51 -07003622
Jeff Sharkey7e19f532017-11-06 13:54:11 -07003623 private void dispatchOnStatus(IVoldTaskListener listener, int status,
3624 PersistableBundle extras) {
3625 if (listener != null) {
3626 try {
3627 listener.onStatus(status, extras);
3628 } catch (RemoteException ignored) {
3629 }
3630 }
3631 }
3632
3633 private void dispatchOnFinished(IVoldTaskListener listener, int status,
3634 PersistableBundle extras) {
3635 if (listener != null) {
3636 try {
3637 listener.onFinished(status, extras);
3638 } catch (RemoteException ignored) {
3639 }
3640 }
3641 }
3642
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003643 private int getMountMode(int uid, String packageName) {
3644 try {
3645 if (Process.isIsolated(uid)) {
3646 return Zygote.MOUNT_EXTERNAL_NONE;
3647 }
3648 if (mIPackageManager.checkUidPermission(WRITE_MEDIA_STORAGE, uid)
3649 == PERMISSION_GRANTED) {
3650 return Zygote.MOUNT_EXTERNAL_FULL;
Jeff Sharkey11697f52018-12-13 10:14:42 -07003651 } else if (mIAppOpsService.checkOperation(OP_LEGACY_STORAGE, uid,
3652 packageName) == MODE_ALLOWED) {
3653 // TODO: define a specific "legacy" mount mode
3654 return Zygote.MOUNT_EXTERNAL_FULL;
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003655 } else if (mIPackageManager.checkUidPermission(INSTALL_PACKAGES, uid)
3656 == PERMISSION_GRANTED || mIAppOpsService.checkOperation(
3657 OP_REQUEST_INSTALL_PACKAGES, uid, packageName) == MODE_ALLOWED) {
3658 return Zygote.MOUNT_EXTERNAL_INSTALLER;
3659 } else {
3660 return Zygote.MOUNT_EXTERNAL_WRITE;
3661 }
3662 } catch (RemoteException e) {
3663 // Should not happen
3664 }
3665 return Zygote.MOUNT_EXTERNAL_NONE;
3666 }
3667
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003668 private static class Callbacks extends Handler {
3669 private static final int MSG_STORAGE_STATE_CHANGED = 1;
3670 private static final int MSG_VOLUME_STATE_CHANGED = 2;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003671 private static final int MSG_VOLUME_RECORD_CHANGED = 3;
3672 private static final int MSG_VOLUME_FORGOTTEN = 4;
3673 private static final int MSG_DISK_SCANNED = 5;
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003674 private static final int MSG_DISK_DESTROYED = 6;
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003675
Sudheer Shanka2250d562016-11-07 15:41:02 -08003676 private final RemoteCallbackList<IStorageEventListener>
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003677 mCallbacks = new RemoteCallbackList<>();
3678
3679 public Callbacks(Looper looper) {
3680 super(looper);
3681 }
3682
Sudheer Shanka2250d562016-11-07 15:41:02 -08003683 public void register(IStorageEventListener callback) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003684 mCallbacks.register(callback);
3685 }
3686
Sudheer Shanka2250d562016-11-07 15:41:02 -08003687 public void unregister(IStorageEventListener callback) {
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003688 mCallbacks.unregister(callback);
3689 }
3690
3691 @Override
3692 public void handleMessage(Message msg) {
3693 final SomeArgs args = (SomeArgs) msg.obj;
3694 final int n = mCallbacks.beginBroadcast();
3695 for (int i = 0; i < n; i++) {
Sudheer Shanka2250d562016-11-07 15:41:02 -08003696 final IStorageEventListener callback = mCallbacks.getBroadcastItem(i);
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003697 try {
3698 invokeCallback(callback, msg.what, args);
3699 } catch (RemoteException ignored) {
3700 }
3701 }
3702 mCallbacks.finishBroadcast();
3703 args.recycle();
3704 }
3705
Sudheer Shanka2250d562016-11-07 15:41:02 -08003706 private void invokeCallback(IStorageEventListener callback, int what, SomeArgs args)
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003707 throws RemoteException {
3708 switch (what) {
3709 case MSG_STORAGE_STATE_CHANGED: {
3710 callback.onStorageStateChanged((String) args.arg1, (String) args.arg2,
3711 (String) args.arg3);
3712 break;
3713 }
3714 case MSG_VOLUME_STATE_CHANGED: {
3715 callback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
3716 break;
3717 }
Jeff Sharkey50a05452015-04-29 11:24:52 -07003718 case MSG_VOLUME_RECORD_CHANGED: {
3719 callback.onVolumeRecordChanged((VolumeRecord) args.arg1);
3720 break;
3721 }
3722 case MSG_VOLUME_FORGOTTEN: {
3723 callback.onVolumeForgotten((String) args.arg1);
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003724 break;
3725 }
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003726 case MSG_DISK_SCANNED: {
3727 callback.onDiskScanned((DiskInfo) args.arg1, args.argi2);
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003728 break;
3729 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003730 case MSG_DISK_DESTROYED: {
3731 callback.onDiskDestroyed((DiskInfo) args.arg1);
3732 break;
3733 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003734 }
3735 }
3736
3737 private void notifyStorageStateChanged(String path, String oldState, String newState) {
3738 final SomeArgs args = SomeArgs.obtain();
3739 args.arg1 = path;
3740 args.arg2 = oldState;
3741 args.arg3 = newState;
3742 obtainMessage(MSG_STORAGE_STATE_CHANGED, args).sendToTarget();
3743 }
3744
3745 private void notifyVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
3746 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003747 args.arg1 = vol.clone();
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003748 args.argi2 = oldState;
3749 args.argi3 = newState;
3750 obtainMessage(MSG_VOLUME_STATE_CHANGED, args).sendToTarget();
3751 }
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003752
Jeff Sharkey50a05452015-04-29 11:24:52 -07003753 private void notifyVolumeRecordChanged(VolumeRecord rec) {
3754 final SomeArgs args = SomeArgs.obtain();
3755 args.arg1 = rec.clone();
3756 obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
3757 }
3758
3759 private void notifyVolumeForgotten(String fsUuid) {
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003760 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003761 args.arg1 = fsUuid;
Jeff Sharkey50a05452015-04-29 11:24:52 -07003762 obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
Jeff Sharkeyd95d3bf2015-04-14 21:39:44 -07003763 }
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003764
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003765 private void notifyDiskScanned(DiskInfo disk, int volumeCount) {
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003766 final SomeArgs args = SomeArgs.obtain();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003767 args.arg1 = disk.clone();
Jeff Sharkey620b32b2015-04-23 19:36:02 -07003768 args.argi2 = volumeCount;
3769 obtainMessage(MSG_DISK_SCANNED, args).sendToTarget();
Jeff Sharkey7e92ef32015-04-17 17:35:07 -07003770 }
Makoto Onuki9dc575d2015-06-12 16:10:25 -07003771
3772 private void notifyDiskDestroyed(DiskInfo disk) {
3773 final SomeArgs args = SomeArgs.obtain();
3774 args.arg1 = disk.clone();
3775 obtainMessage(MSG_DISK_DESTROYED, args).sendToTarget();
3776 }
Jeff Sharkey7151a9a2015-04-04 15:22:37 -07003777 }
3778
Kenny Root38cf8862010-09-26 14:18:51 -07003779 @Override
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003780 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003781 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003782
3783 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003784 synchronized (mLock) {
3785 pw.println("Disks:");
3786 pw.increaseIndent();
3787 for (int i = 0; i < mDisks.size(); i++) {
3788 final DiskInfo disk = mDisks.valueAt(i);
3789 disk.dump(pw);
3790 }
3791 pw.decreaseIndent();
3792
3793 pw.println();
3794 pw.println("Volumes:");
3795 pw.increaseIndent();
3796 for (int i = 0; i < mVolumes.size(); i++) {
3797 final VolumeInfo vol = mVolumes.valueAt(i);
3798 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) continue;
3799 vol.dump(pw);
3800 }
3801 pw.decreaseIndent();
3802
3803 pw.println();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003804 pw.println("Records:");
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003805 pw.increaseIndent();
Jeff Sharkeyb36586a2015-04-27 08:42:28 -07003806 for (int i = 0; i < mRecords.size(); i++) {
3807 final VolumeRecord note = mRecords.valueAt(i);
3808 note.dump(pw);
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003809 }
3810 pw.decreaseIndent();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003811
3812 pw.println();
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07003813 pw.println("mVisibleVols:");
3814 pw.increaseIndent();
3815 for (int i = 0; i < mVisibleVols.size(); i++) {
3816 mVisibleVols.get(i).dump(pw);
3817 }
3818 pw.decreaseIndent();
3819
3820 pw.println();
Jeff Sharkey275e3e42015-04-24 16:10:32 -07003821 pw.println("Primary storage UUID: " + mPrimaryStorageUuid);
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003822
3823 pw.println();
Felipe Leme281389a2016-10-10 17:12:20 -07003824 final Pair<String, Long> pair = StorageManager.getPrimaryStoragePathAndSize();
3825 if (pair == null) {
3826 pw.println("Internal storage total size: N/A");
3827 } else {
3828 pw.print("Internal storage (");
3829 pw.print(pair.first);
3830 pw.print(") total size: ");
3831 pw.print(pair.second);
3832 pw.print(" (");
Jeff Sharkey9f2dc052018-01-07 16:47:31 -07003833 pw.print(DataUnit.MEBIBYTES.toBytes(pair.second));
3834 pw.println(" MiB)");
Felipe Leme281389a2016-10-10 17:12:20 -07003835 }
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003836
3837 pw.println();
Jeff Sharkeyce14cd02015-12-07 15:35:42 -07003838 pw.println("Local unlocked users: " + Arrays.toString(mLocalUnlockedUsers));
3839 pw.println("System unlocked users: " + Arrays.toString(mSystemUnlockedUsers));
Jeff Sharkeyb0c363b22018-12-15 11:53:03 -07003840
3841 final ContentResolver cr = mContext.getContentResolver();
3842 pw.println();
3843 pw.println("Isolated storage, local feature flag: "
3844 + Settings.Global.getInt(cr, Settings.Global.ISOLATED_STORAGE_LOCAL, 0));
3845 pw.println("Isolated storage, remote feature flag: "
3846 + Settings.Global.getInt(cr, Settings.Global.ISOLATED_STORAGE_REMOTE, 0));
3847 pw.println("Isolated storage, resolved: " + StorageManager.hasIsolatedStorage());
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003848 }
Kenny Root38cf8862010-09-26 14:18:51 -07003849
Kenny Root38cf8862010-09-26 14:18:51 -07003850 synchronized (mObbMounts) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -07003851 pw.println();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003852 pw.println("mObbMounts:");
3853 pw.increaseIndent();
3854 final Iterator<Entry<IBinder, List<ObbState>>> binders = mObbMounts.entrySet()
3855 .iterator();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003856 while (binders.hasNext()) {
3857 Entry<IBinder, List<ObbState>> e = binders.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003858 pw.println(e.getKey() + ":");
3859 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003860 final List<ObbState> obbStates = e.getValue();
Kenny Root38cf8862010-09-26 14:18:51 -07003861 for (final ObbState obbState : obbStates) {
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003862 pw.println(obbState);
Kenny Root38cf8862010-09-26 14:18:51 -07003863 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003864 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003865 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003866 pw.decreaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003867
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003868 pw.println();
3869 pw.println("mObbPathToStateMap:");
3870 pw.increaseIndent();
Kenny Rootaf9d6672010-10-08 09:21:39 -07003871 final Iterator<Entry<String, ObbState>> maps = mObbPathToStateMap.entrySet().iterator();
3872 while (maps.hasNext()) {
3873 final Entry<String, ObbState> e = maps.next();
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003874 pw.print(e.getKey());
3875 pw.print(" -> ");
3876 pw.println(e.getValue());
Kenny Rootaf9d6672010-10-08 09:21:39 -07003877 }
Jeff Sharkey5aca2b82013-10-16 16:21:54 -07003878 pw.decreaseIndent();
Kenny Root38cf8862010-09-26 14:18:51 -07003879 }
Kenny Root4161f9b2011-07-13 09:48:33 -07003880
Robert Greenwalt470fd722012-01-18 12:51:15 -08003881 pw.println();
Christopher Tate7265abe2014-11-21 13:54:45 -08003882 pw.print("Last maintenance: ");
Jeff Sharkeye8a4b662015-06-27 15:43:45 -07003883 pw.println(TimeUtils.formatForLogging(mLastMaintenance));
Kenny Root38cf8862010-09-26 14:18:51 -07003884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003886 /** {@inheritDoc} */
Jeff Sharkey48877892015-03-18 11:27:19 -07003887 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003888 public void monitor() {
Jeff Sharkey54402792017-09-15 16:05:19 -06003889 try {
3890 mVold.monitor();
3891 } catch (Exception e) {
3892 Slog.wtf(TAG, e);
Paul Lawrence1c62cbb2015-06-03 14:14:52 -07003893 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07003894 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003895
Sudheer Shanka2250d562016-11-07 15:41:02 -08003896 private final class StorageManagerInternalImpl extends StorageManagerInternal {
Svet Ganov6ee871e2015-07-10 14:29:33 -07003897 // Not guarded by a lock.
3898 private final CopyOnWriteArrayList<ExternalStorageMountPolicy> mPolicies =
3899 new CopyOnWriteArrayList<>();
3900
Risanaec0ee72018-10-31 10:10:12 +09003901 @GuardedBy("mResetListeners")
3902 private final List<StorageManagerInternal.ResetListener> mResetListeners =
3903 new ArrayList<>();
3904
Svet Ganov6ee871e2015-07-10 14:29:33 -07003905 @Override
3906 public void addExternalStoragePolicy(ExternalStorageMountPolicy policy) {
3907 // No locking - CopyOnWriteArrayList
3908 mPolicies.add(policy);
3909 }
3910
3911 @Override
3912 public void onExternalStoragePolicyChanged(int uid, String packageName) {
Sudheer Shanka0a541a52018-07-31 13:21:11 -07003913 // No runtime storage permissions in isolated storage world, so nothing to do here.
Jeff Sharkeyc58fdf32018-08-15 18:49:34 -06003914 if (ENABLE_ISOLATED_STORAGE) return;
Svet Ganov6ee871e2015-07-10 14:29:33 -07003915 final int mountMode = getExternalStorageMountMode(uid, packageName);
3916 remountUidExternalStorage(uid, mountMode);
3917 }
3918
3919 @Override
3920 public int getExternalStorageMountMode(int uid, String packageName) {
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003921 if (ENABLE_ISOLATED_STORAGE) {
3922 return getMountMode(uid, packageName);
3923 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003924 // No locking - CopyOnWriteArrayList
3925 int mountMode = Integer.MAX_VALUE;
3926 for (ExternalStorageMountPolicy policy : mPolicies) {
3927 final int policyMode = policy.getMountMode(uid, packageName);
3928 if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) {
3929 return Zygote.MOUNT_EXTERNAL_NONE;
3930 }
3931 mountMode = Math.min(mountMode, policyMode);
3932 }
3933 if (mountMode == Integer.MAX_VALUE) {
3934 return Zygote.MOUNT_EXTERNAL_NONE;
3935 }
3936 return mountMode;
3937 }
3938
Risanaec0ee72018-10-31 10:10:12 +09003939 @Override
3940 public void addResetListener(StorageManagerInternal.ResetListener listener) {
3941 synchronized (mResetListeners) {
3942 mResetListeners.add(listener);
3943 }
3944 }
3945
3946 public void onReset(IVold vold) {
3947 synchronized (mResetListeners) {
3948 for (StorageManagerInternal.ResetListener listener : mResetListeners) {
3949 listener.onReset(vold);
3950 }
3951 }
3952 }
3953
Svet Ganov6ee871e2015-07-10 14:29:33 -07003954 public boolean hasExternalStorage(int uid, String packageName) {
Amith Yamasani2bd5cff2015-07-22 14:42:31 -07003955 // No need to check for system uid. This avoids a deadlock between
3956 // PackageManagerService and AppOpsService.
3957 if (uid == Process.SYSTEM_UID) {
3958 return true;
3959 }
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -08003960 if (ENABLE_ISOLATED_STORAGE) {
3961 return getMountMode(uid, packageName) != Zygote.MOUNT_EXTERNAL_NONE;
3962 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07003963 // No locking - CopyOnWriteArrayList
3964 for (ExternalStorageMountPolicy policy : mPolicies) {
3965 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
3966 if (!policyHasStorage) {
3967 return false;
3968 }
3969 }
3970 return true;
3971 }
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003972
3973 @Override
Sudheer Shanka584b0682018-10-04 16:26:16 -07003974 public void prepareSandboxForApp(String packageName, int appId, String sharedUserId,
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003975 int userId) {
3976 final String sandboxId;
3977 synchronized (mPackagesLock) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07003978 final ArraySet<String> userPackages = mPackages.get(userId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003979 // If userPackages is empty, it means the user is not started yet, so no need to
3980 // do anything now.
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07003981 if (userPackages == null || userPackages.contains(packageName)) {
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003982 return;
3983 }
3984 userPackages.add(packageName);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003985 sandboxId = getSandboxId(packageName, sharedUserId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07003986 }
3987
3988 try {
Sudheer Shanka584b0682018-10-04 16:26:16 -07003989 mVold.prepareSandboxForApp(packageName, appId, sandboxId, userId);
3990 } catch (Exception e) {
3991 Slog.wtf(TAG, e);
3992 }
3993 }
3994
3995 @Override
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07003996 public void destroySandboxForApp(String packageName, String sharedUserId, int userId) {
Sudheer Shanka584b0682018-10-04 16:26:16 -07003997 if (!ENABLE_ISOLATED_STORAGE) {
3998 return;
3999 }
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004000 final String sandboxId = getSandboxId(packageName, sharedUserId);
Sudheer Shanka584b0682018-10-04 16:26:16 -07004001 synchronized (mPackagesLock) {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004002 final ArraySet<String> userPackages = mPackages.get(userId);
4003 // If the userPackages is null, it means the user is not started but we still
4004 // need to delete the sandbox data though.
4005 if (userPackages != null) {
4006 userPackages.remove(packageName);
Sudheer Shanka584b0682018-10-04 16:26:16 -07004007 }
4008 }
4009 try {
Sudheer Shanka2ac25a92018-10-25 10:59:32 -07004010 mVold.destroySandboxForApp(packageName, sandboxId, userId);
Sudheer Shanka8ff30b12018-08-06 17:29:44 -07004011 } catch (Exception e) {
4012 Slog.wtf(TAG, e);
4013 }
4014 }
Sudheer Shanka3f0645b2018-09-18 13:07:59 -07004015
4016 @Override
4017 public String[] getVisibleVolumesForUser(int userId) {
4018 final ArrayList<String> visibleVolsForUser = new ArrayList<>();
4019 for (int i = mVisibleVols.size() - 1; i >= 0; --i) {
4020 final VolumeInfo vol = mVisibleVols.get(i);
4021 if (vol.isVisibleForUser(userId)) {
4022 visibleVolsForUser.add(getVolumeLabel(vol));
4023 }
4024 }
4025 return visibleVolsForUser.toArray(new String[visibleVolsForUser.size()]);
4026 }
4027
4028 private String getVolumeLabel(VolumeInfo vol) {
4029 // STOPSHIP: Label needs to part of VolumeInfo and need to be passed on from vold
4030 switch (vol.getType()) {
4031 case VolumeInfo.TYPE_EMULATED:
4032 return "emulated";
4033 case VolumeInfo.TYPE_PUBLIC:
4034 return vol.fsUuid == null ? vol.id : vol.fsUuid;
4035 default:
4036 return null;
4037 }
4038 }
Svet Ganov6ee871e2015-07-10 14:29:33 -07004039 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07004040}