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. */
10 #include <sys/types.h>
14 #include <sys/select.h>
21 * Write a buffer to a file descriptor, re-write on short writes.
23 * \param fd The file descriptor.
24 * \param buf The buffer to be sent.
25 * \param len The length of \a buf.
27 * \return Standard. In any case, the number of bytes that have been written is
30 int write_all(int fd
, const char *buf
, size_t *len
)
36 while (*len
< total
) {
37 int ret
= write(fd
, buf
+ *len
, total
- *len
);
39 return -ERRNO_TO_PARA_ERROR(errno
);
46 * Write a buffer to a non-blocking file descriptor.
48 * \param fd The file descriptor.
49 * \param buf the buffer to write.
50 * \param len the number of bytes of \a buf.
51 * \param max_bytes_per_write Do not write more than that many bytes at once.
53 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
56 * EAGAIN is not considered an error condition. For example CCID3 has a
57 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
58 * case means that there is currently no space in the wait queue, but this can
59 * change at any moment.
61 * \return Negative on errors, number of bytes written else.
63 int write_nonblock(int fd
, const char *buf
, size_t len
,
64 size_t max_bytes_per_write
)
69 while (written
< len
) {
70 size_t num
= len
- written
;
72 if (max_bytes_per_write
&& max_bytes_per_write
< num
)
73 num
= max_bytes_per_write
;
74 ret
= write(fd
, buf
+ written
, num
);
75 if (ret
< 0 && errno
== EAGAIN
)
78 return -ERRNO_TO_PARA_ERROR(errno
);
85 * Simple wrapper for readv().
87 * \param fd The file descriptor to read from.
88 * \param iov Scatter/gather array used in readv().
89 * \param iovcnt Number of elements in \a iov.
91 * \return A negative error code on errors, the return value of the underlying
92 * call to readv() otherwise.
96 int para_readv(int fd
, struct iovec
*iov
, int iovcnt
)
98 int ret
= readv(fd
, iov
, iovcnt
);
101 return -ERRNO_TO_PARA_ERROR(errno
);
106 * Check whether a file exists.
108 * \param fn The file name.
110 * \return Non-zero iff file exists.
112 int file_exists(const char *fn
)
116 return !stat(fn
, &statbuf
);
120 * Paraslash's wrapper for select(2).
122 * It calls select(2) (with no exceptfds) and starts over if select() was
123 * interrupted by a signal.
125 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
126 * \param readfds fds that should be checked for readability.
127 * \param writefds fds that should be checked for writablility.
128 * \param timeout_tv upper bound on the amount of time elapsed before select()
131 * \return The return value of the underlying select() call on success, the
132 * negative system error code on errors.
134 * All arguments are passed verbatim to select(2).
135 * \sa select(2) select_tut(2).
137 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
138 struct timeval
*timeout_tv
)
142 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
143 while (ret
< 0 && errno
== EINTR
);
145 return -ERRNO_TO_PARA_ERROR(errno
);
150 * Set a file descriptor to blocking mode.
152 * \param fd The file descriptor.
156 __must_check
int mark_fd_blocking(int fd
)
158 int flags
= fcntl(fd
, F_GETFL
);
160 return -ERRNO_TO_PARA_ERROR(errno
);
161 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
163 return -ERRNO_TO_PARA_ERROR(errno
);
168 * Set a file descriptor to non-blocking mode.
170 * \param fd The file descriptor.
174 __must_check
int mark_fd_nonblocking(int fd
)
176 int flags
= fcntl(fd
, F_GETFL
);
178 return -ERRNO_TO_PARA_ERROR(errno
);
179 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
181 return -ERRNO_TO_PARA_ERROR(errno
);
186 * Set a file descriptor in a fd_set.
188 * \param fd The file descriptor to be set.
189 * \param fds The file descriptor set.
190 * \param max_fileno Highest-numbered file descriptor.
192 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
193 * return, \a max_fileno contains the maximum of the old_value and \a fd.
197 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
199 assert(fd
>= 0 && fd
< FD_SETSIZE
);
202 int flags
= fcntl(fd
, F_GETFL
);
203 if (!(flags
& O_NONBLOCK
)) {
204 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
210 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
214 * Paraslash's wrapper for fgets(3).
216 * \param line Pointer to the buffer to store the line.
217 * \param size The size of the buffer given by \a line.
218 * \param f The stream to read from.
220 * \return Unlike the standard fgets() function, an integer value
221 * is returned. On success, this function returns 1. On errors, -E_FGETS
222 * is returned. A zero return value indicates an end of file condition.
224 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
227 if (fgets(line
, size
, f
))
233 if (errno
!= EINTR
) {
234 PARA_ERROR_LOG("%s\n", strerror(errno
));
242 * Paraslash's wrapper for mmap.
244 * \param length Number of bytes to mmap.
245 * \param prot Either PROT_NONE or the bitwise OR of one or more of
246 * PROT_EXEC PROT_READ PROT_WRITE.
247 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
248 * \param fd The file to mmap from.
249 * \param offset Mmap start.
250 * \param map Result pointer.
256 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
264 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
265 if (*m
!= MAP_FAILED
)
269 return -ERRNO_TO_PARA_ERROR(errno
);
273 * Wrapper for the open(2) system call.
275 * \param path The filename.
276 * \param flags The usual open(2) flags.
277 * \param mode Specifies the permissions to use.
279 * The mode parameter must be specified when O_CREAT is in the flags, and is
282 * \return The file descriptor on success, negative on errors.
286 int para_open(const char *path
, int flags
, mode_t mode
)
288 int ret
= open(path
, flags
, mode
);
292 return -ERRNO_TO_PARA_ERROR(errno
);
296 * Wrapper for chdir(2).
298 * \param path The specified directory.
302 int para_chdir(const char *path
)
304 int ret
= chdir(path
);
308 return -ERRNO_TO_PARA_ERROR(errno
);
312 * Save the cwd and open a given directory.
314 * \param dirname Path to the directory to open.
315 * \param dir Result pointer.
316 * \param cwd File descriptor of the current working directory.
320 * Opening the current directory (".") and calling fchdir() to return is
321 * usually faster and more reliable than saving cwd in some buffer and calling
322 * chdir() afterwards.
324 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
325 * stored in \a cwd. If the function returns success, and \a cwd is not \p
326 * NULL, the caller must close this file descriptor (probably after calling
329 * On errors, the function undos everything, so the caller needs neither close
330 * any files, nor change back to the original working directory.
335 int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
340 ret
= para_open(".", O_RDONLY
, 0);
345 ret
= para_chdir(dirname
);
351 ret
= -ERRNO_TO_PARA_ERROR(errno
);
352 /* Ignore return value of fchdir() and close(). We're busted anyway. */
354 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
363 * A wrapper for fchdir().
365 * \param fd An open file descriptor.
369 int para_fchdir(int fd
)
372 return -ERRNO_TO_PARA_ERROR(errno
);
377 * A wrapper for mkdir(2).
379 * \param path Name of the directory to create.
380 * \param mode The permissions to use.
384 int para_mkdir(const char *path
, mode_t mode
)
386 if (!mkdir(path
, mode
))
388 return -ERRNO_TO_PARA_ERROR(errno
);
392 * Open a file and map it into memory.
394 * \param path Name of the regular file to map.
395 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
396 * \param map On success, the mapping is returned here.
397 * \param size size of the mapping.
398 * \param fd_ptr The file descriptor of the mapping.
400 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
401 * open call is closed after mmap(). Otherwise the file is kept open and the
402 * file descriptor is returned in \a fd_ptr.
406 * \sa para_open(), mmap(2).
408 int mmap_full_file(const char *path
, int open_mode
, void **map
,
409 size_t *size
, int *fd_ptr
)
411 int fd
, ret
, mmap_prot
, mmap_flags
;
412 struct stat file_status
;
414 if (open_mode
== O_RDONLY
) {
415 mmap_prot
= PROT_READ
;
416 mmap_flags
= MAP_PRIVATE
;
418 mmap_prot
= PROT_READ
| PROT_WRITE
;
419 mmap_flags
= MAP_SHARED
;
421 ret
= para_open(path
, open_mode
, 0);
425 if (fstat(fd
, &file_status
) < 0) {
426 ret
= -ERRNO_TO_PARA_ERROR(errno
);
429 *size
= file_status
.st_size
;
430 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
432 if (ret
< 0 || !fd_ptr
)
440 * A wrapper for munmap(2).
442 * \param start The start address of the memory mapping.
443 * \param length The size of the mapping.
447 * \sa munmap(2), mmap_full_file().
449 int para_munmap(void *start
, size_t length
)
452 if (munmap(start
, length
) >= 0)
455 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
457 return -ERRNO_TO_PARA_ERROR(err
);
461 * Check a file descriptor for writability.
463 * \param fd The file descriptor.
465 * \return positive if fd is ready for writing, zero if it isn't, negative if
478 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
482 * Ensure that file descriptors 0, 1, and 2 are valid.
484 * Common approach that opens /dev/null until it gets a file descriptor greater
487 * \sa okir's Black Hats Manual.
489 void valid_fd_012(void)
492 int fd
= open("/dev/null", O_RDWR
);
503 * Traverse the given directory recursively.
505 * \param dirname The directory to traverse.
506 * \param func The function to call for each entry.
507 * \param private_data Pointer to an arbitrary data structure.
509 * For each regular file under \a dirname, the supplied function \a func is
510 * called. The full path of the regular file and the \a private_data pointer
511 * are passed to \a func. Directories for which the calling process has no
512 * permissions to change to are silently ignored.
516 int for_each_file_in_dir(const char *dirname
,
517 int (*func
)(const char *, void *), void *private_data
)
520 struct dirent
*entry
;
521 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
524 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
525 /* scan cwd recursively */
526 while ((entry
= readdir(dir
))) {
531 if (!strcmp(entry
->d_name
, "."))
533 if (!strcmp(entry
->d_name
, ".."))
535 if (lstat(entry
->d_name
, &s
) == -1)
538 if (!S_ISREG(m
) && !S_ISDIR(m
))
540 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
542 ret
= func(tmp
, private_data
);
549 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
557 ret2
= para_fchdir(cwd_fd
);
558 if (ret2
< 0 && ret
>= 0)