]> wimlib.net Git - wimlib/blob - src/util.c
Encodings update (IN PROGRESS)
[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 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 /* Handle %W for UTF16-LE printing and %U for UTF-8 printing.
56  *
57  * TODO: this is not yet done properly--- it's assumed that if the format string
58  * contains %W and/or %U, then it contains no other format specifiers.
59  */
60 static int
61 wimlib_vfprintf(FILE *fp, const tchar *format, va_list va)
62 {
63         const tchar *p;
64
65         for (p = format; *p; p++)
66                 if (*p == '%' && (*(p + 1) == T('W') || *(p + 1) == T('U')))
67                         goto special;
68         return tvfprintf(fp, format, va);
69 special:
70         /* XXX */
71         wimlib_assert(0);
72 #if 0
73         ;
74         int n = 0;
75         for (p = format; *p; p++) {
76                 if (*p == T('%') && (*(p + 1) == T('W') || *(p + 1) == T('U'))) {
77                         int ret;
78                         tchar *mbs;
79                         size_t mbs_nbytes;
80
81                         if (*(p + 1) == T('W')) {
82                                 utf16lechar *ucs = va_arg(va, utf16lechar*);
83                                 size_t ucs_nbytes = utf16le_strlen(ucs);
84                                 ret = utf16le_to_mbs(ucs, ucs_nbytes,
85                                                      &mbs, &mbs_nbytes);
86                         } else {
87                                 utf8char *ucs = va_arg(va, utf8char*);
88                                 size_t ucs_nbytes = strlen(ucs);
89                                 ret = utf8_to_mbs(ucs, ucs_nbytes,
90                                                   &mbs, &mbs_nbytes);
91                         }
92                         if (ret) {
93                                 ret = tfprintf(fp, T("??????"));
94                         } else {
95                                 ret = tfprintf(fp, T("%s"), mbs);
96                                 FREE(mbs);
97                         }
98                         if (ret < 0)
99                                 return -1;
100                         else
101                                 n += ret;
102                         p++;
103                 } else {
104                         if (putc(*p, fp) == EOF)
105                                 return -1;
106                         n++;
107                 }
108         }
109         return n;
110 #endif
111 }
112
113 int
114 wimlib_printf(const tchar *format, ...)
115 {
116         int ret;
117         va_list va;
118
119         va_start(va, format);
120         ret = wimlib_vfprintf(stdout, format, va);
121         va_end(va);
122         return ret;
123 }
124
125 int
126 wimlib_fprintf(FILE *fp, const tchar *format, ...)
127 {
128         int ret;
129         va_list va;
130
131         va_start(va, format);
132         ret = wimlib_vfprintf(fp, format, va);
133         va_end(va);
134         return ret;
135 }
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, "[%"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_WRITE]
367                 = T("Failed to write data to a file"),
368         [WIMLIB_ERR_XML]
369                 = T("The XML data of the WIM is invalid"),
370 };
371
372 WIMLIBAPI const tchar *
373 wimlib_get_error_string(enum wimlib_error_code code)
374 {
375         if (code < 0 || code >= ARRAY_LEN(error_strings))
376                 return NULL;
377         else
378                 return error_strings[code];
379 }
380
381
382
383 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
384 void *(*wimlib_malloc_func) (size_t)         = malloc;
385 void  (*wimlib_free_func)   (void *)         = free;
386 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
387
388 void *
389 wimlib_calloc(size_t nmemb, size_t size)
390 {
391         size_t total_size = nmemb * size;
392         void *p = MALLOC(total_size);
393         if (p)
394                 memset(p, 0, total_size);
395         return p;
396 }
397
398 char *
399 wimlib_strdup(const char *str)
400 {
401         size_t size;
402         char *p;
403
404         size = strlen(str);
405         p = MALLOC(size + 1);
406         if (p)
407                 memcpy(p, str, size + 1);
408         return p;
409 }
410
411 #ifdef __WIN32__
412 wchar_t *
413 wimlib_wcsdup(const wchar_t *str)
414 {
415         size_t size;
416         wchar_t *p;
417
418         size = wcslen(str);
419         p = MALLOC((size + 1) * sizeof(wchar_t));
420         if (p)
421                 memcpy(p, str, (size + 1) * sizeof(wchar_t));
422         return p;
423 }
424 #endif
425
426 extern void
427 xml_set_memory_allocator(void *(*malloc_func)(size_t),
428                          void (*free_func)(void *),
429                          void *(*realloc_func)(void *, size_t));
430 #endif
431
432 WIMLIBAPI int
433 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
434                             void (*free_func)(void *),
435                             void *(*realloc_func)(void *, size_t))
436 {
437 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
438         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
439         wimlib_free_func    = free_func    ? free_func    : free;
440         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
441
442         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
443                                  wimlib_realloc_func);
444         return 0;
445 #else
446         ERROR("Cannot set custom memory allocator functions:");
447         ERROR("wimlib was compiled with the --without-custom-memory-allocator "
448               "flag");
449         return WIMLIB_ERR_UNSUPPORTED;
450 #endif
451 }
452
453 static bool seeded = false;
454
455 static void
456 seed_random()
457 {
458         srand(time(NULL) * getpid());
459         seeded = true;
460 }
461
462 /* Fills @n characters pointed to by @p with random alphanumeric characters. */
463 void
464 randomize_char_array_with_alnum(tchar p[], size_t n)
465 {
466         if (!seeded)
467                 seed_random();
468         while (n--) {
469                 int r = rand() % 62;
470                 if (r < 26)
471                         *p++ = r + 'a';
472                 else if (r < 52)
473                         *p++ = r - 26 + 'A';
474                 else
475                         *p++ = r - 52 + '0';
476         }
477 }
478
479 /* Fills @n bytes pointer to by @p with random numbers. */
480 void
481 randomize_byte_array(u8 *p, size_t n)
482 {
483         if (!seeded)
484                 seed_random();
485         while (n--)
486                 *p++ = rand();
487 }
488
489 /* Takes in a path of length @len in @buf, and transforms it into a string for
490  * the path of its parent directory. */
491 void
492 to_parent_name(tchar *buf, size_t len)
493 {
494         ssize_t i = (ssize_t)len - 1;
495         while (i >= 0 && buf[i] == T('/'))
496                 i--;
497         while (i >= 0 && buf[i] != T('/'))
498                 i--;
499         while (i >= 0 && buf[i] == T('/'))
500                 i--;
501         buf[i + 1] = T('\0');
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         const tchar *p = path;
510         while (*p)
511                 p++;
512         p--;
513
514         /* Trailing slashes. */
515         while (1) {
516                 if (p == path - 1)
517                         return T("");
518                 if (*p != T('/'))
519                         break;
520                 p--;
521         }
522
523         while ((p != path - 1) && *p != T('/'))
524                 p--;
525
526         return p + 1;
527 }
528
529 /*
530  * Returns a pointer to the part of @path following the first colon in the last
531  * path component, or NULL if the last path component does not contain a colon.
532  */
533 const tchar *
534 path_stream_name(const tchar *path)
535 {
536         const tchar *base = path_basename(path);
537         const tchar *stream_name = tstrchr(base, T(':'));
538         if (!stream_name)
539                 return NULL;
540         else
541                 return stream_name + 1;
542 }
543
544 /*
545  * Splits a file path into the part before the first '/', or the entire name if
546  * there is no '/', and the part after the first sequence of '/' characters.
547  *
548  * @path:               The file path to split.
549  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
550  *                              first part of the path will be returned.
551  * @return:             A pointer to the next part of the path, after the first
552  *                              sequence of '/', or a pointer to the terminating
553  *                              null byte in the case of a path without any '/'.
554  */
555 const tchar *
556 path_next_part(const tchar *path, size_t *first_part_len_ret)
557 {
558         size_t i;
559         const tchar *next_part;
560
561         i = 0;
562         while (path[i] != T('/') && path[i] != T('\0'))
563                 i++;
564         if (first_part_len_ret)
565                 *first_part_len_ret = i;
566         next_part = &path[i];
567         while (*next_part == T('/'))
568                 next_part++;
569         return next_part;
570 }
571
572 /* Returns the number of components of @path.  */
573 int
574 get_num_path_components(const char *path)
575 {
576         int num_components = 0;
577         while (*path) {
578                 while (*path == '/')
579                         path++;
580                 if (*path)
581                         num_components++;
582                 while (*path && *path != '/')
583                         path++;
584         }
585         return num_components;
586 }
587
588
589 /*
590  * Prints a string.  Printable characters are printed as-is, while unprintable
591  * characters are printed as their octal escape codes.
592  */
593 void
594 print_string(const void *string, size_t len)
595 {
596         const u8 *p = string;
597
598         while (len--) {
599                 if (isprint(*p))
600                         putchar(*p);
601                 else
602                         printf("\\%03hho", *p);
603                 p++;
604         }
605 }
606
607 u64
608 get_wim_timestamp()
609 {
610         struct timeval tv;
611         gettimeofday(&tv, NULL);
612         return timeval_to_wim_timestamp(tv);
613 }
614
615 void
616 wim_timestamp_to_str(u64 timestamp, tchar *buf, size_t len)
617 {
618         struct tm tm;
619         time_t t = wim_timestamp_to_unix(timestamp);
620         gmtime_r(&t, &tm);
621         tstrftime(buf, len, T("%a %b %d %H:%M:%S %Y UTC"), &tm);
622 }