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