blob: 5bd129f19166930b572ced0c617a63add2e638fc [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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);
Dianne Hackborn18668392010-03-23 22:10:55 -0700116 return fd != null ? new ParcelFileDescriptor(fd) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 }
118
119 /**
120 * Create a new ParcelFileDescriptor from the specified Socket.
121 *
122 * @param socket The Socket whose FileDescriptor is used to create
123 * a new ParcelFileDescriptor.
124 *
125 * @return A new ParcelFileDescriptor with the FileDescriptor of the
126 * specified Socket.
127 */
128 public static ParcelFileDescriptor fromSocket(Socket socket) {
129 FileDescriptor fd = getFileDescriptorFromSocket(socket);
Dianne Hackborn18668392010-03-23 22:10:55 -0700130 return fd != null ? new ParcelFileDescriptor(fd) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 }
132
133 // Extracts the file descriptor from the specified socket and returns it untouched
134 private static native FileDescriptor getFileDescriptorFromSocket(Socket socket);
135
136 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700137 * Create two ParcelFileDescriptors structured as a data pipe. The first
138 * ParcelFileDescriptor in the returned array is the read side; the second
139 * is the write side.
140 */
141 public static ParcelFileDescriptor[] createPipe() throws IOException {
142 FileDescriptor[] fds = new FileDescriptor[2];
143 int res = createPipeNative(fds);
144 if (res == 0) {
145 ParcelFileDescriptor[] pfds = new ParcelFileDescriptor[2];
146 pfds[0] = new ParcelFileDescriptor(fds[0]);
147 pfds[1] = new ParcelFileDescriptor(fds[1]);
148 return pfds;
149 }
150 throw new IOException("Unable to create pipe: errno=" + -res);
151 }
152
153 private static native int createPipeNative(FileDescriptor[] outFds);
154
155 /**
Dianne Hackborn540f86a2011-01-11 17:52:22 -0800156 * @hide Please use createPipe() or ContentProvider.openPipeHelper().
Bjorn Bringerta006b4722010-04-14 14:43:26 +0100157 * Gets a file descriptor for a read-only copy of the given data.
158 *
159 * @param data Data to copy.
160 * @param name Name for the shared memory area that may back the file descriptor.
161 * This is purely informative and may be {@code null}.
162 * @return A ParcelFileDescriptor.
163 * @throws IOException if there is an error while creating the shared memory area.
164 */
Dianne Hackborna2ea7472010-12-20 12:10:01 -0800165 @Deprecated
Bjorn Bringerta006b4722010-04-14 14:43:26 +0100166 public static ParcelFileDescriptor fromData(byte[] data, String name) throws IOException {
167 if (data == null) return null;
168 MemoryFile file = new MemoryFile(name, data.length);
169 if (data.length > 0) {
170 file.writeBytes(data, 0, 0, data.length);
171 }
172 file.deactivate();
173 FileDescriptor fd = file.getFileDescriptor();
174 return fd != null ? new ParcelFileDescriptor(fd) : null;
175 }
176
177 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * Retrieve the actual FileDescriptor associated with this object.
179 *
180 * @return Returns the FileDescriptor associated with this object.
181 */
182 public FileDescriptor getFileDescriptor() {
183 return mFileDescriptor;
184 }
185
186 /**
187 * Return the total size of the file representing this fd, as determined
188 * by stat(). Returns -1 if the fd is not a file.
189 */
190 public native long getStatSize();
191
192 /**
193 * This is needed for implementing AssetFileDescriptor.AutoCloseOutputStream,
194 * and I really don't think we want it to be public.
195 * @hide
196 */
197 public native long seekTo(long pos);
198
199 /**
Dianne Hackbornc9119f52011-02-28 18:03:26 -0800200 * Return the native fd int for this ParcelFileDescriptor. The
201 * ParcelFileDescriptor still owns the fd, and it still must be closed
202 * through this API.
203 */
204 public int getFd() {
205 if (mClosed) {
206 throw new IllegalStateException("Already closed");
207 }
208 return getFdNative();
209 }
210
211 private native int getFdNative();
212
213 /**
214 * Return the native fd int for this ParcelFileDescriptor and detach it
215 * from the object here. You are now responsible for closing the fd in
216 * native code.
217 */
218 public int detachFd() {
219 if (mClosed) {
220 throw new IllegalStateException("Already closed");
221 }
222 if (mParcelDescriptor != null) {
223 int fd = mParcelDescriptor.detachFd();
224 mClosed = true;
225 return fd;
226 }
227 int fd = getFd();
228 mClosed = true;
229 Parcel.clearFileDescriptor(mFileDescriptor);
230 return fd;
231 }
232
233 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 * Close the ParcelFileDescriptor. This implementation closes the underlying
235 * OS resources allocated to represent this stream.
236 *
237 * @throws IOException
238 * If an error occurs attempting to close this ParcelFileDescriptor.
239 */
240 public void close() throws IOException {
Dianne Hackborn18668392010-03-23 22:10:55 -0700241 synchronized (this) {
242 if (mClosed) return;
243 mClosed = true;
244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 if (mParcelDescriptor != null) {
246 // If this is a proxy to another file descriptor, just call through to its
247 // close method.
248 mParcelDescriptor.close();
249 } else {
250 Parcel.closeFileDescriptor(mFileDescriptor);
251 }
252 }
253
254 /**
255 * An InputStream you can create on a ParcelFileDescriptor, which will
256 * take care of calling {@link ParcelFileDescriptor#close
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700257 * ParcelFileDescriptor.close()} for you when the stream is closed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 */
259 public static class AutoCloseInputStream extends FileInputStream {
260 private final ParcelFileDescriptor mFd;
261
262 public AutoCloseInputStream(ParcelFileDescriptor fd) {
263 super(fd.getFileDescriptor());
264 mFd = fd;
265 }
266
267 @Override
268 public void close() throws IOException {
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700269 try {
270 mFd.close();
271 } finally {
272 super.close();
273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 }
275 }
276
277 /**
278 * An OutputStream you can create on a ParcelFileDescriptor, which will
279 * take care of calling {@link ParcelFileDescriptor#close
Christopher Tatefa9e7c02010-05-06 12:07:10 -0700280 * ParcelFileDescriptor.close()} for you when the stream is closed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 */
282 public static class AutoCloseOutputStream extends FileOutputStream {
283 private final ParcelFileDescriptor mFd;
284
285 public AutoCloseOutputStream(ParcelFileDescriptor fd) {
286 super(fd.getFileDescriptor());
287 mFd = fd;
288 }
289
290 @Override
291 public void close() throws IOException {
Brian Carlstromfd9ddd12010-11-04 11:24:58 -0700292 try {
293 mFd.close();
294 } finally {
295 super.close();
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 }
298 }
299
300 @Override
301 public String toString() {
302 return "{ParcelFileDescriptor: " + mFileDescriptor + "}";
303 }
304
305 @Override
306 protected void finalize() throws Throwable {
307 try {
308 if (!mClosed) {
309 close();
310 }
311 } finally {
312 super.finalize();
313 }
314 }
315
316 public ParcelFileDescriptor(ParcelFileDescriptor descriptor) {
317 super();
318 mParcelDescriptor = descriptor;
319 mFileDescriptor = mParcelDescriptor.mFileDescriptor;
320 }
321
322 /*package */ParcelFileDescriptor(FileDescriptor descriptor) {
323 super();
Dianne Hackborn18668392010-03-23 22:10:55 -0700324 if (descriptor == null) {
325 throw new NullPointerException("descriptor must not be null");
326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 mFileDescriptor = descriptor;
328 mParcelDescriptor = null;
329 }
330
331 /* Parcelable interface */
332 public int describeContents() {
333 return Parcelable.CONTENTS_FILE_DESCRIPTOR;
334 }
335
Dan Egnorb3e4ef32010-07-20 09:03:35 -0700336 /**
337 * {@inheritDoc}
338 * If {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set in flags,
339 * the file descriptor will be closed after a copy is written to the Parcel.
340 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 public void writeToParcel(Parcel out, int flags) {
342 out.writeFileDescriptor(mFileDescriptor);
343 if ((flags&PARCELABLE_WRITE_RETURN_VALUE) != 0 && !mClosed) {
344 try {
345 close();
346 } catch (IOException e) {
347 // Empty
348 }
349 }
350 }
351
352 public static final Parcelable.Creator<ParcelFileDescriptor> CREATOR
353 = new Parcelable.Creator<ParcelFileDescriptor>() {
354 public ParcelFileDescriptor createFromParcel(Parcel in) {
355 return in.readFileDescriptor();
356 }
357 public ParcelFileDescriptor[] newArray(int size) {
358 return new ParcelFileDescriptor[size];
359 }
360 };
361
362}