]> wimlib.net Git - wimlib/blob - src/util.c
Fix some compiler warnings
[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         return 0;
223 #else
224         ERROR("Cannot set custom memory allocator functions:\n");
225         ERROR("wimlib was compiled with the "
226                         "--without-custom-memory-allocator flag\n");
227         return WIMLIB_ERR_UNSUPPORTED;
228 #endif
229 }
230
231
232
233 static iconv_t cd_utf16_to_utf8 = (iconv_t)(-1);
234
235 /* Converts a string in the UTF-16 encoding to a newly allocated string in the
236  * UTF-8 encoding.  */
237 char *utf16_to_utf8(const char *utf16_str, size_t utf16_len,
238                                 size_t *utf8_len_ret)
239 {
240         if (cd_utf16_to_utf8 == (iconv_t)(-1)) {
241                 cd_utf16_to_utf8 = iconv_open("UTF-8", "UTF-16LE");
242                 if (cd_utf16_to_utf8 == (iconv_t)-1) {
243                         ERROR("Failed to get conversion descriptor for "
244                                         "converting UTF-16LE to UTF-8: %m\n");
245                         return NULL;
246                 }
247         }
248         size_t utf16_bytes_left  = utf16_len;
249         size_t utf8_bytes_left   = utf16_len;
250
251         char *utf8_str = MALLOC(utf8_bytes_left);
252         if (!utf8_str)
253                 return NULL;
254
255         char *orig_utf8_str = utf8_str;
256
257         size_t num_chars_converted = iconv(cd_utf16_to_utf8, (char**)&utf16_str, 
258                         &utf16_bytes_left, &utf8_str, &utf8_bytes_left);
259
260         if (num_chars_converted == (size_t)(-1)) {
261                 ERROR("Failed to convert UTF-16LE string to UTF-8 string: "
262                                 "%m\n");
263                 FREE(orig_utf8_str);
264                 return NULL;
265         }
266
267         size_t utf8_len = utf16_len - utf8_bytes_left;
268
269         *utf8_len_ret = utf8_len;
270         orig_utf8_str[utf8_len] = '\0';
271         return orig_utf8_str;
272 }
273
274 static iconv_t cd_utf8_to_utf16 = (iconv_t)(-1);
275
276 /* Converts a string in the UTF-8 encoding to a newly allocated string in the
277  * UTF-16 encoding.  */
278 char *utf8_to_utf16(const char *utf8_str, size_t utf8_len, 
279                                                 size_t *utf16_len_ret)
280 {
281         if (cd_utf8_to_utf16 == (iconv_t)(-1)) {
282                 cd_utf8_to_utf16 = iconv_open("UTF-16LE", "UTF-8");
283                 if (cd_utf8_to_utf16 == (iconv_t)-1) {
284                         ERROR("Failed to get conversion descriptor for "
285                                         "converting UTF-8 to UTF-16LE: %m\n");
286                         return NULL;
287                 }
288         }
289
290         size_t utf8_bytes_left   = utf8_len;
291         size_t utf16_capacity    = utf8_len * 4;
292         size_t utf16_bytes_left  = utf16_capacity;
293
294         char *utf16_str = MALLOC(utf16_capacity + 2);
295         if (!utf16_str)
296                 return NULL;
297
298         char *orig_utf16_str = utf16_str;
299
300         size_t num_chars_converted = iconv(cd_utf8_to_utf16, (char**)&utf8_str, 
301                         &utf8_bytes_left, &utf16_str, &utf16_bytes_left);
302
303         if (num_chars_converted == (size_t)(-1)) {
304                 ERROR("Failed to convert UTF-8 string to UTF-16LE string: "
305                                 "%s\n", 
306                                 (errno == E2BIG) ? 
307                                         "Not enough room in output buffer" : 
308                                         strerror(errno));
309                 FREE(orig_utf16_str);
310                 return NULL;
311         }
312
313         size_t utf16_len = utf16_capacity - utf16_bytes_left;
314
315         *utf16_len_ret = utf16_len;
316         orig_utf16_str[utf16_len] = '\0';
317         orig_utf16_str[utf16_len + 1] = '\0';
318         return orig_utf16_str;
319 }
320
321 /* Write @n bytes from @buf to the file descriptor @fd, retrying on interupt and
322  * on short writes.
323  *
324  * Returns short count and set errno on failure. */
325 ssize_t full_write(int fd, const void *buf, size_t n)
326 {
327         const char *p = buf;
328         ssize_t ret;
329         ssize_t total = 0;
330
331         while (total != n) {
332                 ret = write(fd, p, n);
333                 if (ret < 0) {
334                         if (errno == EINTR)
335                                 continue;
336                         else
337                                 break;
338                 }
339                 total += ret;
340                 p += ret;
341         }
342         return total;
343 }
344
345
346 static bool seeded = false;
347
348 /* Fills @n bytes pointed to by @p with random alphanumeric characters. */
349 void randomize_char_array_with_alnum(char p[], size_t n)
350 {
351         int r;
352
353         if (!seeded) {
354                 srand(time(NULL));
355                 seeded = true;
356         }
357         while (n--) {
358                 r = rand() % 62;
359                 if (r < 26)
360                         *p++ = r + 'a';
361                 else if (r < 52)
362                         *p++ = r - 26 + 'A';
363                 else
364                         *p++ = r - 52 + '0';
365         }
366 }
367
368 /* Fills @n bytes pointer to by @p with random numbers. */
369 void randomize_byte_array(void *__p, size_t n)
370 {
371         u8 *p = __p;
372
373         if (!seeded) {
374                 srand(time(NULL));
375                 seeded = true;
376         }
377         while (n--)
378                 *p++ = rand();
379 }
380
381 /* Takes in a path of length @len in @buf, and transforms it into a string for
382  * the path of its parent directory. */
383 void to_parent_name(char buf[], size_t len)
384 {
385         ssize_t i = (ssize_t)len - 1;
386         while (i >= 0 && buf[i] == '/')
387                 i--;
388         while (i >= 0 && buf[i] != '/')
389                 i--;
390         while (i >= 0 && buf[i] == '/')
391                 i--;
392         buf[i + 1] = '\0';
393 }
394
395 /* Like the basename() function, but does not modify @path; it just returns a
396  * pointer to it. */
397 const char *path_basename(const char *path)
398 {
399         const char *p = path;
400         while (*p)
401                 p++;
402         p--;
403
404         /* Trailing slashes. */
405         while ((p != path - 1) && *p == '/')
406                 p--;
407
408         while ((p != path - 1) && *p != '/')
409                 p--;
410
411         return p + 1;
412 }
413
414 /* 
415  * Splits a file path into the part before the first '/', or the entire name if
416  * there is no '/', and the part after the first sequence of '/' characters.
417  *
418  * @path:               The file path to split.
419  * @first_part_len_ret: A pointer to a `size_t' into which the length of the
420  *                              first part of the path will be returned.
421  * @return:             A pointer to the next part of the path, after the first
422  *                              sequence of '/', or a pointer to the terminating 
423  *                              null byte in the case of a path without any '/'.
424  */
425 const char *path_next_part(const char *path, size_t *first_part_len_ret)
426 {
427         size_t i;
428         const char *next_part;
429
430         i = 0;
431         while (path[i] != '/' && path[i] != '\0')
432                 i++;
433         if (first_part_len_ret)
434                 *first_part_len_ret = i;
435         next_part = &path[i];
436         while (*next_part == '/')
437                 next_part++;
438         return next_part;
439 }
440
441 /* Returns the number of components of @path.  */
442 int get_num_path_components(const char *path)
443 {
444         int num_components = 0;
445         while (*path) {
446                 while (*path == '/')
447                         path++;
448                 if (*path)
449                         num_components++;
450                 while (*path && *path != '/')
451                         path++;
452         }
453         return num_components;
454 }
455
456
457 /* 
458  * Prints a string.  Printable characters are printed as-is, while unprintable
459  * characters are printed as their octal escape codes. 
460  */
461 void print_string(const void *string, size_t len)
462 {
463         const u8 *p = string;
464
465         while (len--) {
466                 if (isprint(*p))
467                         putchar(*p);
468                 else
469                         printf("\\%03hho", *p);
470                 p++;
471         }
472 }
473