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