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