d2f93611de1e66ad9bbcd8dcd5aada40546f560f
2 * Copyright (C) 2006-2012 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>
22 * Write an array of buffers to a file descriptor.
24 * \param fd The file descriptor.
25 * \param iov Pointer to one or more buffers.
26 * \param iovcnt The number of buffers.
28 * EAGAIN/EWOULDBLOCK is not considered a fatal error condition. For example
29 * DCCP CCID3 has a sending wait queue which fills up and is emptied
30 * asynchronously. The EAGAIN case means that there is currently no space in
31 * the wait queue, but this can change at any moment.
33 * \return Negative on fatal errors, number of bytes written else.
35 * For blocking file descriptors, this function returns either the sum of all
36 * buffer sizes, or the error code of the fatal error that caused the last
39 * For nonblocking file descriptors there is a third possibility: Any positive
40 * return value less than the sum of the buffer sizes indicates that some bytes
41 * have been written but the next write would block.
43 * \sa writev(2), \ref xwrite().
45 int xwritev(int fd
, struct iovec
*iov
, int iovcnt
)
49 struct iovec saved_iov
, *curiov
;
54 while (i
< iovcnt
&& curiov
->iov_len
> 0) {
55 ssize_t ret
= writev(fd
, curiov
, iovcnt
- i
);
59 if (ret
< curiov
->iov_len
) {
60 curiov
->iov_base
+= ret
;
61 curiov
->iov_len
-= ret
;
64 ret
-= curiov
->iov_len
;
76 * The write() call was interrupted by a signal before
77 * any data was written. Try again.
80 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
)
82 * We don't consider this an error. Note that POSIX
83 * allows either error to be returned, and does not
84 * require these constants to have the same value.
88 return -ERRNO_TO_PARA_ERROR(errno
);
94 * Write a buffer to a file descriptor, re-writing on short writes.
96 * \param fd The file descriptor.
97 * \param buf The buffer to write.
98 * \param len The number of bytes to write.
100 * This is a simple wrapper for \ref xwritev().
102 * \return The return value of the underlying call to \ref xwritev().
104 int xwrite(int fd
, const char *buf
, size_t len
)
106 struct iovec iov
= {.iov_base
= (void *)buf
, .iov_len
= len
};
107 return xwritev(fd
, &iov
, 1);
111 * Write all data to a file descriptor.
113 * \param fd The file descriptor.
114 * \param buf The buffer to be sent.
115 * \param len The length of \a buf.
117 * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
118 * all data could be written.
120 * \return Number of bytes written on success, negative error code else.
122 int write_all(int fd
, const char *buf
, size_t len
)
124 int ret
= xwrite(fd
, buf
, len
);
129 return -E_SHORT_WRITE
;
134 * Write a buffer given by a format string.
136 * \param fd The file descriptor.
137 * \param fmt A format string.
139 * \return The return value of the underlying call to \ref write_all().
141 __printf_2_3
int write_va_buffer(int fd
, const char *fmt
, ...)
146 PARA_VSPRINTF(fmt
, msg
);
147 ret
= write_buffer(fd
, msg
);
153 * Read from a non-blocking file descriptor into multiple buffers.
155 * \param fd The file descriptor to read from.
156 * \param iov Scatter/gather array used in readv().
157 * \param iovcnt Number of elements in \a iov.
158 * \param rfds An optional fd set pointer.
159 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
161 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
162 * not set in \a rfds, this function returns early without doing anything.
163 * Otherwise The function tries to read up to \a sz bytes from \a fd. As for
164 * xwrite(), EAGAIN is not considered an error condition. However, EOF
167 * \return Zero or a negative error code. If the underlying call to readv(2)
168 * returned zero (indicating an end of file condition) or failed for some
169 * reason other than \p EAGAIN, a negative return value is returned.
171 * In any case, \a num_bytes contains the number of bytes that have been
172 * successfully read from \a fd (zero if the first readv() call failed with
173 * EAGAIN). Note that even if the function returns negative, some data might
174 * have been read before the error occurred. In this case \a num_bytes is
177 * \sa \ref xwrite(), read(2), readv(2).
179 int readv_nonblock(int fd
, struct iovec
*iov
, int iovcnt
, fd_set
*rfds
,
186 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
187 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
188 * returning false definitely means that no data can currently be read.
189 * This is the common case, so it is worth to avoid the overhead of the
190 * read() system call in this case.
192 if (rfds
&& !FD_ISSET(fd
, rfds
))
195 for (i
= 0, j
= 0; i
< iovcnt
;) {
197 /* fix up the first iov */
198 assert(j
< iov
[i
].iov_len
);
199 iov
[i
].iov_base
+= j
;
201 ret
= readv(fd
, iov
+ i
, iovcnt
- i
);
202 iov
[i
].iov_base
-= j
;
210 return -ERRNO_TO_PARA_ERROR(errno
);
214 if (ret
< iov
[i
].iov_len
- j
) {
218 ret
-= iov
[i
].iov_len
- j
;
228 * Read from a non-blocking file descriptor into a single buffer.
230 * \param fd The file descriptor to read from.
231 * \param buf The buffer to read data to.
232 * \param sz The size of \a buf.
233 * \param rfds \see \ref readv_nonblock().
234 * \param num_bytes \see \ref readv_nonblock().
236 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
239 * \return The return value of the underlying call to readv_nonblock().
241 int read_nonblock(int fd
, void *buf
, size_t sz
, fd_set
*rfds
, size_t *num_bytes
)
243 struct iovec iov
= {.iov_base
= buf
, .iov_len
= sz
};
244 return readv_nonblock(fd
, &iov
, 1, rfds
, num_bytes
);
248 * Read a buffer and check its content for a pattern.
250 * \param fd The file descriptor to receive from.
251 * \param pattern The expected pattern.
252 * \param bufsize The size of the internal buffer.
253 * \param rfds Passed to read_nonblock().
255 * This function tries to read at most \a bufsize bytes from the non-blocking
256 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
257 * received, the beginning of the received buffer is compared with \a pattern,
260 * \return Positive if \a pattern was received, negative on errors, zero if no data
261 * was available to read.
263 * \sa \ref read_nonblock(), \sa strncasecmp(3).
265 int read_pattern(int fd
, const char *pattern
, size_t bufsize
, fd_set
*rfds
)
268 char *buf
= para_malloc(bufsize
+ 1);
269 int ret
= read_nonblock(fd
, buf
, bufsize
, rfds
, &n
);
277 ret
= -E_READ_PATTERN
;
278 len
= strlen(pattern
);
281 if (strncasecmp(buf
, pattern
, len
) != 0)
286 PARA_NOTICE_LOG("%s\n", para_strerror(-ret
));
287 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n
, buf
);
294 * Check whether a file exists.
296 * \param fn The file name.
298 * \return Non-zero iff file exists.
300 int file_exists(const char *fn
)
304 return !stat(fn
, &statbuf
);
308 * Paraslash's wrapper for select(2).
310 * It calls select(2) (with no exceptfds) and starts over if select() was
311 * interrupted by a signal.
313 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
314 * \param readfds fds that should be checked for readability.
315 * \param writefds fds that should be checked for writablility.
316 * \param timeout_tv upper bound on the amount of time elapsed before select()
319 * \return The return value of the underlying select() call on success, the
320 * negative system error code on errors.
322 * All arguments are passed verbatim to select(2).
323 * \sa select(2) select_tut(2).
325 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
326 struct timeval
*timeout_tv
)
330 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
331 while (ret
< 0 && errno
== EINTR
);
333 return -ERRNO_TO_PARA_ERROR(errno
);
338 * Set a file descriptor to blocking mode.
340 * \param fd The file descriptor.
344 __must_check
int mark_fd_blocking(int fd
)
346 int flags
= fcntl(fd
, F_GETFL
);
348 return -ERRNO_TO_PARA_ERROR(errno
);
349 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
351 return -ERRNO_TO_PARA_ERROR(errno
);
356 * Set a file descriptor to non-blocking mode.
358 * \param fd The file descriptor.
362 __must_check
int mark_fd_nonblocking(int fd
)
364 int flags
= fcntl(fd
, F_GETFL
);
366 return -ERRNO_TO_PARA_ERROR(errno
);
367 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
369 return -ERRNO_TO_PARA_ERROR(errno
);
374 * Set a file descriptor in a fd_set.
376 * \param fd The file descriptor to be set.
377 * \param fds The file descriptor set.
378 * \param max_fileno Highest-numbered file descriptor.
380 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
381 * return, \a max_fileno contains the maximum of the old_value and \a fd.
385 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
387 assert(fd
>= 0 && fd
< FD_SETSIZE
);
390 int flags
= fcntl(fd
, F_GETFL
);
391 if (!(flags
& O_NONBLOCK
)) {
392 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
398 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
402 * Paraslash's wrapper for fgets(3).
404 * \param line Pointer to the buffer to store the line.
405 * \param size The size of the buffer given by \a line.
406 * \param f The stream to read from.
408 * \return Unlike the standard fgets() function, an integer value
409 * is returned. On success, this function returns 1. On errors, -E_FGETS
410 * is returned. A zero return value indicates an end of file condition.
412 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
415 if (fgets(line
, size
, f
))
421 if (errno
!= EINTR
) {
422 PARA_ERROR_LOG("%s\n", strerror(errno
));
430 * Paraslash's wrapper for mmap.
432 * \param length Number of bytes to mmap.
433 * \param prot Either PROT_NONE or the bitwise OR of one or more of
434 * PROT_EXEC PROT_READ PROT_WRITE.
435 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
436 * \param fd The file to mmap from.
437 * \param offset Mmap start.
438 * \param map Result pointer.
444 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
452 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
453 if (*m
!= MAP_FAILED
)
457 return -ERRNO_TO_PARA_ERROR(errno
);
461 * Wrapper for the open(2) system call.
463 * \param path The filename.
464 * \param flags The usual open(2) flags.
465 * \param mode Specifies the permissions to use.
467 * The mode parameter must be specified when O_CREAT is in the flags, and is
470 * \return The file descriptor on success, negative on errors.
474 int para_open(const char *path
, int flags
, mode_t mode
)
476 int ret
= open(path
, flags
, mode
);
480 return -ERRNO_TO_PARA_ERROR(errno
);
484 * Wrapper for chdir(2).
486 * \param path The specified directory.
490 int para_chdir(const char *path
)
492 int ret
= chdir(path
);
496 return -ERRNO_TO_PARA_ERROR(errno
);
500 * Save the cwd and open a given directory.
502 * \param dirname Path to the directory to open.
503 * \param dir Result pointer.
504 * \param cwd File descriptor of the current working directory.
508 * Opening the current directory (".") and calling fchdir() to return is
509 * usually faster and more reliable than saving cwd in some buffer and calling
510 * chdir() afterwards.
512 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
513 * stored in \a cwd. If the function returns success, and \a cwd is not \p
514 * NULL, the caller must close this file descriptor (probably after calling
517 * On errors, the function undos everything, so the caller needs neither close
518 * any files, nor change back to the original working directory.
523 static int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
528 ret
= para_open(".", O_RDONLY
, 0);
533 ret
= para_chdir(dirname
);
539 ret
= -ERRNO_TO_PARA_ERROR(errno
);
540 /* Ignore return value of fchdir() and close(). We're busted anyway. */
542 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
551 * A wrapper for fchdir().
553 * \param fd An open file descriptor.
557 static int para_fchdir(int fd
)
560 return -ERRNO_TO_PARA_ERROR(errno
);
565 * A wrapper for mkdir(2).
567 * \param path Name of the directory to create.
568 * \param mode The permissions to use.
572 int para_mkdir(const char *path
, mode_t mode
)
574 if (!mkdir(path
, mode
))
576 return -ERRNO_TO_PARA_ERROR(errno
);
580 * Open a file and map it into memory.
582 * \param path Name of the regular file to map.
583 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
584 * \param map On success, the mapping is returned here.
585 * \param size size of the mapping.
586 * \param fd_ptr The file descriptor of the mapping.
588 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
589 * open call is closed after mmap(). Otherwise the file is kept open and the
590 * file descriptor is returned in \a fd_ptr.
594 * \sa para_open(), mmap(2).
596 int mmap_full_file(const char *path
, int open_mode
, void **map
,
597 size_t *size
, int *fd_ptr
)
599 int fd
, ret
, mmap_prot
, mmap_flags
;
600 struct stat file_status
;
602 if (open_mode
== O_RDONLY
) {
603 mmap_prot
= PROT_READ
;
604 mmap_flags
= MAP_PRIVATE
;
606 mmap_prot
= PROT_READ
| PROT_WRITE
;
607 mmap_flags
= MAP_SHARED
;
609 ret
= para_open(path
, open_mode
, 0);
613 if (fstat(fd
, &file_status
) < 0) {
614 ret
= -ERRNO_TO_PARA_ERROR(errno
);
617 *size
= file_status
.st_size
;
618 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
620 if (ret
< 0 || !fd_ptr
)
628 * A wrapper for munmap(2).
630 * \param start The start address of the memory mapping.
631 * \param length The size of the mapping.
635 * \sa munmap(2), mmap_full_file().
637 int para_munmap(void *start
, size_t length
)
643 if (munmap(start
, length
) >= 0)
646 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
648 return -ERRNO_TO_PARA_ERROR(err
);
652 * Check a file descriptor for writability.
654 * \param fd The file descriptor.
656 * \return positive if fd is ready for writing, zero if it isn't, negative if
669 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
673 * Ensure that file descriptors 0, 1, and 2 are valid.
675 * Common approach that opens /dev/null until it gets a file descriptor greater
678 * \sa okir's Black Hats Manual.
680 void valid_fd_012(void)
683 int fd
= open("/dev/null", O_RDWR
);
694 * Traverse the given directory recursively.
696 * \param dirname The directory to traverse.
697 * \param func The function to call for each entry.
698 * \param private_data Pointer to an arbitrary data structure.
700 * For each regular file under \a dirname, the supplied function \a func is
701 * called. The full path of the regular file and the \a private_data pointer
702 * are passed to \a func. Directories for which the calling process has no
703 * permissions to change to are silently ignored.
707 int for_each_file_in_dir(const char *dirname
,
708 int (*func
)(const char *, void *), void *private_data
)
711 struct dirent
*entry
;
712 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
715 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
716 /* scan cwd recursively */
717 while ((entry
= readdir(dir
))) {
722 if (!strcmp(entry
->d_name
, "."))
724 if (!strcmp(entry
->d_name
, ".."))
726 if (lstat(entry
->d_name
, &s
) == -1)
729 if (!S_ISREG(m
) && !S_ISDIR(m
))
731 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
733 ret
= func(tmp
, private_data
);
740 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
748 ret2
= para_fchdir(cwd_fd
);
749 if (ret2
< 0 && ret
>= 0)