]> wimlib.net Git - wimlib/blob - src/util.c
verify_swm_set(): Decrease scope of parts_to_swms
[wimlib] / src / util.c
1 /*
2  * util.c
3  */
4
5 /*
6  * Copyright (C) 2012 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                         fputs(buf, stderr);
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_IMAGE_COUNT]
141                 = "Inconsistent image count among the metadata "
142                         "resources, the WIM header, and/or the XML data",
143         [WIMLIB_ERR_IMAGE_NAME_COLLISION]
144                 = "Tried to add an image with a name that is already in use",
145         [WIMLIB_ERR_INTEGRITY]
146                 = "The WIM failed an integrity check",
147         [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
148                 = "The capture configuration string was invalid",
149         [WIMLIB_ERR_INVALID_CHUNK_SIZE]
150                 = "The WIM is compressed but does not have a chunk "
151                         "size of 32768",
152         [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
153                 = "The WIM is compressed, but is not marked as having LZX or "
154                         "XPRESS compression",
155         [WIMLIB_ERR_INVALID_DENTRY]
156                 = "A directory entry in the WIM was invalid",
157         [WIMLIB_ERR_INVALID_HEADER_SIZE]
158                 = "The WIM header was not 208 bytes",
159         [WIMLIB_ERR_INVALID_IMAGE]
160                 = "Tried to select an image that does not exist in the WIM",
161         [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
162                 = "The WIM's integrity table is invalid",
163         [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
164                 = "An entry in the WIM's lookup table is invalid",
165         [WIMLIB_ERR_INVALID_PARAM]
166                 = "An invalid parameter was given",
167         [WIMLIB_ERR_INVALID_PART_NUMBER]
168                 = "The part number or total parts of the WIM is invalid",
169         [WIMLIB_ERR_INVALID_RESOURCE_HASH]
170                 = "The SHA1 message digest of a WIM resource did not match the expected value",
171         [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
172                 = "The iconv() function does not seem to work. "
173                   "Maybe check to make sure the directory /usr/lib/gconv exists",
174         [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
175                 = "A resource entry in the WIM has an invalid size",
176         [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
177                 = "The version of wimlib that has mounted a WIM image is incompatible with the "
178                   "version being used to unmount it",
179         [WIMLIB_ERR_INVALID_UTF8_STRING]
180                 = "A string provided as input by the user was not a valid UTF-8 string",
181         [WIMLIB_ERR_INVALID_UTF16_STRING]
182                 = "A string in a WIM dentry is not a valid UTF-16LE string",
183         [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
184                 = "libxml2 was unable to find a character encoding conversion handler "
185                   "for UTF-16LE",
186         [WIMLIB_ERR_LINK]
187                 = "Failed to create a hard or symbolic link when extracting "
188                         "a file from the WIM",
189         [WIMLIB_ERR_MKDIR]
190                 = "Failed to create a directory",
191         [WIMLIB_ERR_MQUEUE]
192                 = "Failed to create or use a POSIX message queue",
193         [WIMLIB_ERR_NOMEM]
194                 = "Ran out of memory",
195         [WIMLIB_ERR_NOTDIR]
196                 = "Expected a directory",
197         [WIMLIB_ERR_NOT_A_WIM_FILE]
198                 = "The file did not begin with the magic characters that "
199                         "identify a WIM file",
200         [WIMLIB_ERR_NO_FILENAME]
201                 = "The WIM is not identified with a filename",
202         [WIMLIB_ERR_NTFS_3G]
203                 = "NTFS-3g encountered an error (check errno)",
204         [WIMLIB_ERR_OPEN]
205                 = "Failed to open a file",
206         [WIMLIB_ERR_OPENDIR]
207                 = "Failed to open a directory",
208         [WIMLIB_ERR_READ]
209                 = "Could not read data from a file",
210         [WIMLIB_ERR_READLINK]
211                 = "Could not read the target of a symbolic link",
212         [WIMLIB_ERR_RENAME]
213                 = "Could not rename a file",
214         [WIMLIB_ERR_REOPEN]
215                 = "Could not re-open the WIM after overwriting it",
216         [WIMLIB_ERR_RESOURCE_ORDER]
217                 = "The components of the WIM were arranged in an unexpected order",
218         [WIMLIB_ERR_SPECIAL_FILE]
219                 = "Encountered a special file that cannot be archived",
220         [WIMLIB_ERR_SPLIT_INVALID]
221                 = "The WIM is part of an invalid split WIM",
222         [WIMLIB_ERR_SPLIT_UNSUPPORTED]
223                 = "The WIM is part of a split WIM, which is not supported for this operation",
224         [WIMLIB_ERR_STAT]
225                 = "Could not read the metadata for a file or directory",
226         [WIMLIB_ERR_UNKNOWN_VERSION]
227                 = "The WIM file is marked with an unknown version number",
228         [WIMLIB_ERR_UNSUPPORTED]
229                 = "The requested operation is unsupported",
230         [WIMLIB_ERR_WRITE]
231                 = "Failed to write data to a file",
232         [WIMLIB_ERR_XML]
233                 = "The XML data of the WIM is invalid",
234 };
235
236 WIMLIBAPI const char *wimlib_get_error_string(enum wimlib_error_code code)
237 {
238         if (code < WIMLIB_ERR_SUCCESS || code > WIMLIB_ERR_XML)
239                 return NULL;
240         else
241                 return error_strings[code];
242 }
243
244
245
246 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
247 void *(*wimlib_malloc_func) (size_t)         = malloc;
248 void  (*wimlib_free_func)   (void *)         = free;
249 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
250
251 void *wimlib_calloc(size_t nmemb, size_t size)
252 {
253         size_t total_size = nmemb * size;
254         void *p = MALLOC(total_size);
255         if (p)
256                 memset(p, 0, total_size);
257         return p;
258 }
259
260 char *wimlib_strdup(const char *str)
261 {
262         size_t size;
263         char *p;
264
265         size = strlen(str);
266         p = MALLOC(size + 1);
267         if (p)
268                 memcpy(p, str, size + 1);
269         return p;
270 }
271
272 extern void xml_set_memory_allocator(void *(*malloc_func)(size_t),
273                                    void (*free_func)(void *),
274                                    void *(*realloc_func)(void *, size_t));
275 #endif
276
277 WIMLIBAPI int wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
278                                            void (*free_func)(void *),
279                                            void *(*realloc_func)(void *, size_t))
280 {
281 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
282         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
283         wimlib_free_func    = free_func    ? free_func    : free;
284         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
285
286         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
287                                  wimlib_realloc_func);
288         return 0;
289 #else
290         ERROR("Cannot set custom memory allocator functions:");
291         ERROR("wimlib was compiled with the --without-custom-memory-allocator "
292               "flag");
293         return WIMLIB_ERR_UNSUPPORTED;
294 #endif
295 }
296
297 static bool seeded = false;
298
299 static void seed_random()
300 {
301         srand(time(NULL) * getpid());
302         seeded = true;
303 }
304
305 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
306 void randomize_char_array_with_alnum(char p[], size_t n)
307 {
308         if (!seeded)
309                 seed_random();
310         while (n--) {
311                 int r = rand() % 62;
312                 if (r < 26)
313                         *p++ = r + 'a';
314                 else if (r < 52)
315                         *p++ = r - 26 + 'A';
316                 else
317                         *p++ = r - 52 + '0';
318         }
319 }
320
321 /* Fills @n bytes pointer to by @p with random numbers. */
322 void randomize_byte_array(u8 *p, size_t n)
323 {
324         if (!seeded)
325                 seed_random();
326         while (n--)
327                 *p++ = rand();
328 }
329
330 /* Takes in a path of length @len in @buf, and transforms it into a string for
331  * the path of its parent directory. */
332 void to_parent_name(char buf[], size_t len)
333 {
334         ssize_t i = (ssize_t)len - 1;
335         while (i >= 0 && buf[i] == '/')
336                 i--;
337         while (i >= 0 && buf[i] != '/')
338                 i--;
339         while (i >= 0 && buf[i] == '/')
340                 i--;
341         buf[i + 1] = '\0';
342 }
343
344 /* Like the basename() function, but does not modify @path; it just returns a
345  * pointer to it. */
346 const char *path_basename(const char *path)
347 {
348         const char *p = path;
349         while (*p)
350                 p++;
351         p--;
352
353         /* Trailing slashes. */
354         while (1) {
355                 if (p == path - 1)
356                         return "";
357                 if (*p != '/')
358                         break;
359                 p--;
360         }
361
362         while ((p != path - 1) && *p != '/')
363                 p--;
364
365         return p + 1;
366 }
367
368 /*
369  * Returns a pointer to the part of @path following the first colon in the last
370  * path component, or NULL if the last path component does not contain a colon.
371  */
372 const char *path_stream_name(const char *path)
373 {
374         const char *base = path_basename(path);
375         const char *stream_name = strchr(base, ':');
376         if (!stream_name)
377                 return NULL;
378         else
379                 return stream_name + 1;
380 }
381
382 /*
383  * Splits a file path into the part before the first '/', or the entire name if
384  * there is no '/', and the part after the first sequence of '/' characters.
385  *
386  * @path:               The file path to split.
387  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
388  *                              first part of the path will be returned.
389  * @return:             A pointer to the next part of the path, after the first
390  *                              sequence of '/', or a pointer to the terminating
391  *                              null byte in the case of a path without any '/'.
392  */
393 const char *path_next_part(const char *path, size_t *first_part_len_ret)
394 {
395         size_t i;
396         const char *next_part;
397
398         i = 0;
399         while (path[i] != '/' && path[i] != '\0')
400                 i++;
401         if (first_part_len_ret)
402                 *first_part_len_ret = i;
403         next_part = &path[i];
404         while (*next_part == '/')
405                 next_part++;
406         return next_part;
407 }
408
409 /* Returns the number of components of @path.  */
410 int get_num_path_components(const char *path)
411 {
412         int num_components = 0;
413         while (*path) {
414                 while (*path == '/')
415                         path++;
416                 if (*path)
417                         num_components++;
418                 while (*path && *path != '/')
419                         path++;
420         }
421         return num_components;
422 }
423
424
425 /*
426  * Prints a string.  Printable characters are printed as-is, while unprintable
427  * characters are printed as their octal escape codes.
428  */
429 void print_string(const void *string, size_t len)
430 {
431         const u8 *p = string;
432
433         while (len--) {
434                 if (isprint(*p))
435                         putchar(*p);
436                 else
437                         printf("\\%03hho", *p);
438                 p++;
439         }
440 }
441
442 u64 get_wim_timestamp()
443 {
444         struct timeval tv;
445         gettimeofday(&tv, NULL);
446         return timeval_to_wim_timestamp(&tv);
447 }
448
449 void wim_timestamp_to_str(u64 timestamp, char *buf, size_t len)
450 {
451         struct tm tm;
452         time_t t = wim_timestamp_to_unix(timestamp);
453         gmtime_r(&t, &tm);
454         strftime(buf, len, "%a %b %d %H:%M:%S %Y UTC", &tm);
455 }