]> git.tuebingen.mpg.de Git - paraslash.git/blob - fd.c
fd: Drop fd_set parameter from read_nonblock() and friends.
[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 num_bytes Result pointer. Contains the number of bytes read from \a fd.
181  *
182  * This function tries to read up to sz bytes from fd, where sz is the sum of
183  * the lengths of all vectors in iov. Like \ref xwrite(), EAGAIN and EINTR are
184  * not considered error conditions. However, EOF is.
185  *
186  * \return Zero or a negative error code. If the underlying call to readv(2)
187  * returned zero (indicating an end of file condition) or failed for some
188  * reason other than EAGAIN or EINTR, a negative error code is returned.
189  *
190  * In any case, \a num_bytes contains the number of bytes that have been
191  * successfully read from \a fd (zero if the first readv() call failed with
192  * EAGAIN). Note that even if the function returns negative, some data might
193  * have been read before the error occurred. In this case \a num_bytes is
194  * positive.
195  *
196  * \sa \ref xwrite(), read(2), readv(2).
197  */
198 int readv_nonblock(int fd, struct iovec *iov, int iovcnt, size_t *num_bytes)
199 {
200         int ret, i, j;
201
202         *num_bytes = 0;
203         for (i = 0, j = 0; i < iovcnt;) {
204                 /* fix up the first iov */
205                 assert(j < iov[i].iov_len);
206                 iov[i].iov_base += j;
207                 iov[i].iov_len -= j;
208                 ret = readv(fd, iov + i, iovcnt - i);
209                 iov[i].iov_base -= j;
210                 iov[i].iov_len += j;
211
212                 if (ret == 0)
213                         return -E_EOF;
214                 if (ret < 0) {
215                         if (errno == EAGAIN || errno == EINTR)
216                                 return 0;
217                         return -ERRNO_TO_PARA_ERROR(errno);
218                 }
219                 *num_bytes += ret;
220                 while (ret > 0) {
221                         if (ret < iov[i].iov_len - j) {
222                                 j += ret;
223                                 break;
224                         }
225                         ret -= iov[i].iov_len - j;
226                         j = 0;
227                         if (++i >= iovcnt)
228                                 break;
229                 }
230         }
231         return 0;
232 }
233
234 /**
235  * Read from a non-blocking file descriptor into a single buffer.
236  *
237  * \param fd The file descriptor to read from.
238  * \param buf The buffer to read data to.
239  * \param sz The size of \a buf.
240  * \param num_bytes \see \ref readv_nonblock().
241  *
242  * This is a simple wrapper for readv_nonblock() which uses an iovec with a single
243  * buffer.
244  *
245  * \return The return value of the underlying call to readv_nonblock().
246  */
247 int read_nonblock(int fd, void *buf, size_t sz, size_t *num_bytes)
248 {
249         struct iovec iov = {.iov_base = buf, .iov_len = sz};
250         return readv_nonblock(fd, &iov, 1, num_bytes);
251 }
252
253 /**
254  * Read a buffer and check its content for a pattern.
255  *
256  * \param fd The file descriptor to receive from.
257  * \param pattern The expected pattern.
258  * \param bufsize The size of the internal buffer.
259  *
260  * This function tries to read at most \a bufsize bytes from the non-blocking
261  * file descriptor \a fd. If at least \p strlen(\a pattern) bytes have been
262  * received, the beginning of the received buffer is compared with \a pattern,
263  * ignoring case.
264  *
265  * \return Positive if \a pattern was received, negative on errors, zero if no data
266  * was available to read.
267  *
268  * \sa \ref read_nonblock(), \sa strncasecmp(3).
269  */
270 int read_pattern(int fd, const char *pattern, size_t bufsize)
271 {
272         size_t n, len;
273         char *buf = para_malloc(bufsize + 1);
274         int ret = read_nonblock(fd, buf, bufsize, &n);
275
276         buf[n] = '\0';
277         if (ret < 0)
278                 goto out;
279         ret = 0;
280         if (n == 0)
281                 goto out;
282         ret = -E_READ_PATTERN;
283         len = strlen(pattern);
284         if (n < len)
285                 goto out;
286         if (strncasecmp(buf, pattern, len) != 0)
287                 goto out;
288         ret = 1;
289 out:
290         if (ret < 0) {
291                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
292                 PARA_NOTICE_LOG("recvd %zu bytes: %s\n", n, buf);
293         }
294         free(buf);
295         return ret;
296 }
297
298 /**
299  * Check whether a file exists.
300  *
301  * \param fn The file name.
302  *
303  * \return True iff file exists.
304  */
305 bool file_exists(const char *fn)
306 {
307         struct stat statbuf;
308
309         return !stat(fn, &statbuf);
310 }
311
312 /**
313  * Paraslash's wrapper for select(2).
314  *
315  * It calls select(2) (with no exceptfds) and starts over if select() was
316  * interrupted by a signal.
317  *
318  * \param n The highest-numbered descriptor in any of the two sets, plus 1.
319  * \param readfds fds that should be checked for readability.
320  * \param writefds fds that should be checked for writablility.
321  * \param timeout Upper bound in milliseconds.
322  *
323  * \return The return value of the underlying select() call on success, the
324  * negative system error code on errors.
325  *
326  * All arguments are passed verbatim to select(2).
327  * \sa select(2) select_tut(2).
328  */
329 int para_select(int n, fd_set *readfds, fd_set *writefds, int timeout)
330 {
331         int ret;
332         struct timeval tv;
333
334         ms2tv(timeout, &tv);
335         do
336                 ret = select(n, readfds, writefds, NULL, &tv);
337         while (ret < 0 && errno == EINTR);
338         if (ret < 0)
339                 return -ERRNO_TO_PARA_ERROR(errno);
340         return ret;
341 }
342
343 /**
344  * Set a file descriptor to blocking mode.
345  *
346  * \param fd The file descriptor.
347  *
348  * \return Standard.
349  */
350 __must_check int mark_fd_blocking(int fd)
351 {
352         int flags = fcntl(fd, F_GETFL);
353         if (flags < 0)
354                 return -ERRNO_TO_PARA_ERROR(errno);
355         flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
356         if (flags < 0)
357                 return -ERRNO_TO_PARA_ERROR(errno);
358         return 1;
359 }
360
361 /**
362  * Set a file descriptor to non-blocking mode.
363  *
364  * \param fd The file descriptor.
365  *
366  * \return Standard.
367  */
368 __must_check int mark_fd_nonblocking(int fd)
369 {
370         int flags = fcntl(fd, F_GETFL);
371         if (flags < 0)
372                 return -ERRNO_TO_PARA_ERROR(errno);
373         flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
374         if (flags < 0)
375                 return -ERRNO_TO_PARA_ERROR(errno);
376         return 1;
377 }
378
379 /**
380  * Set a file descriptor in a fd_set.
381  *
382  * \param fd The file descriptor to be set.
383  * \param fds The file descriptor set.
384  * \param max_fileno Highest-numbered file descriptor.
385  *
386  * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
387  * return, \a max_fileno contains the maximum of the old_value and \a fd.
388  *
389  * \sa \ref para_select.
390 */
391 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
392 {
393         assert(fd >= 0 && fd < FD_SETSIZE);
394 #if 0
395         {
396                 int flags = fcntl(fd, F_GETFL);
397                 if (!(flags & O_NONBLOCK)) {
398                         PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
399                         exit(EXIT_FAILURE);
400                 }
401         }
402 #endif
403         FD_SET(fd, fds);
404         *max_fileno = PARA_MAX(*max_fileno, fd);
405 }
406
407 /**
408  * Paraslash's wrapper for mmap.
409  *
410  * \param length Number of bytes to mmap.
411  * \param prot Either PROT_NONE or the bitwise OR of one or more of
412  * PROT_EXEC PROT_READ PROT_WRITE.
413  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
414  * \param fd The file to mmap from.
415  * \param map Result pointer.
416  *
417  * \return Standard.
418  *
419  * \sa mmap(2).
420  */
421 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
422 {
423         void **m = map;
424
425         errno = EINVAL;
426         if (!length)
427                 goto err;
428         *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
429         if (*m != MAP_FAILED)
430                 return 1;
431 err:
432         *m = NULL;
433         return -ERRNO_TO_PARA_ERROR(errno);
434 }
435
436 /**
437  * Wrapper for the open(2) system call.
438  *
439  * \param path The filename.
440  * \param flags The usual open(2) flags.
441  * \param mode Specifies the permissions to use.
442  *
443  * The mode parameter must be specified when O_CREAT is in the flags, and is
444  * ignored otherwise.
445  *
446  * \return The file descriptor on success, negative on errors.
447  *
448  * \sa open(2).
449  */
450 int para_open(const char *path, int flags, mode_t mode)
451 {
452         int ret = open(path, flags, mode);
453
454         if (ret >= 0)
455                 return ret;
456         return -ERRNO_TO_PARA_ERROR(errno);
457 }
458
459 /**
460  * Wrapper for chdir(2).
461  *
462  * \param path The specified directory.
463  *
464  * \return Standard.
465  */
466 int para_chdir(const char *path)
467 {
468         int ret = chdir(path);
469
470         if (ret >= 0)
471                 return 1;
472         return -ERRNO_TO_PARA_ERROR(errno);
473 }
474
475 /**
476  * Save the cwd and open a given directory.
477  *
478  * \param dirname Path to the directory to open.
479  * \param dir Result pointer.
480  * \param cwd File descriptor of the current working directory.
481  *
482  * \return Standard.
483  *
484  * Opening the current directory (".") and calling fchdir() to return is
485  * usually faster and more reliable than saving cwd in some buffer and calling
486  * chdir() afterwards.
487  *
488  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
489  * stored in \a cwd. If the function returns success, and \a cwd is not \p
490  * NULL, the caller must close this file descriptor (probably after calling
491  * fchdir(*cwd)).
492  *
493  * On errors, the function undos everything, so the caller needs neither close
494  * any files, nor change back to the original working directory.
495  *
496  * \sa getcwd(3).
497  *
498  */
499 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
500 {
501         int ret;
502
503         *dir = NULL;
504         if (cwd) {
505                 ret = para_open(".", O_RDONLY, 0);
506                 if (ret < 0)
507                         return ret;
508                 *cwd = ret;
509         }
510         ret = para_chdir(dirname);
511         if (ret < 0)
512                 goto close_cwd;
513         *dir = opendir(".");
514         if (*dir)
515                 return 1;
516         ret = -ERRNO_TO_PARA_ERROR(errno);
517         /* Ignore return value of fchdir() and close(). We're busted anyway. */
518         if (cwd) {
519                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
520         }
521 close_cwd:
522         if (cwd)
523                 close(*cwd);
524         return ret;
525 }
526
527 /**
528  * A wrapper for mkdir(2).
529  *
530  * \param path Name of the directory to create.
531  * \param mode The permissions to use.
532  *
533  * \return Standard.
534  */
535 int para_mkdir(const char *path, mode_t mode)
536 {
537         if (!mkdir(path, mode))
538                 return 1;
539         return -ERRNO_TO_PARA_ERROR(errno);
540 }
541
542 /**
543  * Open a file and map it into memory.
544  *
545  * \param path Name of the regular file to map.
546  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
547  * \param map On success, the mapping is returned here.
548  * \param size size of the mapping.
549  * \param fd_ptr The file descriptor of the mapping.
550  *
551  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
552  * open call is closed after mmap().  Otherwise the file is kept open and the
553  * file descriptor is returned in \a fd_ptr.
554  *
555  * \return Standard.
556  *
557  * \sa para_open(), mmap(2).
558  */
559 int mmap_full_file(const char *path, int open_mode, void **map,
560                 size_t *size, int *fd_ptr)
561 {
562         int fd, ret, mmap_prot, mmap_flags;
563         struct stat file_status;
564
565         if (open_mode == O_RDONLY) {
566                 mmap_prot = PROT_READ;
567                 mmap_flags = MAP_PRIVATE;
568         } else {
569                 mmap_prot = PROT_READ | PROT_WRITE;
570                 mmap_flags = MAP_SHARED;
571         }
572         ret = para_open(path, open_mode, 0);
573         if (ret < 0)
574                 return ret;
575         fd = ret;
576         if (fstat(fd, &file_status) < 0) {
577                 ret = -ERRNO_TO_PARA_ERROR(errno);
578                 goto out;
579         }
580         *size = file_status.st_size;
581         /*
582          * If the file is empty, *size is zero and mmap() would return EINVAL
583          * (Invalid argument). This error is common enough to spend an extra
584          * error code which explicitly states the problem.
585          */
586         ret = -E_EMPTY;
587         if (*size == 0)
588                 goto out;
589         /*
590          * If fd refers to a directory, mmap() returns ENODEV (No such device),
591          * at least on Linux. "Is a directory" seems to be more to the point.
592          */
593         ret = -ERRNO_TO_PARA_ERROR(EISDIR);
594         if (S_ISDIR(file_status.st_mode))
595                 goto out;
596
597         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
598 out:
599         if (ret < 0 || !fd_ptr)
600                 close(fd);
601         else
602                 *fd_ptr = fd;
603         return ret;
604 }
605
606 /**
607  * A wrapper for munmap(2).
608  *
609  * \param start The start address of the memory mapping.
610  * \param length The size of the mapping.
611  *
612  * \return Standard.
613  *
614  * \sa munmap(2), \ref mmap_full_file().
615  */
616 int para_munmap(void *start, size_t length)
617 {
618         int err;
619
620         if (!start)
621                 return 0;
622         if (munmap(start, length) >= 0)
623                 return 1;
624         err = errno;
625         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
626                 strerror(err));
627         return -ERRNO_TO_PARA_ERROR(err);
628 }
629
630 static int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
631 {
632         int ret;
633
634         do
635                 ret = poll(fds, nfds, timeout);
636         while (ret < 0 && errno == EINTR);
637         return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
638 }
639
640 /**
641  * Check a file descriptor for readability.
642  *
643  * \param fd The file descriptor.
644  *
645  * \return positive if fd is ready for reading, zero if it isn't, negative if
646  * an error occurred.
647  *
648  * \sa \ref write_ok().
649  */
650 int read_ok(int fd)
651 {
652         struct pollfd pfd = {.fd = fd, .events = POLLIN};
653         int ret = xpoll(&pfd, 1, 0);
654         return ret < 0? ret : pfd.revents & POLLIN;
655 }
656
657 /**
658  * Check a file descriptor for writability.
659  *
660  * \param fd The file descriptor.
661  *
662  * \return positive if fd is ready for writing, zero if it isn't, negative if
663  * an error occurred.
664  *
665  * \sa \ref read_ok().
666  */
667 int write_ok(int fd)
668 {
669         struct pollfd pfd = {.fd = fd, .events = POLLOUT};
670         int ret = xpoll(&pfd, 1, 0);
671         return ret < 0? ret : pfd.revents & POLLOUT;
672 }
673
674 /**
675  * Ensure that file descriptors 0, 1, and 2 are valid.
676  *
677  * Common approach that opens /dev/null until it gets a file descriptor greater
678  * than two.
679  */
680 void valid_fd_012(void)
681 {
682         while (1) {
683                 int fd = open("/dev/null", O_RDWR);
684                 if (fd < 0)
685                         exit(EXIT_FAILURE);
686                 if (fd > 2) {
687                         close(fd);
688                         break;
689                 }
690         }
691 }
692
693 /**
694  * Traverse the given directory recursively.
695  *
696  * \param dirname The directory to traverse.
697  * \param func The function to call for each entry.
698  * \param private_data Pointer to an arbitrary data structure.
699  *
700  * For each regular file under \a dirname, the supplied function \a func is
701  * called.  The full path of the regular file and the \a private_data pointer
702  * are passed to \a func. Directories for which the calling process has no
703  * permissions to change to are silently ignored.
704  *
705  * \return Standard.
706  */
707 int for_each_file_in_dir(const char *dirname,
708                 int (*func)(const char *, void *), void *private_data)
709 {
710         DIR *dir;
711         struct dirent *entry;
712         int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
713
714         if (ret < 0)
715                 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
716         /* scan cwd recursively */
717         while ((entry = readdir(dir))) {
718                 mode_t m;
719                 char *tmp;
720                 struct stat s;
721
722                 if (!strcmp(entry->d_name, "."))
723                         continue;
724                 if (!strcmp(entry->d_name, ".."))
725                         continue;
726                 if (lstat(entry->d_name, &s) == -1)
727                         continue;
728                 m = s.st_mode;
729                 if (!S_ISREG(m) && !S_ISDIR(m))
730                         continue;
731                 tmp = make_message("%s/%s", dirname, entry->d_name);
732                 if (!S_ISDIR(m)) {
733                         ret = func(tmp, private_data);
734                         free(tmp);
735                         if (ret < 0)
736                                 goto out;
737                         continue;
738                 }
739                 /* directory */
740                 ret = for_each_file_in_dir(tmp, func, private_data);
741                 free(tmp);
742                 if (ret < 0)
743                         goto out;
744         }
745         ret = 1;
746 out:
747         closedir(dir);
748         if (fchdir(cwd_fd) < 0 && ret >= 0)
749                 ret = -ERRNO_TO_PARA_ERROR(errno);
750         close(cwd_fd);
751         return ret;
752 }