]> wimlib.net Git - wimlib/blob - src/util.c
imagex unmount --rebuild
[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 #include "wimlib_internal.h"
25 #include "endianness.h"
26 #include "sha1.h"
27 #include "timestamp.h"
28 #include <sys/time.h>
29
30
31 #include <iconv.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <stdlib.h>
35 #include <time.h>
36 #include <unistd.h>
37 #include <errno.h>
38
39 /* True if wimlib is to print an informational message when an error occurs.
40  * This can be turned off by calling wimlib_set_print_errors(false). */
41 #ifdef ENABLE_ERROR_MESSAGES
42 #include <stdarg.h>
43 bool __wimlib_print_errors = false;
44
45 void wimlib_error(const char *format, ...)
46 {
47         if (__wimlib_print_errors) {
48                 va_list va;
49                 int errno_save;
50
51                 va_start(va, format);
52                 errno_save = errno;
53                 fputs("[ERROR] ", stderr);
54                 vfprintf(stderr, format, va);
55                 putc('\n', stderr);
56                 errno = errno_save;
57                 va_end(va);
58         }
59 }
60
61 void wimlib_error_with_errno(const char *format, ...)
62 {
63         if (__wimlib_print_errors) {
64                 va_list va;
65                 int errno_save;
66
67                 va_start(va, format);
68                 errno_save = errno;
69                 fflush(stdout);
70                 fputs("[ERROR] ", stderr);
71                 vfprintf(stderr, format, va);
72                 fprintf(stderr, ": %s\n", strerror(errno_save));
73                 errno = errno_save;
74                 va_end(va);
75         }
76 }
77
78 void wimlib_warning(const char *format, ...)
79 {
80         if (__wimlib_print_errors) {
81                 va_list va;
82                 int errno_save;
83
84                 va_start(va, format);
85                 errno_save = errno;
86                 fflush(stdout);
87                 fputs("[WARNING] ", stderr);
88                 vfprintf(stderr, format, va);
89                 putc('\n', stderr);
90                 errno = errno_save;
91                 va_end(va);
92         }
93 }
94
95 #endif
96
97 WIMLIBAPI int wimlib_set_print_errors(bool show_error_messages)
98 {
99 #ifdef ENABLE_ERROR_MESSAGES
100         __wimlib_print_errors = show_error_messages;
101         return 0;
102 #else
103         if (show_error_messages)
104                 return WIMLIB_ERR_UNSUPPORTED;
105         else
106                 return 0;
107 #endif
108 }
109
110 static const char *error_strings[] = {
111         [WIMLIB_ERR_SUCCESS]
112                 = "Success",
113         [WIMLIB_ERR_ALREADY_LOCKED]
114                 = "The WIM is already locked for writing",
115         [WIMLIB_ERR_CHAR_CONVERSION]
116                 = "Failed to perform a conversion between UTF-8 and UTF-16LE",
117         [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
118                 = "Lookup table is compressed",
119         [WIMLIB_ERR_DECOMPRESSION]
120                 = "Failed to decompress compressed data",
121         [WIMLIB_ERR_DELETE_STAGING_DIR]
122                 = "Failed to delete staging directory",
123         [WIMLIB_ERR_FORK]
124                 = "Failed to fork another process",
125         [WIMLIB_ERR_FUSE]
126                 = "An error was returned by fuse_main()",
127         [WIMLIB_ERR_FUSERMOUNT]
128                 = "Could not execute the `fusermount' program, or it exited "
129                         "with a failure status",
130         [WIMLIB_ERR_IMAGE_COUNT]
131                 = "Inconsistent image count among the metadata "
132                         "resources, the WIM header, and/or the XML data",
133         [WIMLIB_ERR_IMAGE_NAME_COLLISION]
134                 = "Tried to add an image with a name that is already in use",
135         [WIMLIB_ERR_INTEGRITY]
136                 = "The WIM failed an integrity check",
137         [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
138                 = "The capture configuration string was invalid",
139         [WIMLIB_ERR_INVALID_CHUNK_SIZE]
140                 = "The WIM is compressed but does not have a chunk "
141                         "size of 32768",
142         [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
143                 = "The WIM is compressed, but is not marked as having LZX or "
144                         "XPRESS compression",
145         [WIMLIB_ERR_INVALID_DENTRY]
146                 = "A directory entry in the WIM was invalid",
147         [WIMLIB_ERR_INVALID_HEADER_SIZE]
148                 = "The WIM header was not 208 bytes",
149         [WIMLIB_ERR_INVALID_IMAGE]
150                 = "Tried to select an image that does not exist in the WIM",
151         [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
152                 = "The WIM's integrity table is invalid",
153         [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
154                 = "An entry in the WIM's lookup table is invalid",
155         [WIMLIB_ERR_INVALID_PARAM]
156                 = "An invalid parameter was given",
157         [WIMLIB_ERR_INVALID_PART_NUMBER]
158                 = "The part number or total parts of the WIM is invalid",
159         [WIMLIB_ERR_INVALID_RESOURCE_HASH]
160                 = "The SHA1 message digest of a WIM resource did not match the expected value",
161         [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
162                 = "A resource entry in the WIM has an invalid size",
163         [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
164                 = "The version of wimlib that has mounted a WIM image is incompatible with the "
165                   "version being used to unmount it",
166         [WIMLIB_ERR_LINK]
167                 = "Failed to create a hard or symbolic link when extracting "
168                         "a file from the WIM",
169         [WIMLIB_ERR_MKDIR]
170                 = "Failed to create a directory",
171         [WIMLIB_ERR_MQUEUE]
172                 = "Failed to create or use a POSIX message queue",
173         [WIMLIB_ERR_NOMEM]
174                 = "Ran out of memory",
175         [WIMLIB_ERR_NOTDIR]
176                 = "Expected a directory",
177         [WIMLIB_ERR_NOT_A_WIM_FILE]
178                 = "The file did not begin with the magic characters that "
179                         "identify a WIM file",
180         [WIMLIB_ERR_NO_FILENAME]
181                 = "The WIM is not identified with a filename",
182         [WIMLIB_ERR_NTFS_3G]
183                 = "NTFS-3g encountered an error (check errno)",
184         [WIMLIB_ERR_OPEN]
185                 = "Failed to open a file",
186         [WIMLIB_ERR_OPENDIR]
187                 = "Failed to open a directory",
188         [WIMLIB_ERR_READ]
189                 = "Could not read data from a file",
190         [WIMLIB_ERR_READLINK]
191                 = "Could not read the target of a symbolic link",
192         [WIMLIB_ERR_RENAME]
193                 = "Could not rename a file",
194         [WIMLIB_ERR_REOPEN]
195                 = "Could not re-open the WIM after overwriting it",
196         [WIMLIB_ERR_RESOURCE_ORDER]
197                 = "The components of the WIM were arranged in an unexpected order",
198         [WIMLIB_ERR_SPECIAL_FILE]
199                 = "Encountered a special file that cannot be archived",
200         [WIMLIB_ERR_SPLIT_INVALID]
201                 = "The WIM is part of an invalid split WIM",
202         [WIMLIB_ERR_SPLIT_UNSUPPORTED]
203                 = "The WIM is part of a split WIM, which is not supported for this operation",
204         [WIMLIB_ERR_STAT]
205                 = "Could not read the metadata for a file or directory",
206         [WIMLIB_ERR_TIMEOUT]
207                 = "Timed out",
208         [WIMLIB_ERR_UNKNOWN_VERSION]
209                 = "The WIM file is marked with an unknown version number",
210         [WIMLIB_ERR_UNSUPPORTED]
211                 = "The requested operation is unsupported",
212         [WIMLIB_ERR_WRITE]
213                 = "Failed to write data to a file",
214         [WIMLIB_ERR_XML]
215                 = "The XML data of the WIM is invalid",
216 };
217
218 WIMLIBAPI const char *wimlib_get_error_string(enum wimlib_error_code code)
219 {
220         if (code < WIMLIB_ERR_SUCCESS || code > WIMLIB_ERR_XML)
221                 return NULL;
222         else
223                 return error_strings[code];
224 }
225
226
227
228 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
229 void *(*wimlib_malloc_func) (size_t)         = malloc;
230 void  (*wimlib_free_func)   (void *)         = free;
231 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
232
233 void *wimlib_calloc(size_t nmemb, size_t size)
234 {
235         size_t total_size = nmemb * size;
236         void *p = MALLOC(total_size);
237         if (p)
238                 memset(p, 0, total_size);
239         return p;
240 }
241
242 char *wimlib_strdup(const char *str)
243 {
244         size_t size;
245         char *p;
246
247         size = strlen(str);
248         p = MALLOC(size + 1);
249         if (p)
250                 memcpy(p, str, size + 1);
251         return p;
252 }
253
254 extern void xml_set_memory_allocator(void *(*malloc_func)(size_t),
255                                    void (*free_func)(void *),
256                                    void *(*realloc_func)(void *, size_t));
257 #endif
258
259 WIMLIBAPI int wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
260                                            void (*free_func)(void *),
261                                            void *(*realloc_func)(void *, size_t))
262 {
263 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
264         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
265         wimlib_free_func    = free_func    ? free_func    : free;
266         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
267
268         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
269                                  wimlib_realloc_func);
270         return 0;
271 #else
272         ERROR("Cannot set custom memory allocator functions:");
273         ERROR("wimlib was compiled with the --without-custom-memory-allocator "
274               "flag");
275         return WIMLIB_ERR_UNSUPPORTED;
276 #endif
277 }
278
279
280
281 static iconv_t cd_utf16_to_utf8 = (iconv_t)(-1);
282
283 /* Converts a string in the UTF-16 encoding to a newly allocated string in the
284  * UTF-8 encoding.  */
285 char *utf16_to_utf8(const char *utf16_str, size_t utf16_len,
286                     size_t *utf8_len_ret)
287 {
288         if (cd_utf16_to_utf8 == (iconv_t)(-1)) {
289                 cd_utf16_to_utf8 = iconv_open("UTF-8", "UTF-16LE");
290                 if (cd_utf16_to_utf8 == (iconv_t)-1) {
291                         ERROR_WITH_ERRNO("Failed to get conversion descriptor "
292                                          "for converting UTF-16LE to UTF-8");
293                         return NULL;
294                 }
295         }
296         size_t utf16_bytes_left  = utf16_len;
297         size_t utf8_bytes_left   = utf16_len;
298
299         char *utf8_str = MALLOC(utf8_bytes_left);
300         if (!utf8_str)
301                 return NULL;
302
303         char *orig_utf8_str = utf8_str;
304
305         size_t num_chars_converted = iconv(cd_utf16_to_utf8, (char**)&utf16_str,
306                         &utf16_bytes_left, &utf8_str, &utf8_bytes_left);
307
308         if (num_chars_converted == (size_t)(-1)) {
309                 ERROR_WITH_ERRNO("Failed to convert UTF-16LE string to UTF-8 "
310                                  "string");
311                 FREE(orig_utf8_str);
312                 return NULL;
313         }
314
315         size_t utf8_len = utf16_len - utf8_bytes_left;
316
317         *utf8_len_ret = utf8_len;
318         orig_utf8_str[utf8_len] = '\0';
319         return orig_utf8_str;
320 }
321
322 static iconv_t cd_utf8_to_utf16 = (iconv_t)(-1);
323
324 /* Converts a string in the UTF-8 encoding to a newly allocated string in the
325  * UTF-16 encoding.  */
326 char *utf8_to_utf16(const char *utf8_str, size_t utf8_len,
327                     size_t *utf16_len_ret)
328 {
329         if (cd_utf8_to_utf16 == (iconv_t)(-1)) {
330                 cd_utf8_to_utf16 = iconv_open("UTF-16LE", "UTF-8");
331                 if (cd_utf8_to_utf16 == (iconv_t)-1) {
332                         ERROR_WITH_ERRNO("Failed to get conversion descriptor "
333                                          "for converting UTF-8 to UTF-16LE");
334                         return NULL;
335                 }
336         }
337
338         size_t utf8_bytes_left   = utf8_len;
339         size_t utf16_capacity    = utf8_len * 4;
340         size_t utf16_bytes_left  = utf16_capacity;
341
342         char *utf16_str = MALLOC(utf16_capacity + 2);
343         if (!utf16_str)
344                 return NULL;
345
346         char *orig_utf16_str = utf16_str;
347
348         size_t num_chars_converted = iconv(cd_utf8_to_utf16, (char**)&utf8_str,
349                         &utf8_bytes_left, &utf16_str, &utf16_bytes_left);
350
351         if (num_chars_converted == (size_t)(-1)) {
352                 ERROR_WITH_ERRNO("Failed to convert UTF-8 string to UTF-16LE "
353                                  "string");
354                 FREE(orig_utf16_str);
355                 return NULL;
356         }
357
358         size_t utf16_len = utf16_capacity - utf16_bytes_left;
359
360         *utf16_len_ret = utf16_len;
361         orig_utf16_str[utf16_len] = '\0';
362         orig_utf16_str[utf16_len + 1] = '\0';
363         return orig_utf16_str;
364 }
365
366 static bool seeded = false;
367
368 static void seed_random()
369 {
370         srand(time(NULL) * getpid());
371         seeded = true;
372 }
373
374 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
375 void randomize_char_array_with_alnum(char p[], size_t n)
376 {
377         if (!seeded)
378                 seed_random();
379         while (n--) {
380                 int r = rand() % 62;
381                 if (r < 26)
382                         *p++ = r + 'a';
383                 else if (r < 52)
384                         *p++ = r - 26 + 'A';
385                 else
386                         *p++ = r - 52 + '0';
387         }
388 }
389
390 /* Fills @n bytes pointer to by @p with random numbers. */
391 void randomize_byte_array(u8 *p, size_t n)
392 {
393         if (!seeded)
394                 seed_random();
395         while (n--)
396                 *p++ = rand();
397 }
398
399 /* Takes in a path of length @len in @buf, and transforms it into a string for
400  * the path of its parent directory. */
401 void to_parent_name(char buf[], size_t len)
402 {
403         ssize_t i = (ssize_t)len - 1;
404         while (i >= 0 && buf[i] == '/')
405                 i--;
406         while (i >= 0 && buf[i] != '/')
407                 i--;
408         while (i >= 0 && buf[i] == '/')
409                 i--;
410         buf[i + 1] = '\0';
411 }
412
413 /* Like the basename() function, but does not modify @path; it just returns a
414  * pointer to it. */
415 const char *path_basename(const char *path)
416 {
417         const char *p = path;
418         while (*p)
419                 p++;
420         p--;
421
422         /* Trailing slashes. */
423         while (1) {
424                 if (p == path - 1)
425                         return "";
426                 if (*p != '/')
427                         break;
428                 p--;
429         }
430
431         while ((p != path - 1) && *p != '/')
432                 p--;
433
434         return p + 1;
435 }
436
437 /*
438  * Returns a pointer to the part of @path following the first colon in the last
439  * path component, or NULL if the last path component does not contain a colon.
440  */
441 const char *path_stream_name(const char *path)
442 {
443         const char *base = path_basename(path);
444         const char *stream_name = strchr(base, ':');
445         if (!stream_name)
446                 return NULL;
447         else
448                 return stream_name + 1;
449 }
450
451 /*
452  * Splits a file path into the part before the first '/', or the entire name if
453  * there is no '/', and the part after the first sequence of '/' characters.
454  *
455  * @path:               The file path to split.
456  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
457  *                              first part of the path will be returned.
458  * @return:             A pointer to the next part of the path, after the first
459  *                              sequence of '/', or a pointer to the terminating
460  *                              null byte in the case of a path without any '/'.
461  */
462 const char *path_next_part(const char *path, size_t *first_part_len_ret)
463 {
464         size_t i;
465         const char *next_part;
466
467         i = 0;
468         while (path[i] != '/' && path[i] != '\0')
469                 i++;
470         if (first_part_len_ret)
471                 *first_part_len_ret = i;
472         next_part = &path[i];
473         while (*next_part == '/')
474                 next_part++;
475         return next_part;
476 }
477
478 /* Returns the number of components of @path.  */
479 int get_num_path_components(const char *path)
480 {
481         int num_components = 0;
482         while (*path) {
483                 while (*path == '/')
484                         path++;
485                 if (*path)
486                         num_components++;
487                 while (*path && *path != '/')
488                         path++;
489         }
490         return num_components;
491 }
492
493
494 /*
495  * Prints a string.  Printable characters are printed as-is, while unprintable
496  * characters are printed as their octal escape codes.
497  */
498 void print_string(const void *string, size_t len)
499 {
500         const u8 *p = string;
501
502         while (len--) {
503                 if (isprint(*p))
504                         putchar(*p);
505                 else
506                         printf("\\%03hho", *p);
507                 p++;
508         }
509 }
510
511 u64 get_wim_timestamp()
512 {
513         struct timeval tv;
514         gettimeofday(&tv, NULL);
515         return timeval_to_wim_timestamp(&tv);
516 }
517
518 void wim_timestamp_to_str(u64 timestamp, char *buf, size_t len)
519 {
520         struct tm tm;
521         time_t t = wim_timestamp_to_unix(timestamp);
522         gmtime_r(&t, &tm);
523         strftime(buf, len, "%a %b %d %H:%M:%S %Y UTC", &tm);
524 }