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