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