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