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