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