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