]> git.tuebingen.mpg.de Git - paraslash.git/blob - fd.c
Hide implementation of para_fd_set().
[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  * Paraslash's wrapper for mmap.
381  *
382  * \param length Number of bytes to mmap.
383  * \param prot Either PROT_NONE or the bitwise OR of one or more of
384  * PROT_EXEC PROT_READ PROT_WRITE.
385  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
386  * \param fd The file to mmap from.
387  * \param map Result pointer.
388  *
389  * \return Standard.
390  *
391  * \sa mmap(2).
392  */
393 int para_mmap(size_t length, int prot, int flags, int fd, void *map)
394 {
395         void **m = map;
396
397         errno = EINVAL;
398         if (!length)
399                 goto err;
400         *m = mmap(NULL, length, prot, flags, fd, (off_t)0);
401         if (*m != MAP_FAILED)
402                 return 1;
403 err:
404         *m = NULL;
405         return -ERRNO_TO_PARA_ERROR(errno);
406 }
407
408 /**
409  * Wrapper for the open(2) system call.
410  *
411  * \param path The filename.
412  * \param flags The usual open(2) flags.
413  * \param mode Specifies the permissions to use.
414  *
415  * The mode parameter must be specified when O_CREAT is in the flags, and is
416  * ignored otherwise.
417  *
418  * \return The file descriptor on success, negative on errors.
419  *
420  * \sa open(2).
421  */
422 int para_open(const char *path, int flags, mode_t mode)
423 {
424         int ret = open(path, flags, mode);
425
426         if (ret >= 0)
427                 return ret;
428         return -ERRNO_TO_PARA_ERROR(errno);
429 }
430
431 /**
432  * Wrapper for chdir(2).
433  *
434  * \param path The specified directory.
435  *
436  * \return Standard.
437  */
438 int para_chdir(const char *path)
439 {
440         int ret = chdir(path);
441
442         if (ret >= 0)
443                 return 1;
444         return -ERRNO_TO_PARA_ERROR(errno);
445 }
446
447 /**
448  * Save the cwd and open a given directory.
449  *
450  * \param dirname Path to the directory to open.
451  * \param dir Result pointer.
452  * \param cwd File descriptor of the current working directory.
453  *
454  * \return Standard.
455  *
456  * Opening the current directory (".") and calling fchdir() to return is
457  * usually faster and more reliable than saving cwd in some buffer and calling
458  * chdir() afterwards.
459  *
460  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
461  * stored in \a cwd. If the function returns success, and \a cwd is not \p
462  * NULL, the caller must close this file descriptor (probably after calling
463  * fchdir(*cwd)).
464  *
465  * On errors, the function undos everything, so the caller needs neither close
466  * any files, nor change back to the original working directory.
467  *
468  * \sa getcwd(3).
469  *
470  */
471 static int para_opendir(const char *dirname, DIR **dir, int *cwd)
472 {
473         int ret;
474
475         *dir = NULL;
476         if (cwd) {
477                 ret = para_open(".", O_RDONLY, 0);
478                 if (ret < 0)
479                         return ret;
480                 *cwd = ret;
481         }
482         ret = para_chdir(dirname);
483         if (ret < 0)
484                 goto close_cwd;
485         *dir = opendir(".");
486         if (*dir)
487                 return 1;
488         ret = -ERRNO_TO_PARA_ERROR(errno);
489         /* Ignore return value of fchdir() and close(). We're busted anyway. */
490         if (cwd) {
491                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
492         }
493 close_cwd:
494         if (cwd)
495                 close(*cwd);
496         return ret;
497 }
498
499 /**
500  * A wrapper for mkdir(2).
501  *
502  * \param path Name of the directory to create.
503  * \param mode The permissions to use.
504  *
505  * \return Standard.
506  */
507 int para_mkdir(const char *path, mode_t mode)
508 {
509         if (!mkdir(path, mode))
510                 return 1;
511         return -ERRNO_TO_PARA_ERROR(errno);
512 }
513
514 /**
515  * Open a file and map it into memory.
516  *
517  * \param path Name of the regular file to map.
518  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
519  * \param map On success, the mapping is returned here.
520  * \param size size of the mapping.
521  * \param fd_ptr The file descriptor of the mapping.
522  *
523  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
524  * open call is closed after mmap().  Otherwise the file is kept open and the
525  * file descriptor is returned in \a fd_ptr.
526  *
527  * \return Standard.
528  *
529  * \sa para_open(), mmap(2).
530  */
531 int mmap_full_file(const char *path, int open_mode, void **map,
532                 size_t *size, int *fd_ptr)
533 {
534         int fd, ret, mmap_prot, mmap_flags;
535         struct stat file_status;
536
537         if (open_mode == O_RDONLY) {
538                 mmap_prot = PROT_READ;
539                 mmap_flags = MAP_PRIVATE;
540         } else {
541                 mmap_prot = PROT_READ | PROT_WRITE;
542                 mmap_flags = MAP_SHARED;
543         }
544         ret = para_open(path, open_mode, 0);
545         if (ret < 0)
546                 return ret;
547         fd = ret;
548         if (fstat(fd, &file_status) < 0) {
549                 ret = -ERRNO_TO_PARA_ERROR(errno);
550                 goto out;
551         }
552         *size = file_status.st_size;
553         /*
554          * If the file is empty, *size is zero and mmap() would return EINVAL
555          * (Invalid argument). This error is common enough to spend an extra
556          * error code which explicitly states the problem.
557          */
558         ret = -E_EMPTY;
559         if (*size == 0)
560                 goto out;
561         /*
562          * If fd refers to a directory, mmap() returns ENODEV (No such device),
563          * at least on Linux. "Is a directory" seems to be more to the point.
564          */
565         ret = -ERRNO_TO_PARA_ERROR(EISDIR);
566         if (S_ISDIR(file_status.st_mode))
567                 goto out;
568
569         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, map);
570 out:
571         if (ret < 0 || !fd_ptr)
572                 close(fd);
573         else
574                 *fd_ptr = fd;
575         return ret;
576 }
577
578 /**
579  * A wrapper for munmap(2).
580  *
581  * \param start The start address of the memory mapping.
582  * \param length The size of the mapping.
583  *
584  * \return Standard.
585  *
586  * \sa munmap(2), \ref mmap_full_file().
587  */
588 int para_munmap(void *start, size_t length)
589 {
590         int err;
591
592         if (!start)
593                 return 0;
594         if (munmap(start, length) >= 0)
595                 return 1;
596         err = errno;
597         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
598                 strerror(err));
599         return -ERRNO_TO_PARA_ERROR(err);
600 }
601
602 static int xpoll(struct pollfd *fds, nfds_t nfds, int timeout)
603 {
604         int ret;
605
606         do
607                 ret = poll(fds, nfds, timeout);
608         while (ret < 0 && errno == EINTR);
609         return ret < 0? -ERRNO_TO_PARA_ERROR(errno) : ret;
610 }
611
612 /**
613  * Check a file descriptor for readability.
614  *
615  * \param fd The file descriptor.
616  *
617  * \return positive if fd is ready for reading, zero if it isn't, negative if
618  * an error occurred.
619  *
620  * \sa \ref write_ok().
621  */
622 int read_ok(int fd)
623 {
624         struct pollfd pfd = {.fd = fd, .events = POLLIN};
625         int ret = xpoll(&pfd, 1, 0);
626         return ret < 0? ret : pfd.revents & POLLIN;
627 }
628
629 /**
630  * Check a file descriptor for writability.
631  *
632  * \param fd The file descriptor.
633  *
634  * \return positive if fd is ready for writing, zero if it isn't, negative if
635  * an error occurred.
636  *
637  * \sa \ref read_ok().
638  */
639 int write_ok(int fd)
640 {
641         struct pollfd pfd = {.fd = fd, .events = POLLOUT};
642         int ret = xpoll(&pfd, 1, 0);
643         return ret < 0? ret : pfd.revents & POLLOUT;
644 }
645
646 /**
647  * Ensure that file descriptors 0, 1, and 2 are valid.
648  *
649  * Common approach that opens /dev/null until it gets a file descriptor greater
650  * than two.
651  */
652 void valid_fd_012(void)
653 {
654         while (1) {
655                 int fd = open("/dev/null", O_RDWR);
656                 if (fd < 0)
657                         exit(EXIT_FAILURE);
658                 if (fd > 2) {
659                         close(fd);
660                         break;
661                 }
662         }
663 }
664
665 /**
666  * Traverse the given directory recursively.
667  *
668  * \param dirname The directory to traverse.
669  * \param func The function to call for each entry.
670  * \param private_data Pointer to an arbitrary data structure.
671  *
672  * For each regular file under \a dirname, the supplied function \a func is
673  * called.  The full path of the regular file and the \a private_data pointer
674  * are passed to \a func. Directories for which the calling process has no
675  * permissions to change to are silently ignored.
676  *
677  * \return Standard.
678  */
679 int for_each_file_in_dir(const char *dirname,
680                 int (*func)(const char *, void *), void *private_data)
681 {
682         DIR *dir;
683         struct dirent *entry;
684         int cwd_fd, ret = para_opendir(dirname, &dir, &cwd_fd);
685
686         if (ret < 0)
687                 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
688         /* scan cwd recursively */
689         while ((entry = readdir(dir))) {
690                 mode_t m;
691                 char *tmp;
692                 struct stat s;
693
694                 if (!strcmp(entry->d_name, "."))
695                         continue;
696                 if (!strcmp(entry->d_name, ".."))
697                         continue;
698                 if (lstat(entry->d_name, &s) == -1)
699                         continue;
700                 m = s.st_mode;
701                 if (!S_ISREG(m) && !S_ISDIR(m))
702                         continue;
703                 tmp = make_message("%s/%s", dirname, entry->d_name);
704                 if (!S_ISDIR(m)) {
705                         ret = func(tmp, private_data);
706                         free(tmp);
707                         if (ret < 0)
708                                 goto out;
709                         continue;
710                 }
711                 /* directory */
712                 ret = for_each_file_in_dir(tmp, func, private_data);
713                 free(tmp);
714                 if (ret < 0)
715                         goto out;
716         }
717         ret = 1;
718 out:
719         closedir(dir);
720         if (fchdir(cwd_fd) < 0 && ret >= 0)
721                 ret = -ERRNO_TO_PARA_ERROR(errno);
722         close(cwd_fd);
723         return ret;
724 }