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. */
10 #include <sys/types.h>
14 #include <sys/select.h>
21 * Write a buffer to a file descriptor, re-write on short writes.
23 * \param fd The file descriptor.
24 * \param buf The buffer to be sent.
25 * \param len The length of \a buf.
27 * \return Standard. In any case, the number of bytes that have been written is
30 int write_all(int fd
, const char *buf
, size_t *len
)
36 while (*len
< total
) {
37 int ret
= write(fd
, buf
+ *len
, total
- *len
);
39 return -ERRNO_TO_PARA_ERROR(errno
);
46 * Write a buffer to a non-blocking file descriptor.
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.
53 * If \a max_bytes_per_write is non-zero, do not send more than that many bytes
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.
61 * \return Negative on errors, number of bytes written else.
63 int write_nonblock(int fd
, const char *buf
, size_t len
,
64 size_t max_bytes_per_write
)
69 while (written
< len
) {
70 size_t num
= len
- written
;
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
)
78 return -ERRNO_TO_PARA_ERROR(errno
);
85 * Check whether a file exists.
87 * \param fn The file name.
89 * \return Non-zero iff file exists.
91 int file_exists(const char *fn
)
95 return !stat(fn
, &statbuf
);
99 * Paraslash's wrapper for select(2).
101 * It calls select(2) (with no exceptfds) and starts over if select() was
102 * interrupted by a signal.
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()
110 * \return The return value of the underlying select() call on success, the
111 * negative system error code on errors.
113 * All arguments are passed verbatim to select(2).
114 * \sa select(2) select_tut(2).
116 int para_select(int n
, fd_set
*readfds
, fd_set
*writefds
,
117 struct timeval
*timeout_tv
)
121 ret
= select(n
, readfds
, writefds
, NULL
, timeout_tv
);
122 while (ret
< 0 && errno
== EINTR
);
124 return -ERRNO_TO_PARA_ERROR(errno
);
129 * Set a file descriptor to blocking mode.
131 * \param fd The file descriptor.
135 __must_check
int mark_fd_blocking(int fd
)
137 int flags
= fcntl(fd
, F_GETFL
);
139 return -ERRNO_TO_PARA_ERROR(errno
);
140 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) & ~O_NONBLOCK
);
142 return -ERRNO_TO_PARA_ERROR(errno
);
147 * Set a file descriptor to non-blocking mode.
149 * \param fd The file descriptor.
153 __must_check
int mark_fd_nonblocking(int fd
)
155 int flags
= fcntl(fd
, F_GETFL
);
157 return -ERRNO_TO_PARA_ERROR(errno
);
158 flags
= fcntl(fd
, F_SETFL
, ((long)flags
) | O_NONBLOCK
);
160 return -ERRNO_TO_PARA_ERROR(errno
);
165 * Set a file descriptor in a fd_set.
167 * \param fd The file descriptor to be set.
168 * \param fds The file descriptor set.
169 * \param max_fileno Highest-numbered file descriptor.
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.
176 void para_fd_set(int fd
, fd_set
*fds
, int *max_fileno
)
178 assert(fd
>= 0 && fd
< FD_SETSIZE
);
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
);
189 *max_fileno
= PARA_MAX(*max_fileno
, fd
);
193 * Paraslash's wrapper for fgets(3).
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.
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.
203 __must_check
int para_fgets(char *line
, int size
, FILE *f
)
206 if (fgets(line
, size
, f
))
212 if (errno
!= EINTR
) {
213 PARA_ERROR_LOG("%s\n", strerror(errno
));
221 * Paraslash's wrapper for mmap.
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.
235 int para_mmap(size_t length
, int prot
, int flags
, int fd
, off_t offset
,
243 *m
= mmap(NULL
, length
, prot
, flags
, fd
, offset
);
244 if (*m
!= MAP_FAILED
)
248 return -ERRNO_TO_PARA_ERROR(errno
);
252 * Wrapper for the open(2) system call.
254 * \param path The filename.
255 * \param flags The usual open(2) flags.
256 * \param mode Specifies the permissions to use.
258 * The mode parameter must be specified when O_CREAT is in the flags, and is
261 * \return The file descriptor on success, negative on errors.
265 int para_open(const char *path
, int flags
, mode_t mode
)
267 int ret
= open(path
, flags
, mode
);
271 return -ERRNO_TO_PARA_ERROR(errno
);
275 * Wrapper for chdir(2).
277 * \param path The specified directory.
281 int para_chdir(const char *path
)
283 int ret
= chdir(path
);
287 return -ERRNO_TO_PARA_ERROR(errno
);
291 * Save the cwd and open a given directory.
293 * \param dirname Path to the directory to open.
294 * \param dir Result pointer.
295 * \param cwd File descriptor of the current working directory.
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.
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
308 * On errors, the function undos everything, so the caller needs neither close
309 * any files, nor change back to the original working directory.
314 int para_opendir(const char *dirname
, DIR **dir
, int *cwd
)
319 ret
= para_open(".", O_RDONLY
, 0);
324 ret
= para_chdir(dirname
);
330 ret
= -ERRNO_TO_PARA_ERROR(errno
);
331 /* Ignore return value of fchdir() and close(). We're busted anyway. */
333 int __a_unused ret2
= fchdir(*cwd
); /* STFU, gcc */
342 * A wrapper for fchdir().
344 * \param fd An open file descriptor.
348 int para_fchdir(int fd
)
351 return -ERRNO_TO_PARA_ERROR(errno
);
356 * A wrapper for mkdir(2).
358 * \param path Name of the directory to create.
359 * \param mode The permissions to use.
363 int para_mkdir(const char *path
, mode_t mode
)
365 if (!mkdir(path
, mode
))
367 return -ERRNO_TO_PARA_ERROR(errno
);
371 * Open a file and map it into memory.
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.
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.
385 * \sa para_open(), mmap(2).
387 int mmap_full_file(const char *path
, int open_mode
, void **map
,
388 size_t *size
, int *fd_ptr
)
390 int fd
, ret
, mmap_prot
, mmap_flags
;
391 struct stat file_status
;
393 if (open_mode
== O_RDONLY
) {
394 mmap_prot
= PROT_READ
;
395 mmap_flags
= MAP_PRIVATE
;
397 mmap_prot
= PROT_READ
| PROT_WRITE
;
398 mmap_flags
= MAP_SHARED
;
400 ret
= para_open(path
, open_mode
, 0);
404 if (fstat(fd
, &file_status
) < 0) {
405 ret
= -ERRNO_TO_PARA_ERROR(errno
);
408 *size
= file_status
.st_size
;
409 ret
= para_mmap(*size
, mmap_prot
, mmap_flags
, fd
, 0, map
);
411 if (ret
< 0 || !fd_ptr
)
419 * A wrapper for munmap(2).
421 * \param start The start address of the memory mapping.
422 * \param length The size of the mapping.
426 * \sa munmap(2), mmap_full_file().
428 int para_munmap(void *start
, size_t length
)
431 if (munmap(start
, length
) >= 0)
434 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start
, length
,
436 return -ERRNO_TO_PARA_ERROR(err
);
440 * Check a file descriptor for writability.
442 * \param fd The file descriptor.
444 * \return positive if fd is ready for writing, zero if it isn't, negative if
457 return para_select(fd
+ 1, NULL
, &wfds
, &tv
);
461 * Ensure that file descriptors 0, 1, and 2 are valid.
463 * Common approach that opens /dev/null until it gets a file descriptor greater
466 * \sa okir's Black Hats Manual.
468 void valid_fd_012(void)
471 int fd
= open("/dev/null", O_RDWR
);
482 * Traverse the given directory recursively.
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.
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.
495 int for_each_file_in_dir(const char *dirname
,
496 int (*func
)(const char *, void *), void *private_data
)
499 struct dirent
*entry
;
500 int cwd_fd
, ret2
, ret
= para_opendir(dirname
, &dir
, &cwd_fd
);
503 return ret
== -ERRNO_TO_PARA_ERROR(EACCES
)? 1 : ret
;
504 /* scan cwd recursively */
505 while ((entry
= readdir(dir
))) {
510 if (!strcmp(entry
->d_name
, "."))
512 if (!strcmp(entry
->d_name
, ".."))
514 if (lstat(entry
->d_name
, &s
) == -1)
517 if (!S_ISREG(m
) && !S_ISDIR(m
))
519 tmp
= make_message("%s/%s", dirname
, entry
->d_name
);
521 ret
= func(tmp
, private_data
);
528 ret
= for_each_file_in_dir(tmp
, func
, private_data
);
536 ret2
= para_fchdir(cwd_fd
);
537 if (ret2
< 0 && ret
>= 0)