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() */
47 utf16le_strlen(const utf16lechar *s)
49 const utf16lechar *p = s;
52 return (p - s) * sizeof(utf16lechar);
55 /* Handle %W for UTF16-LE printing and %U for UTF-8 printing.
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.
61 wimlib_vfprintf(FILE *fp, const tchar *format, va_list va)
65 for (p = format; *p; p++)
66 if (*p == '%' && (*(p + 1) == T('W') || *(p + 1) == T('U')))
68 return tvfprintf(fp, format, va);
75 for (p = format; *p; p++) {
76 if (*p == T('%') && (*(p + 1) == T('W') || *(p + 1) == T('U'))) {
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,
87 utf8char *ucs = va_arg(va, utf8char*);
88 size_t ucs_nbytes = strlen(ucs);
89 ret = utf8_to_mbs(ucs, ucs_nbytes,
93 ret = tfprintf(fp, T("??????"));
95 ret = tfprintf(fp, T("%s"), mbs);
104 if (putc(*p, fp) == EOF)
114 wimlib_printf(const tchar *format, ...)
119 va_start(va, format);
120 ret = wimlib_vfprintf(stdout, format, va);
126 wimlib_fprintf(FILE *fp, const tchar *format, ...)
131 va_start(va, format);
132 ret = wimlib_vfprintf(fp, format, va);
137 #if defined(ENABLE_ERROR_MESSAGES) || defined(ENABLE_DEBUG)
139 wimlib_vmsg(const tchar *tag, const tchar *format,
140 va_list va, bool perror)
143 if (wimlib_print_errors) {
145 int errno_save = errno;
148 wimlib_vfprintf(stderr, format, va);
149 if (perror && errno_save != 0) {
152 res = tstrerror_r(errno_save, buf, sizeof(buf));
155 T("unknown error (errno=%d)"),
158 tfprintf(stderr, T(": %"TS), buf);
160 tputc(T('\n'), stderr);
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 tchar *format, ...)
179 va_start(va, format);
180 wimlib_vmsg(T("[ERROR] "), format, va, false);
185 wimlib_error_with_errno(const tchar *format, ...)
189 va_start(va, format);
190 wimlib_vmsg(T("[ERROR] "), format, va, true);
195 wimlib_warning(const tchar *format, ...)
199 va_start(va, format);
200 wimlib_vmsg(T("[WARNING] "), format, va, false);
205 wimlib_warning_with_errno(const tchar *format, ...)
209 va_start(va, format);
210 wimlib_vmsg(T("[WARNING] "), format, va, true);
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, ...)
222 tchar buf[tstrlen(file) + strlen(func) + 30];
224 tsprintf(buf, "[%"TS" %d] %s(): ", file, line, func);
226 va_start(va, format);
227 wimlib_vmsg(buf, format, va, false);
233 wimlib_set_print_errors(bool show_error_messages)
235 #ifdef ENABLE_ERROR_MESSAGES
236 wimlib_print_errors = show_error_messages;
239 if (show_error_messages)
240 return WIMLIB_ERR_UNSUPPORTED;
246 static const tchar *error_strings[] = {
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"),
260 = T("Failed to fork another process"),
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 "
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 "
319 = T("Failed to create a hard or symbolic link when extracting "
320 "a file from the WIM"),
322 = T("Failed to create a directory"),
324 = T("Failed to create or use a POSIX message queue"),
326 = T("Ran out of memory"),
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"),
335 = T("NTFS-3g encountered an error (check errno)"),
337 = T("Failed to open a file"),
339 = T("Failed to open a directory"),
341 = T("Could not read data from a file"),
342 [WIMLIB_ERR_READLINK]
343 = T("Could not read the target of a symbolic link"),
345 = T("Could not rename a file"),
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"),
357 = T("Could not read the metadata for a file or directory"),
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"),
367 = T("Failed to write data to a file"),
369 = T("The XML data of the WIM is invalid"),
372 WIMLIBAPI const tchar *
373 wimlib_get_error_string(enum wimlib_error_code code)
375 if (code < 0 || code >= ARRAY_LEN(error_strings))
378 return error_strings[code];
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;
389 wimlib_calloc(size_t nmemb, size_t size)
391 size_t total_size = nmemb * size;
392 void *p = MALLOC(total_size);
394 memset(p, 0, total_size);
399 wimlib_strdup(const char *str)
405 p = MALLOC(size + 1);
407 memcpy(p, str, size + 1);
413 wimlib_wcsdup(const wchar_t *str)
419 p = MALLOC((size + 1) * sizeof(wchar_t));
421 memcpy(p, str, (size + 1) * sizeof(wchar_t));
427 xml_set_memory_allocator(void *(*malloc_func)(size_t),
428 void (*free_func)(void *),
429 void *(*realloc_func)(void *, size_t));
433 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
434 void (*free_func)(void *),
435 void *(*realloc_func)(void *, size_t))
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;
442 xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
443 wimlib_realloc_func);
446 ERROR("Cannot set custom memory allocator functions:");
447 ERROR("wimlib was compiled with the --without-custom-memory-allocator "
449 return WIMLIB_ERR_UNSUPPORTED;
453 static bool seeded = false;
458 srand(time(NULL) * getpid());
462 /* Fills @n characters pointed to by @p with random alphanumeric characters. */
464 randomize_char_array_with_alnum(tchar p[], size_t n)
479 /* Fills @n bytes pointer to by @p with random numbers. */
481 randomize_byte_array(u8 *p, size_t n)
489 /* Takes in a path of length @len in @buf, and transforms it into a string for
490 * the path of its parent directory. */
492 to_parent_name(tchar *buf, size_t len)
494 ssize_t i = (ssize_t)len - 1;
495 while (i >= 0 && buf[i] == T('/'))
497 while (i >= 0 && buf[i] != T('/'))
499 while (i >= 0 && buf[i] == T('/'))
501 buf[i + 1] = T('\0');
505 path_basename_with_len(const tchar *path, size_t len)
507 const tchar *p = &path[len] - 1;
509 /* Trailing slashes. */
518 while ((p != path - 1) && *p != T('/'))
524 /* Like the basename() function, but does not modify @path; it just returns a
527 path_basename(const tchar *path)
529 return path_basename_with_len(path, tstrlen(path));
533 * Returns a pointer to the part of @path following the first colon in the last
534 * path component, or NULL if the last path component does not contain a colon.
537 path_stream_name(const tchar *path)
539 const tchar *base = path_basename(path);
540 const tchar *stream_name = tstrchr(base, T(':'));
544 return stream_name + 1;
548 * Splits a file path into the part before the first '/', or the entire name if
549 * there is no '/', and the part after the first sequence of '/' characters.
551 * @path: The file path to split.
552 * @first_part_len_ret: A pointer to a `size_t' into which the length of the
553 * first part of the path will be returned.
554 * @return: A pointer to the next part of the path, after the first
555 * sequence of '/', or a pointer to the terminating
556 * null byte in the case of a path without any '/'.
559 path_next_part(const tchar *path, size_t *first_part_len_ret)
562 const tchar *next_part;
565 while (path[i] != T('/') && path[i] != T('\0'))
567 if (first_part_len_ret)
568 *first_part_len_ret = i;
569 next_part = &path[i];
570 while (*next_part == T('/'))
575 /* Returns the number of components of @path. */
577 get_num_path_components(const char *path)
579 int num_components = 0;
585 while (*path && *path != '/')
588 return num_components;
593 * Prints a string. Printable characters are printed as-is, while unprintable
594 * characters are printed as their octal escape codes.
597 print_string(const void *string, size_t len)
599 const u8 *p = string;
605 printf("\\%03hho", *p);
614 gettimeofday(&tv, NULL);
615 return timeval_to_wim_timestamp(tv);
619 wim_timestamp_to_str(u64 timestamp, tchar *buf, size_t len)
622 time_t t = wim_timestamp_to_unix(timestamp);
624 tstrftime(buf, len, T("%a %b %d %H:%M:%S %Y UTC"), &tm);