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