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