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