a73325ba5af60adb712213aa789243dc02f74d90
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 a buffer to a file descriptor, re-writing on short writes.
24 * \param fd The file descriptor.
25 * \param buf The buffer to write.
26 * \param len The number of bytes to write.
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. For blocking
34 * file descriptors this function returns either \a len or the error code of
35 * the fatal error that caused the last write call to fail. For nonblocking
36 * file descriptors there is a third possibility: A positive return value < \a
37 * len indicates that some bytes have been written but the next write would
40 int xwrite(int fd
, const char *buf
, size_t len
)
44 while (written
< len
) {
45 ssize_t ret
= write(fd
, buf
+ written
, len
- written
);
52 * The write() call was interrupted by a signal before
53 * any data was written. Try again.
56 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
)
58 * We don't consider this an error. Note that POSIX
59 * allows either error to be returned, and does not
60 * require these constants to have the same value.
64 return -ERRNO_TO_PARA_ERROR(errno
);
70 * Write all data to a file descriptor.
72 * \param fd The file descriptor.
73 * \param buf The buffer to be sent.
74 * \param len The length of \a buf.
76 * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
77 * all data could be written.
79 * \return Number of bytes written on success, negative error code else.
81 int write_all(int fd
, const char *buf
, size_t len
)
83 int ret
= xwrite(fd
, buf
, len
);
88 return -E_SHORT_WRITE
;
93 * Write a buffer given by a format string.
95 * \param fd The file descriptor.
96 * \param fmt A format string.
98 * \return The return value of the underlying call to \ref write_all().
100 __printf_2_3
int write_va_buffer(int fd
, const char *fmt
, ...)
105 PARA_VSPRINTF(fmt
, msg
);
106 ret
= write_buffer(fd
, msg
);
112 * Read from a non-blocking file descriptor into multiple buffers.
114 * \param fd The file descriptor to read from.
115 * \param iov Scatter/gather array used in readv().
116 * \param iovcnt Number of elements in \a iov.
117 * \param rfds An optional fd set pointer.
118 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
120 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
121 * not set in \a rfds, this function returns early without doing anything.
122 * Otherwise The function tries to read up to \a sz bytes from \a fd. As for
123 * xwrite(), EAGAIN is not considered an error condition. However, EOF
126 * \return Zero or a negative error code. If the underlying call to readv(2)
127 * returned zero (indicating an end of file condition) or failed for some
128 * reason other than \p EAGAIN, a negative return value is returned.
130 * In any case, \a num_bytes contains the number of bytes that have been
131 * successfully read from \a fd (zero if the first readv() call failed with
132 * EAGAIN). Note that even if the function returns negative, some data might
133 * have been read before the error occurred. In this case \a num_bytes is
136 * \sa \ref xwrite(), read(2), readv(2).
138 int readv_nonblock(int fd
, struct iovec
*iov
, int iovcnt
, fd_set
*rfds
,
145 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
146 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
147 * returning false definitely means that no data can currently be read.
148 * This is the common case, so it is worth to avoid the overhead of the
149 * read() system call in this case.
151 if (rfds
&& !FD_ISSET(fd
, rfds
))
154 for (i
= 0, j
= 0; i
< iovcnt
;) {
156 /* fix up the first iov */
157 assert(j
< iov
[i
].iov_len
);
158 iov
[i
].iov_base
+= j
;
160 ret
= readv(fd
, iov
+ i
, iovcnt
- i
);
161 iov
[i
].iov_base
-= j
;
169 return -ERRNO_TO_PARA_ERROR(errno
);
173 if (ret
< iov
[i
].iov_len
- j
) {
177 ret
-= iov
[i
].iov_len
- j
;
187 * Read from a non-blocking file descriptor into a single buffer.
189 * \param fd The file descriptor to read from.
190 * \param buf The buffer to read data to.
191 * \param sz The size of \a buf.
192 * \param rfds \see \ref readv_nonblock().
193 * \param num_bytes \see \ref readv_nonblock().
195 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
198 * \return The return value of the underlying call to readv_nonblock().
200 int read_nonblock(int fd
, void *buf
, size_t sz
, fd_set
*rfds
, size_t *num_bytes
)
202 struct iovec iov
= {.iov_base
= buf
, .iov_len
= sz
};
203 return readv_nonblock(fd
, &iov
, 1, rfds
, num_bytes
);
207 * Read a buffer and check its content for a pattern.
209 * \param fd The file descriptor to receive from.
210 * \param pattern The expected pattern.
211 * \param bufsize The size of the internal buffer.
212 * \param rfds Passed to read_nonblock().
214 * This function tries to read at most \a bufsize bytes from the non-blocking
215 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
216 * received, the beginning of the received buffer is compared with \a pattern,
219 * \return Positive if \a pattern was received, negative on errors, zero if no data
220 * was available to read.
222 * \sa \ref read_nonblock(), \sa strncasecmp(3).
224 int read_pattern(int fd
, const char *pattern
, size_t bufsize
, fd_set
*rfds
)
227 char *buf
= para_malloc(bufsize
+ 1);
228 int ret
= read_nonblock(fd
, buf
, bufsize
, rfds
, &n
);
236 ret
= -E_READ_PATTERN
;
237 len
= strlen(pattern
);
240 if (strncasecmp(buf
, pattern
, len
) != 0)
245 PARA_NOTICE_LOG("%s\n", para_strerror(-ret
));
246 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n
, buf
);
253 * Check whether a file exists.
255 * \param fn The file name.
257 * \return Non-zero iff file exists.
259 int file_exists(const char *fn
)
263 return !stat(fn
, &statbuf
);
267 * Paraslash's wrapper for select(2).
269 * It calls select(2) (with no exceptfds) and starts over if select() was
270 * interrupted by a signal.
272 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
273 * \param readfds fds that should be checked for readability.
274 * \param writefds fds that should be checked for writablility.
275 * \param timeout_tv upper bound on the amount of time elapsed before select()
278 * \return The return value of the underlying select() call on success, the
279 * negative system error code on errors.
281 * All arguments are passed verbatim to select(2).
282 * \sa select(2) select_tut(2).
284 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
285 struct timeval
*timeout_tv
)
289 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
290 while (ret
< 0 && errno
== EINTR
);
292 return -ERRNO_TO_PARA_ERROR(errno
);
297 * Set a file descriptor to blocking mode.
299 * \param fd The file descriptor.
303 __must_check
int mark_fd_blocking(int fd
)
305 int flags
= fcntl(fd
, F_GETFL
);
307 return -ERRNO_TO_PARA_ERROR(errno
);
308 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
310 return -ERRNO_TO_PARA_ERROR(errno
);
315 * Set a file descriptor to non-blocking mode.
317 * \param fd The file descriptor.
321 __must_check
int mark_fd_nonblocking(int fd
)
323 int flags
= fcntl(fd
, F_GETFL
);
325 return -ERRNO_TO_PARA_ERROR(errno
);
326 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
328 return -ERRNO_TO_PARA_ERROR(errno
);
333 * Set a file descriptor in a fd_set.
335 * \param fd The file descriptor to be set.
336 * \param fds The file descriptor set.
337 * \param max_fileno Highest-numbered file descriptor.
339 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
340 * return, \a max_fileno contains the maximum of the old_value and \a fd.
344 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
346 assert(fd
>= 0 && fd
< FD_SETSIZE
);
349 int flags
= fcntl(fd
, F_GETFL
);
350 if (!(flags
& O_NONBLOCK
)) {
351 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
357 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
361 * Paraslash's wrapper for fgets(3).
363 * \param line Pointer to the buffer to store the line.
364 * \param size The size of the buffer given by \a line.
365 * \param f The stream to read from.
367 * \return Unlike the standard fgets() function, an integer value
368 * is returned. On success, this function returns 1. On errors, -E_FGETS
369 * is returned. A zero return value indicates an end of file condition.
371 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
374 if (fgets(line
, size
, f
))
380 if (errno
!= EINTR
) {
381 PARA_ERROR_LOG("%s\n", strerror(errno
));
389 * Paraslash's wrapper for mmap.
391 * \param length Number of bytes to mmap.
392 * \param prot Either PROT_NONE or the bitwise OR of one or more of
393 * PROT_EXEC PROT_READ PROT_WRITE.
394 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
395 * \param fd The file to mmap from.
396 * \param offset Mmap start.
397 * \param map Result pointer.
403 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
411 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
412 if (*m
!= MAP_FAILED
)
416 return -ERRNO_TO_PARA_ERROR(errno
);
420 * Wrapper for the open(2) system call.
422 * \param path The filename.
423 * \param flags The usual open(2) flags.
424 * \param mode Specifies the permissions to use.
426 * The mode parameter must be specified when O_CREAT is in the flags, and is
429 * \return The file descriptor on success, negative on errors.
433 int para_open(const char *path
, int flags
, mode_t mode
)
435 int ret
= open(path
, flags
, mode
);
439 return -ERRNO_TO_PARA_ERROR(errno
);
443 * Wrapper for chdir(2).
445 * \param path The specified directory.
449 int para_chdir(const char *path
)
451 int ret
= chdir(path
);
455 return -ERRNO_TO_PARA_ERROR(errno
);
459 * Save the cwd and open a given directory.
461 * \param dirname Path to the directory to open.
462 * \param dir Result pointer.
463 * \param cwd File descriptor of the current working directory.
467 * Opening the current directory (".") and calling fchdir() to return is
468 * usually faster and more reliable than saving cwd in some buffer and calling
469 * chdir() afterwards.
471 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
472 * stored in \a cwd. If the function returns success, and \a cwd is not \p
473 * NULL, the caller must close this file descriptor (probably after calling
476 * On errors, the function undos everything, so the caller needs neither close
477 * any files, nor change back to the original working directory.
482 static int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
487 ret
= para_open(".", O_RDONLY
, 0);
492 ret
= para_chdir(dirname
);
498 ret
= -ERRNO_TO_PARA_ERROR(errno
);
499 /* Ignore return value of fchdir() and close(). We're busted anyway. */
501 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
510 * A wrapper for fchdir().
512 * \param fd An open file descriptor.
516 static int para_fchdir(int fd
)
519 return -ERRNO_TO_PARA_ERROR(errno
);
524 * A wrapper for mkdir(2).
526 * \param path Name of the directory to create.
527 * \param mode The permissions to use.
531 int para_mkdir(const char *path
, mode_t mode
)
533 if (!mkdir(path
, mode
))
535 return -ERRNO_TO_PARA_ERROR(errno
);
539 * Open a file and map it into memory.
541 * \param path Name of the regular file to map.
542 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
543 * \param map On success, the mapping is returned here.
544 * \param size size of the mapping.
545 * \param fd_ptr The file descriptor of the mapping.
547 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
548 * open call is closed after mmap(). Otherwise the file is kept open and the
549 * file descriptor is returned in \a fd_ptr.
553 * \sa para_open(), mmap(2).
555 int mmap_full_file(const char *path
, int open_mode
, void **map
,
556 size_t *size
, int *fd_ptr
)
558 int fd
, ret
, mmap_prot
, mmap_flags
;
559 struct stat file_status
;
561 if (open_mode
== O_RDONLY
) {
562 mmap_prot
= PROT_READ
;
563 mmap_flags
= MAP_PRIVATE
;
565 mmap_prot
= PROT_READ
| PROT_WRITE
;
566 mmap_flags
= MAP_SHARED
;
568 ret
= para_open(path
, open_mode
, 0);
572 if (fstat(fd
, &file_status
) < 0) {
573 ret
= -ERRNO_TO_PARA_ERROR(errno
);
576 *size
= file_status
.st_size
;
577 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
579 if (ret
< 0 || !fd_ptr
)
587 * A wrapper for munmap(2).
589 * \param start The start address of the memory mapping.
590 * \param length The size of the mapping.
594 * \sa munmap(2), mmap_full_file().
596 int para_munmap(void *start
, size_t length
)
602 if (munmap(start
, length
) >= 0)
605 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
607 return -ERRNO_TO_PARA_ERROR(err
);
611 * Check a file descriptor for writability.
613 * \param fd The file descriptor.
615 * \return positive if fd is ready for writing, zero if it isn't, negative if
628 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
632 * Ensure that file descriptors 0, 1, and 2 are valid.
634 * Common approach that opens /dev/null until it gets a file descriptor greater
637 * \sa okir's Black Hats Manual.
639 void valid_fd_012(void)
642 int fd
= open("/dev/null", O_RDWR
);
653 * Traverse the given directory recursively.
655 * \param dirname The directory to traverse.
656 * \param func The function to call for each entry.
657 * \param private_data Pointer to an arbitrary data structure.
659 * For each regular file under \a dirname, the supplied function \a func is
660 * called. The full path of the regular file and the \a private_data pointer
661 * are passed to \a func. Directories for which the calling process has no
662 * permissions to change to are silently ignored.
666 int for_each_file_in_dir(const char *dirname
,
667 int (*func
)(const char *, void *), void *private_data
)
670 struct dirent
*entry
;
671 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
674 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
675 /* scan cwd recursively */
676 while ((entry
= readdir(dir
))) {
681 if (!strcmp(entry
->d_name
, "."))
683 if (!strcmp(entry
->d_name
, ".."))
685 if (lstat(entry
->d_name
, &s
) == -1)
688 if (!S_ISREG(m
) && !S_ISDIR(m
))
690 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
692 ret
= func(tmp
, private_data
);
699 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
707 ret2
= para_fchdir(cwd_fd
);
708 if (ret2
< 0 && ret
>= 0)