2 * Copyright (C) 2006-2012 Andre Noll <maan@systemlinux.org>
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>
22 * Write a buffer to a file descriptor, re-write on short writes.
24 * \param fd The file descriptor.
25 * \param buf The buffer to be sent.
26 * \param len The length of \a buf.
30 int write_all(int fd, const char *buf, size_t len)
37 int ret = write(fd, buf + len, total - len);
39 return -ERRNO_TO_PARA_ERROR(errno);
46 * Send a buffer given by a format string.
48 * \param fd The file descriptor.
49 * \param fmt A format string.
53 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
58 PARA_VSPRINTF(fmt, msg);
59 ret = write_buffer(fd, msg);
65 * Write a buffer to a non-blocking file descriptor.
67 * \param fd The file descriptor.
68 * \param buf the buffer to write.
69 * \param len the number of bytes of \a buf.
71 * EAGAIN is not considered an error condition. For example CCID3 has a
72 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
73 * case means that there is currently no space in the wait queue, but this can
74 * change at any moment.
76 * \return Negative on errors, number of bytes written else.
78 int write_nonblock(int fd, const char *buf, size_t len)
83 while (written < len) {
84 size_t num = len - written;
86 ret = write(fd, buf + written, num);
87 if (ret < 0 && errno == EAGAIN)
90 return -ERRNO_TO_PARA_ERROR(errno);
97 * Read from a non-blocking file descriptor into multiple buffers.
99 * \param fd The file descriptor to read from.
100 * \param iov Scatter/gather array used in readv().
101 * \param iovcnt Number of elements in \a iov.
102 * \param rfds An optional fd set pointer.
103 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
105 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
106 * not set in \a rfds, this function returns early without doing anything.
107 * Otherwise The function tries to read up to \a sz bytes from \a fd. As for
108 * write_nonblock(), EAGAIN is not considered an error condition. However, EOF
111 * \return Zero or a negative error code. If the underlying call to readv(2)
112 * returned zero (indicating an end of file condition) or failed for some
113 * reason other than \p EAGAIN, a negative return value is returned.
115 * In any case, \a num_bytes contains the number of bytes that have been
116 * successfully read from \a fd (zero if the first readv() call failed with
117 * EAGAIN). Note that even if the function returns negative, some data might
118 * have been read before the error occurred. In this case \a num_bytes is
121 * \sa \ref write_nonblock(), read(2), readv(2).
123 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
130 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
131 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
132 * returning false definitely means that no data can currently be read.
133 * This is the common case, so it is worth to avoid the overhead of the
134 * read() system call in this case.
136 if (rfds && !FD_ISSET(fd, rfds))
139 for (i = 0, j = 0; i < iovcnt;) {
141 /* fix up the first iov */
142 assert(j < iov[i].iov_len);
143 iov[i].iov_base += j;
145 ret = readv(fd, iov + i, iovcnt - i);
146 iov[i].iov_base -= j;
154 return -ERRNO_TO_PARA_ERROR(errno);
158 if (ret < iov[i].iov_len - j) {
162 ret -= iov[i].iov_len - j;
172 * Read from a non-blocking file descriptor into a single buffer.
174 * \param fd The file descriptor to read from.
175 * \param buf The buffer to read data to.
176 * \param sz The size of \a buf.
177 * \param rfds \see \ref readv_nonblock().
178 * \param num_bytes \see \ref readv_nonblock().
180 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
183 * \return The return value of the underlying call to readv_nonblock().
185 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
187 struct iovec iov = {.iov_base = buf, .iov_len = sz};
188 return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
192 * Read a buffer and check its content for a pattern.
194 * \param fd The file descriptor to receive from.
195 * \param pattern The expected pattern.
196 * \param bufsize The size of the internal buffer.
197 * \param rfds Passed to read_nonblock().
199 * This function tries to read at most \a bufsize bytes from the non-blocking
200 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
201 * received, the beginning of the received buffer is compared with \a pattern,
204 * \return Positive if \a pattern was received, negative on errors, zero if no data
205 * was available to read.
207 * \sa \ref read_nonblock(), \sa strncasecmp(3).
209 int read_pattern(int fd, const char *pattern, size_t bufsize, fd_set *rfds)
212 char *buf = para_malloc(bufsize + 1);
213 int ret = read_nonblock(fd, buf, bufsize, rfds, &n);
221 ret = -E_READ_PATTERN;
222 len = strlen(pattern);
225 if (strncasecmp(buf, pattern, len) != 0)
230 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
231 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
238 * Check whether a file exists.
240 * \param fn The file name.
242 * \return Non-zero iff file exists.
244 int file_exists(const char *fn)
248 return !stat(fn, &statbuf);
252 * Paraslash's wrapper for select(2).
254 * It calls select(2) (with no exceptfds) and starts over if select() was
255 * interrupted by a signal.
257 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
258 * \param readfds fds that should be checked for readability.
259 * \param writefds fds that should be checked for writablility.
260 * \param timeout_tv upper bound on the amount of time elapsed before select()
263 * \return The return value of the underlying select() call on success, the
264 * negative system error code on errors.
266 * All arguments are passed verbatim to select(2).
267 * \sa select(2) select_tut(2).
269 int para_select(int n, fd_set *readfds, fd_set *writefds,
270 struct timeval *timeout_tv)
274 ret = select(n, readfds, writefds, NULL, timeout_tv);
275 while (ret < 0 && errno == EINTR);
277 return -ERRNO_TO_PARA_ERROR(errno);
282 * Set a file descriptor to blocking mode.
284 * \param fd The file descriptor.
288 __must_check int mark_fd_blocking(int fd)
290 int flags = fcntl(fd, F_GETFL);
292 return -ERRNO_TO_PARA_ERROR(errno);
293 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
295 return -ERRNO_TO_PARA_ERROR(errno);
300 * Set a file descriptor to non-blocking mode.
302 * \param fd The file descriptor.
306 __must_check int mark_fd_nonblocking(int fd)
308 int flags = fcntl(fd, F_GETFL);
310 return -ERRNO_TO_PARA_ERROR(errno);
311 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
313 return -ERRNO_TO_PARA_ERROR(errno);
318 * Set a file descriptor in a fd_set.
320 * \param fd The file descriptor to be set.
321 * \param fds The file descriptor set.
322 * \param max_fileno Highest-numbered file descriptor.
324 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
325 * return, \a max_fileno contains the maximum of the old_value and \a fd.
329 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
331 assert(fd >= 0 && fd < FD_SETSIZE);
334 int flags = fcntl(fd, F_GETFL);
335 if (!(flags & O_NONBLOCK)) {
336 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
342 *max_fileno = PARA_MAX(*max_fileno, fd);
346 * Paraslash's wrapper for fgets(3).
348 * \param line Pointer to the buffer to store the line.
349 * \param size The size of the buffer given by \a line.
350 * \param f The stream to read from.
352 * \return Unlike the standard fgets() function, an integer value
353 * is returned. On success, this function returns 1. On errors, -E_FGETS
354 * is returned. A zero return value indicates an end of file condition.
356 __must_check int para_fgets(char *line, int size, FILE *f)
359 if (fgets(line, size, f))
365 if (errno != EINTR) {
366 PARA_ERROR_LOG("%s\n", strerror(errno));
374 * Paraslash's wrapper for mmap.
376 * \param length Number of bytes to mmap.
377 * \param prot Either PROT_NONE or the bitwise OR of one or more of
378 * PROT_EXEC PROT_READ PROT_WRITE.
379 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
380 * \param fd The file to mmap from.
381 * \param offset Mmap start.
382 * \param map Result pointer.
388 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
396 *m = mmap(NULL, length, prot, flags, fd, offset);
397 if (*m != MAP_FAILED)
401 return -ERRNO_TO_PARA_ERROR(errno);
405 * Wrapper for the open(2) system call.
407 * \param path The filename.
408 * \param flags The usual open(2) flags.
409 * \param mode Specifies the permissions to use.
411 * The mode parameter must be specified when O_CREAT is in the flags, and is
414 * \return The file descriptor on success, negative on errors.
418 int para_open(const char *path, int flags, mode_t mode)
420 int ret = open(path, flags, mode);
424 return -ERRNO_TO_PARA_ERROR(errno);
428 * Wrapper for chdir(2).
430 * \param path The specified directory.
434 int para_chdir(const char *path)
436 int ret = chdir(path);
440 return -ERRNO_TO_PARA_ERROR(errno);
444 * Save the cwd and open a given directory.
446 * \param dirname Path to the directory to open.
447 * \param dir Result pointer.
448 * \param cwd File descriptor of the current working directory.
452 * Opening the current directory (".") and calling fchdir() to return is
453 * usually faster and more reliable than saving cwd in some buffer and calling
454 * chdir() afterwards.
456 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
457 * stored in \a cwd. If the function returns success, and \a cwd is not \p
458 * NULL, the caller must close this file descriptor (probably after calling
461 * On errors, the function undos everything, so the caller needs neither close
462 * any files, nor change back to the original working directory.
467 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
472 ret = para_open(".", O_RDONLY, 0);
477 ret = para_chdir(dirname);
483 ret = -ERRNO_TO_PARA_ERROR(errno);
484 /* Ignore return value of fchdir() and close(). We're busted anyway. */
486 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
495 * A wrapper for fchdir().
497 * \param fd An open file descriptor.
501 static int para_fchdir(int fd)
504 return -ERRNO_TO_PARA_ERROR(errno);
509 * A wrapper for mkdir(2).
511 * \param path Name of the directory to create.
512 * \param mode The permissions to use.
516 int para_mkdir(const char *path, mode_t mode)
518 if (!mkdir(path, mode))
520 return -ERRNO_TO_PARA_ERROR(errno);
524 * Open a file and map it into memory.
526 * \param path Name of the regular file to map.
527 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
528 * \param map On success, the mapping is returned here.
529 * \param size size of the mapping.
530 * \param fd_ptr The file descriptor of the mapping.
532 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
533 * open call is closed after mmap(). Otherwise the file is kept open and the
534 * file descriptor is returned in \a fd_ptr.
538 * \sa para_open(), mmap(2).
540 int mmap_full_file(const char *path, int open_mode, void **map,
541 size_t *size, int *fd_ptr)
543 int fd, ret, mmap_prot, mmap_flags;
544 struct stat file_status;
546 if (open_mode == O_RDONLY) {
547 mmap_prot = PROT_READ;
548 mmap_flags = MAP_PRIVATE;
550 mmap_prot = PROT_READ | PROT_WRITE;
551 mmap_flags = MAP_SHARED;
553 ret = para_open(path, open_mode, 0);
557 if (fstat(fd, &file_status) < 0) {
558 ret = -ERRNO_TO_PARA_ERROR(errno);
561 *size = file_status.st_size;
562 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
564 if (ret < 0 || !fd_ptr)
572 * A wrapper for munmap(2).
574 * \param start The start address of the memory mapping.
575 * \param length The size of the mapping.
579 * \sa munmap(2), mmap_full_file().
581 int para_munmap(void *start, size_t length)
587 if (munmap(start, length) >= 0)
590 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
592 return -ERRNO_TO_PARA_ERROR(err);
596 * Check a file descriptor for writability.
598 * \param fd The file descriptor.
600 * \return positive if fd is ready for writing, zero if it isn't, negative if
613 return para_select(fd + 1, NULL, &wfds, &tv);
617 * Ensure that file descriptors 0, 1, and 2 are valid.
619 * Common approach that opens /dev/null until it gets a file descriptor greater
622 * \sa okir's Black Hats Manual.
624 void valid_fd_012(void)
627 int fd = open("/dev/null", O_RDWR);
638 * Traverse the given directory recursively.
640 * \param dirname The directory to traverse.
641 * \param func The function to call for each entry.
642 * \param private_data Pointer to an arbitrary data structure.
644 * For each regular file under \a dirname, the supplied function \a func is
645 * called. The full path of the regular file and the \a private_data pointer
646 * are passed to \a func. Directories for which the calling process has no
647 * permissions to change to are silently ignored.
651 int for_each_file_in_dir(const char *dirname,
652 int (*func)(const char *, void *), void *private_data)
655 struct dirent *entry;
656 int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
659 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
660 /* scan cwd recursively */
661 while ((entry = readdir(dir))) {
666 if (!strcmp(entry->d_name, "."))
668 if (!strcmp(entry->d_name, ".."))
670 if (lstat(entry->d_name, &s) == -1)
673 if (!S_ISREG(m) && !S_ISDIR(m))
675 tmp = make_message("%s/%s", dirname, entry->d_name);
677 ret = func(tmp, private_data);
684 ret = for_each_file_in_dir(tmp, func, private_data);
692 ret2 = para_fchdir(cwd_fd);
693 if (ret2 < 0 && ret >= 0)