1 /* Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file fd.c Helper functions for file descriptor handling. */
17 * Change the name or location of a file.
19 * \param oldpath File to be moved.
20 * \param newpath Destination.
22 * This is just a simple wrapper for the rename(2) system call which returns a
23 * paraslash error code and prints an error message on failure.
29 int xrename(const char *oldpath, const char *newpath)
31 int ret = rename(oldpath, newpath);
35 ret = -ERRNO_TO_PARA_ERROR(errno);
36 PARA_ERROR_LOG("failed to rename %s -> %s\n", oldpath, newpath);
41 * Write an array of buffers to a file descriptor.
43 * \param fd The file descriptor.
44 * \param iov Pointer to one or more buffers.
45 * \param iovcnt The number of buffers.
47 * EAGAIN/EWOULDBLOCK is not considered a fatal error condition. For example
48 * DCCP CCID3 has a sending wait queue which fills up and is emptied
49 * asynchronously. The EAGAIN case means that there is currently no space in
50 * the wait queue, but this can change at any moment.
52 * \return Negative on fatal errors, number of bytes written else.
54 * For blocking file descriptors, this function returns either the sum of all
55 * buffer sizes, or the error code of the fatal error that caused the last
58 * For nonblocking file descriptors there is a third possibility: Any positive
59 * return value less than the sum of the buffer sizes indicates that some bytes
60 * have been written but the next write would block.
62 * \sa writev(2), \ref xwrite().
64 int xwritev(int fd, struct iovec *iov, int iovcnt)
68 struct iovec saved_iov, *curiov;
73 while (i < iovcnt && curiov->iov_len > 0) {
74 ssize_t ret = writev(fd, curiov, iovcnt - i);
78 if (ret < curiov->iov_len) {
79 curiov->iov_base += ret;
80 curiov->iov_len -= ret;
83 ret -= curiov->iov_len;
95 * The write() call was interrupted by a signal before
96 * any data was written. Try again.
99 if (errno == EAGAIN || errno == EWOULDBLOCK)
101 * We don't consider this an error. Note that POSIX
102 * allows either error to be returned, and does not
103 * require these constants to have the same value.
107 return -ERRNO_TO_PARA_ERROR(errno);
113 * Write a buffer to a file descriptor, re-writing on short writes.
115 * \param fd The file descriptor.
116 * \param buf The buffer to write.
117 * \param len The number of bytes to write.
119 * This is a simple wrapper for \ref xwritev().
121 * \return The return value of the underlying call to \ref xwritev().
123 int xwrite(int fd, const char *buf, size_t len)
125 struct iovec iov = {.iov_base = (void *)buf, .iov_len = len};
126 return xwritev(fd, &iov, 1);
130 * Write all data to a file descriptor.
132 * \param fd The file descriptor.
133 * \param buf The buffer to be sent.
134 * \param len The length of \a buf.
136 * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
137 * all data could be written.
139 * \return Number of bytes written on success, negative error code else.
141 int write_all(int fd, const char *buf, size_t len)
143 int ret = xwrite(fd, buf, len);
148 return -E_SHORT_WRITE;
153 * Write a buffer given by a format string.
155 * \param fd The file descriptor.
156 * \param fmt A format string.
158 * \return The return value of the underlying call to \ref write_all().
160 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
167 ret = xvasprintf(&msg, fmt, ap);
169 ret = write_all(fd, msg, ret);
175 * Read from a non-blocking file descriptor into multiple buffers.
177 * \param fd The file descriptor to read from.
178 * \param iov Scatter/gather array used in readv().
179 * \param iovcnt Number of elements in \a iov.
180 * \param rfds An optional fd set pointer.
181 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
183 * If rfds is not NULL and the (non-blocking) file descriptor fd is not set in
184 * rfds, this function returns early without doing anything. Otherwise it tries
185 * to read up to sz bytes from fd, where sz is the sum of the lengths of all
186 * vectors in iov. Like \ref xwrite(), EAGAIN and EINTR are not considered
187 * error conditions. However, EOF is.
189 * \return Zero or a negative error code. If the underlying call to readv(2)
190 * returned zero (indicating an end of file condition) or failed for some
191 * reason other than EAGAIN or EINTR, a negative error code is returned.
193 * In any case, \a num_bytes contains the number of bytes that have been
194 * successfully read from \a fd (zero if the first readv() call failed with
195 * EAGAIN). Note that even if the function returns negative, some data might
196 * have been read before the error occurred. In this case \a num_bytes is
199 * \sa \ref xwrite(), read(2), readv(2).
201 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
208 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
209 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
210 * returning false definitely means that no data can currently be read.
211 * This is the common case, so it is worth to avoid the overhead of the
212 * read() system call in this case.
214 if (rfds && !FD_ISSET(fd, rfds))
217 for (i = 0, j = 0; i < iovcnt;) {
219 /* fix up the first iov */
220 assert(j < iov[i].iov_len);
221 iov[i].iov_base += j;
223 ret = readv(fd, iov + i, iovcnt - i);
224 iov[i].iov_base -= j;
230 if (errno == EAGAIN || errno == EINTR)
232 return -ERRNO_TO_PARA_ERROR(errno);
236 if (ret < iov[i].iov_len - j) {
240 ret -= iov[i].iov_len - j;
250 * Read from a non-blocking file descriptor into a single buffer.
252 * \param fd The file descriptor to read from.
253 * \param buf The buffer to read data to.
254 * \param sz The size of \a buf.
255 * \param rfds \see \ref readv_nonblock().
256 * \param num_bytes \see \ref readv_nonblock().
258 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
261 * \return The return value of the underlying call to readv_nonblock().
263 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
265 struct iovec iov = {.iov_base = buf, .iov_len = sz};
266 return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
270 * Read a buffer and check its content for a pattern.
272 * \param fd The file descriptor to receive from.
273 * \param pattern The expected pattern.
274 * \param bufsize The size of the internal buffer.
275 * \param rfds Passed to read_nonblock().
277 * This function tries to read at most \a bufsize bytes from the non-blocking
278 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
279 * received, the beginning of the received buffer is compared with \a pattern,
282 * \return Positive if \a pattern was received, negative on errors, zero if no data
283 * was available to read.
285 * \sa \ref read_nonblock(), \sa strncasecmp(3).
287 int read_pattern(int fd, const char *pattern, size_t bufsize, fd_set *rfds)
290 char *buf = para_malloc(bufsize + 1);
291 int ret = read_nonblock(fd, buf, bufsize, rfds, &n);
299 ret = -E_READ_PATTERN;
300 len = strlen(pattern);
303 if (strncasecmp(buf, pattern, len) != 0)
308 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
309 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
316 * Check whether a file exists.
318 * \param fn The file name.
320 * \return True iff file exists.
322 bool file_exists(const char *fn)
326 return !stat(fn, &statbuf);
330 * Paraslash's wrapper for select(2).
332 * It calls select(2) (with no exceptfds) and starts over if select() was
333 * interrupted by a signal.
335 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
336 * \param readfds fds that should be checked for readability.
337 * \param writefds fds that should be checked for writablility.
338 * \param timeout Upper bound in milliseconds.
340 * \return The return value of the underlying select() call on success, the
341 * negative system error code on errors.
343 * All arguments are passed verbatim to select(2).
344 * \sa select(2) select_tut(2).
346 int para_select(int n, fd_set *readfds, fd_set *writefds, int timeout)
353 ret = select(n, readfds, writefds, NULL, &tv);
354 while (ret < 0 && errno == EINTR);
356 return -ERRNO_TO_PARA_ERROR(errno);
361 * Set a file descriptor to blocking mode.
363 * \param fd The file descriptor.
367 __must_check int mark_fd_blocking(int fd)
369 int flags = fcntl(fd, F_GETFL);
371 return -ERRNO_TO_PARA_ERROR(errno);
372 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
374 return -ERRNO_TO_PARA_ERROR(errno);
379 * Set a file descriptor to non-blocking mode.
381 * \param fd The file descriptor.
385 __must_check int mark_fd_nonblocking(int fd)
387 int flags = fcntl(fd, F_GETFL);
389 return -ERRNO_TO_PARA_ERROR(errno);
390 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
392 return -ERRNO_TO_PARA_ERROR(errno);
397 * Set a file descriptor in a fd_set.
399 * \param fd The file descriptor to be set.
400 * \param fds The file descriptor set.
401 * \param max_fileno Highest-numbered file descriptor.
403 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
404 * return, \a max_fileno contains the maximum of the old_value and \a fd.
406 * \sa \ref para_select.
408 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
410 assert(fd >= 0 && fd < FD_SETSIZE);
413 int flags = fcntl(fd, F_GETFL);
414 if (!(flags & O_NONBLOCK)) {
415 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
421 *max_fileno = PARA_MAX(*max_fileno, fd);
425 * Paraslash's wrapper for mmap.
427 * \param length Number of bytes to mmap.
428 * \param prot Either PROT_NONE or the bitwise OR of one or more of
429 * PROT_EXEC PROT_READ PROT_WRITE.
430 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
431 * \param fd The file to mmap from.
432 * \param map Result pointer.
438 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
445 *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
446 if (*m != MAP_FAILED)
450 return -ERRNO_TO_PARA_ERROR(errno);
454 * Wrapper for the open(2) system call.
456 * \param path The filename.
457 * \param flags The usual open(2) flags.
458 * \param mode Specifies the permissions to use.
460 * The mode parameter must be specified when O_CREAT is in the flags, and is
463 * \return The file descriptor on success, negative on errors.
467 int para_open(const char *path, int flags, mode_t mode)
469 int ret = open(path, flags, mode);
473 return -ERRNO_TO_PARA_ERROR(errno);
477 * Wrapper for chdir(2).
479 * \param path The specified directory.
483 int para_chdir(const char *path)
485 int ret = chdir(path);
489 return -ERRNO_TO_PARA_ERROR(errno);
493 * Save the cwd and open a given directory.
495 * \param dirname Path to the directory to open.
496 * \param dir Result pointer.
497 * \param cwd File descriptor of the current working directory.
501 * Opening the current directory (".") and calling fchdir() to return is
502 * usually faster and more reliable than saving cwd in some buffer and calling
503 * chdir() afterwards.
505 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
506 * stored in \a cwd. If the function returns success, and \a cwd is not \p
507 * NULL, the caller must close this file descriptor (probably after calling
510 * On errors, the function undos everything, so the caller needs neither close
511 * any files, nor change back to the original working directory.
516 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
522 ret = para_open(".", O_RDONLY, 0);
527 ret = para_chdir(dirname);
533 ret = -ERRNO_TO_PARA_ERROR(errno);
534 /* Ignore return value of fchdir() and close(). We're busted anyway. */
536 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
545 * A wrapper for mkdir(2).
547 * \param path Name of the directory to create.
548 * \param mode The permissions to use.
552 int para_mkdir(const char *path, mode_t mode)
554 if (!mkdir(path, mode))
556 return -ERRNO_TO_PARA_ERROR(errno);
560 * Open a file and map it into memory.
562 * \param path Name of the regular file to map.
563 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
564 * \param map On success, the mapping is returned here.
565 * \param size size of the mapping.
566 * \param fd_ptr The file descriptor of the mapping.
568 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
569 * open call is closed after mmap(). Otherwise the file is kept open and the
570 * file descriptor is returned in \a fd_ptr.
574 * \sa para_open(), mmap(2).
576 int mmap_full_file(const char *path, int open_mode, void **map,
577 size_t *size, int *fd_ptr)
579 int fd, ret, mmap_prot, mmap_flags;
580 struct stat file_status;
582 if (open_mode == O_RDONLY) {
583 mmap_prot = PROT_READ;
584 mmap_flags = MAP_PRIVATE;
586 mmap_prot = PROT_READ | PROT_WRITE;
587 mmap_flags = MAP_SHARED;
589 ret = para_open(path, open_mode, 0);
593 if (fstat(fd, &file_status) < 0) {
594 ret = -ERRNO_TO_PARA_ERROR(errno);
597 *size = file_status.st_size;
599 * If the file is empty, *size is zero and mmap() would return EINVAL
600 * (Invalid argument). This error is common enough to spend an extra
601 * error code which explicitly states the problem.
607 * If fd refers to a directory, mmap() returns ENODEV (No such device),
608 * at least on Linux. "Is a directory" seems to be more to the point.
610 ret = -ERRNO_TO_PARA_ERROR(EISDIR);
611 if (S_ISDIR(file_status.st_mode))
614 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
616 if (ret < 0 || !fd_ptr)
624 * A wrapper for munmap(2).
626 * \param start The start address of the memory mapping.
627 * \param length The size of the mapping.
631 * \sa munmap(2), \ref mmap_full_file().
633 int para_munmap(void *start, size_t length)
639 if (munmap(start, length) >= 0)
642 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
644 return -ERRNO_TO_PARA_ERROR(err);
647 static int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
652 ret = poll(fds, nfds, timeout);
653 while (ret < 0 && errno == EINTR);
654 return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
658 * Check a file descriptor for readability.
660 * \param fd The file descriptor.
662 * \return positive if fd is ready for reading, zero if it isn't, negative if
665 * \sa \ref write_ok().
669 struct pollfd pfd = {.fd = fd, .events = POLLIN};
670 int ret = xpoll(&pfd, 1, 0);
671 return ret < 0? ret : pfd.revents & POLLIN;
675 * Check a file descriptor for writability.
677 * \param fd The file descriptor.
679 * \return positive if fd is ready for writing, zero if it isn't, negative if
682 * \sa \ref read_ok().
686 struct pollfd pfd = {.fd = fd, .events = POLLOUT};
687 int ret = xpoll(&pfd, 1, 0);
688 return ret < 0? ret : pfd.revents & POLLOUT;
692 * Ensure that file descriptors 0, 1, and 2 are valid.
694 * Common approach that opens /dev/null until it gets a file descriptor greater
697 void valid_fd_012(void)
700 int fd = open("/dev/null", O_RDWR);
711 * Traverse the given directory recursively.
713 * \param dirname The directory to traverse.
714 * \param func The function to call for each entry.
715 * \param private_data Pointer to an arbitrary data structure.
717 * For each regular file under \a dirname, the supplied function \a func is
718 * called. The full path of the regular file and the \a private_data pointer
719 * are passed to \a func. Directories for which the calling process has no
720 * permissions to change to are silently ignored.
724 int for_each_file_in_dir(const char *dirname,
725 int (*func)(const char *, void *), void *private_data)
728 struct dirent *entry;
729 int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
732 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
733 /* scan cwd recursively */
734 while ((entry = readdir(dir))) {
739 if (!strcmp(entry->d_name, "."))
741 if (!strcmp(entry->d_name, ".."))
743 if (lstat(entry->d_name, &s) == -1)
746 if (!S_ISREG(m) && !S_ISDIR(m))
748 tmp = make_message("%s/%s", dirname, entry->d_name);
750 ret = func(tmp, private_data);
757 ret = for_each_file_in_dir(tmp, func, private_data);
765 if (fchdir(cwd_fd) < 0 && ret >= 0)
766 ret = -ERRNO_TO_PARA_ERROR(errno);