2 * Copyright (C) 2006-2010 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.
52 * \param max_bytes_per_write Do not write more than that many bytes at once.
54 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
57 * EAGAIN is not considered an error condition. For example CCID3 has a
58 * sending wait queue which fills up and is emptied asynchronously. The EAGAIN
59 * case means that there is currently no space in the wait queue, but this can
60 * change at any moment.
62 * \return Negative on errors, number of bytes written else.
64 int write_nonblock(int fd, const char *buf, size_t len,
65 size_t max_bytes_per_write)
70 while (written < len) {
71 size_t num = len - written;
73 if (max_bytes_per_write && max_bytes_per_write < num)
74 num = max_bytes_per_write;
75 ret = write(fd, buf + written, num);
76 if (ret < 0 && errno == EAGAIN)
79 return -ERRNO_TO_PARA_ERROR(errno);
86 * Read from a non-blocking file descriptor into multiple buffers.
88 * \param fd The file descriptor to read from.
89 * \param iov Scatter/gather array used in readv().
90 * \param iovcnt Number of elements in \a iov.
91 * \param rfds An optional fd set pointer.
92 * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
94 * If \a rfds is not \p NULL and the (non-blocking) file descriptor \a fd is
95 * not set in \a rfds, this function returns early without doing anything.
96 * Otherwise The function tries to read up to \a sz bytes from \a fd. As for
97 * write_nonblock(), EAGAIN is not considered an error condition. However, EOF
100 * \return Zero or a negative error code. If the underlying call to readv(2)
101 * returned zero (indicating an end of file condition) or failed for some
102 * reason other than \p EAGAIN, a negative return value is returned.
104 * In any case, \a num_bytes contains the number of bytes that have been
105 * successfully read from \a fd (zero if the first readv() call failed with
106 * EAGAIN). Note that even if the function returns negative, some data might
107 * have been read before the error occured. In this case \a num_bytes is
110 * \sa \ref write_nonblock(), read(2), readv(2).
112 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
119 * Avoid a shortcoming of select(): Reads from a non-blocking fd might
120 * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
121 * returning false definitely means that no data can currently be read.
122 * This is the common case, so it is worth to avoid the overhead of the
123 * read() system call in this case.
125 if (rfds && !FD_ISSET(fd, rfds))
128 for (i = 0, j = 0; i < iovcnt;) {
130 /* fix up the first iov */
131 assert(j < iov[i].iov_len);
132 iov[i].iov_base += j;
134 ret = readv(fd, iov + i, iovcnt - i);
135 iov[i].iov_base -= j;
143 return -ERRNO_TO_PARA_ERROR(errno);
147 if (ret < iov[i].iov_len - j) {
151 ret -= iov[i].iov_len - j;
161 * Read from a non-blocking file descriptor into a single buffer.
163 * \param fd The file descriptor to read from.
164 * \param buf The buffer to read data to.
165 * \param sz The size of \a buf.
166 * \param rfds \see \ref readv_nonblock().
167 * \param num_bytes \see \ref readv_nonblock().
169 * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
172 * \return The return value of the underlying call to readv_nonblock().
174 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
176 struct iovec iov = {.iov_base = buf, .iov_len = sz};
177 return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
181 * Check whether a file exists.
183 * \param fn The file name.
185 * \return Non-zero iff file exists.
187 int file_exists(const char *fn)
191 return !stat(fn, &statbuf);
195 * Paraslash's wrapper for select(2).
197 * It calls select(2) (with no exceptfds) and starts over if select() was
198 * interrupted by a signal.
200 * \param n The highest-numbered descriptor in any of the two sets, plus 1.
201 * \param readfds fds that should be checked for readability.
202 * \param writefds fds that should be checked for writablility.
203 * \param timeout_tv upper bound on the amount of time elapsed before select()
206 * \return The return value of the underlying select() call on success, the
207 * negative system error code on errors.
209 * All arguments are passed verbatim to select(2).
210 * \sa select(2) select_tut(2).
212 int para_select(int n, fd_set *readfds, fd_set *writefds,
213 struct timeval *timeout_tv)
217 ret = select(n, readfds, writefds, NULL, timeout_tv);
218 while (ret < 0 && errno == EINTR);
220 return -ERRNO_TO_PARA_ERROR(errno);
225 * Set a file descriptor to blocking mode.
227 * \param fd The file descriptor.
231 __must_check int mark_fd_blocking(int fd)
233 int flags = fcntl(fd, F_GETFL);
235 return -ERRNO_TO_PARA_ERROR(errno);
236 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
238 return -ERRNO_TO_PARA_ERROR(errno);
243 * Set a file descriptor to non-blocking mode.
245 * \param fd The file descriptor.
249 __must_check int mark_fd_nonblocking(int fd)
251 int flags = fcntl(fd, F_GETFL);
253 return -ERRNO_TO_PARA_ERROR(errno);
254 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
256 return -ERRNO_TO_PARA_ERROR(errno);
261 * Set a file descriptor in a fd_set.
263 * \param fd The file descriptor to be set.
264 * \param fds The file descriptor set.
265 * \param max_fileno Highest-numbered file descriptor.
267 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
268 * return, \a max_fileno contains the maximum of the old_value and \a fd.
272 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
274 assert(fd >= 0 && fd < FD_SETSIZE);
277 int flags = fcntl(fd, F_GETFL);
278 if (!(flags & O_NONBLOCK)) {
279 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
285 *max_fileno = PARA_MAX(*max_fileno, fd);
289 * Paraslash's wrapper for fgets(3).
291 * \param line Pointer to the buffer to store the line.
292 * \param size The size of the buffer given by \a line.
293 * \param f The stream to read from.
295 * \return Unlike the standard fgets() function, an integer value
296 * is returned. On success, this function returns 1. On errors, -E_FGETS
297 * is returned. A zero return value indicates an end of file condition.
299 __must_check int para_fgets(char *line, int size, FILE *f)
302 if (fgets(line, size, f))
308 if (errno != EINTR) {
309 PARA_ERROR_LOG("%s\n", strerror(errno));
317 * Paraslash's wrapper for mmap.
319 * \param length Number of bytes to mmap.
320 * \param prot Either PROT_NONE or the bitwise OR of one or more of
321 * PROT_EXEC PROT_READ PROT_WRITE.
322 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
323 * \param fd The file to mmap from.
324 * \param offset Mmap start.
325 * \param map Result pointer.
331 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
339 *m = mmap(NULL, length, prot, flags, fd, offset);
340 if (*m != MAP_FAILED)
344 return -ERRNO_TO_PARA_ERROR(errno);
348 * Wrapper for the open(2) system call.
350 * \param path The filename.
351 * \param flags The usual open(2) flags.
352 * \param mode Specifies the permissions to use.
354 * The mode parameter must be specified when O_CREAT is in the flags, and is
357 * \return The file descriptor on success, negative on errors.
361 int para_open(const char *path, int flags, mode_t mode)
363 int ret = open(path, flags, mode);
367 return -ERRNO_TO_PARA_ERROR(errno);
371 * Wrapper for chdir(2).
373 * \param path The specified directory.
377 int para_chdir(const char *path)
379 int ret = chdir(path);
383 return -ERRNO_TO_PARA_ERROR(errno);
387 * Save the cwd and open a given directory.
389 * \param dirname Path to the directory to open.
390 * \param dir Result pointer.
391 * \param cwd File descriptor of the current working directory.
395 * Opening the current directory (".") and calling fchdir() to return is
396 * usually faster and more reliable than saving cwd in some buffer and calling
397 * chdir() afterwards.
399 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
400 * stored in \a cwd. If the function returns success, and \a cwd is not \p
401 * NULL, the caller must close this file descriptor (probably after calling
404 * On errors, the function undos everything, so the caller needs neither close
405 * any files, nor change back to the original working directory.
410 int para_opendir(const char *dirname, DIR **dir, int *cwd)
415 ret = para_open(".", O_RDONLY, 0);
420 ret = para_chdir(dirname);
426 ret = -ERRNO_TO_PARA_ERROR(errno);
427 /* Ignore return value of fchdir() and close(). We're busted anyway. */
429 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
438 * A wrapper for fchdir().
440 * \param fd An open file descriptor.
444 int para_fchdir(int fd)
447 return -ERRNO_TO_PARA_ERROR(errno);
452 * A wrapper for mkdir(2).
454 * \param path Name of the directory to create.
455 * \param mode The permissions to use.
459 int para_mkdir(const char *path, mode_t mode)
461 if (!mkdir(path, mode))
463 return -ERRNO_TO_PARA_ERROR(errno);
467 * Open a file and map it into memory.
469 * \param path Name of the regular file to map.
470 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
471 * \param map On success, the mapping is returned here.
472 * \param size size of the mapping.
473 * \param fd_ptr The file descriptor of the mapping.
475 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
476 * open call is closed after mmap(). Otherwise the file is kept open and the
477 * file descriptor is returned in \a fd_ptr.
481 * \sa para_open(), mmap(2).
483 int mmap_full_file(const char *path, int open_mode, void **map,
484 size_t *size, int *fd_ptr)
486 int fd, ret, mmap_prot, mmap_flags;
487 struct stat file_status;
489 if (open_mode == O_RDONLY) {
490 mmap_prot = PROT_READ;
491 mmap_flags = MAP_PRIVATE;
493 mmap_prot = PROT_READ | PROT_WRITE;
494 mmap_flags = MAP_SHARED;
496 ret = para_open(path, open_mode, 0);
500 if (fstat(fd, &file_status) < 0) {
501 ret = -ERRNO_TO_PARA_ERROR(errno);
504 *size = file_status.st_size;
505 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
507 if (ret < 0 || !fd_ptr)
515 * A wrapper for munmap(2).
517 * \param start The start address of the memory mapping.
518 * \param length The size of the mapping.
522 * \sa munmap(2), mmap_full_file().
524 int para_munmap(void *start, size_t length)
527 if (munmap(start, length) >= 0)
530 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
532 return -ERRNO_TO_PARA_ERROR(err);
536 * Check a file descriptor for writability.
538 * \param fd The file descriptor.
540 * \return positive if fd is ready for writing, zero if it isn't, negative if
553 return para_select(fd + 1, NULL, &wfds, &tv);
557 * Ensure that file descriptors 0, 1, and 2 are valid.
559 * Common approach that opens /dev/null until it gets a file descriptor greater
562 * \sa okir's Black Hats Manual.
564 void valid_fd_012(void)
567 int fd = open("/dev/null", O_RDWR);
578 * Traverse the given directory recursively.
580 * \param dirname The directory to traverse.
581 * \param func The function to call for each entry.
582 * \param private_data Pointer to an arbitrary data structure.
584 * For each regular file under \a dirname, the supplied function \a func is
585 * called. The full path of the regular file and the \a private_data pointer
586 * are passed to \a func. Directories for which the calling process has no
587 * permissions to change to are silently ignored.
591 int for_each_file_in_dir(const char *dirname,
592 int (*func)(const char *, void *), void *private_data)
595 struct dirent *entry;
596 int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
599 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
600 /* scan cwd recursively */
601 while ((entry = readdir(dir))) {
606 if (!strcmp(entry->d_name, "."))
608 if (!strcmp(entry->d_name, ".."))
610 if (lstat(entry->d_name, &s) == -1)
613 if (!S_ISREG(m) && !S_ISDIR(m))
615 tmp = make_message("%s/%s", dirname, entry->d_name);
617 ret = func(tmp, private_data);
624 ret = for_each_file_in_dir(tmp, func, private_data);
632 ret2 = para_fchdir(cwd_fd);
633 if (ret2 < 0 && ret >= 0)