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