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