2 * Copyright (C) 2006-2011 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.
28 * \return Standard. In any case, the number of bytes that have been written is
31 int write_all(int fd, const char *buf, size_t *len)
37 while (*len < total) {
38 int ret = write(fd, buf + *len, total - *len);
40 return -ERRNO_TO_PARA_ERROR(errno);
47 * Write a buffer to a non-blocking file descriptor.
49 * \param fd The file descriptor.
50 * \param buf the buffer to write.
51 * \param len the number of bytes of \a buf.
53 * EAGAIN is not considered an error condition. For example CCID3 has a
54 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
55 * case means that there is currently no space in the wait queue, but this can
56 * change at any moment.
58 * \return Negative on errors, number of bytes written else.
60 int write_nonblock(int fd, const char *buf, size_t len)
65 while (written < len) {
66 size_t num = len - written;
68 ret = write(fd, buf + written, num);
69 if (ret < 0 && errno == EAGAIN)
72 return -ERRNO_TO_PARA_ERROR(errno);
79 * Read from a non-blocking file descriptor into multiple buffers.
81 * \param fd The file descriptor to read from.
82 * \param iov Scatter/gather array used in readv().
83 * \param iovcnt Number of elements in \a iov.
84 * \param rfds An optional fd set pointer.
85 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
87 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
88 * not set in \a rfds, this function returns early without doing anything.
89 * Otherwise The function tries to read up to \a sz bytes from \a fd. As for
90 * write_nonblock(), EAGAIN is not considered an error condition. However, EOF
93 * \return Zero or a negative error code. If the underlying call to readv(2)
94 * returned zero (indicating an end of file condition) or failed for some
95 * reason other than \p EAGAIN, a negative return value is returned.
97 * In any case, \a num_bytes contains the number of bytes that have been
98 * successfully read from \a fd (zero if the first readv() call failed with
99 * EAGAIN). Note that even if the function returns negative, some data might
100 * have been read before the error occurred. In this case \a num_bytes is
103 * \sa \ref write_nonblock(), read(2), readv(2).
105 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
112 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
113 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
114 * returning false definitely means that no data can currently be read.
115 * This is the common case, so it is worth to avoid the overhead of the
116 * read() system call in this case.
118 if (rfds && !FD_ISSET(fd, rfds))
121 for (i = 0, j = 0; i < iovcnt;) {
123 /* fix up the first iov */
124 assert(j < iov[i].iov_len);
125 iov[i].iov_base += j;
127 ret = readv(fd, iov + i, iovcnt - i);
128 iov[i].iov_base -= j;
136 return -ERRNO_TO_PARA_ERROR(errno);
140 if (ret < iov[i].iov_len - j) {
144 ret -= iov[i].iov_len - j;
154 * Read from a non-blocking file descriptor into a single buffer.
156 * \param fd The file descriptor to read from.
157 * \param buf The buffer to read data to.
158 * \param sz The size of \a buf.
159 * \param rfds \see \ref readv_nonblock().
160 * \param num_bytes \see \ref readv_nonblock().
162 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
165 * \return The return value of the underlying call to readv_nonblock().
167 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
169 struct iovec iov = {.iov_base = buf, .iov_len = sz};
170 return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
174 * Read a buffer and check its content for a pattern.
176 * \param fd The file descriptor to receive from.
177 * \param pattern The expected pattern.
178 * \param bufsize The size of the internal buffer.
179 * \param rfds Passed to read_nonblock().
181 * This function tries to read at most \a bufsize bytes from the non-blocking
182 * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
183 * received, the beginning of the received buffer is compared with \a pattern,
186 * \return Positive if \a pattern was received, negative on errors, zero if no data
187 * was available to read.
189 * \sa \ref read_nonblock(), \sa strncasecmp(3).
191 int read_pattern(int fd, const char *pattern, size_t bufsize, fd_set *rfds)
194 char *buf = para_malloc(bufsize + 1);
195 int ret = read_nonblock(fd, buf, bufsize, rfds, &n);
203 ret = -E_READ_PATTERN;
204 len = strlen(pattern);
207 if (strncasecmp(buf, pattern, len) != 0)
212 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
213 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
220 * Check whether a file exists.
222 * \param fn The file name.
224 * \return Non-zero iff file exists.
226 int file_exists(const char *fn)
230 return !stat(fn, &statbuf);
234 * Paraslash's wrapper for select(2).
236 * It calls select(2) (with no exceptfds) and starts over if select() was
237 * interrupted by a signal.
239 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
240 * \param readfds fds that should be checked for readability.
241 * \param writefds fds that should be checked for writablility.
242 * \param timeout_tv upper bound on the amount of time elapsed before select()
245 * \return The return value of the underlying select() call on success, the
246 * negative system error code on errors.
248 * All arguments are passed verbatim to select(2).
249 * \sa select(2) select_tut(2).
251 int para_select(int n, fd_set *readfds, fd_set *writefds,
252 struct timeval *timeout_tv)
256 ret = select(n, readfds, writefds, NULL, timeout_tv);
257 while (ret < 0 && errno == EINTR);
259 return -ERRNO_TO_PARA_ERROR(errno);
264 * Set a file descriptor to blocking mode.
266 * \param fd The file descriptor.
270 __must_check int mark_fd_blocking(int fd)
272 int flags = fcntl(fd, F_GETFL);
274 return -ERRNO_TO_PARA_ERROR(errno);
275 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
277 return -ERRNO_TO_PARA_ERROR(errno);
282 * Set a file descriptor to non-blocking mode.
284 * \param fd The file descriptor.
288 __must_check int mark_fd_nonblocking(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 in a fd_set.
302 * \param fd The file descriptor to be set.
303 * \param fds The file descriptor set.
304 * \param max_fileno Highest-numbered file descriptor.
306 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
307 * return, \a max_fileno contains the maximum of the old_value and \a fd.
311 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
313 assert(fd >= 0 && fd < FD_SETSIZE);
316 int flags = fcntl(fd, F_GETFL);
317 if (!(flags & O_NONBLOCK)) {
318 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
324 *max_fileno = PARA_MAX(*max_fileno, fd);
328 * Paraslash's wrapper for fgets(3).
330 * \param line Pointer to the buffer to store the line.
331 * \param size The size of the buffer given by \a line.
332 * \param f The stream to read from.
334 * \return Unlike the standard fgets() function, an integer value
335 * is returned. On success, this function returns 1. On errors, -E_FGETS
336 * is returned. A zero return value indicates an end of file condition.
338 __must_check int para_fgets(char *line, int size, FILE *f)
341 if (fgets(line, size, f))
347 if (errno != EINTR) {
348 PARA_ERROR_LOG("%s\n", strerror(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 offset Mmap start.
364 * \param map Result pointer.
370 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
378 *m = mmap(NULL, length, prot, flags, fd, offset);
379 if (*m != MAP_FAILED)
383 return -ERRNO_TO_PARA_ERROR(errno);
387 * Wrapper for the open(2) system call.
389 * \param path The filename.
390 * \param flags The usual open(2) flags.
391 * \param mode Specifies the permissions to use.
393 * The mode parameter must be specified when O_CREAT is in the flags, and is
396 * \return The file descriptor on success, negative on errors.
400 int para_open(const char *path, int flags, mode_t mode)
402 int ret = open(path, flags, mode);
406 return -ERRNO_TO_PARA_ERROR(errno);
410 * Wrapper for chdir(2).
412 * \param path The specified directory.
416 int para_chdir(const char *path)
418 int ret = chdir(path);
422 return -ERRNO_TO_PARA_ERROR(errno);
426 * Save the cwd and open a given directory.
428 * \param dirname Path to the directory to open.
429 * \param dir Result pointer.
430 * \param cwd File descriptor of the current working directory.
434 * Opening the current directory (".") and calling fchdir() to return is
435 * usually faster and more reliable than saving cwd in some buffer and calling
436 * chdir() afterwards.
438 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
439 * stored in \a cwd. If the function returns success, and \a cwd is not \p
440 * NULL, the caller must close this file descriptor (probably after calling
443 * On errors, the function undos everything, so the caller needs neither close
444 * any files, nor change back to the original working directory.
449 int para_opendir(const char *dirname, DIR **dir, int *cwd)
454 ret = para_open(".", O_RDONLY, 0);
459 ret = para_chdir(dirname);
465 ret = -ERRNO_TO_PARA_ERROR(errno);
466 /* Ignore return value of fchdir() and close(). We're busted anyway. */
468 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
477 * A wrapper for fchdir().
479 * \param fd An open file descriptor.
483 int para_fchdir(int fd)
486 return -ERRNO_TO_PARA_ERROR(errno);
491 * A wrapper for mkdir(2).
493 * \param path Name of the directory to create.
494 * \param mode The permissions to use.
498 int para_mkdir(const char *path, mode_t mode)
500 if (!mkdir(path, mode))
502 return -ERRNO_TO_PARA_ERROR(errno);
506 * Open a file and map it into memory.
508 * \param path Name of the regular file to map.
509 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
510 * \param map On success, the mapping is returned here.
511 * \param size size of the mapping.
512 * \param fd_ptr The file descriptor of the mapping.
514 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
515 * open call is closed after mmap(). Otherwise the file is kept open and the
516 * file descriptor is returned in \a fd_ptr.
520 * \sa para_open(), mmap(2).
522 int mmap_full_file(const char *path, int open_mode, void **map,
523 size_t *size, int *fd_ptr)
525 int fd, ret, mmap_prot, mmap_flags;
526 struct stat file_status;
528 if (open_mode == O_RDONLY) {
529 mmap_prot = PROT_READ;
530 mmap_flags = MAP_PRIVATE;
532 mmap_prot = PROT_READ | PROT_WRITE;
533 mmap_flags = MAP_SHARED;
535 ret = para_open(path, open_mode, 0);
539 if (fstat(fd, &file_status) < 0) {
540 ret = -ERRNO_TO_PARA_ERROR(errno);
543 *size = file_status.st_size;
544 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
546 if (ret < 0 || !fd_ptr)
554 * A wrapper for munmap(2).
556 * \param start The start address of the memory mapping.
557 * \param length The size of the mapping.
561 * \sa munmap(2), mmap_full_file().
563 int para_munmap(void *start, size_t length)
566 if (munmap(start, length) >= 0)
569 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
571 return -ERRNO_TO_PARA_ERROR(err);
575 * Check a file descriptor for writability.
577 * \param fd The file descriptor.
579 * \return positive if fd is ready for writing, zero if it isn't, negative if
592 return para_select(fd + 1, NULL, &wfds, &tv);
596 * Ensure that file descriptors 0, 1, and 2 are valid.
598 * Common approach that opens /dev/null until it gets a file descriptor greater
601 * \sa okir's Black Hats Manual.
603 void valid_fd_012(void)
606 int fd = open("/dev/null", O_RDWR);
617 * Traverse the given directory recursively.
619 * \param dirname The directory to traverse.
620 * \param func The function to call for each entry.
621 * \param private_data Pointer to an arbitrary data structure.
623 * For each regular file under \a dirname, the supplied function \a func is
624 * called. The full path of the regular file and the \a private_data pointer
625 * are passed to \a func. Directories for which the calling process has no
626 * permissions to change to are silently ignored.
630 int for_each_file_in_dir(const char *dirname,
631 int (*func)(const char *, void *), void *private_data)
634 struct dirent *entry;
635 int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
638 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
639 /* scan cwd recursively */
640 while ((entry = readdir(dir))) {
645 if (!strcmp(entry->d_name, "."))
647 if (!strcmp(entry->d_name, ".."))
649 if (lstat(entry->d_name, &s) == -1)
652 if (!S_ISREG(m) && !S_ISDIR(m))
654 tmp = make_message("%s/%s", dirname, entry->d_name);
656 ret = func(tmp, private_data);
663 ret = for_each_file_in_dir(tmp, func, private_data);
671 ret2 = para_fchdir(cwd_fd);
672 if (ret2 < 0 && ret >= 0)