6 * Copyright (C) 2012, 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
26 #define MINGW_HAS_SECURE_API
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
35 #include "wimlib_internal.h"
36 #include "endianness.h"
37 #include "timestamp.h"
44 #include <unistd.h> /* for getpid() */
46 /* Windoze compatibility */
48 # define strerror_r(errnum, buf, bufsize) strerror_s(buf, bufsize, errnum)
52 utf16le_strlen(const utf16lechar *s)
54 const utf16lechar *p = s;
57 return (p - s) * sizeof(utf16lechar);
60 /* Handle %W for UTF16-LE printing and %U for UTF-8 printing.
62 * TODO: this is not yet done properly--- it's assumed that if the format string
63 * contains %W and/or %U, then it contains no other format specifiers.
66 wimlib_vfprintf(FILE *fp, const char *format, va_list va)
70 for (p = format; *p; p++)
71 if (*p == '%' && (*(p + 1) == 'W' || *(p + 1) == 'U'))
73 return vfprintf(fp, format, va);
77 for (p = format; *p; p++) {
78 if (*p == '%' && (*(p + 1) == 'W' || *(p + 1) == 'U')) {
83 if (*(p + 1) == 'W') {
84 utf16lechar *ucs = va_arg(va, utf16lechar*);
85 size_t ucs_nbytes = utf16le_strlen(ucs);
86 ret = utf16le_to_mbs(ucs, ucs_nbytes,
89 utf8char *ucs = va_arg(va, utf8char*);
90 size_t ucs_nbytes = strlen(ucs);
91 ret = utf8_to_mbs(ucs, ucs_nbytes,
95 ret = fprintf(fp, "??????");
97 ret = fprintf(fp, "%s", mbs);
106 if (putc(*p, fp) == EOF)
115 wimlib_printf(const char *format, ...)
120 va_start(va, format);
121 ret = wimlib_vfprintf(stdout, format, va);
127 wimlib_fprintf(FILE *fp, const char *format, ...)
132 va_start(va, format);
133 ret = wimlib_vfprintf(fp, format, va);
138 #if defined(ENABLE_ERROR_MESSAGES) || defined(ENABLE_DEBUG)
140 wimlib_vmsg(const char *tag, const char *format,
141 va_list va, bool perror)
144 if (wimlib_print_errors) {
146 int errno_save = errno;
149 wimlib_vfprintf(stderr, format, va);
150 if (perror && errno_save != 0) {
153 res = strerror_r(errno_save, buf, sizeof(buf));
155 snprintf(buf, sizeof(buf),
156 "unknown error (errno=%d)", errno_save);
158 fprintf(stderr, ": %s", buf);
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;
175 wimlib_error(const char *format, ...)
179 va_start(va, format);
180 wimlib_vmsg("[ERROR] ", format, va, false);
185 wimlib_error_with_errno(const char *format, ...)
189 va_start(va, format);
190 wimlib_vmsg("[ERROR] ", format, va, true);
195 wimlib_warning(const char *format, ...)
199 va_start(va, format);
200 wimlib_vmsg("[WARNING] ", format, va, false);
205 wimlib_warning_with_errno(const char *format, ...)
209 va_start(va, format);
210 wimlib_vmsg("[WARNING] ", format, va, true);
217 void wimlib_debug(const char *file, int line, const char *func,
218 const char *format, ...)
222 char buf[strlen(file) + strlen(func) + 30];
224 sprintf(buf, "[%s %d] %s(): ", file, line, func);
225 va_start(va, format);
226 wimlib_vmsg(buf, format, va, false);
232 wimlib_set_print_errors(bool show_error_messages)
234 #ifdef ENABLE_ERROR_MESSAGES
235 wimlib_print_errors = show_error_messages;
238 if (show_error_messages)
239 return WIMLIB_ERR_UNSUPPORTED;
245 static const mbchar *error_strings[] = {
248 [WIMLIB_ERR_ALREADY_LOCKED]
249 = "The WIM is already locked for writing",
250 [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
251 = "Lookup table is compressed",
252 [WIMLIB_ERR_DECOMPRESSION]
253 = "Failed to decompress compressed data",
254 [WIMLIB_ERR_DELETE_STAGING_DIR]
255 = "Failed to delete staging directory",
256 [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
257 = "The process servicing the mounted WIM has crashed",
259 = "Failed to fork another process",
261 = "An error was returned by fuse_main()",
262 [WIMLIB_ERR_FUSERMOUNT]
263 = "Could not execute the `fusermount' program, or it exited "
264 "with a failure status",
265 [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
266 = "The iconv() function does not seem to work. "
267 "Maybe check to make sure the directory /usr/lib/gconv exists",
268 [WIMLIB_ERR_IMAGE_COUNT]
269 = "Inconsistent image count among the metadata "
270 "resources, the WIM header, and/or the XML data",
271 [WIMLIB_ERR_IMAGE_NAME_COLLISION]
272 = "Tried to add an image with a name that is already in use",
273 [WIMLIB_ERR_INTEGRITY]
274 = "The WIM failed an integrity check",
275 [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
276 = "The capture configuration string was invalid",
277 [WIMLIB_ERR_INVALID_CHUNK_SIZE]
278 = "The WIM is compressed but does not have a chunk "
280 [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
281 = "The WIM is compressed, but is not marked as having LZX or "
282 "XPRESS compression",
283 [WIMLIB_ERR_INVALID_DENTRY]
284 = "A directory entry in the WIM was invalid",
285 [WIMLIB_ERR_INVALID_HEADER_SIZE]
286 = "The WIM header was not 208 bytes",
287 [WIMLIB_ERR_INVALID_IMAGE]
288 = "Tried to select an image that does not exist in the WIM",
289 [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
290 = "The WIM's integrity table is invalid",
291 [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
292 = "An entry in the WIM's lookup table is invalid",
293 [WIMLIB_ERR_INVALID_MULTIBYTE_STRING]
294 = "A string was not valid in the current locale's character encoding",
295 [WIMLIB_ERR_INVALID_OVERLAY]
296 = "Conflicting files in overlay when creating a WIM image",
297 [WIMLIB_ERR_INVALID_PARAM]
298 = "An invalid parameter was given",
299 [WIMLIB_ERR_INVALID_PART_NUMBER]
300 = "The part number or total parts of the WIM is invalid",
301 [WIMLIB_ERR_INVALID_RESOURCE_HASH]
302 = "The SHA1 message digest of a WIM resource did not match the expected value",
303 [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
304 = "A resource entry in the WIM has an invalid size",
305 [WIMLIB_ERR_INVALID_SECURITY_DATA]
306 = "The table of security descriptors in the WIM is invalid",
307 [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
308 = "The version of wimlib that has mounted a WIM image is incompatible with the "
309 "version being used to unmount it",
310 [WIMLIB_ERR_INVALID_UTF8_STRING]
311 = "A string provided as input by the user was not a valid UTF-8 string",
312 [WIMLIB_ERR_INVALID_UTF16_STRING]
313 = "A string in a WIM dentry is not a valid UTF-16LE string",
314 [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
315 = "libxml2 was unable to find a character encoding conversion handler "
318 = "Failed to create a hard or symbolic link when extracting "
319 "a file from the WIM",
321 = "Failed to create a directory",
323 = "Failed to create or use a POSIX message queue",
325 = "Ran out of memory",
327 = "Expected a directory",
328 [WIMLIB_ERR_NOT_A_WIM_FILE]
329 = "The file did not begin with the magic characters that "
330 "identify a WIM file",
331 [WIMLIB_ERR_NO_FILENAME]
332 = "The WIM is not identified with a filename",
334 = "NTFS-3g encountered an error (check errno)",
336 = "Failed to open a file",
338 = "Failed to open a directory",
340 = "Could not read data from a file",
341 [WIMLIB_ERR_READLINK]
342 = "Could not read the target of a symbolic link",
344 = "Could not rename a file",
346 = "Could not re-open the WIM after overwriting it",
347 [WIMLIB_ERR_RESOURCE_ORDER]
348 = "The components of the WIM were arranged in an unexpected order",
349 [WIMLIB_ERR_SPECIAL_FILE]
350 = "Encountered a special file that cannot be archived",
351 [WIMLIB_ERR_SPLIT_INVALID]
352 = "The WIM is part of an invalid split WIM",
353 [WIMLIB_ERR_SPLIT_UNSUPPORTED]
354 = "The WIM is part of a split WIM, which is not supported for this operation",
356 = "Could not read the metadata for a file or directory",
358 = "Timed out while waiting for a message to arrive from another process",
359 [WIMLIB_ERR_UNICODE_STRING_NOT_REPRESENTABLE]
360 = "A Unicode string could not be represented in the current locale's encoding",
361 [WIMLIB_ERR_UNKNOWN_VERSION]
362 = "The WIM file is marked with an unknown version number",
363 [WIMLIB_ERR_UNSUPPORTED]
364 = "The requested operation is unsupported",
366 = "Failed to write data to a file",
368 = "The XML data of the WIM is invalid",
371 WIMLIBAPI const mbchar *
372 wimlib_get_error_string(enum wimlib_error_code code)
374 if (code < 0 || code >= ARRAY_LEN(error_strings))
377 return error_strings[code];
382 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
383 void *(*wimlib_malloc_func) (size_t) = malloc;
384 void (*wimlib_free_func) (void *) = free;
385 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
388 wimlib_calloc(size_t nmemb, size_t size)
390 size_t total_size = nmemb * size;
391 void *p = MALLOC(total_size);
393 memset(p, 0, total_size);
398 wimlib_strdup(const char *str)
404 p = MALLOC(size + 1);
406 memcpy(p, str, size + 1);
411 xml_set_memory_allocator(void *(*malloc_func)(size_t),
412 void (*free_func)(void *),
413 void *(*realloc_func)(void *, size_t));
417 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
418 void (*free_func)(void *),
419 void *(*realloc_func)(void *, size_t))
421 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
422 wimlib_malloc_func = malloc_func ? malloc_func : malloc;
423 wimlib_free_func = free_func ? free_func : free;
424 wimlib_realloc_func = realloc_func ? realloc_func : realloc;
426 xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
427 wimlib_realloc_func);
430 ERROR("Cannot set custom memory allocator functions:");
431 ERROR("wimlib was compiled with the --without-custom-memory-allocator "
433 return WIMLIB_ERR_UNSUPPORTED;
437 static bool seeded = false;
442 srand(time(NULL) * getpid());
446 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
448 randomize_char_array_with_alnum(char p[], size_t n)
463 /* Fills @n bytes pointer to by @p with random numbers. */
465 randomize_byte_array(u8 *p, size_t n)
473 /* Takes in a path of length @len in @buf, and transforms it into a string for
474 * the path of its parent directory. */
476 to_parent_name(char buf[], size_t len)
478 ssize_t i = (ssize_t)len - 1;
479 while (i >= 0 && buf[i] == '/')
481 while (i >= 0 && buf[i] != '/')
483 while (i >= 0 && buf[i] == '/')
488 /* Like the basename() function, but does not modify @path; it just returns a
491 path_basename(const char *path)
493 const char *p = path;
498 /* Trailing slashes. */
507 while ((p != path - 1) && *p != '/')
514 * Returns a pointer to the part of @path following the first colon in the last
515 * path component, or NULL if the last path component does not contain a colon.
518 path_stream_name(const char *path)
520 const char *base = path_basename(path);
521 const char *stream_name = strchr(base, ':');
525 return stream_name + 1;
529 * Splits a file path into the part before the first '/', or the entire name if
530 * there is no '/', and the part after the first sequence of '/' characters.
532 * @path: The file path to split.
533 * @first_part_len_ret: A pointer to a `size_t' into which the length of the
534 * first part of the path will be returned.
535 * @return: A pointer to the next part of the path, after the first
536 * sequence of '/', or a pointer to the terminating
537 * null byte in the case of a path without any '/'.
540 path_next_part(const char *path, size_t *first_part_len_ret)
543 const char *next_part;
546 while (path[i] != '/' && path[i] != '\0')
548 if (first_part_len_ret)
549 *first_part_len_ret = i;
550 next_part = &path[i];
551 while (*next_part == '/')
556 /* Returns the number of components of @path. */
558 get_num_path_components(const char *path)
560 int num_components = 0;
566 while (*path && *path != '/')
569 return num_components;
574 * Prints a string. Printable characters are printed as-is, while unprintable
575 * characters are printed as their octal escape codes.
578 print_string(const void *string, size_t len)
580 const u8 *p = string;
586 printf("\\%03hho", *p);
595 gettimeofday(&tv, NULL);
596 return timeval_to_wim_timestamp(tv);
600 wim_timestamp_to_str(u64 timestamp, char *buf, size_t len)
603 time_t t = wim_timestamp_to_unix(timestamp);
605 strftime(buf, len, "%a %b %d %H:%M:%S %Y UTC", &tm);