Merge branch 't/doc'
[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/select.h>
15 #include <sys/uio.h>
16
17 #include "para.h"
18 #include "error.h"
19 #include "string.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  * Simple wrapper for readv().
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  *
92  * \return A negative error code on errors, the return value of the underlying
93  * call to readv() otherwise.
94  *
95  * \sa readv(2).
96  */
97 int para_readv(int fd, struct iovec *iov, int iovcnt)
98 {
99         int ret = readv(fd, iov, iovcnt);
100
101         if (ret < 0)
102                 return -ERRNO_TO_PARA_ERROR(errno);
103         return ret;
104 }
105
106 /**
107  * Check whether a file exists.
108  *
109  * \param fn The file name.
110  *
111  * \return Non-zero iff file exists.
112  */
113 int file_exists(const char *fn)
114 {
115         struct stat statbuf;
116
117         return !stat(fn, &statbuf);
118 }
119
120 /**
121  * Paraslash's wrapper for select(2).
122  *
123  * It calls select(2) (with no exceptfds) and starts over if select() was
124  * interrupted by a signal.
125  *
126  * \param n The highest-numbered descriptor in any of the two sets, plus 1.
127  * \param readfds fds that should be checked for readability.
128  * \param writefds fds that should be checked for writablility.
129  * \param timeout_tv upper bound on the amount of time elapsed before select()
130  * returns.
131  *
132  * \return The return value of the underlying select() call on success, the
133  * negative system error code on errors.
134  *
135  * All arguments are passed verbatim to select(2).
136  * \sa select(2) select_tut(2).
137  */
138 int para_select(int n, fd_set *readfds, fd_set *writefds,
139                 struct timeval *timeout_tv)
140 {
141         int ret;
142         do
143                 ret = select(n, readfds, writefds, NULL, timeout_tv);
144         while (ret < 0 && errno == EINTR);
145         if (ret < 0)
146                 return -ERRNO_TO_PARA_ERROR(errno);
147         return ret;
148 }
149
150 /**
151  * Set a file descriptor to blocking mode.
152  *
153  * \param fd The file descriptor.
154  *
155  * \return Standard.
156  */
157 __must_check int mark_fd_blocking(int fd)
158 {
159         int flags = fcntl(fd, F_GETFL);
160         if (flags < 0)
161                 return -ERRNO_TO_PARA_ERROR(errno);
162         flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
163         if (flags < 0)
164                 return -ERRNO_TO_PARA_ERROR(errno);
165         return 1;
166 }
167
168 /**
169  * Set a file descriptor to non-blocking mode.
170  *
171  * \param fd The file descriptor.
172  *
173  * \return Standard.
174  */
175 __must_check int mark_fd_nonblocking(int fd)
176 {
177         int flags = fcntl(fd, F_GETFL);
178         if (flags < 0)
179                 return -ERRNO_TO_PARA_ERROR(errno);
180         flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
181         if (flags < 0)
182                 return -ERRNO_TO_PARA_ERROR(errno);
183         return 1;
184 }
185
186 /**
187  * Set a file descriptor in a fd_set.
188  *
189  * \param fd The file descriptor to be set.
190  * \param fds The file descriptor set.
191  * \param max_fileno Highest-numbered file descriptor.
192  *
193  * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
194  * return, \a max_fileno contains the maximum of the old_value and \a fd.
195  *
196  * \sa para_select.
197 */
198 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
199 {
200         assert(fd >= 0 && fd < FD_SETSIZE);
201 #if 0
202         {
203                 int flags = fcntl(fd, F_GETFL);
204                 if (!(flags & O_NONBLOCK)) {
205                         PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
206                         exit(EXIT_FAILURE);
207                 }
208         }
209 #endif
210         FD_SET(fd, fds);
211         *max_fileno = PARA_MAX(*max_fileno, fd);
212 }
213
214 /**
215  * Paraslash's wrapper for fgets(3).
216  *
217  * \param line Pointer to the buffer to store the line.
218  * \param size The size of the buffer given by \a line.
219  * \param f The stream to read from.
220  *
221  * \return Unlike the standard fgets() function, an integer value
222  * is returned. On success, this function returns 1. On errors, -E_FGETS
223  * is returned. A zero return value indicates an end of file condition.
224  */
225 __must_check int para_fgets(char *line, int size, FILE *f)
226 {
227 again:
228         if (fgets(line, size, f))
229                 return 1;
230         if (feof(f))
231                 return 0;
232         if (!ferror(f))
233                 return -E_FGETS;
234         if (errno != EINTR) {
235                 PARA_ERROR_LOG("%s\n", strerror(errno));
236                 return -E_FGETS;
237         }
238         clearerr(f);
239         goto again;
240 }
241
242 /**
243  * Paraslash's wrapper for mmap.
244  *
245  * \param length Number of bytes to mmap.
246  * \param prot Either PROT_NONE or the bitwise OR of one or more of
247  * PROT_EXEC PROT_READ PROT_WRITE.
248  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
249  * \param fd The file to mmap from.
250  * \param offset Mmap start.
251  * \param map Result pointer.
252  *
253  * \return Standard.
254  *
255  * \sa mmap(2).
256  */
257 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
258                 void *map)
259 {
260         void **m = map;
261
262         errno = EINVAL;
263         if (!length)
264                 goto err;
265         *m = mmap(NULL, length, prot, flags, fd, offset);
266         if (*m != MAP_FAILED)
267                 return 1;
268 err:
269         *m = NULL;
270         return -ERRNO_TO_PARA_ERROR(errno);
271 }
272
273 /**
274  * Wrapper for the open(2) system call.
275  *
276  * \param path The filename.
277  * \param flags The usual open(2) flags.
278  * \param mode Specifies the permissions to use.
279  *
280  * The mode parameter must be specified when O_CREAT is in the flags, and is
281  * ignored otherwise.
282  *
283  * \return The file descriptor on success, negative on errors.
284  *
285  * \sa open(2).
286  */
287 int para_open(const char *path, int flags, mode_t mode)
288 {
289         int ret = open(path, flags, mode);
290
291         if (ret >= 0)
292                 return ret;
293         return -ERRNO_TO_PARA_ERROR(errno);
294 }
295
296 /**
297  * Wrapper for chdir(2).
298  *
299  * \param path The specified directory.
300  *
301  * \return Standard.
302  */
303 int para_chdir(const char *path)
304 {
305         int ret = chdir(path);
306
307         if (ret >= 0)
308                 return 1;
309         return -ERRNO_TO_PARA_ERROR(errno);
310 }
311
312 /**
313  * Save the cwd and open a given directory.
314  *
315  * \param dirname Path to the directory to open.
316  * \param dir Result pointer.
317  * \param cwd File descriptor of the current working directory.
318  *
319  * \return Standard.
320  *
321  * Opening the current directory (".") and calling fchdir() to return is
322  * usually faster and more reliable than saving cwd in some buffer and calling
323  * chdir() afterwards.
324  *
325  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
326  * stored in \a cwd. If the function returns success, and \a cwd is not \p
327  * NULL, the caller must close this file descriptor (probably after calling
328  * fchdir(*cwd)).
329  *
330  * On errors, the function undos everything, so the caller needs neither close
331  * any files, nor change back to the original working directory.
332  *
333  * \sa getcwd(3).
334  *
335  */
336 int para_opendir(const char *dirname, DIR **dir, int *cwd)
337 {
338         int ret;
339
340         if (cwd) {
341                 ret = para_open(".", O_RDONLY, 0);
342                 if (ret < 0)
343                         return ret;
344                 *cwd = ret;
345         }
346         ret = para_chdir(dirname);
347         if (ret < 0)
348                 goto close_cwd;
349         *dir = opendir(".");
350         if (*dir)
351                 return 1;
352         ret = -ERRNO_TO_PARA_ERROR(errno);
353         /* Ignore return value of fchdir() and close(). We're busted anyway. */
354         if (cwd) {
355                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
356         }
357 close_cwd:
358         if (cwd)
359                 close(*cwd);
360         return ret;
361 }
362
363 /**
364  * A wrapper for fchdir().
365  *
366  * \param fd An open file descriptor.
367  *
368  * \return Standard.
369  */
370 int para_fchdir(int fd)
371 {
372         if (fchdir(fd) < 0)
373                 return -ERRNO_TO_PARA_ERROR(errno);
374         return 1;
375 }
376
377 /**
378  * A wrapper for mkdir(2).
379  *
380  * \param path Name of the directory to create.
381  * \param mode The permissions to use.
382  *
383  * \return Standard.
384  */
385 int para_mkdir(const char *path, mode_t mode)
386 {
387         if (!mkdir(path, mode))
388                 return 1;
389         return -ERRNO_TO_PARA_ERROR(errno);
390 }
391
392 /**
393  * Open a file and map it into memory.
394  *
395  * \param path Name of the regular file to map.
396  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
397  * \param map On success, the mapping is returned here.
398  * \param size size of the mapping.
399  * \param fd_ptr The file descriptor of the mapping.
400  *
401  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
402  * open call is closed after mmap().  Otherwise the file is kept open and the
403  * file descriptor is returned in \a fd_ptr.
404  *
405  * \return Standard.
406  *
407  * \sa para_open(), mmap(2).
408  */
409 int mmap_full_file(const char *path, int open_mode, void **map,
410                 size_t *size, int *fd_ptr)
411 {
412         int fd, ret, mmap_prot, mmap_flags;
413         struct stat file_status;
414
415         if (open_mode == O_RDONLY) {
416                 mmap_prot = PROT_READ;
417                 mmap_flags = MAP_PRIVATE;
418         } else {
419                 mmap_prot = PROT_READ | PROT_WRITE;
420                 mmap_flags = MAP_SHARED;
421         }
422         ret = para_open(path, open_mode, 0);
423         if (ret < 0)
424                 return ret;
425         fd = ret;
426         if (fstat(fd, &file_status) < 0) {
427                 ret = -ERRNO_TO_PARA_ERROR(errno);
428                 goto out;
429         }
430         *size = file_status.st_size;
431         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
432 out:
433         if (ret < 0 || !fd_ptr)
434                 close(fd);
435         else
436                 *fd_ptr = fd;
437         return ret;
438 }
439
440 /**
441  * A wrapper for munmap(2).
442  *
443  * \param start The start address of the memory mapping.
444  * \param length The size of the mapping.
445  *
446  * \return Standard.
447  *
448  * \sa munmap(2), mmap_full_file().
449  */
450 int para_munmap(void *start, size_t length)
451 {
452         int err;
453         if (munmap(start, length) >= 0)
454                 return 1;
455         err = errno;
456         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
457                 strerror(err));
458         return -ERRNO_TO_PARA_ERROR(err);
459 }
460
461 /**
462  * Check a file descriptor for writability.
463  *
464  * \param fd The file descriptor.
465  *
466  * \return positive if fd is ready for writing, zero if it isn't, negative if
467  * an error occurred.
468  */
469
470 int write_ok(int fd)
471 {
472         struct timeval tv;
473         fd_set wfds;
474
475         FD_ZERO(&wfds);
476         FD_SET(fd, &wfds);
477         tv.tv_sec = 0;
478         tv.tv_usec = 0;
479         return para_select(fd + 1, NULL, &wfds, &tv);
480 }
481
482 /**
483  * Ensure that file descriptors 0, 1, and 2 are valid.
484  *
485  * Common approach that opens /dev/null until it gets a file descriptor greater
486  * than two.
487  *
488  * \sa okir's Black Hats Manual.
489  */
490 void valid_fd_012(void)
491 {
492         while (1) {
493                 int fd = open("/dev/null", O_RDWR);
494                 if (fd < 0)
495                         exit(EXIT_FAILURE);
496                 if (fd > 2) {
497                         close(fd);
498                         break;
499                 }
500         }
501 }
502
503 /**
504  * Traverse the given directory recursively.
505  *
506  * \param dirname The directory to traverse.
507  * \param func The function to call for each entry.
508  * \param private_data Pointer to an arbitrary data structure.
509  *
510  * For each regular file under \a dirname, the supplied function \a func is
511  * called.  The full path of the regular file and the \a private_data pointer
512  * are passed to \a func. Directories for which the calling process has no
513  * permissions to change to are silently ignored.
514  *
515  * \return Standard.
516  */
517 int for_each_file_in_dir(const char *dirname,
518                 int (*func)(const char *, void *), void *private_data)
519 {
520         DIR *dir;
521         struct dirent *entry;
522         int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
523
524         if (ret < 0)
525                 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
526         /* scan cwd recursively */
527         while ((entry = readdir(dir))) {
528                 mode_t m;
529                 char *tmp;
530                 struct stat s;
531
532                 if (!strcmp(entry->d_name, "."))
533                         continue;
534                 if (!strcmp(entry->d_name, ".."))
535                         continue;
536                 if (lstat(entry->d_name, &s) == -1)
537                         continue;
538                 m = s.st_mode;
539                 if (!S_ISREG(m) && !S_ISDIR(m))
540                         continue;
541                 tmp = make_message("%s/%s", dirname, entry->d_name);
542                 if (!S_ISDIR(m)) {
543                         ret = func(tmp, private_data);
544                         free(tmp);
545                         if (ret < 0)
546                                 goto out;
547                         continue;
548                 }
549                 /* directory */
550                 ret = for_each_file_in_dir(tmp, func, private_data);
551                 free(tmp);
552                 if (ret < 0)
553                         goto out;
554         }
555         ret = 1;
556 out:
557         closedir(dir);
558         ret2 = para_fchdir(cwd_fd);
559         if (ret2 < 0 && ret >= 0)
560                 ret = ret2;
561         close(cwd_fd);
562         return ret;
563 }