ParcelFileDescriptor.java revision e17aeb31030cfeed339a39a107912ad5e9178390
1/* 2 * Copyright (C) 2006 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 android.os; 18import java.io.File; 19import java.io.FileDescriptor; 20import java.io.FileInputStream; 21import java.io.FileNotFoundException; 22import java.io.FileOutputStream; 23import java.io.IOException; 24import java.net.Socket; 25 26/** 27 * The FileDescriptor returned by {@link Parcel#readFileDescriptor}, allowing 28 * you to close it when done with it. 29 */ 30public class ParcelFileDescriptor implements Parcelable { 31 private final FileDescriptor mFileDescriptor; 32 private boolean mClosed; 33 //this field is to create wrapper for ParcelFileDescriptor using another 34 //PartialFileDescriptor but avoid invoking close twice 35 //consider ParcelFileDescriptor A(fileDescriptor fd), ParcelFileDescriptor B(A) 36 //in this particular case fd.close might be invoked twice. 37 private final ParcelFileDescriptor mParcelDescriptor; 38 39 /** 40 * For use with {@link #open}: if {@link #MODE_CREATE} has been supplied 41 * and this file doesn't already exist, then create the file with 42 * permissions such that any application can read it. 43 */ 44 public static final int MODE_WORLD_READABLE = 0x00000001; 45 46 /** 47 * For use with {@link #open}: if {@link #MODE_CREATE} has been supplied 48 * and this file doesn't already exist, then create the file with 49 * permissions such that any application can write it. 50 */ 51 public static final int MODE_WORLD_WRITEABLE = 0x00000002; 52 53 /** 54 * For use with {@link #open}: open the file with read-only access. 55 */ 56 public static final int MODE_READ_ONLY = 0x10000000; 57 58 /** 59 * For use with {@link #open}: open the file with write-only access. 60 */ 61 public static final int MODE_WRITE_ONLY = 0x20000000; 62 63 /** 64 * For use with {@link #open}: open the file with read and write access. 65 */ 66 public static final int MODE_READ_WRITE = 0x30000000; 67 68 /** 69 * For use with {@link #open}: create the file if it doesn't already exist. 70 */ 71 public static final int MODE_CREATE = 0x08000000; 72 73 /** 74 * For use with {@link #open}: erase contents of file when opening. 75 */ 76 public static final int MODE_TRUNCATE = 0x04000000; 77 78 /** 79 * For use with {@link #open}: append to end of file while writing. 80 */ 81 public static final int MODE_APPEND = 0x02000000; 82 83 /** 84 * Create a new ParcelFileDescriptor accessing a given file. 85 * 86 * @param file The file to be opened. 87 * @param mode The desired access mode, must be one of 88 * {@link #MODE_READ_ONLY}, {@link #MODE_WRITE_ONLY}, or 89 * {@link #MODE_READ_WRITE}; may also be any combination of 90 * {@link #MODE_CREATE}, {@link #MODE_TRUNCATE}, 91 * {@link #MODE_WORLD_READABLE}, and {@link #MODE_WORLD_WRITEABLE}. 92 * 93 * @return Returns a new ParcelFileDescriptor pointing to the given 94 * file. 95 * 96 * @throws FileNotFoundException Throws FileNotFoundException if the given 97 * file does not exist or can not be opened with the requested mode. 98 */ 99 public static ParcelFileDescriptor open(File file, int mode) 100 throws FileNotFoundException { 101 String path = file.getPath(); 102 SecurityManager security = System.getSecurityManager(); 103 if (security != null) { 104 security.checkRead(path); 105 if ((mode&MODE_WRITE_ONLY) != 0) { 106 security.checkWrite(path); 107 } 108 } 109 110 if ((mode&MODE_READ_WRITE) == 0) { 111 throw new IllegalArgumentException( 112 "Must specify MODE_READ_ONLY, MODE_WRITE_ONLY, or MODE_READ_WRITE"); 113 } 114 115 FileDescriptor fd = Parcel.openFileDescriptor(path, mode); 116 return fd != null ? new ParcelFileDescriptor(fd) : null; 117 } 118 119 /** 120 * Create a new ParcelFileDescriptor that is a dup of an existing 121 * FileDescriptor. This obeys standard POSIX semantics, where the 122 * new file descriptor shared state such as file position with the 123 * original file descriptor. 124 */ 125 public static ParcelFileDescriptor dup(FileDescriptor orig) throws IOException { 126 FileDescriptor fd = Parcel.dupFileDescriptor(orig); 127 return fd != null ? new ParcelFileDescriptor(fd) : null; 128 } 129 130 /** 131 * Create a new ParcelFileDescriptor from the specified Socket. 132 * 133 * @param socket The Socket whose FileDescriptor is used to create 134 * a new ParcelFileDescriptor. 135 * 136 * @return A new ParcelFileDescriptor with the FileDescriptor of the 137 * specified Socket. 138 */ 139 public static ParcelFileDescriptor fromSocket(Socket socket) { 140 FileDescriptor fd = getFileDescriptorFromSocket(socket); 141 return fd != null ? new ParcelFileDescriptor(fd) : null; 142 } 143 144 // Extracts the file descriptor from the specified socket and returns it untouched 145 private static native FileDescriptor getFileDescriptorFromSocket(Socket socket); 146 147 /** 148 * Create two ParcelFileDescriptors structured as a data pipe. The first 149 * ParcelFileDescriptor in the returned array is the read side; the second 150 * is the write side. 151 */ 152 public static ParcelFileDescriptor[] createPipe() throws IOException { 153 FileDescriptor[] fds = new FileDescriptor[2]; 154 int res = createPipeNative(fds); 155 if (res == 0) { 156 ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[2]; 157 pfds[0] = new ParcelFileDescriptor(fds[0]); 158 pfds[1] = new ParcelFileDescriptor(fds[1]); 159 return pfds; 160 } 161 throw new IOException("Unable to create pipe: errno=" + -res); 162 } 163 164 private static native int createPipeNative(FileDescriptor[] outFds); 165 166 /** 167 * @hide Please use createPipe() or ContentProvider.openPipeHelper(). 168 * Gets a file descriptor for a read-only copy of the given data. 169 * 170 * @param data Data to copy. 171 * @param name Name for the shared memory area that may back the file descriptor. 172 * This is purely informative and may be {@code null}. 173 * @return A ParcelFileDescriptor. 174 * @throws IOException if there is an error while creating the shared memory area. 175 */ 176 @Deprecated 177 public static ParcelFileDescriptor fromData(byte[] data, String name) throws IOException { 178 if (data == null) return null; 179 MemoryFile file = new MemoryFile(name, data.length); 180 if (data.length > 0) { 181 file.writeBytes(data, 0, 0, data.length); 182 } 183 file.deactivate(); 184 FileDescriptor fd = file.getFileDescriptor(); 185 return fd != null ? new ParcelFileDescriptor(fd) : null; 186 } 187 188 /** 189 * Retrieve the actual FileDescriptor associated with this object. 190 * 191 * @return Returns the FileDescriptor associated with this object. 192 */ 193 public FileDescriptor getFileDescriptor() { 194 return mFileDescriptor; 195 } 196 197 /** 198 * Return the total size of the file representing this fd, as determined 199 * by stat(). Returns -1 if the fd is not a file. 200 */ 201 public native long getStatSize(); 202 203 /** 204 * This is needed for implementing AssetFileDescriptor.AutoCloseOutputStream, 205 * and I really don't think we want it to be public. 206 * @hide 207 */ 208 public native long seekTo(long pos); 209 210 /** 211 * Return the native fd int for this ParcelFileDescriptor. The 212 * ParcelFileDescriptor still owns the fd, and it still must be closed 213 * through this API. 214 */ 215 public int getFd() { 216 if (mClosed) { 217 throw new IllegalStateException("Already closed"); 218 } 219 return getFdNative(); 220 } 221 222 private native int getFdNative(); 223 224 /** 225 * Return the native fd int for this ParcelFileDescriptor and detach it 226 * from the object here. You are now responsible for closing the fd in 227 * native code. 228 */ 229 public int detachFd() { 230 if (mClosed) { 231 throw new IllegalStateException("Already closed"); 232 } 233 if (mParcelDescriptor != null) { 234 int fd = mParcelDescriptor.detachFd(); 235 mClosed = true; 236 return fd; 237 } 238 int fd = getFd(); 239 mClosed = true; 240 Parcel.clearFileDescriptor(mFileDescriptor); 241 return fd; 242 } 243 244 /** 245 * Close the ParcelFileDescriptor. This implementation closes the underlying 246 * OS resources allocated to represent this stream. 247 * 248 * @throws IOException 249 * If an error occurs attempting to close this ParcelFileDescriptor. 250 */ 251 public void close() throws IOException { 252 synchronized (this) { 253 if (mClosed) return; 254 mClosed = true; 255 } 256 if (mParcelDescriptor != null) { 257 // If this is a proxy to another file descriptor, just call through to its 258 // close method. 259 mParcelDescriptor.close(); 260 } else { 261 Parcel.closeFileDescriptor(mFileDescriptor); 262 } 263 } 264 265 /** 266 * An InputStream you can create on a ParcelFileDescriptor, which will 267 * take care of calling {@link ParcelFileDescriptor#close 268 * ParcelFileDescriptor.close()} for you when the stream is closed. 269 */ 270 public static class AutoCloseInputStream extends FileInputStream { 271 private final ParcelFileDescriptor mFd; 272 273 public AutoCloseInputStream(ParcelFileDescriptor fd) { 274 super(fd.getFileDescriptor()); 275 mFd = fd; 276 } 277 278 @Override 279 public void close() throws IOException { 280 try { 281 mFd.close(); 282 } finally { 283 super.close(); 284 } 285 } 286 } 287 288 /** 289 * An OutputStream you can create on a ParcelFileDescriptor, which will 290 * take care of calling {@link ParcelFileDescriptor#close 291 * ParcelFileDescriptor.close()} for you when the stream is closed. 292 */ 293 public static class AutoCloseOutputStream extends FileOutputStream { 294 private final ParcelFileDescriptor mFd; 295 296 public AutoCloseOutputStream(ParcelFileDescriptor fd) { 297 super(fd.getFileDescriptor()); 298 mFd = fd; 299 } 300 301 @Override 302 public void close() throws IOException { 303 try { 304 mFd.close(); 305 } finally { 306 super.close(); 307 } 308 } 309 } 310 311 @Override 312 public String toString() { 313 return "{ParcelFileDescriptor: " + mFileDescriptor + "}"; 314 } 315 316 @Override 317 protected void finalize() throws Throwable { 318 try { 319 if (!mClosed) { 320 close(); 321 } 322 } finally { 323 super.finalize(); 324 } 325 } 326 327 public ParcelFileDescriptor(ParcelFileDescriptor descriptor) { 328 super(); 329 mParcelDescriptor = descriptor; 330 mFileDescriptor = mParcelDescriptor.mFileDescriptor; 331 } 332 333 /*package */ParcelFileDescriptor(FileDescriptor descriptor) { 334 super(); 335 if (descriptor == null) { 336 throw new NullPointerException("descriptor must not be null"); 337 } 338 mFileDescriptor = descriptor; 339 mParcelDescriptor = null; 340 } 341 342 /* Parcelable interface */ 343 public int describeContents() { 344 return Parcelable.CONTENTS_FILE_DESCRIPTOR; 345 } 346 347 /** 348 * {@inheritDoc} 349 * If {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set in flags, 350 * the file descriptor will be closed after a copy is written to the Parcel. 351 */ 352 public void writeToParcel(Parcel out, int flags) { 353 out.writeFileDescriptor(mFileDescriptor); 354 if ((flags&PARCELABLE_WRITE_RETURN_VALUE) != 0 && !mClosed) { 355 try { 356 close(); 357 } catch (IOException e) { 358 // Empty 359 } 360 } 361 } 362 363 public static final Parcelable.Creator<ParcelFileDescriptor> CREATOR 364 = new Parcelable.Creator<ParcelFileDescriptor>() { 365 public ParcelFileDescriptor createFromParcel(Parcel in) { 366 return in.readFileDescriptor(); 367 } 368 public ParcelFileDescriptor[] newArray(int size) { 369 return new ParcelFileDescriptor[size]; 370 } 371 }; 372 373} 374