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