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