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>
22 * Write a buffer to a file descriptor, re-write on short writes.
24 * \param fd The file descriptor.
25 * \param buf The buffer to be sent.
26 * \param len The length of \a buf.
28 * \return Standard. In any case, the number of bytes that have been written is
31 int write_all(int fd
, const char *buf
, size_t *len
)
37 while (*len
< total
) {
38 int ret
= write(fd
, buf
+ *len
, total
- *len
);
40 return -ERRNO_TO_PARA_ERROR(errno
);
47 * Write a buffer to a non-blocking file descriptor.
49 * \param fd The file descriptor.
50 * \param buf the buffer to write.
51 * \param len the number of bytes of \a buf.
52 * \param max_bytes_per_write Do not write more than that many bytes at once.
54 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
57 * EAGAIN is not considered an error condition. For example CCID3 has a
58 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
59 * case means that there is currently no space in the wait queue, but this can
60 * change at any moment.
62 * \return Negative on errors, number of bytes written else.
64 int write_nonblock(int fd
, const char *buf
, size_t len
,
65 size_t max_bytes_per_write
)
70 while (written
< len
) {
71 size_t num
= len
- written
;
73 if (max_bytes_per_write
&& max_bytes_per_write
< num
)
74 num
= max_bytes_per_write
;
75 ret
= write(fd
, buf
+ written
, num
);
76 if (ret
< 0 && errno
== EAGAIN
)
79 return -ERRNO_TO_PARA_ERROR(errno
);
86 * Simple wrapper for readv().
88 * \param fd The file descriptor to read from.
89 * \param iov Scatter/gather array used in readv().
90 * \param iovcnt Number of elements in \a iov.
92 * \return A negative error code on errors, the return value of the underlying
93 * call to readv() otherwise.
97 int para_readv(int fd
, struct iovec
*iov
, int iovcnt
)
99 int ret
= readv(fd
, iov
, iovcnt
);
102 return -ERRNO_TO_PARA_ERROR(errno
);
107 * Check whether a file exists.
109 * \param fn The file name.
111 * \return Non-zero iff file exists.
113 int file_exists(const char *fn
)
117 return !stat(fn
, &statbuf
);
121 * Paraslash's wrapper for select(2).
123 * It calls select(2) (with no exceptfds) and starts over if select() was
124 * interrupted by a signal.
126 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
127 * \param readfds fds that should be checked for readability.
128 * \param writefds fds that should be checked for writablility.
129 * \param timeout_tv upper bound on the amount of time elapsed before select()
132 * \return The return value of the underlying select() call on success, the
133 * negative system error code on errors.
135 * All arguments are passed verbatim to select(2).
136 * \sa select(2) select_tut(2).
138 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
139 struct timeval
*timeout_tv
)
143 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
144 while (ret
< 0 && errno
== EINTR
);
146 return -ERRNO_TO_PARA_ERROR(errno
);
151 * Set a file descriptor to blocking mode.
153 * \param fd The file descriptor.
157 __must_check
int mark_fd_blocking(int fd
)
159 int flags
= fcntl(fd
, F_GETFL
);
161 return -ERRNO_TO_PARA_ERROR(errno
);
162 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
164 return -ERRNO_TO_PARA_ERROR(errno
);
169 * Set a file descriptor to non-blocking mode.
171 * \param fd The file descriptor.
175 __must_check
int mark_fd_nonblocking(int fd
)
177 int flags
= fcntl(fd
, F_GETFL
);
179 return -ERRNO_TO_PARA_ERROR(errno
);
180 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
182 return -ERRNO_TO_PARA_ERROR(errno
);
187 * Set a file descriptor in a fd_set.
189 * \param fd The file descriptor to be set.
190 * \param fds The file descriptor set.
191 * \param max_fileno Highest-numbered file descriptor.
193 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
194 * return, \a max_fileno contains the maximum of the old_value and \a fd.
198 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
200 assert(fd
>= 0 && fd
< FD_SETSIZE
);
203 int flags
= fcntl(fd
, F_GETFL
);
204 if (!(flags
& O_NONBLOCK
)) {
205 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
211 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
215 * Paraslash's wrapper for fgets(3).
217 * \param line Pointer to the buffer to store the line.
218 * \param size The size of the buffer given by \a line.
219 * \param f The stream to read from.
221 * \return Unlike the standard fgets() function, an integer value
222 * is returned. On success, this function returns 1. On errors, -E_FGETS
223 * is returned. A zero return value indicates an end of file condition.
225 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
228 if (fgets(line
, size
, f
))
234 if (errno
!= EINTR
) {
235 PARA_ERROR_LOG("%s\n", strerror(errno
));
243 * Paraslash's wrapper for mmap.
245 * \param length Number of bytes to mmap.
246 * \param prot Either PROT_NONE or the bitwise OR of one or more of
247 * PROT_EXEC PROT_READ PROT_WRITE.
248 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
249 * \param fd The file to mmap from.
250 * \param offset Mmap start.
251 * \param map Result pointer.
257 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
265 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
266 if (*m
!= MAP_FAILED
)
270 return -ERRNO_TO_PARA_ERROR(errno
);
274 * Wrapper for the open(2) system call.
276 * \param path The filename.
277 * \param flags The usual open(2) flags.
278 * \param mode Specifies the permissions to use.
280 * The mode parameter must be specified when O_CREAT is in the flags, and is
283 * \return The file descriptor on success, negative on errors.
287 int para_open(const char *path
, int flags
, mode_t mode
)
289 int ret
= open(path
, flags
, mode
);
293 return -ERRNO_TO_PARA_ERROR(errno
);
297 * Wrapper for chdir(2).
299 * \param path The specified directory.
303 int para_chdir(const char *path
)
305 int ret
= chdir(path
);
309 return -ERRNO_TO_PARA_ERROR(errno
);
313 * Save the cwd and open a given directory.
315 * \param dirname Path to the directory to open.
316 * \param dir Result pointer.
317 * \param cwd File descriptor of the current working directory.
321 * Opening the current directory (".") and calling fchdir() to return is
322 * usually faster and more reliable than saving cwd in some buffer and calling
323 * chdir() afterwards.
325 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
326 * stored in \a cwd. If the function returns success, and \a cwd is not \p
327 * NULL, the caller must close this file descriptor (probably after calling
330 * On errors, the function undos everything, so the caller needs neither close
331 * any files, nor change back to the original working directory.
336 int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
341 ret
= para_open(".", O_RDONLY
, 0);
346 ret
= para_chdir(dirname
);
352 ret
= -ERRNO_TO_PARA_ERROR(errno
);
353 /* Ignore return value of fchdir() and close(). We're busted anyway. */
355 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
364 * A wrapper for fchdir().
366 * \param fd An open file descriptor.
370 int para_fchdir(int fd
)
373 return -ERRNO_TO_PARA_ERROR(errno
);
378 * A wrapper for mkdir(2).
380 * \param path Name of the directory to create.
381 * \param mode The permissions to use.
385 int para_mkdir(const char *path
, mode_t mode
)
387 if (!mkdir(path
, mode
))
389 return -ERRNO_TO_PARA_ERROR(errno
);
393 * Open a file and map it into memory.
395 * \param path Name of the regular file to map.
396 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
397 * \param map On success, the mapping is returned here.
398 * \param size size of the mapping.
399 * \param fd_ptr The file descriptor of the mapping.
401 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
402 * open call is closed after mmap(). Otherwise the file is kept open and the
403 * file descriptor is returned in \a fd_ptr.
407 * \sa para_open(), mmap(2).
409 int mmap_full_file(const char *path
, int open_mode
, void **map
,
410 size_t *size
, int *fd_ptr
)
412 int fd
, ret
, mmap_prot
, mmap_flags
;
413 struct stat file_status
;
415 if (open_mode
== O_RDONLY
) {
416 mmap_prot
= PROT_READ
;
417 mmap_flags
= MAP_PRIVATE
;
419 mmap_prot
= PROT_READ
| PROT_WRITE
;
420 mmap_flags
= MAP_SHARED
;
422 ret
= para_open(path
, open_mode
, 0);
426 if (fstat(fd
, &file_status
) < 0) {
427 ret
= -ERRNO_TO_PARA_ERROR(errno
);
430 *size
= file_status
.st_size
;
431 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
433 if (ret
< 0 || !fd_ptr
)
441 * A wrapper for munmap(2).
443 * \param start The start address of the memory mapping.
444 * \param length The size of the mapping.
448 * \sa munmap(2), mmap_full_file().
450 int para_munmap(void *start
, size_t length
)
453 if (munmap(start
, length
) >= 0)
456 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
458 return -ERRNO_TO_PARA_ERROR(err
);
462 * Check a file descriptor for writability.
464 * \param fd The file descriptor.
466 * \return positive if fd is ready for writing, zero if it isn't, negative if
479 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
483 * Ensure that file descriptors 0, 1, and 2 are valid.
485 * Common approach that opens /dev/null until it gets a file descriptor greater
488 * \sa okir's Black Hats Manual.
490 void valid_fd_012(void)
493 int fd
= open("/dev/null", O_RDWR
);
504 * Traverse the given directory recursively.
506 * \param dirname The directory to traverse.
507 * \param func The function to call for each entry.
508 * \param private_data Pointer to an arbitrary data structure.
510 * For each regular file under \a dirname, the supplied function \a func is
511 * called. The full path of the regular file and the \a private_data pointer
512 * are passed to \a func. Directories for which the calling process has no
513 * permissions to change to are silently ignored.
517 int for_each_file_in_dir(const char *dirname
,
518 int (*func
)(const char *, void *), void *private_data
)
521 struct dirent
*entry
;
522 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
525 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
526 /* scan cwd recursively */
527 while ((entry
= readdir(dir
))) {
532 if (!strcmp(entry
->d_name
, "."))
534 if (!strcmp(entry
->d_name
, ".."))
536 if (lstat(entry
->d_name
, &s
) == -1)
539 if (!S_ISREG(m
) && !S_ISDIR(m
))
541 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
543 ret
= func(tmp
, private_data
);
550 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
558 ret2
= para_fchdir(cwd_fd
);
559 if (ret2
< 0 && ret
>= 0)