Merge commit 'meins/master'
[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  * \param map Result pointer.
229  *
230  * \return Standard.
231  *
232  * \sa mmap(2).
233  */
234 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
235                 void *map)
236 {
237         void **m = map;
238
239         errno = EINVAL;
240         if (!length)
241                 goto err;
242         *m = mmap(NULL, length, prot, flags, fd, offset);
243         if (*m != MAP_FAILED)
244                 return 1;
245 err:
246         *m = NULL;
247         return -ERRNO_TO_PARA_ERROR(errno);
248 }
249
250 /**
251  * Wrapper for the open(2) system call.
252  *
253  * \param path The filename.
254  * \param flags The usual open(2) flags.
255  * \param mode Specifies the permissions to use.
256  *
257  * The mode parameter must be specified when O_CREAT is in the flags, and is
258  * ignored otherwise.
259  *
260  * \return The file descriptor on success, negative on errors.
261  *
262  * \sa open(2).
263  */
264 int para_open(const char *path, int flags, mode_t mode)
265 {
266         int ret = open(path, flags, mode);
267
268         if (ret >= 0)
269                 return ret;
270         return -ERRNO_TO_PARA_ERROR(errno);
271 }
272
273 /**
274  * Wrapper for chdir(2).
275  *
276  * \param path The specified directory.
277  *
278  * \return Standard.
279  */
280 int para_chdir(const char *path)
281 {
282         int ret = chdir(path);
283
284         if (ret >= 0)
285                 return 1;
286         return -ERRNO_TO_PARA_ERROR(errno);
287 }
288
289 /**
290  * Save the cwd and open a given directory.
291  *
292  * \param dirname Path to the directory to open.
293  * \param dir Result pointer.
294  * \param cwd File descriptor of the current working directory.
295  *
296  * \return Standard.
297  *
298  * Opening the current directory (".") and calling fchdir() to return is
299  * usually faster and more reliable than saving cwd in some buffer and calling
300  * chdir() afterwards.
301  *
302  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
303  * stored in \a cwd. If the function returns success, and \a cwd is not \p
304  * NULL, the caller must close this file descriptor (probably after calling
305  * fchdir(*cwd)).
306  *
307  * On errors, the function undos everything, so the caller needs neither close
308  * any files, nor change back to the original working directory.
309  *
310  * \sa getcwd(3).
311  *
312  */
313 int para_opendir(const char *dirname, DIR **dir, int *cwd)
314 {
315         int ret;
316
317         if (cwd) {
318                 ret = para_open(".", O_RDONLY, 0);
319                 if (ret < 0)
320                         return ret;
321                 *cwd = ret;
322         }
323         ret = para_chdir(dirname);
324         if (ret < 0)
325                 goto close_cwd;
326         *dir = opendir(".");
327         if (*dir)
328                 return 1;
329         ret = -ERRNO_TO_PARA_ERROR(errno);
330         /* Ignore return value of fchdir() and close(). We're busted anyway. */
331         if (cwd) {
332                 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
333         }
334 close_cwd:
335         if (cwd)
336                 close(*cwd);
337         return ret;
338 }
339
340 /**
341  * A wrapper for fchdir().
342  *
343  * \param fd An open file descriptor.
344  *
345  * \return Standard.
346  */
347 int para_fchdir(int fd)
348 {
349         if (fchdir(fd) < 0)
350                 return -ERRNO_TO_PARA_ERROR(errno);
351         return 1;
352 }
353
354 /**
355  * A wrapper for mkdir(2).
356  *
357  * \param path Name of the directory to create.
358  * \param mode The permissions to use.
359  *
360  * \return Standard.
361  */
362 int para_mkdir(const char *path, mode_t mode)
363 {
364         if (!mkdir(path, mode))
365                 return 1;
366         return -ERRNO_TO_PARA_ERROR(errno);
367 }
368
369 /**
370  * Open a file and map it into memory.
371  *
372  * \param path Name of the regular file to map.
373  * \param open_mode Either \p O_RDONLY or \p O_RDWR.
374  * \param map On success, the mapping is returned here.
375  * \param size size of the mapping.
376  * \param fd_ptr The file descriptor of the mapping.
377  *
378  * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
379  * open call is closed after mmap().  Otherwise the file is kept open and the
380  * file descriptor is returned in \a fd_ptr.
381  *
382  * \return Standard.
383  *
384  * \sa para_open(), mmap(2).
385  */
386 int mmap_full_file(const char *path, int open_mode, void **map,
387                 size_t *size, int *fd_ptr)
388 {
389         int fd, ret, mmap_prot, mmap_flags;
390         struct stat file_status;
391
392         if (open_mode == O_RDONLY) {
393                 mmap_prot = PROT_READ;
394                 mmap_flags = MAP_PRIVATE;
395         } else {
396                 mmap_prot = PROT_READ | PROT_WRITE;
397                 mmap_flags = MAP_SHARED;
398         }
399         ret = para_open(path, open_mode, 0);
400         if (ret < 0)
401                 return ret;
402         fd = ret;
403         if (fstat(fd, &file_status) < 0) {
404                 ret = -ERRNO_TO_PARA_ERROR(errno);
405                 goto out;
406         }
407         *size = file_status.st_size;
408         ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
409 out:
410         if (ret < 0 || !fd_ptr)
411                 close(fd);
412         else
413                 *fd_ptr = fd;
414         return ret;
415 }
416
417 /**
418  * A wrapper for munmap(2).
419  *
420  * \param start The start address of the memory mapping.
421  * \param length The size of the mapping.
422  *
423  * \return Positive on success, \p -E_MUNMAP on errors.
424  *
425  * \sa munmap(2), mmap_full_file().
426  */
427 int para_munmap(void *start, size_t length)
428 {
429         int err;
430         if (munmap(start, length) >= 0)
431                 return 1;
432         err = errno;
433         PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
434                 strerror(err));
435         return -ERRNO_TO_PARA_ERROR(err);
436 }
437
438 /**
439  * Check a file descriptor for writability.
440  *
441  * \param fd The file descriptor.
442  *
443  * \return positive if fd is ready for writing, zero if it isn't, negative if
444  * an error occurred.
445  */
446
447 int write_ok(int fd)
448 {
449         struct timeval tv = {0, 0};
450         fd_set wfds;
451         int ret;
452 again:
453         FD_ZERO(&wfds);
454         FD_SET(fd, &wfds);
455         tv.tv_sec = 0;
456         tv.tv_usec = 0;
457         ret = select(fd + 1, NULL, &wfds, NULL, &tv);
458         if (ret < 0 && errno == EINTR)
459                 goto again;
460         return ret;
461 }
462
463 /**
464  * Ensure that file descriptors 0, 1, and 2 are valid.
465  *
466  * Common approach that opens /dev/null until it gets a file descriptor greater
467  * than two.
468  *
469  * \sa okir's Black Hats Manual.
470  */
471 void valid_fd_012(void)
472 {
473         while (1) {
474                 int fd = open("/dev/null", O_RDWR);
475                 if (fd < 0)
476                         exit(EXIT_FAILURE);
477                 if (fd > 2) {
478                         close(fd);
479                         break;
480                 }
481         }
482 }