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, handling non-fatal errors.
42 * \param fd The file descriptor to write to.
43 * \param iov Pointer to one or more buffers.
44 * \param iovcnt The number of buffers.
46 * EAGAIN, EWOULDBLOCK and EINTR are not considered error conditions. If a
47 * write operation fails with EAGAIN or EWOULDBLOCK, the number of bytes that
48 * have been written so far is returned. In the EINTR case the operation is
49 * retried. Short writes are handled by issuing a subsequent write operation
50 * for the remaining part.
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 a negative error code which indicates the fatal error that
56 * caused a write call to fail.
58 * For nonblocking file descriptors there is a third possibility: Any
59 * non-negative return value less than the sum of the buffer sizes indicates
60 * that a write operation returned EAGAIN/EWOULDBLOCK.
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 to a file descriptor, fail on short writes.
132 * \param fd The file descriptor.
133 * \param buf The buffer to be written.
134 * \param len The length of the buffer.
136 * For blocking file descriptors this function behaves identical to \ref
137 * xwrite(). For non-blocking file descriptors it returns -E_SHORT_WRITE
138 * (rather than a value less than len) if not all data could be written.
140 * \return Number of bytes written on success, negative error code else.
142 int write_all(int fd, const char *buf, size_t len)
144 int ret = xwrite(fd, buf, len);
149 return -E_SHORT_WRITE;
154 * A fprintf-like function for raw file descriptors.
156 * This function creates a string buffer according to the given format and
157 * writes this buffer to a file descriptor.
159 * \param fd The file descriptor.
160 * \param fmt A format string.
162 * The difference to fprintf(3) is that the first argument is a file
163 * descriptor, not a FILE pointer. This function does not rely on stdio.
165 * \return The return value of the underlying call to \ref write_all().
167 * \sa fprintf(3), \ref xvasprintf().
169 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
176 ret = xvasprintf(&msg, fmt, ap);
178 ret = write_all(fd, msg, ret);
184 * Read from a non-blocking file descriptor into multiple buffers.
186 * \param fd The file descriptor to read from.
187 * \param iov Scatter/gather array used in readv().
188 * \param iovcnt Number of elements in \a iov.
189 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
191 * This function tries to read up to sz bytes from fd, where sz is the sum of
192 * the lengths of all vectors in iov. Like \ref xwrite(), EAGAIN and EINTR are
193 * not considered error conditions. However, EOF is.
195 * \return Zero or a negative error code. If the underlying call to readv(2)
196 * returned zero (indicating an end of file condition) or failed for some
197 * reason other than EAGAIN or EINTR, a negative error code is returned.
199 * In any case, \a num_bytes contains the number of bytes that have been
200 * successfully read from \a fd (zero if the first readv() call failed with
201 * EAGAIN). Note that even if the function returns negative, some data might
202 * have been read before the error occurred. In this case \a num_bytes is
205 * \sa \ref xwrite(), read(2), readv(2).
207 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, size_t *num_bytes)
212 for (i = 0, j = 0; i < iovcnt;) {
213 /* fix up the first iov */
214 assert(j < iov[i].iov_len);
215 iov[i].iov_base += j;
217 ret = readv(fd, iov + i, iovcnt - i);
218 iov[i].iov_base -= j;
224 if (errno == EAGAIN || errno == EINTR)
226 return -ERRNO_TO_PARA_ERROR(errno);
230 if (ret < iov[i].iov_len - j) {
234 ret -= iov[i].iov_len - j;
244 * Read from a non-blocking file descriptor into a single buffer.
246 * \param fd The file descriptor to read from.
247 * \param buf The buffer to read data to.
248 * \param sz The size of \a buf.
249 * \param num_bytes \see \ref readv_nonblock().
251 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
254 * \return The return value of the underlying call to readv_nonblock().
256 int read_nonblock(int fd, void *buf, size_t sz, size_t *num_bytes)
258 struct iovec iov = {.iov_base = buf, .iov_len = sz};
259 return readv_nonblock(fd, &iov, 1, num_bytes);
263 * Read a buffer and compare its contents to a string, ignoring case.
265 * \param fd The file descriptor to read from.
266 * \param expectation The expected string to compare to.
268 * The given file descriptor is expected to be in non-blocking mode. The string
269 * comparison is performed using strncasecmp(3).
271 * \return Zero if no data was available, positive if a buffer was read whose
272 * contents compare as equal to the expected string, negative otherwise.
273 * Possible errors: (a) not enough data was read, (b) the buffer contents
274 * compared as non-equal, (c) a read error occurred. In the first two cases,
275 * -E_READ_PATTERN is returned. In the read error case the (negative) return
276 * value of the underlying call to \ref read_nonblock() is returned.
278 int read_and_compare(int fd, const char *expectation)
280 size_t n, len = strlen(expectation);
281 char *buf = alloc(len + 1);
282 int ret = read_nonblock(fd, buf, len, &n);
290 ret = -E_READ_PATTERN;
293 if (strncasecmp(buf, expectation, len) != 0)
302 * Set a file descriptor to blocking mode.
304 * \param fd The file descriptor.
308 __must_check int mark_fd_blocking(int fd)
310 int flags = fcntl(fd, F_GETFL);
312 return -ERRNO_TO_PARA_ERROR(errno);
313 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
315 return -ERRNO_TO_PARA_ERROR(errno);
320 * Set a file descriptor to non-blocking mode.
322 * \param fd The file descriptor.
326 __must_check int mark_fd_nonblocking(int fd)
328 int flags = fcntl(fd, F_GETFL);
330 return -ERRNO_TO_PARA_ERROR(errno);
331 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
333 return -ERRNO_TO_PARA_ERROR(errno);
338 * Paraslash's wrapper for mmap.
340 * \param length Number of bytes to mmap.
341 * \param prot Either PROT_NONE or the bitwise OR of one or more of
342 * PROT_EXEC PROT_READ PROT_WRITE.
343 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
344 * \param fd The file to mmap from.
345 * \param map Result pointer.
351 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
358 *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
359 if (*m != MAP_FAILED)
363 return -ERRNO_TO_PARA_ERROR(errno);
367 * Wrapper for the open(2) system call.
369 * \param path The filename.
370 * \param flags The usual open(2) flags.
371 * \param mode Specifies the permissions to use.
373 * The mode parameter must be specified when O_CREAT is in the flags, and is
376 * \return The file descriptor on success, negative on errors.
380 int para_open(const char *path, int flags, mode_t mode)
382 int ret = open(path, flags, mode);
386 return -ERRNO_TO_PARA_ERROR(errno);
390 * Save the cwd and open a given directory.
392 * \param dirname Path to the directory to open.
393 * \param dir Result pointer.
394 * \param cwd File descriptor of the current working directory.
398 * Opening the current directory (".") and calling fchdir() to return is
399 * usually faster and more reliable than saving cwd in some buffer and calling
400 * chdir() afterwards.
402 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
403 * stored in \a cwd. If the function returns success, and \a cwd is not \p
404 * NULL, the caller must close this file descriptor (probably after calling
407 * On errors, the function undos everything, so the caller needs neither close
408 * any files, nor change back to the original working directory.
413 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
419 ret = para_open(".", O_RDONLY, 0);
424 if (chdir(dirname) != 0) {
425 ret = -ERRNO_TO_PARA_ERROR(errno);
431 ret = -ERRNO_TO_PARA_ERROR(errno);
432 /* Ignore return value of fchdir() and close(). We're busted anyway. */
434 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
443 * A wrapper for mkdir(2).
445 * \param path Name of the directory to create.
446 * \param mode The permissions to use.
450 int para_mkdir(const char *path, mode_t mode)
452 if (!mkdir(path, mode))
454 return -ERRNO_TO_PARA_ERROR(errno);
458 * Open a file and map it into memory.
460 * \param path Name of the regular file to map.
461 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
462 * \param map On success, the mapping is returned here.
463 * \param size size of the mapping.
464 * \param fd_ptr The file descriptor of the mapping.
466 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
467 * open call is closed after mmap(). Otherwise the file is kept open and the
468 * file descriptor is returned in \a fd_ptr.
472 * \sa para_open(), mmap(2).
474 int mmap_full_file(const char *path, int open_mode, void **map,
475 size_t *size, int *fd_ptr)
477 int fd, ret, mmap_prot, mmap_flags;
478 struct stat file_status;
480 if (open_mode == O_RDONLY) {
481 mmap_prot = PROT_READ;
482 mmap_flags = MAP_PRIVATE;
484 mmap_prot = PROT_READ | PROT_WRITE;
485 mmap_flags = MAP_SHARED;
487 ret = para_open(path, open_mode, 0);
491 if (fstat(fd, &file_status) < 0) {
492 ret = -ERRNO_TO_PARA_ERROR(errno);
495 *size = file_status.st_size;
497 * If the file is empty, *size is zero and mmap() would return EINVAL
498 * (Invalid argument). This error is common enough to spend an extra
499 * error code which explicitly states the problem.
505 * If fd refers to a directory, mmap() returns ENODEV (No such device),
506 * at least on Linux. "Is a directory" seems to be more to the point.
508 ret = -ERRNO_TO_PARA_ERROR(EISDIR);
509 if (S_ISDIR(file_status.st_mode))
512 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
514 if (ret < 0 || !fd_ptr)
522 * A wrapper for munmap(2).
524 * \param start The start address of the memory mapping.
525 * \param length The size of the mapping.
527 * If NULL is passed as the start address, the length value is ignored and the
528 * function does nothing.
530 * \return Zero if NULL was passed, one if the memory area was successfully
531 * unmapped, a negative error code otherwise.
533 * \sa munmap(2), \ref mmap_full_file().
535 int para_munmap(void *start, size_t length)
539 if (munmap(start, length) >= 0)
541 return -ERRNO_TO_PARA_ERROR(errno);
545 * Simple wrapper for poll(2).
547 * It calls poll(2) and starts over if the call was interrupted by a signal.
549 * \param fds See poll(2).
550 * \param nfds See poll(2).
551 * \param timeout See poll(2).
553 * \return The return value of the underlying poll() call on success, the
554 * negative paraslash error code on errors.
556 * All arguments are passed verbatim to poll(2).
558 int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
563 ret = poll(fds, nfds, timeout);
564 while (ret < 0 && errno == EINTR);
565 return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
569 * Check a file descriptor for readability.
571 * \param fd The file descriptor.
573 * \return positive if fd is ready for reading, zero if it isn't, negative if
576 * \sa \ref write_ok().
580 struct pollfd pfd = {.fd = fd, .events = POLLIN};
581 int ret = xpoll(&pfd, 1, 0);
582 return ret < 0? ret : pfd.revents & POLLIN;
586 * Check a file descriptor for writability.
588 * \param fd The file descriptor.
590 * \return positive if fd is ready for writing, zero if it isn't, negative if
593 * \sa \ref read_ok().
597 struct pollfd pfd = {.fd = fd, .events = POLLOUT};
598 int ret = xpoll(&pfd, 1, 0);
599 return ret < 0? ret : pfd.revents & POLLOUT;
603 * Ensure that file descriptors 0, 1, and 2 are valid.
605 * Common approach that opens /dev/null until it gets a file descriptor greater
608 void valid_fd_012(void)
611 int fd = open("/dev/null", O_RDWR);
622 * Traverse the given directory recursively.
624 * \param dirname The directory to traverse.
625 * \param func The function to call for each entry.
626 * \param private_data Pointer to an arbitrary data structure.
628 * For each regular file under \a dirname, the supplied function \a func is
629 * called. The full path of the regular file and the \a private_data pointer
630 * are passed to \a func. Directories for which the calling process has no
631 * permissions to change to are silently ignored.
635 int for_each_file_in_dir(const char *dirname,
636 int (*func)(const char *, void *), void *private_data)
639 struct dirent *entry;
640 int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
643 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
644 /* scan cwd recursively */
645 while ((entry = readdir(dir))) {
650 if (!strcmp(entry->d_name, "."))
652 if (!strcmp(entry->d_name, ".."))
654 if (lstat(entry->d_name, &s) == -1)
657 if (!S_ISREG(m) && !S_ISDIR(m))
659 tmp = make_message("%s/%s", dirname, entry->d_name);
661 ret = func(tmp, private_data);
668 ret = for_each_file_in_dir(tmp, func, private_data);
676 if (fchdir(cwd_fd) < 0 && ret >= 0)
677 ret = -ERRNO_TO_PARA_ERROR(errno);