2 * Copyright (C) 2006-2009 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file fd.c Helper functions for file descriptor handling. */
13 #include <sys/select.h>
19 * Write a buffer to a file descriptor, re-write on short writes.
21 * \param fd The file descriptor.
22 * \param buf The buffer to be sent.
23 * \param len The length of \a buf.
25 * \return Standard. In any case, the number of bytes that have been written is
28 int write_all(int fd, const char *buf, size_t *len)
34 while (*len < total) {
35 int ret = write(fd, buf + *len, total - *len);
37 return -ERRNO_TO_PARA_ERROR(errno);
44 * Write a buffer to a non-blocking file descriptor.
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.
51 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
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.
59 * \return Negative on errors, number of bytes written else.
61 int write_nonblock(int fd, const char *buf, size_t len,
62 size_t max_bytes_per_write)
67 while (written < len) {
68 size_t num = len - written;
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)
76 return -ERRNO_TO_PARA_ERROR(errno);
83 * Check whether a file exists.
85 * \param fn The file name.
87 * \return Non-zero iff file exists.
89 int file_exists(const char *fn)
93 return !stat(fn, &statbuf);
97 * Paraslash's wrapper for select(2).
99 * It calls select(2) (with no exceptfds) and starts over if select() was
100 * interrupted by a signal.
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()
108 * \return The return value of the underlying select() call on success, the
109 * negative system error code on errors.
111 * All arguments are passed verbatim to select(2).
112 * \sa select(2) select_tut(2).
114 int para_select(int n, fd_set *readfds, fd_set *writefds,
115 struct timeval *timeout_tv)
119 ret = select(n, readfds, writefds, NULL, timeout_tv);
120 while (ret < 0 && errno == EINTR);
122 return -ERRNO_TO_PARA_ERROR(errno);
127 * Set a file descriptor to blocking mode.
129 * \param fd The file descriptor.
133 __must_check int mark_fd_blocking(int fd)
135 int flags = fcntl(fd, F_GETFL);
137 return -ERRNO_TO_PARA_ERROR(errno);
138 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
140 return -ERRNO_TO_PARA_ERROR(errno);
145 * Set a file descriptor to non-blocking mode.
147 * \param fd The file descriptor.
151 __must_check int mark_fd_nonblocking(int fd)
153 int flags = fcntl(fd, F_GETFL);
155 return -ERRNO_TO_PARA_ERROR(errno);
156 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
158 return -ERRNO_TO_PARA_ERROR(errno);
163 * Set a file descriptor in a fd_set.
165 * \param fd The file descriptor to be set.
166 * \param fds The file descriptor set.
167 * \param max_fileno Highest-numbered file descriptor.
169 * This wrapper for FD_SET() passes its first two arguments to \p FD_SET. Upon
170 * return, \a max_fileno contains the maximum of the old_value and \a fd.
174 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
176 assert(fd >= 0 && fd < FD_SETSIZE);
179 int flags = fcntl(fd, F_GETFL);
180 if (!(flags & O_NONBLOCK)) {
181 PARA_EMERG_LOG("fd %d is a blocking file descriptor\n", fd);
187 *max_fileno = PARA_MAX(*max_fileno, fd);
191 * Paraslash's wrapper for fgets(3).
193 * \param line Pointer to the buffer to store the line.
194 * \param size The size of the buffer given by \a line.
195 * \param f The stream to read from.
197 * \return Unlike the standard fgets() function, an integer value
198 * is returned. On success, this function returns 1. On errors, -E_FGETS
199 * is returned. A zero return value indicates an end of file condition.
201 __must_check int para_fgets(char *line, int size, FILE *f)
204 if (fgets(line, size, f))
210 if (errno != EINTR) {
211 PARA_ERROR_LOG("%s\n", strerror(errno));
219 * Paraslash's wrapper for mmap.
221 * \param length Number of bytes to mmap.
222 * \param prot Either PROT_NONE or the bitwise OR of one or more of
223 * PROT_EXEC PROT_READ PROT_WRITE.
224 * \param flags Exactly one of MAP_SHARED and MAP_PRIVATE.
225 * \param fd The file to mmap from.
226 * \param offset Mmap start.
227 * \param map Result pointer.
233 int para_mmap(size_t length, int prot, int flags, int fd, off_t offset,
241 *m = mmap(NULL, length, prot, flags, fd, offset);
242 if (*m != MAP_FAILED)
246 return -ERRNO_TO_PARA_ERROR(errno);
250 * Wrapper for the open(2) system call.
252 * \param path The filename.
253 * \param flags The usual open(2) flags.
254 * \param mode Specifies the permissions to use.
256 * The mode parameter must be specified when O_CREAT is in the flags, and is
259 * \return The file descriptor on success, negative on errors.
263 int para_open(const char *path, int flags, mode_t mode)
265 int ret = open(path, flags, mode);
269 return -ERRNO_TO_PARA_ERROR(errno);
273 * Wrapper for chdir(2).
275 * \param path The specified directory.
279 int para_chdir(const char *path)
281 int ret = chdir(path);
285 return -ERRNO_TO_PARA_ERROR(errno);
289 * Save the cwd and open a given directory.
291 * \param dirname Path to the directory to open.
292 * \param dir Result pointer.
293 * \param cwd File descriptor of the current working directory.
297 * Opening the current directory (".") and calling fchdir() to return is
298 * usually faster and more reliable than saving cwd in some buffer and calling
299 * chdir() afterwards.
301 * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
302 * stored in \a cwd. If the function returns success, and \a cwd is not \p
303 * NULL, the caller must close this file descriptor (probably after calling
306 * On errors, the function undos everything, so the caller needs neither close
307 * any files, nor change back to the original working directory.
312 int para_opendir(const char *dirname, DIR **dir, int *cwd)
317 ret = para_open(".", O_RDONLY, 0);
322 ret = para_chdir(dirname);
328 ret = -ERRNO_TO_PARA_ERROR(errno);
329 /* Ignore return value of fchdir() and close(). We're busted anyway. */
331 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
340 * A wrapper for fchdir().
342 * \param fd An open file descriptor.
346 int para_fchdir(int fd)
349 return -ERRNO_TO_PARA_ERROR(errno);
354 * A wrapper for mkdir(2).
356 * \param path Name of the directory to create.
357 * \param mode The permissions to use.
361 int para_mkdir(const char *path, mode_t mode)
363 if (!mkdir(path, mode))
365 return -ERRNO_TO_PARA_ERROR(errno);
369 * Open a file and map it into memory.
371 * \param path Name of the regular file to map.
372 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
373 * \param map On success, the mapping is returned here.
374 * \param size size of the mapping.
375 * \param fd_ptr The file descriptor of the mapping.
377 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
378 * open call is closed after mmap(). Otherwise the file is kept open and the
379 * file descriptor is returned in \a fd_ptr.
383 * \sa para_open(), mmap(2).
385 int mmap_full_file(const char *path, int open_mode, void **map,
386 size_t *size, int *fd_ptr)
388 int fd, ret, mmap_prot, mmap_flags;
389 struct stat file_status;
391 if (open_mode == O_RDONLY) {
392 mmap_prot = PROT_READ;
393 mmap_flags = MAP_PRIVATE;
395 mmap_prot = PROT_READ | PROT_WRITE;
396 mmap_flags = MAP_SHARED;
398 ret = para_open(path, open_mode, 0);
402 if (fstat(fd, &file_status) < 0) {
403 ret = -ERRNO_TO_PARA_ERROR(errno);
406 *size = file_status.st_size;
407 ret = para_mmap(*size, mmap_prot, mmap_flags, fd, 0, map);
409 if (ret < 0 || !fd_ptr)
417 * A wrapper for munmap(2).
419 * \param start The start address of the memory mapping.
420 * \param length The size of the mapping.
422 * \return Positive on success, \p -E_MUNMAP on errors.
424 * \sa munmap(2), mmap_full_file().
426 int para_munmap(void *start, size_t length)
429 if (munmap(start, length) >= 0)
432 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
434 return -ERRNO_TO_PARA_ERROR(err);
438 * Check a file descriptor for writability.
440 * \param fd The file descriptor.
442 * \return positive if fd is ready for writing, zero if it isn't, negative if
455 return para_select(fd + 1, NULL, &wfds, &tv);
459 * Ensure that file descriptors 0, 1, and 2 are valid.
461 * Common approach that opens /dev/null until it gets a file descriptor greater
464 * \sa okir's Black Hats Manual.
466 void valid_fd_012(void)
469 int fd = open("/dev/null", O_RDWR);
480 * Traverse the given directory recursively.
482 * \param dirname The directory to traverse.
483 * \param func The function to call for each entry.
484 * \param private_data Pointer to an arbitrary data structure.
486 * For each regular file under \a dirname, the supplied function \a func is
487 * called. The full path of the regular file and the \a private_data pointer
488 * are passed to \a func. Directories for which the calling process has no
489 * permissions to change to are silently ignored.
493 int for_each_file_in_dir(const char *dirname,
494 int (*func)(const char *, void *), void *private_data)
497 struct dirent *entry;
498 int cwd_fd, ret2, ret = para_opendir(dirname, &dir, &cwd_fd);
501 return ret == -ERRNO_TO_PARA_ERROR(EACCES)? 1 : ret;
502 /* scan cwd recursively */
503 while ((entry = readdir(dir))) {
508 if (!strcmp(entry->d_name, "."))
510 if (!strcmp(entry->d_name, ".."))
512 if (lstat(entry->d_name, &s) == -1)
515 if (!S_ISREG(m) && !S_ISDIR(m))
517 tmp = make_message("%s/%s", dirname, entry->d_name);
519 ret = func(tmp, private_data);
526 ret = for_each_file_in_dir(tmp, func, private_data);
534 ret2 = para_fchdir(cwd_fd);
535 if (ret2 < 0 && ret >= 0)