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