blob: 2a82fc9b28df5a20860cca3d620fa1a81c7e3c18 [file] [log] [blame]
Jeff Sharkey9e0036e2013-04-26 16:54:55 -07001/*
2 * Copyright (C) 2013 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.externalstorage;
18
Garfield Tan06940e12016-10-07 16:03:17 -070019import android.annotation.Nullable;
Jeff Sharkey06823d42017-05-09 16:55:29 -060020import android.app.usage.StorageStatsManager;
Jeff Sharkeydb5ef122013-10-25 17:12:49 -070021import android.content.ContentResolver;
Garfield Tan92b96ba2016-11-01 14:33:48 -070022import android.content.UriPermission;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070023import android.database.Cursor;
24import android.database.MatrixCursor;
Jeff Sharkey9d0843d2013-05-07 12:41:33 -070025import android.database.MatrixCursor.RowBuilder;
Jeff Sharkeydb5ef122013-10-25 17:12:49 -070026import android.net.Uri;
Ben Line7822fb2016-06-24 15:21:08 -070027import android.os.Binder;
Felipe Lemeb012f912016-01-22 16:49:55 -080028import android.os.Bundle;
Steve McKay5c462a02016-01-29 16:13:21 -080029import android.os.Environment;
Jeff Sharkeyb78b754d2018-01-04 15:07:38 -070030import android.os.IBinder;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070031import android.os.UserHandle;
Jeff Sharkeyb78b754d2018-01-04 15:07:38 -070032import android.os.UserManager;
Steve McKayba23e542016-03-02 15:15:00 -080033import android.os.storage.DiskInfo;
Jeff Sharkey1f706c62013-10-17 10:52:17 -070034import android.os.storage.StorageManager;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070035import android.os.storage.VolumeInfo;
Jeff Sharkey1f706c62013-10-17 10:52:17 -070036import android.provider.DocumentsContract;
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070037import android.provider.DocumentsContract.Document;
Garfield Tanaba97f32016-10-06 17:34:19 +000038import android.provider.DocumentsContract.Path;
Garfield Tan06940e12016-10-07 16:03:17 -070039import android.provider.DocumentsContract.Root;
Steve McKayecec7cb2016-03-02 11:35:39 -080040import android.provider.Settings;
Jeff Sharkeyb7e12552014-05-21 22:22:03 -070041import android.text.TextUtils;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070042import android.util.ArrayMap;
43import android.util.DebugUtils;
Jeff Sharkey1f706c62013-10-17 10:52:17 -070044import android.util.Log;
Garfield Tanaba97f32016-10-06 17:34:19 +000045import android.util.Pair;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070046
Jeff Sharkey1f706c62013-10-17 10:52:17 -070047import com.android.internal.annotations.GuardedBy;
Garfield Tan75379db2017-02-08 15:32:56 -080048import com.android.internal.content.FileSystemProvider;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070049import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070050
51import java.io.File;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070052import java.io.FileDescriptor;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070053import java.io.FileNotFoundException;
Jeff Sharkey06823d42017-05-09 16:55:29 -060054import java.io.IOException;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070055import java.io.PrintWriter;
Garfield Tan75379db2017-02-08 15:32:56 -080056import java.util.Collections;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070057import java.util.List;
Garfield Tan92b96ba2016-11-01 14:33:48 -070058import java.util.Objects;
Jeff Sharkey06823d42017-05-09 16:55:29 -060059import java.util.UUID;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070060
Garfield Tan75379db2017-02-08 15:32:56 -080061public class ExternalStorageProvider extends FileSystemProvider {
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070062 private static final String TAG = "ExternalStorage";
63
Steve McKayecec7cb2016-03-02 11:35:39 -080064 private static final boolean DEBUG = false;
Jeff Sharkeydb5ef122013-10-25 17:12:49 -070065
Jeff Sharkey1f706c62013-10-17 10:52:17 -070066 public static final String AUTHORITY = "com.android.externalstorage.documents";
67
Makoto Onuki14a6df72015-07-01 14:55:14 -070068 private static final Uri BASE_URI =
69 new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY).build();
70
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -070071 // docId format: root:path/to/file
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070072
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070073 private static final String[] DEFAULT_ROOT_PROJECTION = new String[] {
Jeff Sharkey6efba222013-09-27 16:44:11 -070074 Root.COLUMN_ROOT_ID, Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE,
75 Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES,
Jeff Sharkey9d0843d2013-05-07 12:41:33 -070076 };
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070077
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070078 private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
79 Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
80 Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
81 };
82
83 private static class RootInfo {
84 public String rootId;
Ben Line7822fb2016-06-24 15:21:08 -070085 public String volumeId;
Jeff Sharkey06823d42017-05-09 16:55:29 -060086 public UUID storageUuid;
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070087 public int flags;
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070088 public String title;
89 public String docId;
Jeff Sharkey27de30d2015-04-18 16:20:27 -070090 public File visiblePath;
91 public File path;
Steve McKayc6a4cd82015-11-18 14:56:50 -080092 public boolean reportAvailableBytes = true;
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070093 }
94
Jeff Sharkey1f706c62013-10-17 10:52:17 -070095 private static final String ROOT_ID_PRIMARY_EMULATED = "primary";
Steve McKayc6a4cd82015-11-18 14:56:50 -080096 private static final String ROOT_ID_HOME = "home";
Jeff Sharkey1f706c62013-10-17 10:52:17 -070097
98 private StorageManager mStorageManager;
Jeff Sharkeyb78b754d2018-01-04 15:07:38 -070099 private UserManager mUserManager;
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700100
101 private final Object mRootsLock = new Object();
102
103 @GuardedBy("mRootsLock")
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700104 private ArrayMap<String, RootInfo> mRoots = new ArrayMap<>();
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700105
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700106 @Override
107 public boolean onCreate() {
Garfield Tan75379db2017-02-08 15:32:56 -0800108 super.onCreate(DEFAULT_DOCUMENT_PROJECTION);
109
Jeff Sharkeyb78b754d2018-01-04 15:07:38 -0700110 mStorageManager = getContext().getSystemService(StorageManager.class);
111 mUserManager = getContext().getSystemService(UserManager.class);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700112
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700113 updateVolumes();
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700114 return true;
115 }
116
Jeff Sharkeyb78b754d2018-01-04 15:07:38 -0700117 private void enforceShellRestrictions() {
118 if (UserHandle.getCallingAppId() == android.os.Process.SHELL_UID
119 && mUserManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER)) {
120 throw new SecurityException(
121 "Shell user cannot access files for user " + UserHandle.myUserId());
122 }
123 }
124
125 @Override
126 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
127 throws SecurityException {
128 enforceShellRestrictions();
129 return super.enforceReadPermissionInner(uri, callingPkg, callerToken);
130 }
131
132 @Override
133 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
134 throws SecurityException {
135 enforceShellRestrictions();
136 return super.enforceWritePermissionInner(uri, callingPkg, callerToken);
137 }
138
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700139 public void updateVolumes() {
140 synchronized (mRootsLock) {
141 updateVolumesLocked();
142 }
143 }
144
145 private void updateVolumesLocked() {
146 mRoots.clear();
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700147
Steve McKayc6a4cd82015-11-18 14:56:50 -0800148 VolumeInfo primaryVolume = null;
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700149 final int userId = UserHandle.myUserId();
150 final List<VolumeInfo> volumes = mStorageManager.getVolumes();
151 for (VolumeInfo volume : volumes) {
152 if (!volume.isMountedReadable()) continue;
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700153
154 final String rootId;
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700155 final String title;
Jeff Sharkey06823d42017-05-09 16:55:29 -0600156 final UUID storageUuid;
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700157 if (volume.getType() == VolumeInfo.TYPE_EMULATED) {
158 // We currently only support a single emulated volume mounted at
159 // a time, and it's always considered the primary
Steve McKayecec7cb2016-03-02 11:35:39 -0800160 if (DEBUG) Log.d(TAG, "Found primary volume: " + volume);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700161 rootId = ROOT_ID_PRIMARY_EMULATED;
Steve McKayecec7cb2016-03-02 11:35:39 -0800162
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700163 if (VolumeInfo.ID_EMULATED_INTERNAL.equals(volume.getId())) {
Steve McKayecec7cb2016-03-02 11:35:39 -0800164 // This is basically the user's primary device storage.
165 // Use device name for the volume since this is likely same thing
166 // the user sees when they mount their phone on another device.
167 String deviceName = Settings.Global.getString(
168 getContext().getContentResolver(), Settings.Global.DEVICE_NAME);
169
170 // Device name should always be set. In case it isn't, though,
171 // fall back to a localized "Internal Storage" string.
172 title = !TextUtils.isEmpty(deviceName)
173 ? deviceName
174 : getContext().getString(R.string.root_internal_storage);
Jeff Sharkey06823d42017-05-09 16:55:29 -0600175 storageUuid = StorageManager.UUID_DEFAULT;
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700176 } else {
Steve McKayecec7cb2016-03-02 11:35:39 -0800177 // This should cover all other storage devices, like an SD card
178 // or USB OTG drive plugged in. Using getBestVolumeDescription()
179 // will give us a nice string like "Samsung SD card" or "SanDisk USB drive"
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700180 final VolumeInfo privateVol = mStorageManager.findPrivateForEmulated(volume);
181 title = mStorageManager.getBestVolumeDescription(privateVol);
Jeff Sharkey06823d42017-05-09 16:55:29 -0600182 storageUuid = StorageManager.convert(privateVol.fsUuid);
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700183 }
Jeff Sharkey3b699d72016-10-31 14:33:49 -0600184 } else if (volume.getType() == VolumeInfo.TYPE_PUBLIC
185 && volume.getMountUserId() == userId) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700186 rootId = volume.getFsUuid();
Jeff Sharkeyb521fea2015-06-15 21:09:10 -0700187 title = mStorageManager.getBestVolumeDescription(volume);
Jeff Sharkey06823d42017-05-09 16:55:29 -0600188 storageUuid = null;
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700189 } else {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700190 // Unsupported volume; ignore
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700191 continue;
192 }
193
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700194 if (TextUtils.isEmpty(rootId)) {
195 Log.d(TAG, "Missing UUID for " + volume.getId() + "; skipping");
196 continue;
197 }
198 if (mRoots.containsKey(rootId)) {
199 Log.w(TAG, "Duplicate UUID " + rootId + " for " + volume.getId() + "; skipping");
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700200 continue;
201 }
202
Steve McKayc6a4cd82015-11-18 14:56:50 -0800203 final RootInfo root = new RootInfo();
204 mRoots.put(rootId, root);
205
206 root.rootId = rootId;
Ben Line7822fb2016-06-24 15:21:08 -0700207 root.volumeId = volume.id;
Jeff Sharkey06823d42017-05-09 16:55:29 -0600208 root.storageUuid = storageUuid;
Steve McKayefa17612016-01-29 18:15:39 -0800209 root.flags = Root.FLAG_LOCAL_ONLY
Garfield Tanaba97f32016-10-06 17:34:19 +0000210 | Root.FLAG_SUPPORTS_SEARCH
211 | Root.FLAG_SUPPORTS_IS_CHILD;
Steve McKayc6a4cd82015-11-18 14:56:50 -0800212
Steve McKayba23e542016-03-02 15:15:00 -0800213 final DiskInfo disk = volume.getDisk();
214 if (DEBUG) Log.d(TAG, "Disk for root " + rootId + " is " + disk);
215 if (disk != null && disk.isSd()) {
216 root.flags |= Root.FLAG_REMOVABLE_SD;
217 } else if (disk != null && disk.isUsb()) {
218 root.flags |= Root.FLAG_REMOVABLE_USB;
219 }
220
Ben Line7822fb2016-06-24 15:21:08 -0700221 if (!VolumeInfo.ID_EMULATED_INTERNAL.equals(volume.getId())) {
222 root.flags |= Root.FLAG_SUPPORTS_EJECT;
223 }
224
Steve McKayefa17612016-01-29 18:15:39 -0800225 if (volume.isPrimary()) {
226 // save off the primary volume for subsequent "Home" dir initialization.
227 primaryVolume = volume;
Aga Wronska1719b352016-03-21 11:28:03 -0700228 root.flags |= Root.FLAG_ADVANCED;
Steve McKayefa17612016-01-29 18:15:39 -0800229 }
Steve McKayc6a4cd82015-11-18 14:56:50 -0800230 // Dunno when this would NOT be the case, but never hurts to be correct.
231 if (volume.isMountedWritable()) {
232 root.flags |= Root.FLAG_SUPPORTS_CREATE;
233 }
234 root.title = title;
235 if (volume.getType() == VolumeInfo.TYPE_PUBLIC) {
236 root.flags |= Root.FLAG_HAS_SETTINGS;
237 }
238 if (volume.isVisibleForRead(userId)) {
239 root.visiblePath = volume.getPathForUser(userId);
240 } else {
241 root.visiblePath = null;
242 }
243 root.path = volume.getInternalPathForUser(userId);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700244 try {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700245 root.docId = getDocIdForFile(root.path);
Steve McKayc6a4cd82015-11-18 14:56:50 -0800246 } catch (FileNotFoundException e) {
247 throw new IllegalStateException(e);
248 }
249 }
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700250
Steve McKayecec7cb2016-03-02 11:35:39 -0800251 // Finally, if primary storage is available we add the "Documents" directory.
252 // If I recall correctly the actual directory is created on demand
253 // by calling either getPathForUser, or getInternalPathForUser.
Steve McKayc6a4cd82015-11-18 14:56:50 -0800254 if (primaryVolume != null && primaryVolume.isVisible()) {
255 final RootInfo root = new RootInfo();
256 root.rootId = ROOT_ID_HOME;
257 mRoots.put(root.rootId, root);
Steve McKayab3b8932016-02-16 11:37:03 -0800258 root.title = getContext().getString(R.string.root_documents);
Steve McKayc6a4cd82015-11-18 14:56:50 -0800259
260 // Only report bytes on *volumes*...as a matter of policy.
261 root.reportAvailableBytes = false;
262 root.flags = Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_SEARCH
263 | Root.FLAG_SUPPORTS_IS_CHILD;
264
265 // Dunno when this would NOT be the case, but never hurts to be correct.
266 if (primaryVolume.isMountedWritable()) {
267 root.flags |= Root.FLAG_SUPPORTS_CREATE;
268 }
269
Steve McKayecec7cb2016-03-02 11:35:39 -0800270 // Create the "Documents" directory on disk (don't use the localized title).
Steve McKayc6a4cd82015-11-18 14:56:50 -0800271 root.visiblePath = new File(
Steve McKayab3b8932016-02-16 11:37:03 -0800272 primaryVolume.getPathForUser(userId), Environment.DIRECTORY_DOCUMENTS);
Steve McKayc6a4cd82015-11-18 14:56:50 -0800273 root.path = new File(
Steve McKayab3b8932016-02-16 11:37:03 -0800274 primaryVolume.getInternalPathForUser(userId), Environment.DIRECTORY_DOCUMENTS);
Steve McKayc6a4cd82015-11-18 14:56:50 -0800275 try {
276 root.docId = getDocIdForFile(root.path);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700277 } catch (FileNotFoundException e) {
278 throw new IllegalStateException(e);
279 }
280 }
281
282 Log.d(TAG, "After updating volumes, found " + mRoots.size() + " active roots");
283
Makoto Onuki14a6df72015-07-01 14:55:14 -0700284 // Note this affects content://com.android.externalstorage.documents/root/39BD-07C5
285 // as well as content://com.android.externalstorage.documents/document/*/children,
286 // so just notify on content://com.android.externalstorage.documents/.
287 getContext().getContentResolver().notifyChange(BASE_URI, null, false);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700288 }
289
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -0700290 private static String[] resolveRootProjection(String[] projection) {
291 return projection != null ? projection : DEFAULT_ROOT_PROJECTION;
292 }
293
Garfield Tan75379db2017-02-08 15:32:56 -0800294 @Override
295 protected String getDocIdForFile(File file) throws FileNotFoundException {
Felipe Lemeb012f912016-01-22 16:49:55 -0800296 return getDocIdForFileMaybeCreate(file, false);
297 }
298
299 private String getDocIdForFileMaybeCreate(File file, boolean createNewDir)
300 throws FileNotFoundException {
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700301 String path = file.getAbsolutePath();
Jeff Sharkey92d7e692013-08-02 10:33:21 -0700302
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700303 // Find the most-specific root path
Garfield Tandc9593e2017-01-09 18:04:43 -0800304 boolean visiblePath = false;
305 RootInfo mostSpecificRoot = getMostSpecificRootForPath(path, false);
306
307 if (mostSpecificRoot == null) {
308 // Try visible path if no internal path matches. MediaStore uses visible paths.
309 visiblePath = true;
310 mostSpecificRoot = getMostSpecificRootForPath(path, true);
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700311 }
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700312
Garfield Tandc9593e2017-01-09 18:04:43 -0800313 if (mostSpecificRoot == null) {
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700314 throw new FileNotFoundException("Failed to find root that contains " + path);
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700315 }
Jeff Sharkey20d96d82013-07-30 17:08:39 -0700316
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700317 // Start at first char of path under root
Garfield Tandc9593e2017-01-09 18:04:43 -0800318 final String rootPath = visiblePath
319 ? mostSpecificRoot.visiblePath.getAbsolutePath()
320 : mostSpecificRoot.path.getAbsolutePath();
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700321 if (rootPath.equals(path)) {
322 path = "";
323 } else if (rootPath.endsWith("/")) {
324 path = path.substring(rootPath.length());
Jeff Sharkey92d7e692013-08-02 10:33:21 -0700325 } else {
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700326 path = path.substring(rootPath.length() + 1);
Jeff Sharkey92d7e692013-08-02 10:33:21 -0700327 }
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700328
Felipe Lemeb012f912016-01-22 16:49:55 -0800329 if (!file.exists() && createNewDir) {
330 Log.i(TAG, "Creating new directory " + file);
331 if (!file.mkdir()) {
332 Log.e(TAG, "Could not create directory " + file);
333 }
334 }
335
Garfield Tandc9593e2017-01-09 18:04:43 -0800336 return mostSpecificRoot.rootId + ':' + path;
337 }
338
339 private RootInfo getMostSpecificRootForPath(String path, boolean visible) {
340 // Find the most-specific root path
341 RootInfo mostSpecificRoot = null;
342 String mostSpecificPath = null;
343 synchronized (mRootsLock) {
344 for (int i = 0; i < mRoots.size(); i++) {
345 final RootInfo root = mRoots.valueAt(i);
346 final File rootFile = visible ? root.visiblePath : root.path;
347 if (rootFile != null) {
348 final String rootPath = rootFile.getAbsolutePath();
349 if (path.startsWith(rootPath) && (mostSpecificPath == null
350 || rootPath.length() > mostSpecificPath.length())) {
351 mostSpecificRoot = root;
352 mostSpecificPath = rootPath;
353 }
354 }
355 }
356 }
357
358 return mostSpecificRoot;
Jeff Sharkey20d96d82013-07-30 17:08:39 -0700359 }
360
Garfield Tan75379db2017-02-08 15:32:56 -0800361 @Override
362 protected File getFileForDocId(String docId, boolean visible) throws FileNotFoundException {
Garfield Tan06940e12016-10-07 16:03:17 -0700363 RootInfo root = getRootFromDocId(docId);
364 return buildFile(root, docId, visible);
Garfield Tanaba97f32016-10-06 17:34:19 +0000365 }
366
367 private Pair<RootInfo, File> resolveDocId(String docId, boolean visible)
368 throws FileNotFoundException {
Garfield Tan06940e12016-10-07 16:03:17 -0700369 RootInfo root = getRootFromDocId(docId);
370 return Pair.create(root, buildFile(root, docId, visible));
371 }
372
373 private RootInfo getRootFromDocId(String docId) throws FileNotFoundException {
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700374 final int splitIndex = docId.indexOf(':', 1);
375 final String tag = docId.substring(0, splitIndex);
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700376
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700377 RootInfo root;
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700378 synchronized (mRootsLock) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700379 root = mRoots.get(tag);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700380 }
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700381 if (root == null) {
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700382 throw new FileNotFoundException("No root for " + tag);
383 }
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700384
Garfield Tan06940e12016-10-07 16:03:17 -0700385 return root;
386 }
387
388 private File buildFile(RootInfo root, String docId, boolean visible)
389 throws FileNotFoundException {
390 final int splitIndex = docId.indexOf(':', 1);
391 final String path = docId.substring(splitIndex + 1);
392
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700393 File target = visible ? root.visiblePath : root.path;
394 if (target == null) {
395 return null;
396 }
Jeff Sharkey3e1189b2013-09-12 21:59:06 -0700397 if (!target.exists()) {
398 target.mkdirs();
399 }
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700400 target = new File(target, path);
401 if (!target.exists()) {
402 throw new FileNotFoundException("Missing file for " + docId + " at " + target);
403 }
Garfield Tan06940e12016-10-07 16:03:17 -0700404 return target;
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700405 }
406
Garfield Tan75379db2017-02-08 15:32:56 -0800407 @Override
408 protected Uri buildNotificationUri(String docId) {
409 return DocumentsContract.buildChildDocumentsUri(AUTHORITY, docId);
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700410 }
411
412 @Override
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -0700413 public Cursor queryRoots(String[] projection) throws FileNotFoundException {
414 final MatrixCursor result = new MatrixCursor(resolveRootProjection(projection));
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700415 synchronized (mRootsLock) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700416 for (RootInfo root : mRoots.values()) {
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700417 final RowBuilder row = result.newRow();
418 row.add(Root.COLUMN_ROOT_ID, root.rootId);
419 row.add(Root.COLUMN_FLAGS, root.flags);
420 row.add(Root.COLUMN_TITLE, root.title);
421 row.add(Root.COLUMN_DOCUMENT_ID, root.docId);
Jeff Sharkey06823d42017-05-09 16:55:29 -0600422
423 long availableBytes = -1;
424 if (root.reportAvailableBytes) {
425 if (root.storageUuid != null) {
426 try {
427 availableBytes = getContext()
428 .getSystemService(StorageStatsManager.class)
429 .getFreeBytes(root.storageUuid);
430 } catch (IOException e) {
431 Log.w(TAG, e);
432 }
433 } else {
434 availableBytes = root.path.getUsableSpace();
435 }
436 }
437 row.add(Root.COLUMN_AVAILABLE_BYTES, availableBytes);
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700438 }
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700439 }
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -0700440 return result;
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700441 }
442
443 @Override
Garfield Tanb690b4d2017-03-01 16:05:23 -0800444 public Path findDocumentPath(@Nullable String parentDocId, String childDocId)
Garfield Tanaba97f32016-10-06 17:34:19 +0000445 throws FileNotFoundException {
Garfield Tan06940e12016-10-07 16:03:17 -0700446 final Pair<RootInfo, File> resolvedDocId = resolveDocId(childDocId, false);
447 final RootInfo root = resolvedDocId.first;
448 File child = resolvedDocId.second;
Garfield Tanaba97f32016-10-06 17:34:19 +0000449
Garfield Tan06940e12016-10-07 16:03:17 -0700450 final File parent = TextUtils.isEmpty(parentDocId)
451 ? root.path
452 : getFileForDocId(parentDocId);
453
Garfield Tan75379db2017-02-08 15:32:56 -0800454 return new Path(parentDocId == null ? root.rootId : null, findDocumentPath(parent, child));
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700455 }
456
Garfield Tan92b96ba2016-11-01 14:33:48 -0700457 private Uri getDocumentUri(String path, List<UriPermission> accessUriPermissions)
458 throws FileNotFoundException {
459 File doc = new File(path);
460
461 final String docId = getDocIdForFile(doc);
462
463 UriPermission docUriPermission = null;
464 UriPermission treeUriPermission = null;
465 for (UriPermission uriPermission : accessUriPermissions) {
466 final Uri uri = uriPermission.getUri();
467 if (AUTHORITY.equals(uri.getAuthority())) {
468 boolean matchesRequestedDoc = false;
469 if (DocumentsContract.isTreeUri(uri)) {
470 final String parentDocId = DocumentsContract.getTreeDocumentId(uri);
Garfield Tandc9593e2017-01-09 18:04:43 -0800471 if (isChildDocument(parentDocId, docId)) {
Garfield Tan92b96ba2016-11-01 14:33:48 -0700472 treeUriPermission = uriPermission;
473 matchesRequestedDoc = true;
474 }
475 } else {
476 final String candidateDocId = DocumentsContract.getDocumentId(uri);
Garfield Tandc9593e2017-01-09 18:04:43 -0800477 if (Objects.equals(docId, candidateDocId)) {
Garfield Tan92b96ba2016-11-01 14:33:48 -0700478 docUriPermission = uriPermission;
479 matchesRequestedDoc = true;
480 }
481 }
482
483 if (matchesRequestedDoc && allowsBothReadAndWrite(uriPermission)) {
484 // This URI permission provides everything an app can get, no need to
485 // further check any other granted URI.
486 break;
487 }
488 }
489 }
490
491 // Full permission URI first.
492 if (allowsBothReadAndWrite(treeUriPermission)) {
493 return DocumentsContract.buildDocumentUriUsingTree(treeUriPermission.getUri(), docId);
494 }
495
496 if (allowsBothReadAndWrite(docUriPermission)) {
497 return docUriPermission.getUri();
498 }
499
500 // Then partial permission URI.
501 if (treeUriPermission != null) {
502 return DocumentsContract.buildDocumentUriUsingTree(treeUriPermission.getUri(), docId);
503 }
504
505 if (docUriPermission != null) {
506 return docUriPermission.getUri();
507 }
508
509 throw new SecurityException("The app is not given any access to the document under path " +
510 path + " with permissions granted in " + accessUriPermissions);
511 }
512
513 private static boolean allowsBothReadAndWrite(UriPermission permission) {
514 return permission != null
515 && permission.isReadPermission()
516 && permission.isWritePermission();
517 }
518
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700519 @Override
Jeff Sharkey3e1189b2013-09-12 21:59:06 -0700520 public Cursor querySearchDocuments(String rootId, String query, String[] projection)
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -0700521 throws FileNotFoundException {
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700522 final File parent;
523 synchronized (mRootsLock) {
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700524 parent = mRoots.get(rootId).path;
Jeff Sharkey1f706c62013-10-17 10:52:17 -0700525 }
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700526
Garfield Tan75379db2017-02-08 15:32:56 -0800527 return querySearchDocuments(parent, query, projection, Collections.emptySet());
Jeff Sharkeyaeb16e22013-08-27 18:26:48 -0700528 }
529
530 @Override
Garfield Tan87877032017-03-22 12:01:14 -0700531 public void ejectRoot(String rootId) {
Ben Line7822fb2016-06-24 15:21:08 -0700532 final long token = Binder.clearCallingIdentity();
Ben Line7822fb2016-06-24 15:21:08 -0700533 RootInfo root = mRoots.get(rootId);
534 if (root != null) {
535 try {
536 mStorageManager.unmount(root.volumeId);
Ben Line7822fb2016-06-24 15:21:08 -0700537 } catch (RuntimeException e) {
Garfield Tan87877032017-03-22 12:01:14 -0700538 throw new IllegalStateException(e);
Ben Line7822fb2016-06-24 15:21:08 -0700539 } finally {
540 Binder.restoreCallingIdentity(token);
541 }
542 }
Ben Line7822fb2016-06-24 15:21:08 -0700543 }
544
545 @Override
Jeff Sharkey27de30d2015-04-18 16:20:27 -0700546 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
547 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 160);
548 synchronized (mRootsLock) {
549 for (int i = 0; i < mRoots.size(); i++) {
550 final RootInfo root = mRoots.valueAt(i);
551 pw.println("Root{" + root.rootId + "}:");
552 pw.increaseIndent();
553 pw.printPair("flags", DebugUtils.flagsToString(Root.class, "FLAG_", root.flags));
554 pw.println();
555 pw.printPair("title", root.title);
556 pw.printPair("docId", root.docId);
557 pw.println();
558 pw.printPair("path", root.path);
559 pw.printPair("visiblePath", root.visiblePath);
560 pw.decreaseIndent();
561 pw.println();
562 }
563 }
564 }
565
Felipe Lemeb012f912016-01-22 16:49:55 -0800566 @Override
567 public Bundle call(String method, String arg, Bundle extras) {
568 Bundle bundle = super.call(method, arg, extras);
569 if (bundle == null && !TextUtils.isEmpty(method)) {
570 switch (method) {
571 case "getDocIdForFileCreateNewDir": {
572 getContext().enforceCallingPermission(
573 android.Manifest.permission.MANAGE_DOCUMENTS, null);
574 if (TextUtils.isEmpty(arg)) {
575 return null;
576 }
577 try {
578 final String docId = getDocIdForFileMaybeCreate(new File(arg), true);
579 bundle = new Bundle();
580 bundle.putString("DOC_ID", docId);
581 } catch (FileNotFoundException e) {
582 Log.w(TAG, "file '" + arg + "' not found");
583 return null;
584 }
585 break;
586 }
Garfield Tan92b96ba2016-11-01 14:33:48 -0700587 case "getDocumentId": {
588 final String path = arg;
589 final List<UriPermission> accessUriPermissions =
590 extras.getParcelableArrayList(AUTHORITY + ".extra.uriPermissions");
591
592 try {
593 final Bundle out = new Bundle();
594 final Uri uri = getDocumentUri(path, accessUriPermissions);
595 out.putParcelable(DocumentsContract.EXTRA_URI, uri);
596 return out;
597 } catch (FileNotFoundException e) {
598 throw new IllegalStateException("File in " + path + " is not found.", e);
599 }
600
601 }
Felipe Lemeb012f912016-01-22 16:49:55 -0800602 default:
603 Log.w(TAG, "unknown method passed to call(): " + method);
604 }
605 }
606 return bundle;
607 }
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700608}