2 * Copyright (C) 2006-2009 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file fd.c Helper functions for file descriptor handling. */
13 #include <sys/select.h>
19 * Write a buffer to a file descriptor, re-write on short writes.
21 * \param fd The file descriptor.
22 * \param buf The buffer to be sent.
23 * \param len The length of \a buf.
25 * \return Standard. In any case, the number of bytes that have been written is
28 int write_all(int fd
, const char *buf
, size_t *len
)
34 while (*len
< total
) {
35 int ret
= write(fd
, buf
+ *len
, total
- *len
);
37 return -ERRNO_TO_PARA_ERROR(errno
);
44 * Write a buffer to a non-blocking file descriptor.
46 * \param fd The file descriptor.
47 * \param buf the buffer to write.
48 * \param len the number of bytes of \a buf.
49 * \param max_bytes_per_write Do not write more than that many bytes at once.
51 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
54 * EAGAIN is not considered an error condition. For example CCID3 has a
55 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
56 * case means that there is currently no space in the wait queue, but this can
57 * change at any moment.
59 * \return Negative on errors, number of bytes written else.
61 int write_nonblock(int fd
, const char *buf
, size_t len
,
62 size_t max_bytes_per_write
)
67 while (written
< len
) {
68 size_t num
= len
- written
;
70 if (max_bytes_per_write
&& max_bytes_per_write
< num
)
71 num
= max_bytes_per_write
;
72 ret
= write(fd
, buf
+ written
, num
);
73 if (ret
< 0 && errno
== EAGAIN
)
76 return -ERRNO_TO_PARA_ERROR(errno
);
83 * Check whether a file exists.
85 * \param fn The file name.
87 * \return Non-zero iff file exists.
89 int file_exists(const char *fn
)
93 return !stat(fn
, &statbuf
);
97 * Paraslash's wrapper for select(2).
99 * It calls select(2) (with no exceptfds) and starts over if select() was
100 * interrupted by a signal.
102 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
103 * \param readfds fds that should be checked for readability.
104 * \param writefds fds that should be checked for writablility.
105 * \param timeout_tv upper bound on the amount of time elapsed before select()
108 * \return The return value of the underlying select() call on success, the
109 * negative system error code on errors.
111 * All arguments are passed verbatim to select(2).
112 * \sa select(2) select_tut(2).
114 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
115 struct timeval
*timeout_tv
)
119 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
121 } while (ret
< 0 && err
== EINTR
);
123 return -ERRNO_TO_PARA_ERROR(errno
);
128 * Set a file descriptor to blocking mode.
130 * \param fd The file descriptor.
134 __must_check
int mark_fd_blocking(int fd
)
136 int flags
= fcntl(fd
, F_GETFL
);
138 return -ERRNO_TO_PARA_ERROR(errno
);
139 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
141 return -ERRNO_TO_PARA_ERROR(errno
);
146 * Set a file descriptor to non-blocking mode.
148 * \param fd The file descriptor.
152 __must_check
int mark_fd_nonblocking(int fd
)
154 int flags
= fcntl(fd
, F_GETFL
);
156 return -ERRNO_TO_PARA_ERROR(errno
);
157 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
159 return -ERRNO_TO_PARA_ERROR(errno
);
164 * Set a file descriptor in a fd_set.
166 * \param fd The file descriptor to be set.
167 * \param fds The file descriptor set.
168 * \param max_fileno Highest-numbered file descriptor.
170 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
171 * return, \a max_fileno contains the maximum of the old_value and \a fd.
175 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
177 assert(fd
>= 0 && fd
< FD_SETSIZE
);
180 int flags
= fcntl(fd
, F_GETFL
);
181 if (!(flags
& O_NONBLOCK
)) {
182 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
188 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
192 * Paraslash's wrapper for fgets(3).
194 * \param line Pointer to the buffer to store the line.
195 * \param size The size of the buffer given by \a line.
196 * \param f The stream to read from.
198 * \return Unlike the standard fgets() function, an integer value
199 * is returned. On success, this function returns 1. On errors, -E_FGETS
200 * is returned. A zero return value indicates an end of file condition.
202 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
205 if (fgets(line
, size
, f
))
211 if (errno
!= EINTR
) {
212 PARA_ERROR_LOG("%s\n", strerror(errno
));
220 * Paraslash's wrapper for mmap.
222 * \param length Number of bytes to mmap.
223 * \param prot Either PROT_NONE or the bitwise OR of one or more of
224 * PROT_EXEC PROT_READ PROT_WRITE.
225 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
226 * \param fd The file to mmap from.
227 * \param offset Mmap start.
228 * \param map Result pointer.
234 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
242 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
243 if (*m
!= MAP_FAILED
)
247 return -ERRNO_TO_PARA_ERROR(errno
);
251 * Wrapper for the open(2) system call.
253 * \param path The filename.
254 * \param flags The usual open(2) flags.
255 * \param mode Specifies the permissions to use.
257 * The mode parameter must be specified when O_CREAT is in the flags, and is
260 * \return The file descriptor on success, negative on errors.
264 int para_open(const char *path
, int flags
, mode_t mode
)
266 int ret
= open(path
, flags
, mode
);
270 return -ERRNO_TO_PARA_ERROR(errno
);
274 * Wrapper for chdir(2).
276 * \param path The specified directory.
280 int para_chdir(const char *path
)
282 int ret
= chdir(path
);
286 return -ERRNO_TO_PARA_ERROR(errno
);
290 * Save the cwd and open a given directory.
292 * \param dirname Path to the directory to open.
293 * \param dir Result pointer.
294 * \param cwd File descriptor of the current working directory.
298 * Opening the current directory (".") and calling fchdir() to return is
299 * usually faster and more reliable than saving cwd in some buffer and calling
300 * chdir() afterwards.
302 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
303 * stored in \a cwd. If the function returns success, and \a cwd is not \p
304 * NULL, the caller must close this file descriptor (probably after calling
307 * On errors, the function undos everything, so the caller needs neither close
308 * any files, nor change back to the original working directory.
313 int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
318 ret
= para_open(".", O_RDONLY
, 0);
323 ret
= para_chdir(dirname
);
329 ret
= -ERRNO_TO_PARA_ERROR(errno
);
330 /* Ignore return value of fchdir() and close(). We're busted anyway. */
332 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
341 * A wrapper for fchdir().
343 * \param fd An open file descriptor.
347 int para_fchdir(int fd
)
350 return -ERRNO_TO_PARA_ERROR(errno
);
355 * A wrapper for mkdir(2).
357 * \param path Name of the directory to create.
358 * \param mode The permissions to use.
362 int para_mkdir(const char *path
, mode_t mode
)
364 if (!mkdir(path
, mode
))
366 return -ERRNO_TO_PARA_ERROR(errno
);
370 * Open a file and map it into memory.
372 * \param path Name of the regular file to map.
373 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
374 * \param map On success, the mapping is returned here.
375 * \param size size of the mapping.
376 * \param fd_ptr The file descriptor of the mapping.
378 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
379 * open call is closed after mmap(). Otherwise the file is kept open and the
380 * file descriptor is returned in \a fd_ptr.
384 * \sa para_open(), mmap(2).
386 int mmap_full_file(const char *path
, int open_mode
, void **map
,
387 size_t *size
, int *fd_ptr
)
389 int fd
, ret
, mmap_prot
, mmap_flags
;
390 struct stat file_status
;
392 if (open_mode
== O_RDONLY
) {
393 mmap_prot
= PROT_READ
;
394 mmap_flags
= MAP_PRIVATE
;
396 mmap_prot
= PROT_READ
| PROT_WRITE
;
397 mmap_flags
= MAP_SHARED
;
399 ret
= para_open(path
, open_mode
, 0);
403 if (fstat(fd
, &file_status
) < 0) {
404 ret
= -ERRNO_TO_PARA_ERROR(errno
);
407 *size
= file_status
.st_size
;
408 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
410 if (ret
< 0 || !fd_ptr
)
418 * A wrapper for munmap(2).
420 * \param start The start address of the memory mapping.
421 * \param length The size of the mapping.
425 * \sa munmap(2), mmap_full_file().
427 int para_munmap(void *start
, size_t length
)
430 if (munmap(start
, length
) >= 0)
433 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
435 return -ERRNO_TO_PARA_ERROR(err
);
439 * Check a file descriptor for writability.
441 * \param fd The file descriptor.
443 * \return positive if fd is ready for writing, zero if it isn't, negative if
449 struct timeval tv
= {0, 0};
457 ret
= select(fd
+ 1, NULL
, &wfds
, NULL
, &tv
);
458 if (ret
< 0 && errno
== EINTR
)
464 * Ensure that file descriptors 0, 1, and 2 are valid.
466 * Common approach that opens /dev/null until it gets a file descriptor greater
469 * \sa okir's Black Hats Manual.
471 void valid_fd_012(void)
474 int fd
= open("/dev/null", O_RDWR
);