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