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