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