ParcelFileDescriptor.java revision ea2117bdc03316a9292e2344c6fd157c85c13167
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 a raw native fd. The new 132 * ParcelFileDescriptor holds a dup of the original fd passed in here, 133 * so you must still close that fd as well as the new ParcelFileDescriptor. 134 * 135 * @param fd The native fd that the ParcelFileDescriptor should dup. 136 * 137 * @return Returns a new ParcelFileDescriptor holding a FileDescriptor 138 * for a dup of the given fd. 139 */ 140 public static ParcelFileDescriptor fromFd(int fd) throws IOException { 141 FileDescriptor fdesc = getFileDescriptorFromFd(fd); 142 return new ParcelFileDescriptor(fdesc); 143 } 144 145 // Extracts the file descriptor from the specified socket and returns it untouched 146 private static native FileDescriptor getFileDescriptorFromFd(int fd) throws IOException; 147 148 /** 149 * Take ownership of a raw native fd in to a new ParcelFileDescriptor. 150 * The returned ParcelFileDescriptor now owns the given fd, and will be 151 * responsible for closing it. You must not close the fd yourself. 152 * 153 * @param fd The native fd that the ParcelFileDescriptor should adopt. 154 * 155 * @return Returns a new ParcelFileDescriptor holding a FileDescriptor 156 * for the given fd. 157 */ 158 public static ParcelFileDescriptor adoptFd(int fd) { 159 FileDescriptor fdesc = getFileDescriptorFromFdNoDup(fd); 160 return new ParcelFileDescriptor(fdesc); 161 } 162 163 // Extracts the file descriptor from the specified socket and returns it untouched 164 private static native FileDescriptor getFileDescriptorFromFdNoDup(int fd); 165 166 /** 167 * Create a new ParcelFileDescriptor from the specified Socket. The new 168 * ParcelFileDescriptor holds a dup of the original FileDescriptor in 169 * the Socket, so you must still close the Socket as well as the new 170 * ParcelFileDescriptor. 171 * 172 * @param socket The Socket whose FileDescriptor is used to create 173 * a new ParcelFileDescriptor. 174 * 175 * @return A new ParcelFileDescriptor with the FileDescriptor of the 176 * specified Socket. 177 */ 178 public static ParcelFileDescriptor fromSocket(Socket socket) { 179 FileDescriptor fd = getFileDescriptorFromSocket(socket); 180 return fd != null ? new ParcelFileDescriptor(fd) : null; 181 } 182 183 // Extracts the file descriptor from the specified socket and returns it untouched 184 private static native FileDescriptor getFileDescriptorFromSocket(Socket socket); 185 186 /** 187 * Create two ParcelFileDescriptors structured as a data pipe. The first 188 * ParcelFileDescriptor in the returned array is the read side; the second 189 * is the write side. 190 */ 191 public static ParcelFileDescriptor[] createPipe() throws IOException { 192 FileDescriptor[] fds = new FileDescriptor[2]; 193 createPipeNative(fds); 194 ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[2]; 195 pfds[0] = new ParcelFileDescriptor(fds[0]); 196 pfds[1] = new ParcelFileDescriptor(fds[1]); 197 return pfds; 198 } 199 200 private static native void createPipeNative(FileDescriptor[] outFds) throws IOException; 201 202 /** 203 * @hide Please use createPipe() or ContentProvider.openPipeHelper(). 204 * Gets a file descriptor for a read-only copy of the given data. 205 * 206 * @param data Data to copy. 207 * @param name Name for the shared memory area that may back the file descriptor. 208 * This is purely informative and may be {@code null}. 209 * @return A ParcelFileDescriptor. 210 * @throws IOException if there is an error while creating the shared memory area. 211 */ 212 @Deprecated 213 public static ParcelFileDescriptor fromData(byte[] data, String name) throws IOException { 214 if (data == null) return null; 215 MemoryFile file = new MemoryFile(name, data.length); 216 if (data.length > 0) { 217 file.writeBytes(data, 0, 0, data.length); 218 } 219 file.deactivate(); 220 FileDescriptor fd = file.getFileDescriptor(); 221 return fd != null ? new ParcelFileDescriptor(fd) : null; 222 } 223 224 /** 225 * Retrieve the actual FileDescriptor associated with this object. 226 * 227 * @return Returns the FileDescriptor associated with this object. 228 */ 229 public FileDescriptor getFileDescriptor() { 230 return mFileDescriptor; 231 } 232 233 /** 234 * Return the total size of the file representing this fd, as determined 235 * by stat(). Returns -1 if the fd is not a file. 236 */ 237 public native long getStatSize(); 238 239 /** 240 * This is needed for implementing AssetFileDescriptor.AutoCloseOutputStream, 241 * and I really don't think we want it to be public. 242 * @hide 243 */ 244 public native long seekTo(long pos); 245 246 /** 247 * Return the native fd int for this ParcelFileDescriptor. The 248 * ParcelFileDescriptor still owns the fd, and it still must be closed 249 * through this API. 250 */ 251 public int getFd() { 252 if (mClosed) { 253 throw new IllegalStateException("Already closed"); 254 } 255 return getFdNative(); 256 } 257 258 private native int getFdNative(); 259 260 /** 261 * Return the native fd int for this ParcelFileDescriptor and detach it 262 * from the object here. You are now responsible for closing the fd in 263 * native code. 264 */ 265 public int detachFd() { 266 if (mClosed) { 267 throw new IllegalStateException("Already closed"); 268 } 269 if (mParcelDescriptor != null) { 270 int fd = mParcelDescriptor.detachFd(); 271 mClosed = true; 272 return fd; 273 } 274 int fd = getFd(); 275 mClosed = true; 276 Parcel.clearFileDescriptor(mFileDescriptor); 277 return fd; 278 } 279 280 /** 281 * Close the ParcelFileDescriptor. This implementation closes the underlying 282 * OS resources allocated to represent this stream. 283 * 284 * @throws IOException 285 * If an error occurs attempting to close this ParcelFileDescriptor. 286 */ 287 public void close() throws IOException { 288 synchronized (this) { 289 if (mClosed) return; 290 mClosed = true; 291 } 292 if (mParcelDescriptor != null) { 293 // If this is a proxy to another file descriptor, just call through to its 294 // close method. 295 mParcelDescriptor.close(); 296 } else { 297 Parcel.closeFileDescriptor(mFileDescriptor); 298 } 299 } 300 301 /** 302 * An InputStream you can create on a ParcelFileDescriptor, which will 303 * take care of calling {@link ParcelFileDescriptor#close 304 * ParcelFileDescriptor.close()} for you when the stream is closed. 305 */ 306 public static class AutoCloseInputStream extends FileInputStream { 307 private final ParcelFileDescriptor mFd; 308 309 public AutoCloseInputStream(ParcelFileDescriptor fd) { 310 super(fd.getFileDescriptor()); 311 mFd = fd; 312 } 313 314 @Override 315 public void close() throws IOException { 316 try { 317 mFd.close(); 318 } finally { 319 super.close(); 320 } 321 } 322 } 323 324 /** 325 * An OutputStream you can create on a ParcelFileDescriptor, which will 326 * take care of calling {@link ParcelFileDescriptor#close 327 * ParcelFileDescriptor.close()} for you when the stream is closed. 328 */ 329 public static class AutoCloseOutputStream extends FileOutputStream { 330 private final ParcelFileDescriptor mFd; 331 332 public AutoCloseOutputStream(ParcelFileDescriptor fd) { 333 super(fd.getFileDescriptor()); 334 mFd = fd; 335 } 336 337 @Override 338 public void close() throws IOException { 339 try { 340 mFd.close(); 341 } finally { 342 super.close(); 343 } 344 } 345 } 346 347 @Override 348 public String toString() { 349 return "{ParcelFileDescriptor: " + mFileDescriptor + "}"; 350 } 351 352 @Override 353 protected void finalize() throws Throwable { 354 try { 355 if (!mClosed) { 356 close(); 357 } 358 } finally { 359 super.finalize(); 360 } 361 } 362 363 public ParcelFileDescriptor(ParcelFileDescriptor descriptor) { 364 super(); 365 mParcelDescriptor = descriptor; 366 mFileDescriptor = mParcelDescriptor.mFileDescriptor; 367 } 368 369 /*package */ParcelFileDescriptor(FileDescriptor descriptor) { 370 super(); 371 if (descriptor == null) { 372 throw new NullPointerException("descriptor must not be null"); 373 } 374 mFileDescriptor = descriptor; 375 mParcelDescriptor = null; 376 } 377 378 /* Parcelable interface */ 379 public int describeContents() { 380 return Parcelable.CONTENTS_FILE_DESCRIPTOR; 381 } 382 383 /** 384 * {@inheritDoc} 385 * If {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set in flags, 386 * the file descriptor will be closed after a copy is written to the Parcel. 387 */ 388 public void writeToParcel(Parcel out, int flags) { 389 out.writeFileDescriptor(mFileDescriptor); 390 if ((flags&PARCELABLE_WRITE_RETURN_VALUE) != 0 && !mClosed) { 391 try { 392 close(); 393 } catch (IOException e) { 394 // Empty 395 } 396 } 397 } 398 399 public static final Parcelable.Creator<ParcelFileDescriptor> CREATOR 400 = new Parcelable.Creator<ParcelFileDescriptor>() { 401 public ParcelFileDescriptor createFromParcel(Parcel in) { 402 return in.readFileDescriptor(); 403 } 404 public ParcelFileDescriptor[] newArray(int size) { 405 return new ParcelFileDescriptor[size]; 406 } 407 }; 408 409} 410