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