]> wimlib.net Git - wimlib/blob - src/util.c
Print names of dentries in split link groups when in debug mode
[wimlib] / src / util.c
1 /*
2  * util.c
3  */
4
5 /*
6  * Copyright (C) 2010 Carl Thijssen
7  * Copyright (C) 2012 Eric Biggers
8  *
9  * This file is part of wimlib, a library for working with WIM files.
10  *
11  * wimlib is free software; you can redistribute it and/or modify it under the
12  * terms of the GNU Lesser General Public License as published by the Free
13  * Software Foundation; either version 2.1 of the License, or (at your option)
14  * any later version.
15  *
16  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
17  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with wimlib; if not, see http://www.gnu.org/licenses/.
23  */
24
25 #include "wimlib_internal.h"
26 #include "endianness.h"
27 #include "sha1.h"
28 #include "timestamp.h"
29 #include <sys/time.h>
30
31
32 #include <iconv.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <stdlib.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <errno.h>
39
40 /* True if wimlib is to print an informational message when an error occurs.
41  * This can be turned off by calling wimlib_set_print_errors(false). */
42 #ifdef ENABLE_ERROR_MESSAGES
43 #include <stdarg.h>
44 bool __wimlib_print_errors = false;
45
46 void wimlib_error(const char *format, ...)
47 {
48         if (__wimlib_print_errors) {
49                 va_list va;
50                 int errno_save;
51
52                 va_start(va, format);
53                 errno_save = errno;
54                 fputs("[ERROR] ", stderr);
55                 vfprintf(stderr, format, va);
56                 putc('\n', stderr);
57                 errno = errno_save;
58                 va_end(va);
59         }
60 }
61
62 void wimlib_error_with_errno(const char *format, ...)
63 {
64         if (__wimlib_print_errors) {
65                 va_list va;
66                 int errno_save;
67
68                 va_start(va, format);
69                 errno_save = errno;
70                 fflush(stdout);
71                 fputs("[ERROR] ", stderr);
72                 vfprintf(stderr, format, va);
73                 fprintf(stderr, ": %s\n", strerror(errno_save));
74                 errno = errno_save;
75                 va_end(va);
76         }
77 }
78
79 void wimlib_warning(const char *format, ...)
80 {
81         if (__wimlib_print_errors) {
82                 va_list va;
83                 int errno_save;
84
85                 va_start(va, format);
86                 errno_save = errno;
87                 fflush(stdout);
88                 fputs("[WARNING] ", stderr);
89                 vfprintf(stderr, format, va);
90                 putc('\n', stderr);
91                 errno = errno_save;
92                 va_end(va);
93         }
94 }
95
96 #endif
97
98 WIMLIBAPI int wimlib_set_print_errors(bool show_error_messages)
99 {
100 #ifdef ENABLE_ERROR_MESSAGES
101         __wimlib_print_errors = show_error_messages;
102         return 0;
103 #else
104         if (show_error_messages)
105                 return WIMLIB_ERR_UNSUPPORTED;
106 #endif
107 }
108
109 static const char *error_strings[] = {
110         [WIMLIB_ERR_SUCCESS] 
111                 = "Success",
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_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_RESOURCE_HASH]
153                 = "The SHA1 message digest of a WIM resource did not match the expected value",
154         [WIMLIB_ERR_INVALID_RESOURCE_SIZE] 
155                 = "A resource entry in the WIM is invalid",
156         [WIMLIB_ERR_LINK] 
157                 = "Failed to create a hard or symbolic link when extracting "
158                         "a file from the WIM",
159         [WIMLIB_ERR_MKDIR] 
160                 = "Failed to create a directory",
161         [WIMLIB_ERR_MQUEUE] 
162                 = "Failed to create or use a POSIX message queue",
163         [WIMLIB_ERR_NOMEM] 
164                 = "Ran out of memory",
165         [WIMLIB_ERR_NOTDIR] 
166                 = "Expected a directory",
167         [WIMLIB_ERR_NOT_A_WIM_FILE] 
168                 = "The file did not begin with the magic characters that "
169                         "identify a WIM file",
170         [WIMLIB_ERR_NO_FILENAME] 
171                 = "The WIM is not identified with a filename",
172         [WIMLIB_ERR_NTFS_3G]
173                 = "NTFS-3g encountered an error (check errno)",
174         [WIMLIB_ERR_OPEN] 
175                 = "Failed to open a file",
176         [WIMLIB_ERR_OPENDIR] 
177                 = "Failed to open a directory",
178         [WIMLIB_ERR_READ] 
179                 = "Could not read data from a file",
180         [WIMLIB_ERR_READLINK]
181                 = "Could not read the target of a symbolic link",
182         [WIMLIB_ERR_RENAME] 
183                 = "Could not rename a file",
184         [WIMLIB_ERR_SPECIAL_FILE]
185                 = "Encountered a special file that cannot be archived",
186         [WIMLIB_ERR_SPLIT_INVALID] 
187                 = "The WIM is part of an invalid split WIM",
188         [WIMLIB_ERR_SPLIT_UNSUPPORTED] 
189                 = "The WIM is part of a split WIM, which is not supported for this operation",
190         [WIMLIB_ERR_STAT] 
191                 = "Could not read the metadata for a file or directory",
192         [WIMLIB_ERR_TIMEOUT] 
193                 = "Timed out",
194         [WIMLIB_ERR_UNKNOWN_VERSION] 
195                 = "The WIM file is marked with an unknown version number",
196         [WIMLIB_ERR_UNSUPPORTED] 
197                 = "The requested operation is unsupported",
198         [WIMLIB_ERR_WRITE] 
199                 = "Failed to write data to a file",
200         [WIMLIB_ERR_XML] 
201                 = "The XML data of the WIM is invalid",
202 };
203
204 WIMLIBAPI const char *wimlib_get_error_string(enum wimlib_error_code code)
205 {
206         if (code < WIMLIB_ERR_SUCCESS || code > WIMLIB_ERR_XML)
207                 return NULL;
208         else
209                 return error_strings[code];
210 }
211
212
213
214 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
215 void *(*wimlib_malloc_func) (size_t)         = malloc;
216 void  (*wimlib_free_func)   (void *)         = free;
217 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
218
219 void *wimlib_calloc(size_t nmemb, size_t size)
220 {
221         size_t total_size = nmemb * size;
222         void *p = MALLOC(total_size);
223         if (p)
224                 memset(p, 0, total_size);
225         return p;
226 }
227
228 char *wimlib_strdup(const char *str)
229 {
230         size_t size;
231         char *p;
232         
233         size = strlen(str); 
234         p = MALLOC(size + 1);
235         if (p)
236                 memcpy(p, str, size + 1);
237         return p;
238 }
239
240 extern void xml_set_memory_allocator(void *(*malloc_func)(size_t),
241                                    void (*free_func)(void *),
242                                    void *(*realloc_func)(void *, size_t));
243 #endif
244
245 WIMLIBAPI int wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
246                                            void (*free_func)(void *),
247                                            void *(*realloc_func)(void *, size_t))
248 {
249 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
250         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
251         wimlib_free_func    = free_func    ? free_func    : free;
252         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
253
254         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func, 
255                                  wimlib_realloc_func);
256         return 0;
257 #else
258         ERROR("Cannot set custom memory allocator functions:");
259         ERROR("wimlib was compiled with the --without-custom-memory-allocator "
260               "flag");
261         return WIMLIB_ERR_UNSUPPORTED;
262 #endif
263 }
264
265
266
267 static iconv_t cd_utf16_to_utf8 = (iconv_t)(-1);
268
269 /* Converts a string in the UTF-16 encoding to a newly allocated string in the
270  * UTF-8 encoding.  */
271 char *utf16_to_utf8(const char *utf16_str, size_t utf16_len,
272                     size_t *utf8_len_ret)
273 {
274         if (cd_utf16_to_utf8 == (iconv_t)(-1)) {
275                 cd_utf16_to_utf8 = iconv_open("UTF-8", "UTF-16LE");
276                 if (cd_utf16_to_utf8 == (iconv_t)-1) {
277                         ERROR_WITH_ERRNO("Failed to get conversion descriptor "
278                                          "for converting UTF-16LE to UTF-8");
279                         return NULL;
280                 }
281         }
282         size_t utf16_bytes_left  = utf16_len;
283         size_t utf8_bytes_left   = utf16_len;
284
285         char *utf8_str = MALLOC(utf8_bytes_left);
286         if (!utf8_str)
287                 return NULL;
288
289         char *orig_utf8_str = utf8_str;
290
291         size_t num_chars_converted = iconv(cd_utf16_to_utf8, (char**)&utf16_str, 
292                         &utf16_bytes_left, &utf8_str, &utf8_bytes_left);
293
294         if (num_chars_converted == (size_t)(-1)) {
295                 ERROR_WITH_ERRNO("Failed to convert UTF-16LE string to UTF-8 "
296                                  "string");
297                 FREE(orig_utf8_str);
298                 return NULL;
299         }
300
301         size_t utf8_len = utf16_len - utf8_bytes_left;
302
303         *utf8_len_ret = utf8_len;
304         orig_utf8_str[utf8_len] = '\0';
305         return orig_utf8_str;
306 }
307
308 static iconv_t cd_utf8_to_utf16 = (iconv_t)(-1);
309
310 /* Converts a string in the UTF-8 encoding to a newly allocated string in the
311  * UTF-16 encoding.  */
312 char *utf8_to_utf16(const char *utf8_str, size_t utf8_len,
313                     size_t *utf16_len_ret)
314 {
315         if (cd_utf8_to_utf16 == (iconv_t)(-1)) {
316                 cd_utf8_to_utf16 = iconv_open("UTF-16LE", "UTF-8");
317                 if (cd_utf8_to_utf16 == (iconv_t)-1) {
318                         ERROR_WITH_ERRNO("Failed to get conversion descriptor "
319                                          "for converting UTF-8 to UTF-16LE");
320                         return NULL;
321                 }
322         }
323
324         size_t utf8_bytes_left   = utf8_len;
325         size_t utf16_capacity    = utf8_len * 4;
326         size_t utf16_bytes_left  = utf16_capacity;
327
328         char *utf16_str = MALLOC(utf16_capacity + 2);
329         if (!utf16_str)
330                 return NULL;
331
332         char *orig_utf16_str = utf16_str;
333
334         size_t num_chars_converted = iconv(cd_utf8_to_utf16, (char**)&utf8_str, 
335                         &utf8_bytes_left, &utf16_str, &utf16_bytes_left);
336
337         if (num_chars_converted == (size_t)(-1)) {
338                 ERROR_WITH_ERRNO("Failed to convert UTF-8 string to UTF-16LE "
339                                  "string");
340                 FREE(orig_utf16_str);
341                 return NULL;
342         }
343
344         size_t utf16_len = utf16_capacity - utf16_bytes_left;
345
346         *utf16_len_ret = utf16_len;
347         orig_utf16_str[utf16_len] = '\0';
348         orig_utf16_str[utf16_len + 1] = '\0';
349         return orig_utf16_str;
350 }
351
352 /* Write @n bytes from @buf to the file descriptor @fd, retrying on interupt and
353  * on short writes.
354  *
355  * Returns short count and set errno on failure. */
356 ssize_t full_write(int fd, const void *buf, size_t n)
357 {
358         const char *p = buf;
359         ssize_t ret;
360         ssize_t total = 0;
361
362         while (total != n) {
363                 ret = write(fd, p, n);
364                 if (ret < 0) {
365                         if (errno == EINTR)
366                                 continue;
367                         else
368                                 break;
369                 }
370                 total += ret;
371                 p += ret;
372         }
373         return total;
374 }
375
376
377 static bool seeded = false;
378
379 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
380 void randomize_char_array_with_alnum(char p[], size_t n)
381 {
382         int r;
383
384         if (!seeded) {
385                 srand(time(NULL));
386                 seeded = true;
387         }
388         while (n--) {
389                 r = rand() % 62;
390                 if (r < 26)
391                         *p++ = r + 'a';
392                 else if (r < 52)
393                         *p++ = r - 26 + 'A';
394                 else
395                         *p++ = r - 52 + '0';
396         }
397 }
398
399 /* Fills @n bytes pointer to by @p with random numbers. */
400 void randomize_byte_array(u8 *p, size_t n)
401 {
402         if (!seeded) {
403                 srand(time(NULL));
404                 seeded = true;
405         }
406         while (n--)
407                 *p++ = rand();
408 }
409
410 /* Takes in a path of length @len in @buf, and transforms it into a string for
411  * the path of its parent directory. */
412 void to_parent_name(char buf[], size_t len)
413 {
414         ssize_t i = (ssize_t)len - 1;
415         while (i >= 0 && buf[i] == '/')
416                 i--;
417         while (i >= 0 && buf[i] != '/')
418                 i--;
419         while (i >= 0 && buf[i] == '/')
420                 i--;
421         buf[i + 1] = '\0';
422 }
423
424 /* Like the basename() function, but does not modify @path; it just returns a
425  * pointer to it. */
426 const char *path_basename(const char *path)
427 {
428         const char *p = path;
429         while (*p)
430                 p++;
431         p--;
432
433         /* Trailing slashes. */
434         while (1) {
435                 if (p == path - 1)
436                         return "";
437                 if (*p != '/')
438                         break;
439                 p--;
440         }
441
442         while ((p != path - 1) && *p != '/')
443                 p--;
444
445         return p + 1;
446 }
447
448 /* 
449  * Returns a pointer to the part of @path following the first colon in the last
450  * path component, or NULL if the last path component does not contain a colon.
451  */
452 const char *path_stream_name(const char *path)
453 {
454         const char *base = path_basename(path);
455         const char *stream_name = strchr(base, ':');
456         if (!stream_name)
457                 return NULL;
458         else
459                 return stream_name + 1;
460 }
461
462 /* 
463  * Splits a file path into the part before the first '/', or the entire name if
464  * there is no '/', and the part after the first sequence of '/' characters.
465  *
466  * @path:               The file path to split.
467  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
468  *                              first part of the path will be returned.
469  * @return:             A pointer to the next part of the path, after the first
470  *                              sequence of '/', or a pointer to the terminating 
471  *                              null byte in the case of a path without any '/'.
472  */
473 const char *path_next_part(const char *path, size_t *first_part_len_ret)
474 {
475         size_t i;
476         const char *next_part;
477
478         i = 0;
479         while (path[i] != '/' && path[i] != '\0')
480                 i++;
481         if (first_part_len_ret)
482                 *first_part_len_ret = i;
483         next_part = &path[i];
484         while (*next_part == '/')
485                 next_part++;
486         return next_part;
487 }
488
489 /* Returns the number of components of @path.  */
490 int get_num_path_components(const char *path)
491 {
492         int num_components = 0;
493         while (*path) {
494                 while (*path == '/')
495                         path++;
496                 if (*path)
497                         num_components++;
498                 while (*path && *path != '/')
499                         path++;
500         }
501         return num_components;
502 }
503
504
505 /* 
506  * Prints a string.  Printable characters are printed as-is, while unprintable
507  * characters are printed as their octal escape codes. 
508  */
509 void print_string(const void *string, size_t len)
510 {
511         const u8 *p = string;
512
513         while (len--) {
514                 if (isprint(*p))
515                         putchar(*p);
516                 else
517                         printf("\\%03hho", *p);
518                 p++;
519         }
520 }
521
522 u64 get_wim_timestamp()
523 {
524         struct timeval tv;
525         gettimeofday(&tv, NULL);
526         return timeval_to_wim_timestamp(&tv);
527 }
528
529