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