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