2 * Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>
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>
20 * Change the name or location of a file.
22 * \param oldpath File to be moved.
23 * \param newpath Destination.
25 * This is just a simple wrapper for the rename(2) system call which returns a
26 * paraslash error code and prints an error message on failure.
32 int xrename(const char *oldpath
, const char *newpath
)
34 int ret
= rename(oldpath
, newpath
);
38 ret
= -ERRNO_TO_PARA_ERROR(errno
);
39 PARA_ERROR_LOG("failed to rename %s -> %s\n", oldpath
, newpath
);
44 * Write an array of buffers to a file descriptor.
46 * \param fd The file descriptor.
47 * \param iov Pointer to one or more buffers.
48 * \param iovcnt The number of buffers.
50 * EAGAIN/EWOULDBLOCK is not considered a fatal error condition. For example
51 * DCCP CCID3 has a sending wait queue which fills up and is emptied
52 * asynchronously. The EAGAIN case means that there is currently no space in
53 * the wait queue, but this can change at any moment.
55 * \return Negative on fatal errors, number of bytes written else.
57 * For blocking file descriptors, this function returns either the sum of all
58 * buffer sizes, or the error code of the fatal error that caused the last
61 * For nonblocking file descriptors there is a third possibility: Any positive
62 * return value less than the sum of the buffer sizes indicates that some bytes
63 * have been written but the next write would block.
65 * \sa writev(2), \ref xwrite().
67 int xwritev(int fd
, struct iovec
*iov
, int iovcnt
)
71 struct iovec saved_iov
, *curiov
;
76 while (i
< iovcnt
&& curiov
->iov_len
> 0) {
77 ssize_t ret
= writev(fd
, curiov
, iovcnt
- i
);
81 if (ret
< curiov
->iov_len
) {
82 curiov
->iov_base
+= ret
;
83 curiov
->iov_len
-= ret
;
86 ret
-= curiov
->iov_len
;
98 * The write() call was interrupted by a signal before
99 * any data was written. Try again.
102 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
)
104 * We don't consider this an error. Note that POSIX
105 * allows either error to be returned, and does not
106 * require these constants to have the same value.
110 return -ERRNO_TO_PARA_ERROR(errno
);
116 * Write a buffer to a file descriptor, re-writing on short writes.
118 * \param fd The file descriptor.
119 * \param buf The buffer to write.
120 * \param len The number of bytes to write.
122 * This is a simple wrapper for \ref xwritev().
124 * \return The return value of the underlying call to \ref xwritev().
126 int xwrite(int fd
, const char *buf
, size_t len
)
128 struct iovec iov
= {.iov_base
= (void *)buf
, .iov_len
= len
};
129 return xwritev(fd
, &iov
, 1);
133 * Write all data to a file descriptor.
135 * \param fd The file descriptor.
136 * \param buf The buffer to be sent.
137 * \param len The length of \a buf.
139 * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
140 * all data could be written.
142 * \return Number of bytes written on success, negative error code else.
144 int write_all(int fd
, const char *buf
, size_t len
)
146 int ret
= xwrite(fd
, buf
, len
);
151 return -E_SHORT_WRITE
;
156 * Write a buffer given by a format string.
158 * \param fd The file descriptor.
159 * \param fmt A format string.
161 * \return The return value of the underlying call to \ref write_all().
163 __printf_2_3
int write_va_buffer(int fd
, const char *fmt
, ...)
170 ret
= xvasprintf(&msg
, fmt
, ap
);
172 ret
= write_all(fd
, msg
, ret
);
178 * Read from a non-blocking file descriptor into multiple buffers.
180 * \param fd The file descriptor to read from.
181 * \param iov Scatter/gather array used in readv().
182 * \param iovcnt Number of elements in \a iov.
183 * \param rfds An optional fd set pointer.
184 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
186 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
187 * not set in \a rfds, this function returns early without doing anything.
188 * Otherwise The function tries to read up to \a sz bytes from \a fd, where \a
189 * sz is the sum of the lengths of all vectors in \a iov. As for xwrite(),
190 * \p EAGAIN is not considered an error condition. However, \p EOF is.
192 * \return Zero or a negative error code. If the underlying call to readv(2)
193 * returned zero (indicating an end of file condition) or failed for some
194 * reason other than \p EAGAIN, a negative error code is returned.
196 * In any case, \a num_bytes contains the number of bytes that have been
197 * successfully read from \a fd (zero if the first readv() call failed with
198 * EAGAIN). Note that even if the function returns negative, some data might
199 * have been read before the error occurred. In this case \a num_bytes is
202 * \sa \ref xwrite(), read(2), readv(2).
204 int readv_nonblock(int fd
, struct iovec
*iov
, int iovcnt
, fd_set
*rfds
,
211 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
212 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
213 * returning false definitely means that no data can currently be read.
214 * This is the common case, so it is worth to avoid the overhead of the
215 * read() system call in this case.
217 if (rfds
&& !FD_ISSET(fd
, rfds
))
220 for (i
= 0, j
= 0; i
< iovcnt
;) {
222 /* fix up the first iov */
223 assert(j
< iov
[i
].iov_len
);
224 iov
[i
].iov_base
+= j
;
226 ret
= readv(fd
, iov
+ i
, iovcnt
- i
);
227 iov
[i
].iov_base
-= j
;
235 return -ERRNO_TO_PARA_ERROR(errno
);
239 if (ret
< iov
[i
].iov_len
- j
) {
243 ret
-= iov
[i
].iov_len
- j
;
253 * Read from a non-blocking file descriptor into a single buffer.
255 * \param fd The file descriptor to read from.
256 * \param buf The buffer to read data to.
257 * \param sz The size of \a buf.
258 * \param rfds \see \ref readv_nonblock().
259 * \param num_bytes \see \ref readv_nonblock().
261 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
264 * \return The return value of the underlying call to readv_nonblock().
266 int read_nonblock(int fd
, void *buf
, size_t sz
, fd_set
*rfds
, size_t *num_bytes
)
268 struct iovec iov
= {.iov_base
= buf
, .iov_len
= sz
};
269 return readv_nonblock(fd
, &iov
, 1, rfds
, num_bytes
);
273 * Read a buffer and check its content for a pattern.
275 * \param fd The file descriptor to receive from.
276 * \param pattern The expected pattern.
277 * \param bufsize The size of the internal buffer.
278 * \param rfds Passed to read_nonblock().
280 * This function tries to read at most \a bufsize bytes from the non-blocking
281 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
282 * received, the beginning of the received buffer is compared with \a pattern,
285 * \return Positive if \a pattern was received, negative on errors, zero if no data
286 * was available to read.
288 * \sa \ref read_nonblock(), \sa strncasecmp(3).
290 int read_pattern(int fd
, const char *pattern
, size_t bufsize
, fd_set
*rfds
)
293 char *buf
= para_malloc(bufsize
+ 1);
294 int ret
= read_nonblock(fd
, buf
, bufsize
, rfds
, &n
);
302 ret
= -E_READ_PATTERN
;
303 len
= strlen(pattern
);
306 if (strncasecmp(buf
, pattern
, len
) != 0)
311 PARA_NOTICE_LOG("%s\n", para_strerror(-ret
));
312 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n
, buf
);
319 * Check whether a file exists.
321 * \param fn The file name.
323 * \return Non-zero iff file exists.
325 int file_exists(const char *fn
)
329 return !stat(fn
, &statbuf
);
333 * Paraslash's wrapper for select(2).
335 * It calls select(2) (with no exceptfds) and starts over if select() was
336 * interrupted by a signal.
338 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
339 * \param readfds fds that should be checked for readability.
340 * \param writefds fds that should be checked for writablility.
341 * \param timeout_tv upper bound on the amount of time elapsed before select()
344 * \return The return value of the underlying select() call on success, the
345 * negative system error code on errors.
347 * All arguments are passed verbatim to select(2).
348 * \sa select(2) select_tut(2).
350 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
351 struct timeval
*timeout_tv
)
355 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
356 while (ret
< 0 && errno
== EINTR
);
358 return -ERRNO_TO_PARA_ERROR(errno
);
363 * Set a file descriptor to blocking mode.
365 * \param fd The file descriptor.
369 __must_check
int mark_fd_blocking(int fd
)
371 int flags
= fcntl(fd
, F_GETFL
);
373 return -ERRNO_TO_PARA_ERROR(errno
);
374 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
376 return -ERRNO_TO_PARA_ERROR(errno
);
381 * Set a file descriptor to non-blocking mode.
383 * \param fd The file descriptor.
387 __must_check
int mark_fd_nonblocking(int fd
)
389 int flags
= fcntl(fd
, F_GETFL
);
391 return -ERRNO_TO_PARA_ERROR(errno
);
392 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
394 return -ERRNO_TO_PARA_ERROR(errno
);
399 * Set a file descriptor in a fd_set.
401 * \param fd The file descriptor to be set.
402 * \param fds The file descriptor set.
403 * \param max_fileno Highest-numbered file descriptor.
405 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
406 * return, \a max_fileno contains the maximum of the old_value and \a fd.
410 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
412 assert(fd
>= 0 && fd
< FD_SETSIZE
);
415 int flags
= fcntl(fd
, F_GETFL
);
416 if (!(flags
& O_NONBLOCK
)) {
417 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd
);
423 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
427 * Paraslash's wrapper for fgets(3).
429 * \param line Pointer to the buffer to store the line.
430 * \param size The size of the buffer given by \a line.
431 * \param f The stream to read from.
433 * \return Unlike the standard fgets() function, an integer value
434 * is returned. On success, this function returns 1. On errors, -E_FGETS
435 * is returned. A zero return value indicates an end of file condition.
437 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
440 if (fgets(line
, size
, f
))
446 if (errno
!= EINTR
) {
447 PARA_ERROR_LOG("%s\n", strerror(errno
));
455 * Paraslash's wrapper for mmap.
457 * \param length Number of bytes to mmap.
458 * \param prot Either PROT_NONE or the bitwise OR of one or more of
459 * PROT_EXEC PROT_READ PROT_WRITE.
460 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
461 * \param fd The file to mmap from.
462 * \param offset Mmap start.
463 * \param map Result pointer.
469 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
477 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
478 if (*m
!= MAP_FAILED
)
482 return -ERRNO_TO_PARA_ERROR(errno
);
486 * Wrapper for the open(2) system call.
488 * \param path The filename.
489 * \param flags The usual open(2) flags.
490 * \param mode Specifies the permissions to use.
492 * The mode parameter must be specified when O_CREAT is in the flags, and is
495 * \return The file descriptor on success, negative on errors.
499 int para_open(const char *path
, int flags
, mode_t mode
)
501 int ret
= open(path
, flags
, mode
);
505 return -ERRNO_TO_PARA_ERROR(errno
);
509 * Wrapper for chdir(2).
511 * \param path The specified directory.
515 int para_chdir(const char *path
)
517 int ret
= chdir(path
);
521 return -ERRNO_TO_PARA_ERROR(errno
);
525 * Save the cwd and open a given directory.
527 * \param dirname Path to the directory to open.
528 * \param dir Result pointer.
529 * \param cwd File descriptor of the current working directory.
533 * Opening the current directory (".") and calling fchdir() to return is
534 * usually faster and more reliable than saving cwd in some buffer and calling
535 * chdir() afterwards.
537 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
538 * stored in \a cwd. If the function returns success, and \a cwd is not \p
539 * NULL, the caller must close this file descriptor (probably after calling
542 * On errors, the function undos everything, so the caller needs neither close
543 * any files, nor change back to the original working directory.
548 static int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
554 ret
= para_open(".", O_RDONLY
, 0);
559 ret
= para_chdir(dirname
);
565 ret
= -ERRNO_TO_PARA_ERROR(errno
);
566 /* Ignore return value of fchdir() and close(). We're busted anyway. */
568 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
577 * A wrapper for fchdir().
579 * \param fd An open file descriptor.
583 static int para_fchdir(int fd
)
586 return -ERRNO_TO_PARA_ERROR(errno
);
591 * A wrapper for mkdir(2).
593 * \param path Name of the directory to create.
594 * \param mode The permissions to use.
598 int para_mkdir(const char *path
, mode_t mode
)
600 if (!mkdir(path
, mode
))
602 return -ERRNO_TO_PARA_ERROR(errno
);
606 * Open a file and map it into memory.
608 * \param path Name of the regular file to map.
609 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
610 * \param map On success, the mapping is returned here.
611 * \param size size of the mapping.
612 * \param fd_ptr The file descriptor of the mapping.
614 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
615 * open call is closed after mmap(). Otherwise the file is kept open and the
616 * file descriptor is returned in \a fd_ptr.
620 * \sa para_open(), mmap(2).
622 int mmap_full_file(const char *path
, int open_mode
, void **map
,
623 size_t *size
, int *fd_ptr
)
625 int fd
, ret
, mmap_prot
, mmap_flags
;
626 struct stat file_status
;
628 if (open_mode
== O_RDONLY
) {
629 mmap_prot
= PROT_READ
;
630 mmap_flags
= MAP_PRIVATE
;
632 mmap_prot
= PROT_READ
| PROT_WRITE
;
633 mmap_flags
= MAP_SHARED
;
635 ret
= para_open(path
, open_mode
, 0);
639 if (fstat(fd
, &file_status
) < 0) {
640 ret
= -ERRNO_TO_PARA_ERROR(errno
);
643 *size
= file_status
.st_size
;
645 * If the file is empty, *size is zero and mmap() would return EINVAL
646 * (Invalid argument). This error is common enough to spend an extra
647 * error code which explicitly states the problem.
653 * If fd refers to a directory, mmap() returns ENODEV (No such device),
654 * at least on Linux. "Is a directory" seems to be more to the point.
656 ret
= -ERRNO_TO_PARA_ERROR(EISDIR
);
657 if (S_ISDIR(file_status
.st_mode
))
660 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
662 if (ret
< 0 || !fd_ptr
)
670 * A wrapper for munmap(2).
672 * \param start The start address of the memory mapping.
673 * \param length The size of the mapping.
677 * \sa munmap(2), mmap_full_file().
679 int para_munmap(void *start
, size_t length
)
685 if (munmap(start
, length
) >= 0)
688 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
690 return -ERRNO_TO_PARA_ERROR(err
);
694 * Check a file descriptor for writability.
696 * \param fd The file descriptor.
698 * \return positive if fd is ready for writing, zero if it isn't, negative if
711 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
715 * Ensure that file descriptors 0, 1, and 2 are valid.
717 * Common approach that opens /dev/null until it gets a file descriptor greater
720 * \sa okir's Black Hats Manual.
722 void valid_fd_012(void)
725 int fd
= open("/dev/null", O_RDWR
);
736 * Traverse the given directory recursively.
738 * \param dirname The directory to traverse.
739 * \param func The function to call for each entry.
740 * \param private_data Pointer to an arbitrary data structure.
742 * For each regular file under \a dirname, the supplied function \a func is
743 * called. The full path of the regular file and the \a private_data pointer
744 * are passed to \a func. Directories for which the calling process has no
745 * permissions to change to are silently ignored.
749 int for_each_file_in_dir(const char *dirname
,
750 int (*func
)(const char *, void *), void *private_data
)
753 struct dirent
*entry
;
754 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
757 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
758 /* scan cwd recursively */
759 while ((entry
= readdir(dir
))) {
764 if (!strcmp(entry
->d_name
, "."))
766 if (!strcmp(entry
->d_name
, ".."))
768 if (lstat(entry
->d_name
, &s
) == -1)
771 if (!S_ISREG(m
) && !S_ISDIR(m
))
773 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
775 ret
= func(tmp
, private_data
);
782 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
790 ret2
= para_fchdir(cwd_fd
);
791 if (ret2
< 0 && ret
>= 0)