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