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)
51 static size_t utf16le_strlen(const utf16lechar *s)
53 const utf16lechar *p = s;
56 return (p - s) / sizeof(utf16lechar);
59 /* Handle %W for UTF16-LE printing and %U for UTF-8 printing.
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.
65 wimlib_vfprintf(FILE *fp, const char *format, va_list va)
69 for (p = format; *p; p++)
70 if (*p == '%' && (*(p + 1) == 'W' || *(p + 1) == 'U'))
72 return vfprintf(fp, format, va);
76 for (p = format; *p; p++) {
77 if (*p == '%' && (*(p + 1) == 'W' || *(p + 1) == 'U')) {
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,
88 utf8char *ucs = va_arg(va, utf8char*);
89 size_t ucs_nbytes = strlen(ucs);
90 ret = utf8_to_mbs(ucs, ucs_nbytes,
94 ret = fprintf(fp, "???CONVERSION FAILURE???");
96 ret = fprintf(fp, "%s", mbs);
105 if (putc(*p, fp) == EOF)
114 wimlib_printf(const char *format, ...)
119 va_start(va, format);
120 ret = wimlib_vfprintf(stdout, format, va);
126 wimlib_fprintf(FILE *fp, const char *format, ...)
131 va_start(va, format);
132 ret = wimlib_vfprintf(fp, format, va);
137 /* True if wimlib is to print an informational message when an error occurs.
138 * This can be turned off by calling wimlib_set_print_errors(false). */
139 #ifdef ENABLE_ERROR_MESSAGES
141 static bool wimlib_print_errors = false;
144 wimlib_vmsg(const char *tag, const char *format,
145 va_list va, bool perror)
147 if (wimlib_print_errors) {
148 int errno_save = errno;
151 wimlib_vfprintf(stderr, format, va);
152 if (perror && errno_save != 0) {
155 res = strerror_r(errno_save, buf, sizeof(buf));
157 snprintf(buf, sizeof(buf),
158 "unknown error (errno=%d)", errno_save);
160 fprintf(stderr, ": %s", buf);
168 wimlib_error(const char *format, ...)
172 va_start(va, format);
173 wimlib_vmsg("[ERROR] ", format, va, false);
178 wimlib_error_with_errno(const char *format, ...)
182 va_start(va, format);
183 wimlib_vmsg("[ERROR] ", format, va, true);
188 wimlib_warning(const char *format, ...)
192 va_start(va, format);
193 wimlib_vmsg("[WARNING] ", format, va, false);
198 wimlib_warning_with_errno(const char *format, ...)
202 va_start(va, format);
203 wimlib_vmsg("[WARNING] ", format, va, true);
210 wimlib_set_print_errors(bool show_error_messages)
212 #ifdef ENABLE_ERROR_MESSAGES
213 wimlib_print_errors = show_error_messages;
216 if (show_error_messages)
217 return WIMLIB_ERR_UNSUPPORTED;
223 static const mbchar *error_strings[] = {
226 [WIMLIB_ERR_ALREADY_LOCKED]
227 = "The WIM is already locked for writing",
228 [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
229 = "Lookup table is compressed",
230 [WIMLIB_ERR_DECOMPRESSION]
231 = "Failed to decompress compressed data",
232 [WIMLIB_ERR_DELETE_STAGING_DIR]
233 = "Failed to delete staging directory",
234 [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
235 = "The process servicing the mounted WIM has crashed",
237 = "Failed to fork another process",
239 = "An error was returned by fuse_main()",
240 [WIMLIB_ERR_FUSERMOUNT]
241 = "Could not execute the `fusermount' program, or it exited "
242 "with a failure status",
243 [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
244 = "The iconv() function does not seem to work. "
245 "Maybe check to make sure the directory /usr/lib/gconv exists",
246 [WIMLIB_ERR_IMAGE_COUNT]
247 = "Inconsistent image count among the metadata "
248 "resources, the WIM header, and/or the XML data",
249 [WIMLIB_ERR_IMAGE_NAME_COLLISION]
250 = "Tried to add an image with a name that is already in use",
251 [WIMLIB_ERR_INTEGRITY]
252 = "The WIM failed an integrity check",
253 [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
254 = "The capture configuration string was invalid",
255 [WIMLIB_ERR_INVALID_CHUNK_SIZE]
256 = "The WIM is compressed but does not have a chunk "
258 [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
259 = "The WIM is compressed, but is not marked as having LZX or "
260 "XPRESS compression",
261 [WIMLIB_ERR_INVALID_DENTRY]
262 = "A directory entry in the WIM was invalid",
263 [WIMLIB_ERR_INVALID_HEADER_SIZE]
264 = "The WIM header was not 208 bytes",
265 [WIMLIB_ERR_INVALID_IMAGE]
266 = "Tried to select an image that does not exist in the WIM",
267 [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
268 = "The WIM's integrity table is invalid",
269 [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
270 = "An entry in the WIM's lookup table is invalid",
271 [WIMLIB_ERR_INVALID_MULTIBYTE_STRING]
272 = "A string was not valid in the current locale's character encoding",
273 [WIMLIB_ERR_INVALID_OVERLAY]
274 = "Conflicting files in overlay when creating a WIM image",
275 [WIMLIB_ERR_INVALID_PARAM]
276 = "An invalid parameter was given",
277 [WIMLIB_ERR_INVALID_PART_NUMBER]
278 = "The part number or total parts of the WIM is invalid",
279 [WIMLIB_ERR_INVALID_RESOURCE_HASH]
280 = "The SHA1 message digest of a WIM resource did not match the expected value",
281 [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
282 = "A resource entry in the WIM has an invalid size",
283 [WIMLIB_ERR_INVALID_SECURITY_DATA]
284 = "The table of security descriptors in the WIM is invalid",
285 [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
286 = "The version of wimlib that has mounted a WIM image is incompatible with the "
287 "version being used to unmount it",
288 [WIMLIB_ERR_INVALID_UTF8_STRING]
289 = "A string provided as input by the user was not a valid UTF-8 string",
290 [WIMLIB_ERR_INVALID_UTF16_STRING]
291 = "A string in a WIM dentry is not a valid UTF-16LE string",
292 [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
293 = "libxml2 was unable to find a character encoding conversion handler "
296 = "Failed to create a hard or symbolic link when extracting "
297 "a file from the WIM",
299 = "Failed to create a directory",
301 = "Failed to create or use a POSIX message queue",
303 = "Ran out of memory",
305 = "Expected a directory",
306 [WIMLIB_ERR_NOT_A_WIM_FILE]
307 = "The file did not begin with the magic characters that "
308 "identify a WIM file",
309 [WIMLIB_ERR_NO_FILENAME]
310 = "The WIM is not identified with a filename",
312 = "NTFS-3g encountered an error (check errno)",
314 = "Failed to open a file",
316 = "Failed to open a directory",
318 = "Could not read data from a file",
319 [WIMLIB_ERR_READLINK]
320 = "Could not read the target of a symbolic link",
322 = "Could not rename a file",
324 = "Could not re-open the WIM after overwriting it",
325 [WIMLIB_ERR_RESOURCE_ORDER]
326 = "The components of the WIM were arranged in an unexpected order",
327 [WIMLIB_ERR_SPECIAL_FILE]
328 = "Encountered a special file that cannot be archived",
329 [WIMLIB_ERR_SPLIT_INVALID]
330 = "The WIM is part of an invalid split WIM",
331 [WIMLIB_ERR_SPLIT_UNSUPPORTED]
332 = "The WIM is part of a split WIM, which is not supported for this operation",
334 = "Could not read the metadata for a file or directory",
336 = "Timed out while waiting for a message to arrive from another process",
337 [WIMLIB_ERR_UNICODE_STRING_NOT_REPRESENTABLE]
338 = "A Unicode string could not be represented in the current locale's encoding",
339 [WIMLIB_ERR_UNKNOWN_VERSION]
340 = "The WIM file is marked with an unknown version number",
341 [WIMLIB_ERR_UNSUPPORTED]
342 = "The requested operation is unsupported",
344 = "Failed to write data to a file",
346 = "The XML data of the WIM is invalid",
349 WIMLIBAPI const mbchar *
350 wimlib_get_error_string(enum wimlib_error_code code)
352 if (code < 0 || code >= ARRAY_LEN(error_strings))
355 return error_strings[code];
360 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
361 void *(*wimlib_malloc_func) (size_t) = malloc;
362 void (*wimlib_free_func) (void *) = free;
363 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
366 wimlib_calloc(size_t nmemb, size_t size)
368 size_t total_size = nmemb * size;
369 void *p = MALLOC(total_size);
371 memset(p, 0, total_size);
376 wimlib_strdup(const char *str)
382 p = MALLOC(size + 1);
384 memcpy(p, str, size + 1);
389 xml_set_memory_allocator(void *(*malloc_func)(size_t),
390 void (*free_func)(void *),
391 void *(*realloc_func)(void *, size_t));
395 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
396 void (*free_func)(void *),
397 void *(*realloc_func)(void *, size_t))
399 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
400 wimlib_malloc_func = malloc_func ? malloc_func : malloc;
401 wimlib_free_func = free_func ? free_func : free;
402 wimlib_realloc_func = realloc_func ? realloc_func : realloc;
404 xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
405 wimlib_realloc_func);
408 ERROR("Cannot set custom memory allocator functions:");
409 ERROR("wimlib was compiled with the --without-custom-memory-allocator "
411 return WIMLIB_ERR_UNSUPPORTED;
415 static bool seeded = false;
420 srand(time(NULL) * getpid());
424 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
426 randomize_char_array_with_alnum(char p[], size_t n)
441 /* Fills @n bytes pointer to by @p with random numbers. */
443 randomize_byte_array(u8 *p, size_t n)
451 /* Takes in a path of length @len in @buf, and transforms it into a string for
452 * the path of its parent directory. */
454 to_parent_name(char buf[], size_t len)
456 ssize_t i = (ssize_t)len - 1;
457 while (i >= 0 && buf[i] == '/')
459 while (i >= 0 && buf[i] != '/')
461 while (i >= 0 && buf[i] == '/')
466 /* Like the basename() function, but does not modify @path; it just returns a
469 path_basename(const char *path)
471 const char *p = path;
476 /* Trailing slashes. */
485 while ((p != path - 1) && *p != '/')
492 * Returns a pointer to the part of @path following the first colon in the last
493 * path component, or NULL if the last path component does not contain a colon.
496 path_stream_name(const char *path)
498 const char *base = path_basename(path);
499 const char *stream_name = strchr(base, ':');
503 return stream_name + 1;
507 * Splits a file path into the part before the first '/', or the entire name if
508 * there is no '/', and the part after the first sequence of '/' characters.
510 * @path: The file path to split.
511 * @first_part_len_ret: A pointer to a `size_t' into which the length of the
512 * first part of the path will be returned.
513 * @return: A pointer to the next part of the path, after the first
514 * sequence of '/', or a pointer to the terminating
515 * null byte in the case of a path without any '/'.
518 path_next_part(const char *path, size_t *first_part_len_ret)
521 const char *next_part;
524 while (path[i] != '/' && path[i] != '\0')
526 if (first_part_len_ret)
527 *first_part_len_ret = i;
528 next_part = &path[i];
529 while (*next_part == '/')
534 /* Returns the number of components of @path. */
536 get_num_path_components(const char *path)
538 int num_components = 0;
544 while (*path && *path != '/')
547 return num_components;
552 * Prints a string. Printable characters are printed as-is, while unprintable
553 * characters are printed as their octal escape codes.
556 print_string(const void *string, size_t len)
558 const u8 *p = string;
564 printf("\\%03hho", *p);
573 gettimeofday(&tv, NULL);
574 return timeval_to_wim_timestamp(tv);
578 wim_timestamp_to_str(u64 timestamp, char *buf, size_t len)
581 time_t t = wim_timestamp_to_unix(timestamp);
583 strftime(buf, len, "%a %b %d %H:%M:%S %Y UTC", &tm);