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