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