1 /* Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file fd.c Helper functions for file descriptor handling. */
16 * Change the name or location of a file.
18 * \param oldpath File to be moved.
19 * \param newpath Destination.
21 * This is just a simple wrapper for the rename(2) system call which returns a
22 * paraslash error code and prints an error message on failure.
28 int xrename(const char *oldpath, const char *newpath)
30 int ret = rename(oldpath, newpath);
34 ret = -ERRNO_TO_PARA_ERROR(errno);
35 PARA_ERROR_LOG("failed to rename %s -> %s\n", oldpath, newpath);
40 * Write an array of buffers to a file descriptor.
42 * \param fd The file descriptor.
43 * \param iov Pointer to one or more buffers.
44 * \param iovcnt The number of buffers.
46 * EAGAIN/EWOULDBLOCK is not considered a fatal error condition. For example
47 * DCCP CCID3 has a sending wait queue which fills up and is emptied
48 * asynchronously. The EAGAIN case means that there is currently no space in
49 * the wait queue, but this can change at any moment.
51 * \return Negative on fatal errors, number of bytes written else.
53 * For blocking file descriptors, this function returns either the sum of all
54 * buffer sizes, or the error code of the fatal error that caused the last
57 * For nonblocking file descriptors there is a third possibility: Any positive
58 * return value less than the sum of the buffer sizes indicates that some bytes
59 * have been written but the next write would block.
61 * \sa writev(2), \ref xwrite().
63 int xwritev(int fd, struct iovec *iov, int iovcnt)
67 struct iovec saved_iov, *curiov;
72 while (i < iovcnt && curiov->iov_len > 0) {
73 ssize_t ret = writev(fd, curiov, iovcnt - i);
77 if (ret < curiov->iov_len) {
78 curiov->iov_base += ret;
79 curiov->iov_len -= ret;
82 ret -= curiov->iov_len;
94 * The write() call was interrupted by a signal before
95 * any data was written. Try again.
98 if (errno == EAGAIN || errno == EWOULDBLOCK)
100 * We don't consider this an error. Note that POSIX
101 * allows either error to be returned, and does not
102 * require these constants to have the same value.
106 return -ERRNO_TO_PARA_ERROR(errno);
112 * Write a buffer to a file descriptor, re-writing on short writes.
114 * \param fd The file descriptor.
115 * \param buf The buffer to write.
116 * \param len The number of bytes to write.
118 * This is a simple wrapper for \ref xwritev().
120 * \return The return value of the underlying call to \ref xwritev().
122 int xwrite(int fd, const char *buf, size_t len)
124 struct iovec iov = {.iov_base = (void *)buf, .iov_len = len};
125 return xwritev(fd, &iov, 1);
129 * Write all data to a file descriptor.
131 * \param fd The file descriptor.
132 * \param buf The buffer to be sent.
133 * \param len The length of \a buf.
135 * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
136 * all data could be written.
138 * \return Number of bytes written on success, negative error code else.
140 int write_all(int fd, const char *buf, size_t len)
142 int ret = xwrite(fd, buf, len);
147 return -E_SHORT_WRITE;
152 * Write a buffer given by a format string.
154 * \param fd The file descriptor.
155 * \param fmt A format string.
157 * \return The return value of the underlying call to \ref write_all().
159 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
166 ret = xvasprintf(&msg, fmt, ap);
168 ret = write_all(fd, msg, ret);
174 * Read from a non-blocking file descriptor into multiple buffers.
176 * \param fd The file descriptor to read from.
177 * \param iov Scatter/gather array used in readv().
178 * \param iovcnt Number of elements in \a iov.
179 * \param rfds An optional fd set pointer.
180 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
182 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
183 * not set in \a rfds, this function returns early without doing anything.
184 * Otherwise The function tries to read up to \a sz bytes from \a fd, where \a
185 * sz is the sum of the lengths of all vectors in \a iov. As for xwrite(),
186 * \p EAGAIN is not considered an error condition. However, \p EOF is.
188 * \return Zero or a negative error code. If the underlying call to readv(2)
189 * returned zero (indicating an end of file condition) or failed for some
190 * reason other than \p EAGAIN, a negative error code is returned.
192 * In any case, \a num_bytes contains the number of bytes that have been
193 * successfully read from \a fd (zero if the first readv() call failed with
194 * EAGAIN). Note that even if the function returns negative, some data might
195 * have been read before the error occurred. In this case \a num_bytes is
198 * \sa \ref xwrite(), read(2), readv(2).
200 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
207 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
208 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
209 * returning false definitely means that no data can currently be read.
210 * This is the common case, so it is worth to avoid the overhead of the
211 * read() system call in this case.
213 if (rfds && !FD_ISSET(fd, rfds))
216 for (i = 0, j = 0; i < iovcnt;) {
218 /* fix up the first iov */
219 assert(j < iov[i].iov_len);
220 iov[i].iov_base += j;
222 ret = readv(fd, iov + i, iovcnt - i);
223 iov[i].iov_base -= j;
231 return -ERRNO_TO_PARA_ERROR(errno);
235 if (ret < iov[i].iov_len - j) {
239 ret -= iov[i].iov_len - j;
249 * Read from a non-blocking file descriptor into a single buffer.
251 * \param fd The file descriptor to read from.
252 * \param buf The buffer to read data to.
253 * \param sz The size of \a buf.
254 * \param rfds \see \ref readv_nonblock().
255 * \param num_bytes \see \ref readv_nonblock().
257 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
260 * \return The return value of the underlying call to readv_nonblock().
262 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
264 struct iovec iov = {.iov_base = buf, .iov_len = sz};
265 return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
269 * Read a buffer and check its content for a pattern.
271 * \param fd The file descriptor to receive from.
272 * \param pattern The expected pattern.
273 * \param bufsize The size of the internal buffer.
274 * \param rfds Passed to read_nonblock().
276 * This function tries to read at most \a bufsize bytes from the non-blocking
277 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
278 * received, the beginning of the received buffer is compared with \a pattern,
281 * \return Positive if \a pattern was received, negative on errors, zero if no data
282 * was available to read.
284 * \sa \ref read_nonblock(), \sa strncasecmp(3).
286 int read_pattern(int fd, const char *pattern, size_t bufsize, fd_set *rfds)
289 char *buf = para_malloc(bufsize + 1);
290 int ret = read_nonblock(fd, buf, bufsize, rfds, &n);
298 ret = -E_READ_PATTERN;
299 len = strlen(pattern);
302 if (strncasecmp(buf, pattern, len) != 0)
307 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
308 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
315 * Check whether a file exists.
317 * \param fn The file name.
319 * \return True iff file exists.
321 bool file_exists(const char *fn)
325 return !stat(fn, &statbuf);
329 * Paraslash's wrapper for select(2).
331 * It calls select(2) (with no exceptfds) and starts over if select() was
332 * interrupted by a signal.
334 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
335 * \param readfds fds that should be checked for readability.
336 * \param writefds fds that should be checked for writablility.
337 * \param timeout_tv upper bound on the amount of time elapsed before select()
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,
347 struct timeval *timeout_tv)
351 ret = select(n, readfds, writefds, NULL, timeout_tv);
352 while (ret < 0 && errno == EINTR);
354 return -ERRNO_TO_PARA_ERROR(errno);
359 * Set a file descriptor to blocking mode.
361 * \param fd The file descriptor.
365 __must_check int mark_fd_blocking(int fd)
367 int flags = fcntl(fd, F_GETFL);
369 return -ERRNO_TO_PARA_ERROR(errno);
370 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
372 return -ERRNO_TO_PARA_ERROR(errno);
377 * Set a file descriptor to non-blocking mode.
379 * \param fd The file descriptor.
383 __must_check int mark_fd_nonblocking(int fd)
385 int flags = fcntl(fd, F_GETFL);
387 return -ERRNO_TO_PARA_ERROR(errno);
388 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
390 return -ERRNO_TO_PARA_ERROR(errno);
395 * Set a file descriptor in a fd_set.
397 * \param fd The file descriptor to be set.
398 * \param fds The file descriptor set.
399 * \param max_fileno Highest-numbered file descriptor.
401 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
402 * return, \a max_fileno contains the maximum of the old_value and \a fd.
404 * \sa \ref para_select.
406 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
408 assert(fd >= 0 && fd < FD_SETSIZE);
411 int flags = fcntl(fd, F_GETFL);
412 if (!(flags & O_NONBLOCK)) {
413 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
419 *max_fileno = PARA_MAX(*max_fileno, fd);
423 * Paraslash's wrapper for fgets(3).
425 * \param line Pointer to the buffer to store the line.
426 * \param size The size of the buffer given by \a line.
427 * \param f The stream to read from.
429 * \return Unlike the standard fgets() function, an integer value
430 * is returned. On success, this function returns 1. On errors, -E_FGETS
431 * is returned. A zero return value indicates an end of file condition.
433 __must_check int para_fgets(char *line, int size, FILE *f)
436 if (fgets(line, size, f))
442 if (errno != EINTR) {
443 PARA_ERROR_LOG("%s\n", strerror(errno));
451 * Paraslash's wrapper for mmap.
453 * \param length Number of bytes to mmap.
454 * \param prot Either PROT_NONE or the bitwise OR of one or more of
455 * PROT_EXEC PROT_READ PROT_WRITE.
456 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
457 * \param fd The file to mmap from.
458 * \param offset Mmap start.
459 * \param map Result pointer.
465 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
473 *m = mmap(NULL, length, prot, flags, fd, offset);
474 if (*m != MAP_FAILED)
478 return -ERRNO_TO_PARA_ERROR(errno);
482 * Wrapper for the open(2) system call.
484 * \param path The filename.
485 * \param flags The usual open(2) flags.
486 * \param mode Specifies the permissions to use.
488 * The mode parameter must be specified when O_CREAT is in the flags, and is
491 * \return The file descriptor on success, negative on errors.
495 int para_open(const char *path, int flags, mode_t mode)
497 int ret = open(path, flags, mode);
501 return -ERRNO_TO_PARA_ERROR(errno);
505 * Wrapper for chdir(2).
507 * \param path The specified directory.
511 int para_chdir(const char *path)
513 int ret = chdir(path);
517 return -ERRNO_TO_PARA_ERROR(errno);
521 * Save the cwd and open a given directory.
523 * \param dirname Path to the directory to open.
524 * \param dir Result pointer.
525 * \param cwd File descriptor of the current working directory.
529 * Opening the current directory (".") and calling fchdir() to return is
530 * usually faster and more reliable than saving cwd in some buffer and calling
531 * chdir() afterwards.
533 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
534 * stored in \a cwd. If the function returns success, and \a cwd is not \p
535 * NULL, the caller must close this file descriptor (probably after calling
538 * On errors, the function undos everything, so the caller needs neither close
539 * any files, nor change back to the original working directory.
544 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
550 ret = para_open(".", O_RDONLY, 0);
555 ret = para_chdir(dirname);
561 ret = -ERRNO_TO_PARA_ERROR(errno);
562 /* Ignore return value of fchdir() and close(). We're busted anyway. */
564 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
573 * A wrapper for mkdir(2).
575 * \param path Name of the directory to create.
576 * \param mode The permissions to use.
580 int para_mkdir(const char *path, mode_t mode)
582 if (!mkdir(path, mode))
584 return -ERRNO_TO_PARA_ERROR(errno);
588 * Open a file and map it into memory.
590 * \param path Name of the regular file to map.
591 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
592 * \param map On success, the mapping is returned here.
593 * \param size size of the mapping.
594 * \param fd_ptr The file descriptor of the mapping.
596 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
597 * open call is closed after mmap(). Otherwise the file is kept open and the
598 * file descriptor is returned in \a fd_ptr.
602 * \sa para_open(), mmap(2).
604 int mmap_full_file(const char *path, int open_mode, void **map,
605 size_t *size, int *fd_ptr)
607 int fd, ret, mmap_prot, mmap_flags;
608 struct stat file_status;
610 if (open_mode == O_RDONLY) {
611 mmap_prot = PROT_READ;
612 mmap_flags = MAP_PRIVATE;
614 mmap_prot = PROT_READ | PROT_WRITE;
615 mmap_flags = MAP_SHARED;
617 ret = para_open(path, open_mode, 0);
621 if (fstat(fd, &file_status) < 0) {
622 ret = -ERRNO_TO_PARA_ERROR(errno);
625 *size = file_status.st_size;
627 * If the file is empty, *size is zero and mmap() would return EINVAL
628 * (Invalid argument). This error is common enough to spend an extra
629 * error code which explicitly states the problem.
635 * If fd refers to a directory, mmap() returns ENODEV (No such device),
636 * at least on Linux. "Is a directory" seems to be more to the point.
638 ret = -ERRNO_TO_PARA_ERROR(EISDIR);
639 if (S_ISDIR(file_status.st_mode))
642 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
644 if (ret < 0 || !fd_ptr)
652 * A wrapper for munmap(2).
654 * \param start The start address of the memory mapping.
655 * \param length The size of the mapping.
659 * \sa munmap(2), \ref mmap_full_file().
661 int para_munmap(void *start, size_t length)
667 if (munmap(start, length) >= 0)
670 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
672 return -ERRNO_TO_PARA_ERROR(err);
676 * Check a file descriptor for writability.
678 * \param fd The file descriptor.
680 * \return positive if fd is ready for writing, zero if it isn't, negative if
693 return para_select(fd + 1, NULL, &wfds, &tv);
697 * Ensure that file descriptors 0, 1, and 2 are valid.
699 * Common approach that opens /dev/null until it gets a file descriptor greater
702 void valid_fd_012(void)
705 int fd = open("/dev/null", O_RDWR);
716 * Traverse the given directory recursively.
718 * \param dirname The directory to traverse.
719 * \param func The function to call for each entry.
720 * \param private_data Pointer to an arbitrary data structure.
722 * For each regular file under \a dirname, the supplied function \a func is
723 * called. The full path of the regular file and the \a private_data pointer
724 * are passed to \a func. Directories for which the calling process has no
725 * permissions to change to are silently ignored.
729 int for_each_file_in_dir(const char *dirname,
730 int (*func)(const char *, void *), void *private_data)
733 struct dirent *entry;
734 int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
737 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
738 /* scan cwd recursively */
739 while ((entry = readdir(dir))) {
744 if (!strcmp(entry->d_name, "."))
746 if (!strcmp(entry->d_name, ".."))
748 if (lstat(entry->d_name, &s) == -1)
751 if (!S_ISREG(m) && !S_ISDIR(m))
753 tmp = make_message("%s/%s", dirname, entry->d_name);
755 ret = func(tmp, private_data);
762 ret = for_each_file_in_dir(tmp, func, private_data);
770 if (fchdir(cwd_fd) < 0 && ret >= 0)
771 ret = -ERRNO_TO_PARA_ERROR(errno);