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