d0b5c895a5f25d02b9f566fbe693a38898057203
[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 int __a_unused ret2 = fchdir(*cwd); /* STFU, gcc */
291 }
292 close_cwd:
293 if (cwd)
294 close(*cwd);
295 return ret;
296 }
297
298 /**
299 * A wrapper for fchdir().
300 *
301 * \param fd An open file descriptor.
302 *
303 * \return Standard.
304 */
305 int para_fchdir(int fd)
306 {
307 if (fchdir(fd) < 0)
308 return -ERRNO_TO_PARA_ERROR(errno);
309 return 1;
310 }
311
312 /**
313 * A wrapper for mkdir(2).
314 *
315 * \param path Name of the directory to create.
316 * \param mode The permissions to use.
317 *
318 * \return Standard.
319 */
320 int para_mkdir(const char *path, mode_t mode)
321 {
322 if (!mkdir(path, mode))
323 return 1;
324 return -ERRNO_TO_PARA_ERROR(errno);
325 }
326
327 /**
328 * Open a file and map it into memory.
329 *
330 * \param path Name of the regular file to map.
331 * \param open_mode Either \p O_RDONLY or \p O_RDWR.
332 * \param map On success, the mapping is returned here.
333 * \param size size of the mapping.
334 * \param fd_ptr The file descriptor of the mapping.
335 *
336 * If \a fd_ptr is \p NULL, the file descriptor resulting from the underlying
337 * open call is closed after mmap(). Otherwise the file is kept open and the
338 * file descriptor is returned in \a fd_ptr.
339 *
340 * \return Standard.
341 *
342 * \sa para_open(), mmap(2).
343 */
344 int mmap_full_file(const char *path, int open_mode, void **map,
345 size_t *size, int *fd_ptr)
346 {
347 int fd, ret, mmap_prot, mmap_flags;
348 struct stat file_status;
349
350 if (open_mode == O_RDONLY) {
351 mmap_prot = PROT_READ;
352 mmap_flags = MAP_PRIVATE;
353 } else {
354 mmap_prot = PROT_READ | PROT_WRITE;
355 mmap_flags = MAP_SHARED;
356 }
357 ret = para_open(path, open_mode, 0);
358 if (ret < 0)
359 return ret;
360 fd = ret;
361 if (fstat(fd, &file_status) < 0) {
362 ret = -ERRNO_TO_PARA_ERROR(errno);
363 goto out;
364 }
365 *size = file_status.st_size;
366 ret = -E_EMPTY;
367 PARA_DEBUG_LOG("%s: size %zu\n", path, *size);
368 if (!*size)
369 goto out;
370 *map = mmap(NULL, *size, mmap_prot, mmap_flags, fd, 0);
371 if (*map == MAP_FAILED) {
372 *map = NULL;
373 ret = -E_MMAP;
374 goto out;
375 }
376 ret = 1;
377 out:
378 if (ret < 0 || !fd_ptr)
379 close(fd);
380 else
381 *fd_ptr = fd;
382 return ret;
383 }
384
385 /**
386 * A wrapper for munmap(2).
387 *
388 * \param start The start address of the memory mapping.
389 * \param length The size of the mapping.
390 *
391 * \return Positive on success, \p -E_MUNMAP on errors.
392 *
393 * \sa munmap(2), mmap_full_file().
394 */
395 int para_munmap(void *start, size_t length)
396 {
397 int err;
398 if (munmap(start, length) >= 0)
399 return 1;
400 err = errno;
401 PARA_ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
402 strerror(err));
403 return -ERRNO_TO_PARA_ERROR(err);
404 }
405
406 /**
407 * Check a file descriptor for writability.
408 *
409 * \param fd The file descriptor.
410 *
411 * \return positive if fd is ready for writing, zero if it isn't, negative if
412 * an error occurred.
413 */
414
415 int write_ok(int fd)
416 {
417 struct timeval tv = {0, 0};
418 fd_set wfds;
419 int ret;
420 again:
421 FD_ZERO(&wfds);
422 FD_SET(fd, &wfds);
423 tv.tv_sec = 0;
424 tv.tv_usec = 0;
425 ret = select(fd + 1, NULL, &wfds, NULL, &tv);
426 if (ret < 0 && errno == EINTR)
427 goto again;
428 return ret;
429 }