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