]> git.tuebingen.mpg.de Git - paraslash.git/blob - fd.c
interactive: Avoid select(2) in input_available().
[paraslash.git] / fd.c
1 /* Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file fd.c Helper functions for file descriptor handling. */
4
5 #include <regex.h>
6 #include <sys/types.h>
7 #include <dirent.h>
8 #include <sys/mman.h>
9 #include <poll.h>
10
11 #include "para.h"
12 #include "error.h"
13 #include "string.h"
14 #include "fd.h"
15
16 /**
17  * Change the name or location of a file.
18  *
19  * \param oldpath File to be moved.
20  * \param newpath Destination.
21  *
22  * This is just a simple wrapper for the rename(2) system call which returns a
23  * paraslash error code and prints an error message on failure.
24  *
25  * \return Standard.
26  *
27  * \sa rename(2).
28  */
29 int xrename(const char *oldpath, const char *newpath)
30 {
31         int ret = rename(oldpath, newpath);
32
33         if (ret >= 0)
34                 return 1;
35         ret = -ERRNO_TO_PARA_ERROR(errno);
36         PARA_ERROR_LOG("failed to rename %s -> %s\n", oldpath, newpath);
37         return ret;
38 }
39
40 /**
41  * Write an array of buffers to a file descriptor.
42  *
43  * \param fd The file descriptor.
44  * \param iov Pointer to one or more buffers.
45  * \param iovcnt The number of buffers.
46  *
47  * EAGAIN/EWOULDBLOCK is not considered a fatal error condition. For example
48  * DCCP CCID3 has a sending wait queue which fills up and is emptied
49  * asynchronously. The EAGAIN case means that there is currently no space in
50  * the wait queue, but this can change at any moment.
51  *
52  * \return Negative on fatal errors, number of bytes written else.
53  *
54  * For blocking file descriptors, this function returns either the sum of all
55  * buffer sizes, or the error code of the fatal error that caused the last
56  * write call to fail.
57  *
58  * For nonblocking file descriptors there is a third possibility: Any positive
59  * return value less than the sum of the buffer sizes indicates that some bytes
60  * have been written but the next write would block.
61  *
62  * \sa writev(2), \ref xwrite().
63  */
64 int xwritev(int fd, struct iovec *iov, int iovcnt)
65 {
66         size_t written = 0;
67         int i;
68         struct iovec saved_iov, *curiov;
69
70         i = 0;
71         curiov = iov;
72         saved_iov = *curiov;
73         while (i < iovcnt && curiov->iov_len > 0) {
74                 ssize_t ret = writev(fd, curiov, iovcnt - i);
75                 if (ret >= 0) {
76                         written += ret;
77                         while (ret > 0) {
78                                 if (ret < curiov->iov_len) {
79                                         curiov->iov_base += ret;
80                                         curiov->iov_len -= ret;
81                                         break;
82                                 }
83                                 ret -= curiov->iov_len;
84                                 *curiov = saved_iov;
85                                 i++;
86                                 if (i >= iovcnt)
87                                         return written;
88                                 curiov++;
89                                 saved_iov = *curiov;
90                         }
91                         continue;
92                 }
93                 if (errno == EINTR)
94                         /*
95                          * The write() call was interrupted by a signal before
96                          * any data was written. Try again.
97                          */
98                         continue;
99                 if (errno == EAGAIN || errno == EWOULDBLOCK)
100                         /*
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.
104                          */
105                         return written;
106                 /* fatal error */
107                 return -ERRNO_TO_PARA_ERROR(errno);
108         }
109         return written;
110 }
111
112 /**
113  * Write a buffer to a file descriptor, re-writing on short writes.
114  *
115  * \param fd The file descriptor.
116  * \param buf The buffer to write.
117  * \param len The number of bytes to write.
118  *
119  * This is a simple wrapper for \ref xwritev().
120  *
121  * \return The return value of the underlying call to \ref xwritev().
122  */
123 int xwrite(int fd, const char *buf, size_t len)
124 {
125         struct iovec iov = {.iov_base = (void *)buf, .iov_len = len};
126         return xwritev(fd, &iov, 1);
127 }
128
129 /**
130  * Write all data to a file descriptor.
131  *
132  * \param fd The file descriptor.
133  * \param buf The buffer to be sent.
134  * \param len The length of \a buf.
135  *
136  * This is like \ref xwrite() but returns \p -E_SHORT_WRITE if not
137  * all data could be written.
138  *
139  * \return Number of bytes written on success, negative error code else.
140  */
141 int write_all(int fd, const char *buf, size_t len)
142 {
143         int ret = xwrite(fd, buf, len);
144
145         if (ret < 0)
146                 return ret;
147         if (ret != len)
148                 return -E_SHORT_WRITE;
149         return ret;
150 }
151
152 /**
153  * Write a buffer given by a format string.
154  *
155  * \param fd The file descriptor.
156  * \param fmt A format string.
157  *
158  * \return The return value of the underlying call to \ref write_all().
159  */
160 __printf_2_3 int write_va_buffer(int fd, const char *fmt, ...)
161 {
162         char *msg;
163         int ret;
164         va_list ap;
165
166         va_start(ap, fmt);
167         ret = xvasprintf(&msg, fmt, ap);
168         va_end(ap);
169         ret = write_all(fd, msg, ret);
170         free(msg);
171         return ret;
172 }
173
174 /**
175  * Read from a non-blocking file descriptor into multiple buffers.
176  *
177  * \param fd The file descriptor to read from.
178  * \param iov Scatter/gather array used in readv().
179  * \param iovcnt Number of elements in \a iov.
180  * \param rfds An optional fd set pointer.
181  * \param num_bytes Result pointer. Contains the number of bytes read from \a fd.
182  *
183  * If rfds is not NULL and the (non-blocking) file descriptor fd is not set in
184  * rfds, this function returns early without doing anything. Otherwise it tries
185  * to read up to sz bytes from fd, where sz is the sum of the lengths of all
186  * vectors in iov. Like \ref xwrite(), EAGAIN and EINTR are not considered
187  * error conditions. However, EOF is.
188  *
189  * \return Zero or a negative error code. If the underlying call to readv(2)
190  * returned zero (indicating an end of file condition) or failed for some
191  * reason other than EAGAIN or EINTR, a negative error code is returned.
192  *
193  * In any case, \a num_bytes contains the number of bytes that have been
194  * successfully read from \a fd (zero if the first readv() call failed with
195  * EAGAIN). Note that even if the function returns negative, some data might
196  * have been read before the error occurred. In this case \a num_bytes is
197  * positive.
198  *
199  * \sa \ref xwrite(), read(2), readv(2).
200  */
201 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, fd_set *rfds,
202                 size_t *num_bytes)
203 {
204         int ret, i, j;
205
206         *num_bytes = 0;
207         /*
208          * Avoid a shortcoming of select(): Reads from a non-blocking fd might
209          * return EAGAIN even if FD_ISSET() returns true. However, FD_ISSET()
210          * returning false definitely means that no data can currently be read.
211          * This is the common case, so it is worth to avoid the overhead of the
212          * read() system call in this case.
213          */
214         if (rfds && !FD_ISSET(fd, rfds))
215                 return 0;
216
217         for (i = 0, j = 0; i < iovcnt;) {
218
219                 /* fix up the first iov */
220                 assert(j < iov[i].iov_len);
221                 iov[i].iov_base += j;
222                 iov[i].iov_len -= j;
223                 ret = readv(fd, iov + i, iovcnt - i);
224                 iov[i].iov_base -= j;
225                 iov[i].iov_len += j;
226
227                 if (ret == 0)
228                         return -E_EOF;
229                 if (ret < 0) {
230                         if (errno == EAGAIN || errno == EINTR)
231                                 return 0;
232                         return -ERRNO_TO_PARA_ERROR(errno);
233                 }
234                 *num_bytes += ret;
235                 while (ret > 0) {
236                         if (ret < iov[i].iov_len - j) {
237                                 j += ret;
238                                 break;
239                         }
240                         ret -= iov[i].iov_len - j;
241                         j = 0;
242                         if (++i >= iovcnt)
243                                 break;
244                 }
245         }
246         return 0;
247 }
248
249 /**
250  * Read from a non-blocking file descriptor into a single buffer.
251  *
252  * \param fd The file descriptor to read from.
253  * \param buf The buffer to read data to.
254  * \param sz The size of \a buf.
255  * \param rfds \see \ref readv_nonblock().
256  * \param num_bytes \see \ref readv_nonblock().
257  *
258  * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
259  * buffer.
260  *
261  * \return The return value of the underlying call to readv_nonblock().
262  */
263 int read_nonblock(int fd, void *buf, size_t sz, fd_set *rfds, size_t *num_bytes)
264 {
265         struct iovec iov = {.iov_base = buf, .iov_len = sz};
266         return readv_nonblock(fd, &iov, 1, rfds, num_bytes);
267 }
268
269 /**
270  * Read a buffer and check its content for a pattern.
271  *
272  * \param fd The file descriptor to receive from.
273  * \param pattern The expected pattern.
274  * \param bufsize The size of the internal buffer.
275  * \param rfds Passed to read_nonblock().
276  *
277  * This function tries to read at most \a bufsize bytes from the non-blocking
278  * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
279  * received, the beginning of the received buffer is compared with \a pattern,
280  * ignoring case.
281  *
282  * \return Positive if \a pattern was received, negative on errors, zero if no data
283  * was available to read.
284  *
285  * \sa \ref read_nonblock(), \sa strncasecmp(3).
286  */
287 int read_pattern(int fd, const char *pattern, size_t bufsize, fd_set *rfds)
288 {
289         size_t n, len;
290         char *buf = para_malloc(bufsize + 1);
291         int ret = read_nonblock(fd, buf, bufsize, rfds, &n);
292
293         buf[n] = '\0';
294         if (ret < 0)
295                 goto out;
296         ret = 0;
297         if (n == 0)
298                 goto out;
299         ret = -E_READ_PATTERN;
300         len = strlen(pattern);
301         if (n < len)
302                 goto out;
303         if (strncasecmp(buf, pattern, len) != 0)
304                 goto out;
305         ret = 1;
306 out:
307         if (ret < 0) {
308                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
309                 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
310         }
311         free(buf);
312         return ret;
313 }
314
315 /**
316  * Check whether a file exists.
317  *
318  * \param fn The file name.
319  *
320  * \return True iff file exists.
321  */
322 bool file_exists(const char *fn)
323 {
324         struct stat statbuf;
325
326         return !stat(fn, &statbuf);
327 }
328
329 /**
330  * Paraslash's wrapper for select(2).
331  *
332  * It calls select(2) (with no exceptfds) and starts over if select() was
333  * interrupted by a signal.
334  *
335  * \param n The highest-numbered descriptor in any of the two sets, plus 1.
336  * \param readfds fds that should be checked for readability.
337  * \param writefds fds that should be checked for writablility.
338  * \param timeout Upper bound in milliseconds.
339  *
340  * \return The return value of the underlying select() call on success, the
341  * negative system error code on errors.
342  *
343  * All arguments are passed verbatim to select(2).
344  * \sa select(2) select_tut(2).
345  */
346 int para_select(int n, fd_set *readfds, fd_set *writefds, int timeout)
347 {
348         int ret;
349         struct timeval tv;
350
351         ms2tv(timeout, &tv);
352         do
353                 ret = select(n, readfds, writefds, NULL, &tv);
354         while (ret < 0 && errno == EINTR);
355         if (ret < 0)
356                 return -ERRNO_TO_PARA_ERROR(errno);
357         return ret;
358 }
359
360 /**
361  * Set a file descriptor to blocking mode.
362  *
363  * \param fd The file descriptor.
364  *
365  * \return Standard.
366  */
367 __must_check int mark_fd_blocking(int fd)
368 {
369         int flags = fcntl(fd, F_GETFL);
370         if (flags < 0)
371                 return -ERRNO_TO_PARA_ERROR(errno);
372         flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
373         if (flags < 0)
374                 return -ERRNO_TO_PARA_ERROR(errno);
375         return 1;
376 }
377
378 /**
379  * Set a file descriptor to non-blocking mode.
380  *
381  * \param fd The file descriptor.
382  *
383  * \return Standard.
384  */
385 __must_check int mark_fd_nonblocking(int fd)
386 {
387         int flags = fcntl(fd, F_GETFL);
388         if (flags < 0)
389                 return -ERRNO_TO_PARA_ERROR(errno);
390         flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
391         if (flags < 0)
392                 return -ERRNO_TO_PARA_ERROR(errno);
393         return 1;
394 }
395
396 /**
397  * Set a file descriptor in a fd_set.
398  *
399  * \param fd The file descriptor to be set.
400  * \param fds The file descriptor set.
401  * \param max_fileno Highest-numbered file descriptor.
402  *
403  * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
404  * return, \a max_fileno contains the maximum of the old_value and \a fd.
405  *
406  * \sa \ref para_select.
407 */
408 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
409 {
410         assert(fd >= 0 && fd < FD_SETSIZE);
411 #if 0
412         {
413                 int flags = fcntl(fd, F_GETFL);
414                 if (!(flags & O_NONBLOCK)) {
415                         PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
416                         exit(EXIT_FAILURE);
417                 }
418         }
419 #endif
420         FD_SET(fd, fds);
421         *max_fileno = PARA_MAX(*max_fileno, fd);
422 }
423
424 /**
425  * Paraslash's wrapper for mmap.
426  *
427  * \param length Number of bytes to mmap.
428  * \param prot Either PROT_NONE or the bitwise OR of one or more of
429  * PROT_EXEC PROT_READ PROT_WRITE.
430  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
431  * \param fd The file to mmap from.
432  * \param map Result pointer.
433  *
434  * \return Standard.
435  *
436  * \sa mmap(2).
437  */
438 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
439 {
440         void **m = map;
441
442         errno = EINVAL;
443         if (!length)
444                 goto err;
445         *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
446         if (*m != MAP_FAILED)
447                 return 1;
448 err:
449         *m = NULL;
450         return -ERRNO_TO_PARA_ERROR(errno);
451 }
452
453 /**
454  * Wrapper for the open(2) system call.
455  *
456  * \param path The filename.
457  * \param flags The usual open(2) flags.
458  * \param mode Specifies the permissions to use.
459  *
460  * The mode parameter must be specified when O_CREAT is in the flags, and is
461  * ignored otherwise.
462  *
463  * \return The file descriptor on success, negative on errors.
464  *
465  * \sa open(2).
466  */
467 int para_open(const char *path, int flags, mode_t mode)
468 {
469         int ret = open(path, flags, mode);
470
471         if (ret >= 0)
472                 return ret;
473         return -ERRNO_TO_PARA_ERROR(errno);
474 }
475
476 /**
477  * Wrapper for chdir(2).
478  *
479  * \param path The specified directory.
480  *
481  * \return Standard.
482  */
483 int para_chdir(const char *path)
484 {
485         int ret = chdir(path);
486
487         if (ret >= 0)
488                 return 1;
489         return -ERRNO_TO_PARA_ERROR(errno);
490 }
491
492 /**
493  * Save the cwd and open a given directory.
494  *
495  * \param dirname Path to the directory to open.
496  * \param dir Result pointer.
497  * \param cwd File descriptor of the current working directory.
498  *
499  * \return Standard.
500  *
501  * Opening the current directory (".") and calling fchdir() to return is
502  * usually faster and more reliable than saving cwd in some buffer and calling
503  * chdir() afterwards.
504  *
505  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
506  * stored in \a cwd. If the function returns success, and \a cwd is not \p
507  * NULL, the caller must close this file descriptor (probably after calling
508  * fchdir(*cwd)).
509  *
510  * On errors, the function undos everything, so the caller needs neither close
511  * any files, nor change back to the original working directory.
512  *
513  * \sa getcwd(3).
514  *
515  */
516 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
517 {
518         int ret;
519
520         *dir = NULL;
521         if (cwd) {
522                 ret = para_open(".", O_RDONLY, 0);
523                 if (ret < 0)
524                         return ret;
525                 *cwd = ret;
526         }
527         ret = para_chdir(dirname);
528         if (ret < 0)
529                 goto close_cwd;
530         *dir = opendir(".");
531         if (*dir)
532                 return 1;
533         ret = -ERRNO_TO_PARA_ERROR(errno);
534         /* Ignore return value of fchdir() and close(). We're busted anyway. */
535         if (cwd) {
536                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
537         }
538 close_cwd:
539         if (cwd)
540                 close(*cwd);
541         return ret;
542 }
543
544 /**
545  * A wrapper for mkdir(2).
546  *
547  * \param path Name of the directory to create.
548  * \param mode The permissions to use.
549  *
550  * \return Standard.
551  */
552 int para_mkdir(const char *path, mode_t mode)
553 {
554         if (!mkdir(path, mode))
555                 return 1;
556         return -ERRNO_TO_PARA_ERROR(errno);
557 }
558
559 /**
560  * Open a file and map it into memory.
561  *
562  * \param path Name of the regular file to map.
563  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
564  * \param map On success, the mapping is returned here.
565  * \param size size of the mapping.
566  * \param fd_ptr The file descriptor of the mapping.
567  *
568  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
569  * open call is closed after mmap().  Otherwise the file is kept open and the
570  * file descriptor is returned in \a fd_ptr.
571  *
572  * \return Standard.
573  *
574  * \sa para_open(), mmap(2).
575  */
576 int mmap_full_file(const char *path, int open_mode, void **map,
577                 size_t *size, int *fd_ptr)
578 {
579         int fd, ret, mmap_prot, mmap_flags;
580         struct stat file_status;
581
582         if (open_mode == O_RDONLY) {
583                 mmap_prot = PROT_READ;
584                 mmap_flags = MAP_PRIVATE;
585         } else {
586                 mmap_prot = PROT_READ | PROT_WRITE;
587                 mmap_flags = MAP_SHARED;
588         }
589         ret = para_open(path, open_mode, 0);
590         if (ret < 0)
591                 return ret;
592         fd = ret;
593         if (fstat(fd, &file_status) < 0) {
594                 ret = -ERRNO_TO_PARA_ERROR(errno);
595                 goto out;
596         }
597         *size = file_status.st_size;
598         /*
599          * If the file is empty, *size is zero and mmap() would return EINVAL
600          * (Invalid argument). This error is common enough to spend an extra
601          * error code which explicitly states the problem.
602          */
603         ret = -E_EMPTY;
604         if (*size == 0)
605                 goto out;
606         /*
607          * If fd refers to a directory, mmap() returns ENODEV (No such device),
608          * at least on Linux. "Is a directory" seems to be more to the point.
609          */
610         ret = -ERRNO_TO_PARA_ERROR(EISDIR);
611         if (S_ISDIR(file_status.st_mode))
612                 goto out;
613
614         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
615 out:
616         if (ret < 0 || !fd_ptr)
617                 close(fd);
618         else
619                 *fd_ptr = fd;
620         return ret;
621 }
622
623 /**
624  * A wrapper for munmap(2).
625  *
626  * \param start The start address of the memory mapping.
627  * \param length The size of the mapping.
628  *
629  * \return Standard.
630  *
631  * \sa munmap(2), \ref mmap_full_file().
632  */
633 int para_munmap(void *start, size_t length)
634 {
635         int err;
636
637         if (!start)
638                 return 0;
639         if (munmap(start, length) >= 0)
640                 return 1;
641         err = errno;
642         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
643                 strerror(err));
644         return -ERRNO_TO_PARA_ERROR(err);
645 }
646
647 static int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
648 {
649         int ret;
650
651         do
652                 ret = poll(fds, nfds, timeout);
653         while (ret < 0 && errno == EINTR);
654         return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
655 }
656
657 /**
658  * Check a file descriptor for readability.
659  *
660  * \param fd The file descriptor.
661  *
662  * \return positive if fd is ready for reading, zero if it isn't, negative if
663  * an error occurred.
664  *
665  * \sa \ref write_ok().
666  */
667 int read_ok(int fd)
668 {
669         struct pollfd pfd = {.fd = fd, .events = POLLIN};
670         int ret = xpoll(&pfd, 1, 0);
671         return ret < 0? ret : pfd.revents & POLLIN;
672 }
673
674 /**
675  * Check a file descriptor for writability.
676  *
677  * \param fd The file descriptor.
678  *
679  * \return positive if fd is ready for writing, zero if it isn't, negative if
680  * an error occurred.
681  *
682  * \sa \ref read_ok().
683  */
684 int write_ok(int fd)
685 {
686         struct pollfd pfd = {.fd = fd, .events = POLLOUT};
687         int ret = xpoll(&pfd, 1, 0);
688         return ret < 0? ret : pfd.revents & POLLOUT;
689 }
690
691 /**
692  * Ensure that file descriptors 0, 1, and 2 are valid.
693  *
694  * Common approach that opens /dev/null until it gets a file descriptor greater
695  * than two.
696  */
697 void valid_fd_012(void)
698 {
699         while (1) {
700                 int fd = open("/dev/null", O_RDWR);
701                 if (fd < 0)
702                         exit(EXIT_FAILURE);
703                 if (fd > 2) {
704                         close(fd);
705                         break;
706                 }
707         }
708 }
709
710 /**
711  * Traverse the given directory recursively.
712  *
713  * \param dirname The directory to traverse.
714  * \param func The function to call for each entry.
715  * \param private_data Pointer to an arbitrary data structure.
716  *
717  * For each regular file under \a dirname, the supplied function \a func is
718  * called.  The full path of the regular file and the \a private_data pointer
719  * are passed to \a func. Directories for which the calling process has no
720  * permissions to change to are silently ignored.
721  *
722  * \return Standard.
723  */
724 int for_each_file_in_dir(const char *dirname,
725                 int (*func)(const char *, void *), void *private_data)
726 {
727         DIR *dir;
728         struct dirent *entry;
729         int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
730
731         if (ret < 0)
732                 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
733         /* scan cwd recursively */
734         while ((entry = readdir(dir))) {
735                 mode_t m;
736                 char *tmp;
737                 struct stat s;
738
739                 if (!strcmp(entry->d_name, "."))
740                         continue;
741                 if (!strcmp(entry->d_name, ".."))
742                         continue;
743                 if (lstat(entry->d_name, &s) == -1)
744                         continue;
745                 m = s.st_mode;
746                 if (!S_ISREG(m) && !S_ISDIR(m))
747                         continue;
748                 tmp = make_message("%s/%s", dirname, entry->d_name);
749                 if (!S_ISDIR(m)) {
750                         ret = func(tmp, private_data);
751                         free(tmp);
752                         if (ret < 0)
753                                 goto out;
754                         continue;
755                 }
756                 /* directory */
757                 ret = for_each_file_in_dir(tmp, func, private_data);
758                 free(tmp);
759                 if (ret < 0)
760                         goto out;
761         }
762         ret = 1;
763 out:
764         closedir(dir);
765         if (fchdir(cwd_fd) < 0 && ret >= 0)
766                 ret = -ERRNO_TO_PARA_ERROR(errno);
767         close(cwd_fd);
768         return ret;
769 }