1 /* 2 * Copyright 2022 Google LLC 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 package com.google.android.libraries.mobiledatadownload.file.openers; 17 18 import android.net.Uri; 19 import android.os.ParcelFileDescriptor; 20 import android.util.Pair; 21 import com.google.android.libraries.mobiledatadownload.file.OpenContext; 22 import com.google.android.libraries.mobiledatadownload.file.Opener; 23 import com.google.android.libraries.mobiledatadownload.file.backends.FileDescriptorUri; 24 import com.google.android.libraries.mobiledatadownload.file.common.UnsupportedFileStorageOperation; 25 import java.io.Closeable; 26 import java.io.IOException; 27 28 /** 29 * Opener that returns an ParcelFileDescriptor. Caller must close the ParcelFileDescriptor when done 30 * reading from it. Does not support Monitors or Transforms. 31 */ 32 public final class ParcelFileDescriptorOpener implements Opener<ParcelFileDescriptor> { 33 ParcelFileDescriptorOpener()34 private ParcelFileDescriptorOpener() {} 35 create()36 public static ParcelFileDescriptorOpener create() { 37 return new ParcelFileDescriptorOpener(); 38 } 39 40 @Override open(OpenContext openContext)41 public ParcelFileDescriptor open(OpenContext openContext) throws IOException { 42 Pair<Uri, Closeable> result = openContext.backend().openForNativeRead(openContext.encodedUri()); 43 try { 44 if (openContext.hasTransforms()) { 45 throw new UnsupportedFileStorageOperation( 46 "Accessing file descriptor directly would skip transforms for " 47 + openContext.originalUri()); 48 } 49 50 int nativeFd = FileDescriptorUri.getFd(result.first); 51 // NOTE: Could also use adoptFd to avoid dup and closing original, but it's slightly 52 // cleaner this way to ensure that we cannot leak file descriptors when exception is thrown. 53 // TODO(b/115933017): consider wrapping the PFD to force it to implement Closeable on all sdks 54 return ParcelFileDescriptor.fromFd(nativeFd); 55 } finally { 56 result.second.close(); 57 } 58 } 59 } 60