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