]> wimlib.net Git - wimlib/blob - src/util.c
wimlib_mount_image(): Send final status after fuse_main() returns
[wimlib] / src / util.c
1 /*
2  * util.c
3  */
4
5 /*
6  * Copyright (C) 2012 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #undef _GNU_SOURCE
25 /* Make sure the POSIX-compatible strerror_r() is declared, rather than the GNU
26  * version, which has a different return type. */
27 #define _POSIX_C_SOURCE 200112
28 #include <string.h>
29 #define _GNU_SOURCE
30
31 #include "wimlib_internal.h"
32 #include "endianness.h"
33 #include "timestamp.h"
34
35 #include <ctype.h>
36 #include <errno.h>
37 #include <stdlib.h>
38
39 #include <unistd.h> /* for getpid() */
40
41 /* True if wimlib is to print an informational message when an error occurs.
42  * This can be turned off by calling wimlib_set_print_errors(false). */
43 #ifdef ENABLE_ERROR_MESSAGES
44 #include <stdarg.h>
45 static bool wimlib_print_errors = false;
46
47 static void wimlib_vmsg(const char *tag, const char *format,
48                         va_list va, bool perror)
49 {
50         if (wimlib_print_errors) {
51                 int errno_save = errno;
52                 fflush(stdout);
53                 fputs(tag, stderr);
54                 vfprintf(stderr, format, va);
55                 if (perror && errno_save != 0) {
56                         char buf[50];
57                         int res = strerror_r(errno_save, buf, sizeof(buf));
58                         if (res) {
59                                 snprintf(buf, sizeof(buf),
60                                          "unknown error (errno=%d)", errno_save);
61                         }
62                         fprintf(stderr, ": %s", buf);
63                 }
64                 putc('\n', stderr);
65                 errno = errno_save;
66         }
67 }
68
69 void wimlib_error(const char *format, ...)
70 {
71         va_list va;
72
73         va_start(va, format);
74         wimlib_vmsg("[ERROR] ", format, va, false);
75         va_end(va);
76 }
77
78 void wimlib_error_with_errno(const char *format, ...)
79 {
80         va_list va;
81
82         va_start(va, format);
83         wimlib_vmsg("[ERROR] ", format, va, true);
84         va_end(va);
85 }
86
87 void wimlib_warning(const char *format, ...)
88 {
89         va_list va;
90
91         va_start(va, format);
92         wimlib_vmsg("[WARNING] ", format, va, false);
93         va_end(va);
94 }
95
96 void wimlib_warning_with_errno(const char *format, ...)
97 {
98         va_list va;
99
100         va_start(va, format);
101         wimlib_vmsg("[WARNING] ", format, va, true);
102         va_end(va);
103 }
104
105 #endif
106
107 WIMLIBAPI int wimlib_set_print_errors(bool show_error_messages)
108 {
109 #ifdef ENABLE_ERROR_MESSAGES
110         wimlib_print_errors = show_error_messages;
111         return 0;
112 #else
113         if (show_error_messages)
114                 return WIMLIB_ERR_UNSUPPORTED;
115         else
116                 return 0;
117 #endif
118 }
119
120 static const char *error_strings[] = {
121         [WIMLIB_ERR_SUCCESS]
122                 = "Success",
123         [WIMLIB_ERR_ALREADY_LOCKED]
124                 = "The WIM is already locked for writing",
125         [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
126                 = "Lookup table is compressed",
127         [WIMLIB_ERR_DECOMPRESSION]
128                 = "Failed to decompress compressed data",
129         [WIMLIB_ERR_DELETE_STAGING_DIR]
130                 = "Failed to delete staging directory",
131         [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
132                 = "The process servicing the mounted WIM has crashed",
133         [WIMLIB_ERR_FORK]
134                 = "Failed to fork another process",
135         [WIMLIB_ERR_FUSE]
136                 = "An error was returned by fuse_main()",
137         [WIMLIB_ERR_FUSERMOUNT]
138                 = "Could not execute the `fusermount' program, or it exited "
139                         "with a failure status",
140         [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
141                 = "The iconv() function does not seem to work. "
142                   "Maybe check to make sure the directory /usr/lib/gconv exists",
143         [WIMLIB_ERR_IMAGE_COUNT]
144                 = "Inconsistent image count among the metadata "
145                         "resources, the WIM header, and/or the XML data",
146         [WIMLIB_ERR_IMAGE_NAME_COLLISION]
147                 = "Tried to add an image with a name that is already in use",
148         [WIMLIB_ERR_INTEGRITY]
149                 = "The WIM failed an integrity check",
150         [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
151                 = "The capture configuration string was invalid",
152         [WIMLIB_ERR_INVALID_CHUNK_SIZE]
153                 = "The WIM is compressed but does not have a chunk "
154                         "size of 32768",
155         [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
156                 = "The WIM is compressed, but is not marked as having LZX or "
157                         "XPRESS compression",
158         [WIMLIB_ERR_INVALID_DENTRY]
159                 = "A directory entry in the WIM was invalid",
160         [WIMLIB_ERR_INVALID_HEADER_SIZE]
161                 = "The WIM header was not 208 bytes",
162         [WIMLIB_ERR_INVALID_IMAGE]
163                 = "Tried to select an image that does not exist in the WIM",
164         [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
165                 = "The WIM's integrity table is invalid",
166         [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
167                 = "An entry in the WIM's lookup table is invalid",
168         [WIMLIB_ERR_INVALID_PARAM]
169                 = "An invalid parameter was given",
170         [WIMLIB_ERR_INVALID_PART_NUMBER]
171                 = "The part number or total parts of the WIM is invalid",
172         [WIMLIB_ERR_INVALID_RESOURCE_HASH]
173                 = "The SHA1 message digest of a WIM resource did not match the expected value",
174         [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
175                 = "A resource entry in the WIM has an invalid size",
176         [WIMLIB_ERR_INVALID_SECURITY_DATA]
177                 = "The table of security descriptors in the WIM is invalid",
178         [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
179                 = "The version of wimlib that has mounted a WIM image is incompatible with the "
180                   "version being used to unmount it",
181         [WIMLIB_ERR_INVALID_UTF8_STRING]
182                 = "A string provided as input by the user was not a valid UTF-8 string",
183         [WIMLIB_ERR_INVALID_UTF16_STRING]
184                 = "A string in a WIM dentry is not a valid UTF-16LE string",
185         [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
186                 = "libxml2 was unable to find a character encoding conversion handler "
187                   "for UTF-16LE",
188         [WIMLIB_ERR_LINK]
189                 = "Failed to create a hard or symbolic link when extracting "
190                         "a file from the WIM",
191         [WIMLIB_ERR_MKDIR]
192                 = "Failed to create a directory",
193         [WIMLIB_ERR_MQUEUE]
194                 = "Failed to create or use a POSIX message queue",
195         [WIMLIB_ERR_NOMEM]
196                 = "Ran out of memory",
197         [WIMLIB_ERR_NOTDIR]
198                 = "Expected a directory",
199         [WIMLIB_ERR_NOT_A_WIM_FILE]
200                 = "The file did not begin with the magic characters that "
201                         "identify a WIM file",
202         [WIMLIB_ERR_NO_FILENAME]
203                 = "The WIM is not identified with a filename",
204         [WIMLIB_ERR_NTFS_3G]
205                 = "NTFS-3g encountered an error (check errno)",
206         [WIMLIB_ERR_OPEN]
207                 = "Failed to open a file",
208         [WIMLIB_ERR_OPENDIR]
209                 = "Failed to open a directory",
210         [WIMLIB_ERR_READ]
211                 = "Could not read data from a file",
212         [WIMLIB_ERR_READLINK]
213                 = "Could not read the target of a symbolic link",
214         [WIMLIB_ERR_RENAME]
215                 = "Could not rename a file",
216         [WIMLIB_ERR_REOPEN]
217                 = "Could not re-open the WIM after overwriting it",
218         [WIMLIB_ERR_RESOURCE_ORDER]
219                 = "The components of the WIM were arranged in an unexpected order",
220         [WIMLIB_ERR_SPECIAL_FILE]
221                 = "Encountered a special file that cannot be archived",
222         [WIMLIB_ERR_SPLIT_INVALID]
223                 = "The WIM is part of an invalid split WIM",
224         [WIMLIB_ERR_SPLIT_UNSUPPORTED]
225                 = "The WIM is part of a split WIM, which is not supported for this operation",
226         [WIMLIB_ERR_STAT]
227                 = "Could not read the metadata for a file or directory",
228         [WIMLIB_ERR_TIMEOUT]
229                 = "Timed out while waiting for a message to arrive from another process",
230         [WIMLIB_ERR_UNKNOWN_VERSION]
231                 = "The WIM file is marked with an unknown version number",
232         [WIMLIB_ERR_UNSUPPORTED]
233                 = "The requested operation is unsupported",
234         [WIMLIB_ERR_WRITE]
235                 = "Failed to write data to a file",
236         [WIMLIB_ERR_XML]
237                 = "The XML data of the WIM is invalid",
238 };
239
240 WIMLIBAPI const char *wimlib_get_error_string(enum wimlib_error_code code)
241 {
242         if (code < WIMLIB_ERR_SUCCESS || code > WIMLIB_ERR_XML)
243                 return NULL;
244         else
245                 return error_strings[code];
246 }
247
248
249
250 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
251 void *(*wimlib_malloc_func) (size_t)         = malloc;
252 void  (*wimlib_free_func)   (void *)         = free;
253 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
254
255 void *wimlib_calloc(size_t nmemb, size_t size)
256 {
257         size_t total_size = nmemb * size;
258         void *p = MALLOC(total_size);
259         if (p)
260                 memset(p, 0, total_size);
261         return p;
262 }
263
264 char *wimlib_strdup(const char *str)
265 {
266         size_t size;
267         char *p;
268
269         size = strlen(str);
270         p = MALLOC(size + 1);
271         if (p)
272                 memcpy(p, str, size + 1);
273         return p;
274 }
275
276 extern void xml_set_memory_allocator(void *(*malloc_func)(size_t),
277                                    void (*free_func)(void *),
278                                    void *(*realloc_func)(void *, size_t));
279 #endif
280
281 WIMLIBAPI int wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
282                                            void (*free_func)(void *),
283                                            void *(*realloc_func)(void *, size_t))
284 {
285 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
286         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
287         wimlib_free_func    = free_func    ? free_func    : free;
288         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
289
290         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
291                                  wimlib_realloc_func);
292         return 0;
293 #else
294         ERROR("Cannot set custom memory allocator functions:");
295         ERROR("wimlib was compiled with the --without-custom-memory-allocator "
296               "flag");
297         return WIMLIB_ERR_UNSUPPORTED;
298 #endif
299 }
300
301 static bool seeded = false;
302
303 static void seed_random()
304 {
305         srand(time(NULL) * getpid());
306         seeded = true;
307 }
308
309 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
310 void randomize_char_array_with_alnum(char p[], size_t n)
311 {
312         if (!seeded)
313                 seed_random();
314         while (n--) {
315                 int r = rand() % 62;
316                 if (r < 26)
317                         *p++ = r + 'a';
318                 else if (r < 52)
319                         *p++ = r - 26 + 'A';
320                 else
321                         *p++ = r - 52 + '0';
322         }
323 }
324
325 /* Fills @n bytes pointer to by @p with random numbers. */
326 void randomize_byte_array(u8 *p, size_t n)
327 {
328         if (!seeded)
329                 seed_random();
330         while (n--)
331                 *p++ = rand();
332 }
333
334 /* Takes in a path of length @len in @buf, and transforms it into a string for
335  * the path of its parent directory. */
336 void to_parent_name(char buf[], size_t len)
337 {
338         ssize_t i = (ssize_t)len - 1;
339         while (i >= 0 && buf[i] == '/')
340                 i--;
341         while (i >= 0 && buf[i] != '/')
342                 i--;
343         while (i >= 0 && buf[i] == '/')
344                 i--;
345         buf[i + 1] = '\0';
346 }
347
348 /* Like the basename() function, but does not modify @path; it just returns a
349  * pointer to it. */
350 const char *path_basename(const char *path)
351 {
352         const char *p = path;
353         while (*p)
354                 p++;
355         p--;
356
357         /* Trailing slashes. */
358         while (1) {
359                 if (p == path - 1)
360                         return "";
361                 if (*p != '/')
362                         break;
363                 p--;
364         }
365
366         while ((p != path - 1) && *p != '/')
367                 p--;
368
369         return p + 1;
370 }
371
372 /*
373  * Returns a pointer to the part of @path following the first colon in the last
374  * path component, or NULL if the last path component does not contain a colon.
375  */
376 const char *path_stream_name(const char *path)
377 {
378         const char *base = path_basename(path);
379         const char *stream_name = strchr(base, ':');
380         if (!stream_name)
381                 return NULL;
382         else
383                 return stream_name + 1;
384 }
385
386 /*
387  * Splits a file path into the part before the first '/', or the entire name if
388  * there is no '/', and the part after the first sequence of '/' characters.
389  *
390  * @path:               The file path to split.
391  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
392  *                              first part of the path will be returned.
393  * @return:             A pointer to the next part of the path, after the first
394  *                              sequence of '/', or a pointer to the terminating
395  *                              null byte in the case of a path without any '/'.
396  */
397 const char *path_next_part(const char *path, size_t *first_part_len_ret)
398 {
399         size_t i;
400         const char *next_part;
401
402         i = 0;
403         while (path[i] != '/' && path[i] != '\0')
404                 i++;
405         if (first_part_len_ret)
406                 *first_part_len_ret = i;
407         next_part = &path[i];
408         while (*next_part == '/')
409                 next_part++;
410         return next_part;
411 }
412
413 /* Returns the number of components of @path.  */
414 int get_num_path_components(const char *path)
415 {
416         int num_components = 0;
417         while (*path) {
418                 while (*path == '/')
419                         path++;
420                 if (*path)
421                         num_components++;
422                 while (*path && *path != '/')
423                         path++;
424         }
425         return num_components;
426 }
427
428
429 /*
430  * Prints a string.  Printable characters are printed as-is, while unprintable
431  * characters are printed as their octal escape codes.
432  */
433 void print_string(const void *string, size_t len)
434 {
435         const u8 *p = string;
436
437         while (len--) {
438                 if (isprint(*p))
439                         putchar(*p);
440                 else
441                         printf("\\%03hho", *p);
442                 p++;
443         }
444 }
445
446 u64 get_wim_timestamp()
447 {
448         struct timeval tv;
449         gettimeofday(&tv, NULL);
450         return timeval_to_wim_timestamp(&tv);
451 }
452
453 void wim_timestamp_to_str(u64 timestamp, char *buf, size_t len)
454 {
455         struct tm tm;
456         time_t t = wim_timestamp_to_unix(timestamp);
457         gmtime_r(&t, &tm);
458         strftime(buf, len, "%a %b %d %H:%M:%S %Y UTC", &tm);
459 }