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 * A fprintf-like function for raw file descriptors.
154 * This function creates a string buffer according to the given format and
155 * writes this buffer to a file descriptor.
157 * \param fd The file descriptor.
158 * \param fmt A format string.
160 * The difference to fprintf(3) is that the first argument is a file
161 * descriptor, not a FILE pointer. This function does not rely on stdio.
163 * \return The return value of the underlying call to \ref write_all().
165 * \sa fprintf(3), \ref xvasprintf().
167 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
174 ret = xvasprintf(&msg, fmt, ap);
176 ret = write_all(fd, msg, ret);
182 * Read from a non-blocking file descriptor into multiple buffers.
184 * \param fd The file descriptor to read from.
185 * \param iov Scatter/gather array used in readv().
186 * \param iovcnt Number of elements in \a iov.
187 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
189 * This function tries to read up to sz bytes from fd, where sz is the sum of
190 * the lengths of all vectors in iov. Like \ref xwrite(), EAGAIN and EINTR are
191 * not considered error conditions. However, EOF is.
193 * \return Zero or a negative error code. If the underlying call to readv(2)
194 * returned zero (indicating an end of file condition) or failed for some
195 * reason other than EAGAIN or EINTR, a negative error code is returned.
197 * In any case, \a num_bytes contains the number of bytes that have been
198 * successfully read from \a fd (zero if the first readv() call failed with
199 * EAGAIN). Note that even if the function returns negative, some data might
200 * have been read before the error occurred. In this case \a num_bytes is
203 * \sa \ref xwrite(), read(2), readv(2).
205 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, size_t *num_bytes)
210 for (i = 0, j = 0; i < iovcnt;) {
211 /* fix up the first iov */
212 assert(j < iov[i].iov_len);
213 iov[i].iov_base += j;
215 ret = readv(fd, iov + i, iovcnt - i);
216 iov[i].iov_base -= j;
222 if (errno == EAGAIN || errno == EINTR)
224 return -ERRNO_TO_PARA_ERROR(errno);
228 if (ret < iov[i].iov_len - j) {
232 ret -= iov[i].iov_len - j;
242 * Read from a non-blocking file descriptor into a single buffer.
244 * \param fd The file descriptor to read from.
245 * \param buf The buffer to read data to.
246 * \param sz The size of \a buf.
247 * \param num_bytes \see \ref readv_nonblock().
249 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
252 * \return The return value of the underlying call to readv_nonblock().
254 int read_nonblock(int fd, void *buf, size_t sz, size_t *num_bytes)
256 struct iovec iov = {.iov_base = buf, .iov_len = sz};
257 return readv_nonblock(fd, &iov, 1, num_bytes);
261 * Read a buffer and check its content for a pattern.
263 * \param fd The file descriptor to receive from.
264 * \param pattern The expected pattern.
265 * \param bufsize The size of the internal buffer.
267 * This function tries to read at most \a bufsize bytes from the non-blocking
268 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
269 * received, the beginning of the received buffer is compared with \a pattern,
272 * \return Positive if \a pattern was received, negative on errors, zero if no data
273 * was available to read.
275 * \sa \ref read_nonblock(), \sa strncasecmp(3).
277 int read_pattern(int fd, const char *pattern, size_t bufsize)
280 char *buf = alloc(bufsize + 1);
281 int ret = read_nonblock(fd, buf, bufsize, &n);
289 ret = -E_READ_PATTERN;
290 len = strlen(pattern);
293 if (strncasecmp(buf, pattern, len) != 0)
298 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
299 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
306 * Check whether a file exists.
308 * \param fn The file name.
310 * \return True iff file exists.
312 bool file_exists(const char *fn)
316 return !stat(fn, &statbuf);
320 * Set a file descriptor to blocking mode.
322 * \param fd The file descriptor.
326 __must_check int mark_fd_blocking(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 * Set a file descriptor to non-blocking mode.
340 * \param fd The file descriptor.
344 __must_check int mark_fd_nonblocking(int fd)
346 int flags = fcntl(fd, F_GETFL);
348 return -ERRNO_TO_PARA_ERROR(errno);
349 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
351 return -ERRNO_TO_PARA_ERROR(errno);
356 * Paraslash's wrapper for mmap.
358 * \param length Number of bytes to mmap.
359 * \param prot Either PROT_NONE or the bitwise OR of one or more of
360 * PROT_EXEC PROT_READ PROT_WRITE.
361 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
362 * \param fd The file to mmap from.
363 * \param map Result pointer.
369 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
376 *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
377 if (*m != MAP_FAILED)
381 return -ERRNO_TO_PARA_ERROR(errno);
385 * Wrapper for the open(2) system call.
387 * \param path The filename.
388 * \param flags The usual open(2) flags.
389 * \param mode Specifies the permissions to use.
391 * The mode parameter must be specified when O_CREAT is in the flags, and is
394 * \return The file descriptor on success, negative on errors.
398 int para_open(const char *path, int flags, mode_t mode)
400 int ret = open(path, flags, mode);
404 return -ERRNO_TO_PARA_ERROR(errno);
408 * Wrapper for chdir(2).
410 * \param path The specified directory.
414 int para_chdir(const char *path)
416 int ret = chdir(path);
420 return -ERRNO_TO_PARA_ERROR(errno);
424 * Save the cwd and open a given directory.
426 * \param dirname Path to the directory to open.
427 * \param dir Result pointer.
428 * \param cwd File descriptor of the current working directory.
432 * Opening the current directory (".") and calling fchdir() to return is
433 * usually faster and more reliable than saving cwd in some buffer and calling
434 * chdir() afterwards.
436 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
437 * stored in \a cwd. If the function returns success, and \a cwd is not \p
438 * NULL, the caller must close this file descriptor (probably after calling
441 * On errors, the function undos everything, so the caller needs neither close
442 * any files, nor change back to the original working directory.
447 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
453 ret = para_open(".", O_RDONLY, 0);
458 ret = para_chdir(dirname);
464 ret = -ERRNO_TO_PARA_ERROR(errno);
465 /* Ignore return value of fchdir() and close(). We're busted anyway. */
467 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
476 * A wrapper for mkdir(2).
478 * \param path Name of the directory to create.
479 * \param mode The permissions to use.
483 int para_mkdir(const char *path, mode_t mode)
485 if (!mkdir(path, mode))
487 return -ERRNO_TO_PARA_ERROR(errno);
491 * Open a file and map it into memory.
493 * \param path Name of the regular file to map.
494 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
495 * \param map On success, the mapping is returned here.
496 * \param size size of the mapping.
497 * \param fd_ptr The file descriptor of the mapping.
499 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
500 * open call is closed after mmap(). Otherwise the file is kept open and the
501 * file descriptor is returned in \a fd_ptr.
505 * \sa para_open(), mmap(2).
507 int mmap_full_file(const char *path, int open_mode, void **map,
508 size_t *size, int *fd_ptr)
510 int fd, ret, mmap_prot, mmap_flags;
511 struct stat file_status;
513 if (open_mode == O_RDONLY) {
514 mmap_prot = PROT_READ;
515 mmap_flags = MAP_PRIVATE;
517 mmap_prot = PROT_READ | PROT_WRITE;
518 mmap_flags = MAP_SHARED;
520 ret = para_open(path, open_mode, 0);
524 if (fstat(fd, &file_status) < 0) {
525 ret = -ERRNO_TO_PARA_ERROR(errno);
528 *size = file_status.st_size;
530 * If the file is empty, *size is zero and mmap() would return EINVAL
531 * (Invalid argument). This error is common enough to spend an extra
532 * error code which explicitly states the problem.
538 * If fd refers to a directory, mmap() returns ENODEV (No such device),
539 * at least on Linux. "Is a directory" seems to be more to the point.
541 ret = -ERRNO_TO_PARA_ERROR(EISDIR);
542 if (S_ISDIR(file_status.st_mode))
545 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
547 if (ret < 0 || !fd_ptr)
555 * A wrapper for munmap(2).
557 * \param start The start address of the memory mapping.
558 * \param length The size of the mapping.
562 * \sa munmap(2), \ref mmap_full_file().
564 int para_munmap(void *start, size_t length)
570 if (munmap(start, length) >= 0)
573 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
575 return -ERRNO_TO_PARA_ERROR(err);
579 * Simple wrapper for poll(2).
581 * It calls poll(2) and starts over if the call was interrupted by a signal.
583 * \param fds See poll(2).
584 * \param nfds See poll(2).
585 * \param timeout See poll(2).
587 * \return The return value of the underlying poll() call on success, the
588 * negative paraslash error code on errors.
590 * All arguments are passed verbatim to poll(2).
592 int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
597 ret = poll(fds, nfds, timeout);
598 while (ret < 0 && errno == EINTR);
599 return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
603 * Check a file descriptor for readability.
605 * \param fd The file descriptor.
607 * \return positive if fd is ready for reading, zero if it isn't, negative if
610 * \sa \ref write_ok().
614 struct pollfd pfd = {.fd = fd, .events = POLLIN};
615 int ret = xpoll(&pfd, 1, 0);
616 return ret < 0? ret : pfd.revents & POLLIN;
620 * Check a file descriptor for writability.
622 * \param fd The file descriptor.
624 * \return positive if fd is ready for writing, zero if it isn't, negative if
627 * \sa \ref read_ok().
631 struct pollfd pfd = {.fd = fd, .events = POLLOUT};
632 int ret = xpoll(&pfd, 1, 0);
633 return ret < 0? ret : pfd.revents & POLLOUT;
637 * Ensure that file descriptors 0, 1, and 2 are valid.
639 * Common approach that opens /dev/null until it gets a file descriptor greater
642 void valid_fd_012(void)
645 int fd = open("/dev/null", O_RDWR);
656 * Traverse the given directory recursively.
658 * \param dirname The directory to traverse.
659 * \param func The function to call for each entry.
660 * \param private_data Pointer to an arbitrary data structure.
662 * For each regular file under \a dirname, the supplied function \a func is
663 * called. The full path of the regular file and the \a private_data pointer
664 * are passed to \a func. Directories for which the calling process has no
665 * permissions to change to are silently ignored.
669 int for_each_file_in_dir(const char *dirname,
670 int (*func)(const char *, void *), void *private_data)
673 struct dirent *entry;
674 int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
677 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
678 /* scan cwd recursively */
679 while ((entry = readdir(dir))) {
684 if (!strcmp(entry->d_name, "."))
686 if (!strcmp(entry->d_name, ".."))
688 if (lstat(entry->d_name, &s) == -1)
691 if (!S_ISREG(m) && !S_ISDIR(m))
693 tmp = make_message("%s/%s", dirname, entry->d_name);
695 ret = func(tmp, private_data);
702 ret = for_each_file_in_dir(tmp, func, private_data);
710 if (fchdir(cwd_fd) < 0 && ret >= 0)
711 ret = -ERRNO_TO_PARA_ERROR(errno);