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