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);
121 } while (ret < 0 && err == EINTR);
123 return -ERRNO_TO_PARA_ERROR(errno);
128 * Set a file descriptor to blocking mode.
130 * \param fd The file descriptor.
134 __must_check int mark_fd_blocking(int fd)
136 int flags = fcntl(fd, F_GETFL);
138 return -ERRNO_TO_PARA_ERROR(errno);
139 flags = fcntl(fd, F_SETFL, ((long)flags) & ~O_NONBLOCK);
141 return -ERRNO_TO_PARA_ERROR(errno);
146 * Set a file descriptor to non-blocking mode.
148 * \param fd The file descriptor.
152 __must_check int mark_fd_nonblocking(int fd)
154 int flags = fcntl(fd, F_GETFL);
156 return -ERRNO_TO_PARA_ERROR(errno);
157 flags = fcntl(fd, F_SETFL, ((long)flags) | O_NONBLOCK);
159 return -ERRNO_TO_PARA_ERROR(errno);
164 * Set a file descriptor in a fd_set.
166 * \param fd The file descriptor to be set.
167 * \param fds The file descriptor set.
168 * \param max_fileno Highest-numbered file descriptor.
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.
175 void para_fd_set(int fd, fd_set *fds, int *max_fileno)
178 if (fd < 0 || fd >= FD_SETSIZE) {
179 PARA_EMERG_LOG("fatal: tried to add invalid fd %d\n", fd);
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);
192 *max_fileno = PARA_MAX(*max_fileno, fd);
196 * Paraslash's wrapper for fgets(3).
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.
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.
206 __must_check int para_fgets(char *line, int size, FILE *f)
209 if (fgets(line, size, f))
215 if (errno != EINTR) {
216 PARA_ERROR_LOG("%s\n", strerror(errno));
224 * Paraslash's wrapper for mmap.
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.
233 * \return This function either returns a valid pointer to the mapped area
234 * or calls exit() on errors.
236 void *para_mmap(size_t length, int prot, int flags, int fd, off_t offset)
238 void *ret = mmap(NULL, length, prot, flags, fd, offset);
239 if (ret != MAP_FAILED)
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);
248 * Wrapper for the open(2) system call.
250 * \param path The filename.
251 * \param flags The usual open(2) flags.
252 * \param mode Specifies the permissions to use.
254 * The mode parameter must be specified when O_CREAT is in the flags, and is
257 * \return The file descriptor on success, negative on errors.
261 int para_open(const char *path, int flags, mode_t mode)
263 int ret = open(path, flags, mode);
267 return -ERRNO_TO_PARA_ERROR(errno);
271 * Wrapper for chdir(2).
273 * \param path The specified directory.
277 int para_chdir(const char *path)
279 int ret = chdir(path);
283 return -ERRNO_TO_PARA_ERROR(errno);
287 * Save the cwd and open a given directory.
289 * \param dirname Path to the directory to open.
290 * \param dir Result pointer.
291 * \param cwd File descriptor of the current working directory.
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.
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
304 * On errors, the function undos everything, so the caller needs neither close
305 * any files, nor change back to the original working directory.
310 int para_opendir(const char *dirname, DIR **dir, int *cwd)
315 ret = para_open(".", O_RDONLY, 0);
320 ret = para_chdir(dirname);
326 ret = -ERRNO_TO_PARA_ERROR(errno);
327 /* Ignore return value of fchdir() and close(). We're busted anyway. */
329 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
338 * A wrapper for fchdir().
340 * \param fd An open file descriptor.
344 int para_fchdir(int fd)
347 return -ERRNO_TO_PARA_ERROR(errno);
352 * A wrapper for mkdir(2).
354 * \param path Name of the directory to create.
355 * \param mode The permissions to use.
359 int para_mkdir(const char *path, mode_t mode)
361 if (!mkdir(path, mode))
363 return -ERRNO_TO_PARA_ERROR(errno);
367 * Open a file and map it into memory.
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.
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.
381 * \sa para_open(), mmap(2).
383 int mmap_full_file(const char *path, int open_mode, void **map,
384 size_t *size, int *fd_ptr)
386 int fd, ret, mmap_prot, mmap_flags;
387 struct stat file_status;
389 if (open_mode == O_RDONLY) {
390 mmap_prot = PROT_READ;
391 mmap_flags = MAP_PRIVATE;
393 mmap_prot = PROT_READ | PROT_WRITE;
394 mmap_flags = MAP_SHARED;
396 ret = para_open(path, open_mode, 0);
400 if (fstat(fd, &file_status) < 0) {
401 ret = -ERRNO_TO_PARA_ERROR(errno);
404 *size = file_status.st_size;
406 PARA_DEBUG_LOG("%s: size %zu\n", path, *size);
409 *map = mmap(NULL, *size, mmap_prot, mmap_flags, fd, 0);
410 if (*map == MAP_FAILED) {
417 if (ret < 0 || !fd_ptr)
425 * A wrapper for munmap(2).
427 * \param start The start address of the memory mapping.
428 * \param length The size of the mapping.
430 * \return Positive on success, \p -E_MUNMAP on errors.
432 * \sa munmap(2), mmap_full_file().
434 int para_munmap(void *start, size_t length)
437 if (munmap(start, length) >= 0)
440 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
442 return -ERRNO_TO_PARA_ERROR(err);
446 * Check a file descriptor for writability.
448 * \param fd The file descriptor.
450 * \return positive if fd is ready for writing, zero if it isn't, negative if
456 struct timeval tv = {0, 0};
464 ret = select(fd + 1, NULL, &wfds, NULL, &tv);
465 if (ret < 0 && errno == EINTR)
471 * Ensure that file descriptors 0, 1, and 2 are valid.
473 * Common approach that opens /dev/null until it gets a file descriptor greater
476 * \sa okir's Black Hats Manual.
478 void valid_fd_012(void)
481 int fd = open("/dev/null", O_RDWR);