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