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