cb6724a2c473827b36d8b3716872ebab6a0d588e
[adu.git] / fd.c
1 /*
2  * Copyright (C) 2006-2008 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file fd.c \brief Helper functions for file descriptor handling. */
8
9 #include <sys/types.h>
10 #include <dirent.h>
11 #include <sys/mman.h>
12 #include <string.h>
13
14 #include "adu.h"
15 #include "error.h"
16 #include "string.h"
17 #include "fd.h"
18
19 /**
20  * Wrapper for the write system call.
21  *
22  * \param fd The file descriptor to write to.
23  * \param buf The buffer to write.
24  * \param size The length of \a buf in bytes.
25  *
26  * This function writes out the given buffer and retries if an interrupt
27  * occurred during the write.
28  *
29  * \return Standard.
30  *
31  * \sa write(2).
32  */
33 static ssize_t __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  * Write the whole buffer to a file descriptor.
47  *
48  * \param fd The file descriptor to write to.
49  * \param buf The buffer to write.
50  * \param size The length of \a buf in bytes.
51  *
52  * This function writes the given buffer and continues on short writes and
53  * when interrupted by a signal.
54  *
55  * \return Standard.
56  */
57 static ssize_t write_all(int fd, const void *buf, size_t size)
58 {
59 //      DEBUG_LOG("writing %zu bytes\n", size);
60         const char *b = buf;
61         while (size) {
62                 ssize_t ret = __write(fd, b, size);
63 //              DEBUG_LOG("ret: %zd\n", ret);
64                 if (ret < 0)
65                         return ret;
66                 b += ret;
67                 size -= ret;
68         }
69         return 1;
70 }
71
72 /**
73  * Wrapper for the open(2) system call.
74  *
75  * \param path The filename.
76  * \param flags The usual open(2) flags.
77  * \param mode Specifies the permissions to use.
78  *
79  * The mode parameter must be specified when O_CREAT is in the flags, and is
80  * ignored otherwise.
81  *
82  * \return The file descriptor on success, negative on errors.
83  *
84  * \sa open(2).
85  */
86 static int __open(const char *path, int flags, mode_t mode)
87 {
88         int ret = open(path, flags, mode);
89
90         if (ret >= 0)
91                 return ret;
92         return -ERRNO_TO_ERROR(errno);
93 }
94
95 /**
96  * Open a file, write the given buffer and close the file.
97  *
98  * \param filename Full path to the file to open.
99  * \param buf The buffer to write to the file.
100  * \param size The size of \a buf.
101  *
102  * \return Standard.
103  */
104 int adu_write_file(const char *filename, const void *buf, size_t size)
105 {
106         int ret, fd;
107
108         ret = __open(filename, O_WRONLY | O_CREAT | O_EXCL, 0644);
109         if (ret < 0)
110                 return ret;
111         fd = ret;
112         ret = write_all(fd, buf, size);
113         if (ret < 0)
114                 goto out;
115         ret = 1;
116 out:
117         close(fd);
118         return ret;
119 }
120
121 /**
122  * Wrapper for chdir(2).
123  *
124  * \param path The specified directory.
125  *
126  * \return Standard.
127  */
128 static int __chdir(const char *path)
129 {
130         int ret = chdir(path);
131
132         if (ret >= 0)
133                 return 1;
134         return -ERRNO_TO_ERROR(errno);
135 }
136
137 /**
138  * Save the cwd and open a given directory.
139  *
140  * \param dirname Path to the directory to open.
141  * \param dir Result pointer.
142  * \param cwd File descriptor of the current working directory.
143  *
144  * \return Standard.
145  *
146  * Opening the current directory (".") and calling fchdir() to return is
147  * usually faster and more reliable than saving cwd in some buffer and calling
148  * chdir() afterwards.
149  *
150  * If \a cwd is not \p NULL "." is opened and the resulting file descriptor is
151  * stored in \a cwd. If the function returns success, and \a cwd is not \p
152  * NULL, the caller must close this file descriptor (probably after calling
153  * fchdir(*cwd)).
154  *
155  * On errors, the function undos everything, so the caller needs neither close
156  * any files, nor change back to the original working directory.
157  *
158  * \sa getcwd(3).
159  *
160  */
161 int adu_opendir(const char *dirname, DIR **dir, int *cwd)
162 {
163         int ret;
164
165         if (cwd) {
166                 ret = __open(".", O_RDONLY, 0);
167                 if (ret < 0)
168                         return ret;
169                 *cwd = ret;
170         }
171         ret = __chdir(dirname);
172         if (ret < 0)
173                 goto close_cwd;
174         *dir = opendir(".");
175         if (*dir)
176                 return 1;
177         ret = -ERRNO_TO_ERROR(errno);
178 /* Ignore return value of fchdir() and close(). We're busted anyway. */
179         if (cwd)
180                 fchdir(*cwd);
181 close_cwd:
182         if (cwd)
183                 close(*cwd);
184         return ret;
185 }
186
187 /**
188  * A wrapper for fchdir().
189  *
190  * \param fd An open file descriptor.
191  *
192  * \return Standard.
193  */
194 int adu_fchdir(int fd)
195 {
196         if (fchdir(fd) < 0)
197                 return -ERRNO_TO_ERROR(errno);
198         return 1;
199 }
200
201 /**
202  * Open a file read-only and map it into memory.
203  *
204  * \param path Name of the regular file to map.
205  * \param map On success, the mapping is returned here.
206  * \param size Result parameter: size of the mapping in bytes.
207  *
208  * The file will be mapped privately with memory protection PROT_READ. The file
209  * descriptor resulting from the underlying open call is closed after mmap().
210  *
211  * \return Standard.
212  *
213  * \sa mmap(2).
214  */
215 int mmap_file_ro(const char *path, void **map, size_t *size)
216 {
217         int fd, ret;
218         struct stat file_status;
219
220         ret = __open(path, O_RDONLY, 0);
221         if (ret < 0)
222                 return ret;
223         fd = ret;
224         if (fstat(fd, &file_status) < 0) {
225                 ret = -ERRNO_TO_ERROR(errno);
226                 goto out;
227         }
228         *size = file_status.st_size;
229         ret = -E_EMPTY;
230         DEBUG_LOG("%s: size %zu\n", path, *size);
231         if (!*size)
232                 goto out;
233         *map = mmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
234         if (*map == MAP_FAILED) {
235                 *map = NULL;
236                 ret = -E_MMAP;
237                 goto out;
238         }
239         ret = 1;
240 out:
241         close(fd);
242         return ret;
243 }
244
245 /**
246  * A wrapper for munmap(2).
247  *
248  * \param start The start address of the memory mapping.
249  * \param length The size of the mapping.
250  *
251  * \return Positive on success, \p -E_MUNMAP on errors.
252  *
253  * \sa munmap(2), mmap_full_file().
254  */
255 int adu_munmap(void *start, size_t length)
256 {
257         int err;
258         if (munmap(start, length) >= 0)
259                 return 1;
260         err = errno;
261         ERROR_LOG("munmap (%p/%zu) failed: %s\n", start, length,
262                 strerror(err));
263         return -ERRNO_TO_ERROR(err);
264 }
265
266 __must_check __malloc static char *adu_dirname(const char *name)
267 {
268         char *p, *ret;
269
270         if (!name || !*name)
271                 return NULL;
272         ret = adu_strdup(name);
273         p = strrchr(ret, '/');
274         if (!p)
275                 *ret = '\0';
276         else
277                 *p = '\0';
278         return ret;
279 }
280
281 /**
282  * Recursive mkdir
283  *
284  * \param p Full path that should be created.
285  *
286  * \param mode Use this mode when creating directories.
287  *
288  * \return 0 if successful, -E_MKDIR on errors.
289  */
290 int mkpath(const char *p, mode_t mode)
291 {
292         char *parent, *path;
293         int ret = -E_MKDIR;
294
295         DEBUG_LOG("%s\n", p);
296         if (strcmp(p, ".") == 0 || strcmp(p, "/") == 0 || strcmp(p, "") == 0) {
297                 DEBUG_LOG("reached beginning of path\n");
298                 return 0;
299         }
300         path = adu_strdup(p);
301         parent = adu_dirname(p);
302         if (!parent)
303                 goto out;
304         ret = mkpath(parent, mode);
305         if (ret < 0)
306                 goto out;
307         INFO_LOG("making dir %s\n", path);
308         ret = 0;
309         if ((mkdir(path, mode) == -1) && (errno != EEXIST))
310                 ret = -E_MKDIR;
311 out:
312         free(parent);
313         free(path);
314         return ret;
315 }