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