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