]> git.tuebingen.mpg.de Git - paraslash.git/blob - fd.c
Introduce the new nonblock API.
[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  * Simple wrapper for readv().
182  *
183  * \param fd The file descriptor to read from.
184  * \param iov Scatter/gather array used in readv().
185  * \param iovcnt Number of elements in \a iov.
186  *
187  * \return A negative error code on errors, the return value of the underlying
188  * call to readv() otherwise.
189  *
190  * \sa readv(2).
191  */
192 int para_readv(int fd, struct iovec *iov, int iovcnt)
193 {
194         int ret = readv(fd, iov, iovcnt);
195
196         if (ret < 0)
197                 return -ERRNO_TO_PARA_ERROR(errno);
198         return ret;
199 }
200
201 /**
202  * Check whether a file exists.
203  *
204  * \param fn The file name.
205  *
206  * \return Non-zero iff file exists.
207  */
208 int file_exists(const char *fn)
209 {
210         struct stat statbuf;
211
212         return !stat(fn, &statbuf);
213 }
214
215 /**
216  * Paraslash's wrapper for select(2).
217  *
218  * It calls select(2) (with no exceptfds) and starts over if select() was
219  * interrupted by a signal.
220  *
221  * \param n The highest-numbered descriptor in any of the two sets, plus 1.
222  * \param readfds fds that should be checked for readability.
223  * \param writefds fds that should be checked for writablility.
224  * \param timeout_tv upper bound on the amount of time elapsed before select()
225  * returns.
226  *
227  * \return The return value of the underlying select() call on success, the
228  * negative system error code on errors.
229  *
230  * All arguments are passed verbatim to select(2).
231  * \sa select(2) select_tut(2).
232  */
233 int para_select(int n, fd_set *readfds, fd_set *writefds,
234                 struct timeval *timeout_tv)
235 {
236         int ret;
237         do
238                 ret = select(n, readfds, writefds, NULL, timeout_tv);
239         while (ret < 0 && errno == EINTR);
240         if (ret < 0)
241                 return -ERRNO_TO_PARA_ERROR(errno);
242         return ret;
243 }
244
245 /**
246  * Set a file descriptor to blocking mode.
247  *
248  * \param fd The file descriptor.
249  *
250  * \return Standard.
251  */
252 __must_check int mark_fd_blocking(int fd)
253 {
254         int flags = fcntl(fd, F_GETFL);
255         if (flags < 0)
256                 return -ERRNO_TO_PARA_ERROR(errno);
257         flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
258         if (flags < 0)
259                 return -ERRNO_TO_PARA_ERROR(errno);
260         return 1;
261 }
262
263 /**
264  * Set a file descriptor to non-blocking mode.
265  *
266  * \param fd The file descriptor.
267  *
268  * \return Standard.
269  */
270 __must_check int mark_fd_nonblocking(int fd)
271 {
272         int flags = fcntl(fd, F_GETFL);
273         if (flags < 0)
274                 return -ERRNO_TO_PARA_ERROR(errno);
275         flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
276         if (flags < 0)
277                 return -ERRNO_TO_PARA_ERROR(errno);
278         return 1;
279 }
280
281 /**
282  * Set a file descriptor in a fd_set.
283  *
284  * \param fd The file descriptor to be set.
285  * \param fds The file descriptor set.
286  * \param max_fileno Highest-numbered file descriptor.
287  *
288  * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
289  * return, \a max_fileno contains the maximum of the old_value and \a fd.
290  *
291  * \sa para_select.
292 */
293 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
294 {
295         assert(fd >= 0 && fd < FD_SETSIZE);
296 #if 0
297         {
298                 int flags = fcntl(fd, F_GETFL);
299                 if (!(flags & O_NONBLOCK)) {
300                         PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
301                         exit(EXIT_FAILURE);
302                 }
303         }
304 #endif
305         FD_SET(fd, fds);
306         *max_fileno = PARA_MAX(*max_fileno, fd);
307 }
308
309 /**
310  * Paraslash's wrapper for fgets(3).
311  *
312  * \param line Pointer to the buffer to store the line.
313  * \param size The size of the buffer given by \a line.
314  * \param f The stream to read from.
315  *
316  * \return Unlike the standard fgets() function, an integer value
317  * is returned. On success, this function returns 1. On errors, -E_FGETS
318  * is returned. A zero return value indicates an end of file condition.
319  */
320 __must_check int para_fgets(char *line, int size, FILE *f)
321 {
322 again:
323         if (fgets(line, size, f))
324                 return 1;
325         if (feof(f))
326                 return 0;
327         if (!ferror(f))
328                 return -E_FGETS;
329         if (errno != EINTR) {
330                 PARA_ERROR_LOG("%s\n", strerror(errno));
331                 return -E_FGETS;
332         }
333         clearerr(f);
334         goto again;
335 }
336
337 /**
338  * Paraslash's wrapper for mmap.
339  *
340  * \param length Number of bytes to mmap.
341  * \param prot Either PROT_NONE or the bitwise OR of one or more of
342  * PROT_EXEC PROT_READ PROT_WRITE.
343  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
344  * \param fd The file to mmap from.
345  * \param offset Mmap start.
346  * \param map Result pointer.
347  *
348  * \return Standard.
349  *
350  * \sa mmap(2).
351  */
352 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
353                 void *map)
354 {
355         void **m = map;
356
357         errno = EINVAL;
358         if (!length)
359                 goto err;
360         *m = mmap(NULL, length, prot, flags, fd, offset);
361         if (*m != MAP_FAILED)
362                 return 1;
363 err:
364         *m = NULL;
365         return -ERRNO_TO_PARA_ERROR(errno);
366 }
367
368 /**
369  * Wrapper for the open(2) system call.
370  *
371  * \param path The filename.
372  * \param flags The usual open(2) flags.
373  * \param mode Specifies the permissions to use.
374  *
375  * The mode parameter must be specified when O_CREAT is in the flags, and is
376  * ignored otherwise.
377  *
378  * \return The file descriptor on success, negative on errors.
379  *
380  * \sa open(2).
381  */
382 int para_open(const char *path, int flags, mode_t mode)
383 {
384         int ret = open(path, flags, mode);
385
386         if (ret >= 0)
387                 return ret;
388         return -ERRNO_TO_PARA_ERROR(errno);
389 }
390
391 /**
392  * Wrapper for chdir(2).
393  *
394  * \param path The specified directory.
395  *
396  * \return Standard.
397  */
398 int para_chdir(const char *path)
399 {
400         int ret = chdir(path);
401
402         if (ret >= 0)
403                 return 1;
404         return -ERRNO_TO_PARA_ERROR(errno);
405 }
406
407 /**
408  * Save the cwd and open a given directory.
409  *
410  * \param dirname Path to the directory to open.
411  * \param dir Result pointer.
412  * \param cwd File descriptor of the current working directory.
413  *
414  * \return Standard.
415  *
416  * Opening the current directory (".") and calling fchdir() to return is
417  * usually faster and more reliable than saving cwd in some buffer and calling
418  * chdir() afterwards.
419  *
420  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
421  * stored in \a cwd. If the function returns success, and \a cwd is not \p
422  * NULL, the caller must close this file descriptor (probably after calling
423  * fchdir(*cwd)).
424  *
425  * On errors, the function undos everything, so the caller needs neither close
426  * any files, nor change back to the original working directory.
427  *
428  * \sa getcwd(3).
429  *
430  */
431 int para_opendir(const char *dirname, DIR **dir, int *cwd)
432 {
433         int ret;
434
435         if (cwd) {
436                 ret = para_open(".", O_RDONLY, 0);
437                 if (ret < 0)
438                         return ret;
439                 *cwd = ret;
440         }
441         ret = para_chdir(dirname);
442         if (ret < 0)
443                 goto close_cwd;
444         *dir = opendir(".");
445         if (*dir)
446                 return 1;
447         ret = -ERRNO_TO_PARA_ERROR(errno);
448         /* Ignore return value of fchdir() and close(). We're busted anyway. */
449         if (cwd) {
450                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
451         }
452 close_cwd:
453         if (cwd)
454                 close(*cwd);
455         return ret;
456 }
457
458 /**
459  * A wrapper for fchdir().
460  *
461  * \param fd An open file descriptor.
462  *
463  * \return Standard.
464  */
465 int para_fchdir(int fd)
466 {
467         if (fchdir(fd) < 0)
468                 return -ERRNO_TO_PARA_ERROR(errno);
469         return 1;
470 }
471
472 /**
473  * A wrapper for mkdir(2).
474  *
475  * \param path Name of the directory to create.
476  * \param mode The permissions to use.
477  *
478  * \return Standard.
479  */
480 int para_mkdir(const char *path, mode_t mode)
481 {
482         if (!mkdir(path, mode))
483                 return 1;
484         return -ERRNO_TO_PARA_ERROR(errno);
485 }
486
487 /**
488  * Open a file and map it into memory.
489  *
490  * \param path Name of the regular file to map.
491  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
492  * \param map On success, the mapping is returned here.
493  * \param size size of the mapping.
494  * \param fd_ptr The file descriptor of the mapping.
495  *
496  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
497  * open call is closed after mmap().  Otherwise the file is kept open and the
498  * file descriptor is returned in \a fd_ptr.
499  *
500  * \return Standard.
501  *
502  * \sa para_open(), mmap(2).
503  */
504 int mmap_full_file(const char *path, int open_mode, void **map,
505                 size_t *size, int *fd_ptr)
506 {
507         int fd, ret, mmap_prot, mmap_flags;
508         struct stat file_status;
509
510         if (open_mode == O_RDONLY) {
511                 mmap_prot = PROT_READ;
512                 mmap_flags = MAP_PRIVATE;
513         } else {
514                 mmap_prot = PROT_READ | PROT_WRITE;
515                 mmap_flags = MAP_SHARED;
516         }
517         ret = para_open(path, open_mode, 0);
518         if (ret < 0)
519                 return ret;
520         fd = ret;
521         if (fstat(fd, &file_status) < 0) {
522                 ret = -ERRNO_TO_PARA_ERROR(errno);
523                 goto out;
524         }
525         *size = file_status.st_size;
526         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
527 out:
528         if (ret < 0 || !fd_ptr)
529                 close(fd);
530         else
531                 *fd_ptr = fd;
532         return ret;
533 }
534
535 /**
536  * A wrapper for munmap(2).
537  *
538  * \param start The start address of the memory mapping.
539  * \param length The size of the mapping.
540  *
541  * \return Standard.
542  *
543  * \sa munmap(2), mmap_full_file().
544  */
545 int para_munmap(void *start, size_t length)
546 {
547         int err;
548         if (munmap(start, length) >= 0)
549                 return 1;
550         err = errno;
551         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
552                 strerror(err));
553         return -ERRNO_TO_PARA_ERROR(err);
554 }
555
556 /**
557  * Check a file descriptor for writability.
558  *
559  * \param fd The file descriptor.
560  *
561  * \return positive if fd is ready for writing, zero if it isn't, negative if
562  * an error occurred.
563  */
564
565 int write_ok(int fd)
566 {
567         struct timeval tv;
568         fd_set wfds;
569
570         FD_ZERO(&wfds);
571         FD_SET(fd, &wfds);
572         tv.tv_sec = 0;
573         tv.tv_usec = 0;
574         return para_select(fd + 1, NULL, &wfds, &tv);
575 }
576
577 /**
578  * Ensure that file descriptors 0, 1, and 2 are valid.
579  *
580  * Common approach that opens /dev/null until it gets a file descriptor greater
581  * than two.
582  *
583  * \sa okir's Black Hats Manual.
584  */
585 void valid_fd_012(void)
586 {
587         while (1) {
588                 int fd = open("/dev/null", O_RDWR);
589                 if (fd < 0)
590                         exit(EXIT_FAILURE);
591                 if (fd > 2) {
592                         close(fd);
593                         break;
594                 }
595         }
596 }
597
598 /**
599  * Traverse the given directory recursively.
600  *
601  * \param dirname The directory to traverse.
602  * \param func The function to call for each entry.
603  * \param private_data Pointer to an arbitrary data structure.
604  *
605  * For each regular file under \a dirname, the supplied function \a func is
606  * called.  The full path of the regular file and the \a private_data pointer
607  * are passed to \a func. Directories for which the calling process has no
608  * permissions to change to are silently ignored.
609  *
610  * \return Standard.
611  */
612 int for_each_file_in_dir(const char *dirname,
613                 int (*func)(const char *, void *), void *private_data)
614 {
615         DIR *dir;
616         struct dirent *entry;
617         int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
618
619         if (ret < 0)
620                 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
621         /* scan cwd recursively */
622         while ((entry = readdir(dir))) {
623                 mode_t m;
624                 char *tmp;
625                 struct stat s;
626
627                 if (!strcmp(entry->d_name, "."))
628                         continue;
629                 if (!strcmp(entry->d_name, ".."))
630                         continue;
631                 if (lstat(entry->d_name, &s) == -1)
632                         continue;
633                 m = s.st_mode;
634                 if (!S_ISREG(m) && !S_ISDIR(m))
635                         continue;
636                 tmp = make_message("%s/%s", dirname, entry->d_name);
637                 if (!S_ISDIR(m)) {
638                         ret = func(tmp, private_data);
639                         free(tmp);
640                         if (ret < 0)
641                                 goto out;
642                         continue;
643                 }
644                 /* directory */
645                 ret = for_each_file_in_dir(tmp, func, private_data);
646                 free(tmp);
647                 if (ret < 0)
648                         goto out;
649         }
650         ret = 1;
651 out:
652         closedir(dir);
653         ret2 = para_fchdir(cwd_fd);
654         if (ret2 < 0 && ret >= 0)
655                 ret = ret2;
656         close(cwd_fd);
657         return ret;
658 }