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