]> git.tuebingen.mpg.de Git - paraslash.git/blob - fd.c
6d32e93eeca6d205725390ea59b8e97fdd09b376
[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
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, err;
118         do {
119                 ret = select(n, readfds, writefds, NULL, timeout_tv);
120                 err = errno;
121         } while (ret < 0 && err == EINTR);
122         if (ret < 0)
123                 return -ERRNO_TO_PARA_ERROR(errno);
124         return ret;
125 }
126
127 /**
128  * Set a file descriptor to blocking mode.
129  *
130  * \param fd The file descriptor.
131  *
132  * \return Standard.
133  */
134 __must_check int mark_fd_blocking(int fd)
135 {
136         int flags = fcntl(fd, F_GETFL);
137         if (flags < 0)
138                 return -ERRNO_TO_PARA_ERROR(errno);
139         flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
140         if (flags < 0)
141                 return -ERRNO_TO_PARA_ERROR(errno);
142         return 1;
143 }
144
145 /**
146  * Set a file descriptor to non-blocking mode.
147  *
148  * \param fd The file descriptor.
149  *
150  * \return Standard.
151  */
152 __must_check int mark_fd_nonblocking(int fd)
153 {
154         int flags = fcntl(fd, F_GETFL);
155         if (flags < 0)
156                 return -ERRNO_TO_PARA_ERROR(errno);
157         flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
158         if (flags < 0)
159                 return -ERRNO_TO_PARA_ERROR(errno);
160         return 1;
161 }
162
163 /**
164  * Set a file descriptor in a fd_set.
165  *
166  * \param fd The file descriptor to be set.
167  * \param fds The file descriptor set.
168  * \param max_fileno Highest-numbered file descriptor.
169  *
170  * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
171  * return, \a max_fileno contains the maximum of the old_value and \a fd.
172  *
173  * \sa para_select.
174 */
175 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
176 {
177         assert(fd >= 0 && fd < FD_SETSIZE);
178 #if 0
179         {
180                 int flags = fcntl(fd, F_GETFL);
181                 if (!(flags & O_NONBLOCK)) {
182                         PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
183                         exit(EXIT_FAILURE);
184                 }
185         }
186 #endif
187         FD_SET(fd, fds);
188         *max_fileno = PARA_MAX(*max_fileno, fd);
189 }
190
191 /**
192  * Paraslash's wrapper for fgets(3).
193  *
194  * \param line Pointer to the buffer to store the line.
195  * \param size The size of the buffer given by \a line.
196  * \param f The stream to read from.
197  *
198  * \return Unlike the standard fgets() function, an integer value
199  * is returned. On success, this function returns 1. On errors, -E_FGETS
200  * is returned. A zero return value indicates an end of file condition.
201  */
202 __must_check int para_fgets(char *line, int size, FILE *f)
203 {
204 again:
205         if (fgets(line, size, f))
206                 return 1;
207         if (feof(f))
208                 return 0;
209         if (!ferror(f))
210                 return -E_FGETS;
211         if (errno != EINTR) {
212                 PARA_ERROR_LOG("%s\n", strerror(errno));
213                 return -E_FGETS;
214         }
215         clearerr(f);
216         goto again;
217 }
218
219 /**
220  * Paraslash's wrapper for mmap.
221  *
222  * \param length Number of bytes to mmap.
223  * \param prot Either PROT_NONE or the bitwise OR of one or more of
224  * PROT_EXEC PROT_READ PROT_WRITE.
225  * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
226  * \param fd The file to mmap from.
227  * \param offset Mmap start.
228  *
229  * \return This function either returns a valid pointer to the mapped area
230  * or calls exit() on errors.
231  */
232 void *para_mmap(size_t length, int prot, int flags, int fd, off_t offset)
233 {
234         void *ret = mmap(NULL, length, prot, flags, fd, offset);
235         if (ret != MAP_FAILED)
236                 return ret;
237         PARA_EMERG_LOG("mmap failed: %s\n", strerror(errno));
238         PARA_EMERG_LOG("length: %zu, flags: %d, fd: %d, offset: %zu\n",
239                 length, flags, fd, (size_t)offset);
240         exit(EXIT_FAILURE);
241 }
242
243 /**
244  * Wrapper for the open(2) system call.
245  *
246  * \param path The filename.
247  * \param flags The usual open(2) flags.
248  * \param mode Specifies the permissions to use.
249  *
250  * The mode parameter must be specified when O_CREAT is in the flags, and is
251  * ignored otherwise.
252  *
253  * \return The file descriptor on success, negative on errors.
254  *
255  * \sa open(2).
256  */
257 int para_open(const char *path, int flags, mode_t mode)
258 {
259         int ret = open(path, flags, mode);
260
261         if (ret >= 0)
262                 return ret;
263         return -ERRNO_TO_PARA_ERROR(errno);
264 }
265
266 /**
267  * Wrapper for chdir(2).
268  *
269  * \param path The specified directory.
270  *
271  * \return Standard.
272  */
273 int para_chdir(const char *path)
274 {
275         int ret = chdir(path);
276
277         if (ret >= 0)
278                 return 1;
279         return -ERRNO_TO_PARA_ERROR(errno);
280 }
281
282 /**
283  * Save the cwd and open a given directory.
284  *
285  * \param dirname Path to the directory to open.
286  * \param dir Result pointer.
287  * \param cwd File descriptor of the current working directory.
288  *
289  * \return Standard.
290  *
291  * Opening the current directory (".") and calling fchdir() to return is
292  * usually faster and more reliable than saving cwd in some buffer and calling
293  * chdir() afterwards.
294  *
295  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
296  * stored in \a cwd. If the function returns success, and \a cwd is not \p
297  * NULL, the caller must close this file descriptor (probably after calling
298  * fchdir(*cwd)).
299  *
300  * On errors, the function undos everything, so the caller needs neither close
301  * any files, nor change back to the original working directory.
302  *
303  * \sa getcwd(3).
304  *
305  */
306 int para_opendir(const char *dirname, DIR **dir, int *cwd)
307 {
308         int ret;
309
310         if (cwd) {
311                 ret = para_open(".", O_RDONLY, 0);
312                 if (ret < 0)
313                         return ret;
314                 *cwd = ret;
315         }
316         ret = para_chdir(dirname);
317         if (ret < 0)
318                 goto close_cwd;
319         *dir = opendir(".");
320         if (*dir)
321                 return 1;
322         ret = -ERRNO_TO_PARA_ERROR(errno);
323         /* Ignore return value of fchdir() and close(). We're busted anyway. */
324         if (cwd) {
325                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
326         }
327 close_cwd:
328         if (cwd)
329                 close(*cwd);
330         return ret;
331 }
332
333 /**
334  * A wrapper for fchdir().
335  *
336  * \param fd An open file descriptor.
337  *
338  * \return Standard.
339  */
340 int para_fchdir(int fd)
341 {
342         if (fchdir(fd) < 0)
343                 return -ERRNO_TO_PARA_ERROR(errno);
344         return 1;
345 }
346
347 /**
348  * A wrapper for mkdir(2).
349  *
350  * \param path Name of the directory to create.
351  * \param mode The permissions to use.
352  *
353  * \return Standard.
354  */
355 int para_mkdir(const char *path, mode_t mode)
356 {
357         if (!mkdir(path, mode))
358                 return 1;
359         return -ERRNO_TO_PARA_ERROR(errno);
360 }
361
362 /**
363  * Open a file and map it into memory.
364  *
365  * \param path Name of the regular file to map.
366  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
367  * \param map On success, the mapping is returned here.
368  * \param size size of the mapping.
369  * \param fd_ptr The file descriptor of the mapping.
370  *
371  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
372  * open call is closed after mmap().  Otherwise the file is kept open and the
373  * file descriptor is returned in \a fd_ptr.
374  *
375  * \return Standard.
376  *
377  * \sa para_open(), mmap(2).
378  */
379 int mmap_full_file(const char *path, int open_mode, void **map,
380                 size_t *size, int *fd_ptr)
381 {
382         int fd, ret, mmap_prot, mmap_flags;
383         struct stat file_status;
384
385         if (open_mode == O_RDONLY) {
386                 mmap_prot = PROT_READ;
387                 mmap_flags = MAP_PRIVATE;
388         } else {
389                 mmap_prot = PROT_READ | PROT_WRITE;
390                 mmap_flags = MAP_SHARED;
391         }
392         ret = para_open(path, open_mode, 0);
393         if (ret < 0)
394                 return ret;
395         fd = ret;
396         if (fstat(fd, &file_status) < 0) {
397                 ret = -ERRNO_TO_PARA_ERROR(errno);
398                 goto out;
399         }
400         *size = file_status.st_size;
401         ret = -E_EMPTY;
402         PARA_DEBUG_LOG("%s: size %zu\n", path, *size);
403         if (!*size)
404                 goto out;
405         *map = mmap(NULL, *size, mmap_prot, mmap_flags, fd, 0);
406         if (*map == MAP_FAILED) {
407                 *map = NULL;
408                 ret = -E_MMAP;
409                 goto out;
410         }
411         ret = 1;
412 out:
413         if (ret < 0 || !fd_ptr)
414                 close(fd);
415         else
416                 *fd_ptr = fd;
417         return ret;
418 }
419
420 /**
421  * A wrapper for munmap(2).
422  *
423  * \param start The start address of the memory mapping.
424  * \param length The size of the mapping.
425  *
426  * \return Positive on success, \p -E_MUNMAP on errors.
427  *
428  * \sa munmap(2), mmap_full_file().
429  */
430 int para_munmap(void *start, size_t length)
431 {
432         int err;
433         if (munmap(start, length) >= 0)
434                 return 1;
435         err = errno;
436         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
437                 strerror(err));
438         return -ERRNO_TO_PARA_ERROR(err);
439 }
440
441 /**
442  * Check a file descriptor for writability.
443  *
444  * \param fd The file descriptor.
445  *
446  * \return positive if fd is ready for writing, zero if it isn't, negative if
447  * an error occurred.
448  */
449
450 int write_ok(int fd)
451 {
452         struct timeval tv = {0, 0};
453         fd_set wfds;
454         int ret;
455 again:
456         FD_ZERO(&wfds);
457         FD_SET(fd, &wfds);
458         tv.tv_sec = 0;
459         tv.tv_usec = 0;
460         ret = select(fd + 1, NULL, &wfds, NULL, &tv);
461         if (ret < 0 && errno == EINTR)
462                 goto again;
463         return ret;
464 }
465
466 /**
467  * Ensure that file descriptors 0, 1, and 2 are valid.
468  *
469  * Common approach that opens /dev/null until it gets a file descriptor greater
470  * than two.
471  *
472  * \sa okir's Black Hats Manual.
473  */
474 void valid_fd_012(void)
475 {
476         while (1) {
477                 int fd = open("/dev/null", O_RDWR);
478                 if (fd < 0)
479                         exit(EXIT_FAILURE);
480                 if (fd > 2) {
481                         close(fd);
482                         break;
483                 }
484         }
485 }