]> wimlib.net Git - wimlib/blob - src/wim.c
Check return value of wimlib_global_init() when called in lib
[wimlib] / src / wim.c
1 /*
2  * wim.c - Stuff that doesn't fit into any other file
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 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 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/error.h"
29 #include "wimlib/dentry.h"
30 #include "wimlib/encoding.h"
31 #include "wimlib/file_io.h"
32 #include "wimlib/integrity.h"
33 #include "wimlib/lookup_table.h"
34 #include "wimlib/metadata.h"
35 #ifdef WITH_NTFS_3G
36 #  include "wimlib/ntfs_3g.h" /* for do_ntfs_umount() */
37 #endif
38 #include "wimlib/security.h"
39 #include "wimlib/wim.h"
40 #include "wimlib/xml.h"
41 #include "wimlib/version.h"
42
43 #ifdef __WIN32__
44 #  include "wimlib/win32.h" /* for realpath() replacement */
45 #endif
46
47 #include <errno.h>
48 #include <fcntl.h>
49 #ifndef __WIN32__
50 #  include <langinfo.h>
51 #endif
52 #include <limits.h>
53 #include <stdarg.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56
57 static int
58 wim_default_pack_compression_type(void)
59 {
60         return WIMLIB_COMPRESSION_TYPE_LZMS;
61 }
62
63 static u32
64 wim_default_pack_chunk_size(int ctype) {
65         switch (ctype) {
66         case WIMLIB_COMPRESSION_TYPE_LZMS:
67                 return 1U << 25; /* 33554432  */
68         default:
69                 return 1U << 15; /* 32768     */
70         }
71 }
72
73 static WIMStruct *
74 new_wim_struct(void)
75 {
76         WIMStruct *wim = CALLOC(1, sizeof(WIMStruct));
77         if (wim) {
78                 filedes_invalidate(&wim->in_fd);
79                 filedes_invalidate(&wim->out_fd);
80                 wim->out_pack_compression_type = wim_default_pack_compression_type();
81                 wim->out_pack_chunk_size = wim_default_pack_chunk_size(
82                                                 wim->out_pack_compression_type);
83                 INIT_LIST_HEAD(&wim->subwims);
84         }
85         return wim;
86 }
87
88 /* Determine if the chunk size is valid for the specified compression type.  */
89 static bool
90 wim_chunk_size_valid(u32 chunk_size, int ctype)
91 {
92         u32 order;
93
94         /* Chunk size is meaningless for uncompressed WIMs --- any value is
95          * okay.  */
96         if (ctype == WIMLIB_COMPRESSION_TYPE_NONE)
97                 return true;
98
99         /* Chunk size must be power of 2.  */
100         if (chunk_size == 0)
101                 return false;
102         order = bsr32(chunk_size);
103         if (chunk_size != 1U << order)
104                 return false;
105
106         /* Order        Size
107          * =====        ====
108          * 15           32768
109          * 16           65536
110          * 17           131072
111          * 18           262144
112          * 19           524288
113          * 20           1048576
114          * 21           2097152
115          * 22           4194304
116          * 23           8388608
117          * 24           16777216
118          * 25           33554432
119          * 26           67108864
120          */
121
122         /* See the documentation for the --chunk-size option of `wimlib-imagex
123          * capture' for information about allowed chunk sizes.  */
124         switch (ctype) {
125         case WIMLIB_COMPRESSION_TYPE_LZX:
126                 return order >= 15 && order <= 21;
127         case WIMLIB_COMPRESSION_TYPE_XPRESS:
128                 return order >= 12 && order <= 16;
129         case WIMLIB_COMPRESSION_TYPE_LZMS:
130                 return order >= 15 && order <= 30;
131         }
132         return false;
133 }
134
135 /* Return the default chunk size to use for the specified compression type.
136  *
137  * See notes above in wim_chunk_size_valid().  */
138 static u32
139 wim_default_chunk_size(int ctype)
140 {
141         switch (ctype) {
142         case WIMLIB_COMPRESSION_TYPE_LZMS:
143                 return 1U << 17; /* 131072  */
144         default:
145                 return 1U << 15; /* 32768   */
146         }
147 }
148
149 /*
150  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES,
151  * @visitor is called on the WIM once for each image, with each image selected
152  * as the current image in turn.  If @image is a certain image, @visitor is
153  * called on the WIM only once, with that image selected.
154  */
155 int
156 for_image(WIMStruct *wim, int image, int (*visitor)(WIMStruct *))
157 {
158         int ret;
159         int start;
160         int end;
161         int i;
162
163         if (image == WIMLIB_ALL_IMAGES) {
164                 start = 1;
165                 end = wim->hdr.image_count;
166         } else if (image >= 1 && image <= wim->hdr.image_count) {
167                 start = image;
168                 end = image;
169         } else {
170                 return WIMLIB_ERR_INVALID_IMAGE;
171         }
172         for (i = start; i <= end; i++) {
173                 ret = select_wim_image(wim, i);
174                 if (ret != 0)
175                         return ret;
176                 ret = visitor(wim);
177                 if (ret != 0)
178                         return ret;
179         }
180         return 0;
181 }
182
183 /* API function documented in wimlib.h  */
184 WIMLIBAPI int
185 wimlib_create_new_wim(int ctype, WIMStruct **wim_ret)
186 {
187         WIMStruct *wim;
188         struct wim_lookup_table *table;
189         int ret;
190
191         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
192         if (ret)
193                 return ret;
194
195         DEBUG("Creating new WIM with %"TS" compression.",
196               wimlib_get_compression_type_string(ctype));
197
198         /* Allocate the WIMStruct. */
199         wim = new_wim_struct();
200         if (wim == NULL)
201                 return WIMLIB_ERR_NOMEM;
202
203         ret = init_wim_header(&wim->hdr, ctype, wim_default_chunk_size(ctype));
204         if (ret)
205                 goto out_free;
206
207         table = new_lookup_table(9001);
208         if (table == NULL) {
209                 ret = WIMLIB_ERR_NOMEM;
210                 goto out_free;
211         }
212         wim->lookup_table = table;
213         wim->refcnts_ok = 1;
214         wim->compression_type = ctype;
215         wim->out_compression_type = ctype;
216         wim->chunk_size = wim->hdr.chunk_size;
217         wim->out_chunk_size = wim->hdr.chunk_size;
218         *wim_ret = wim;
219         return 0;
220 out_free:
221         FREE(wim);
222         return ret;
223 }
224
225 static void
226 destroy_image_metadata(struct wim_image_metadata *imd,
227                        struct wim_lookup_table *table,
228                        bool free_metadata_lte)
229 {
230         free_dentry_tree(imd->root_dentry, table);
231         imd->root_dentry = NULL;
232         free_wim_security_data(imd->security_data);
233         imd->security_data = NULL;
234
235         if (free_metadata_lte) {
236                 free_lookup_table_entry(imd->metadata_lte);
237                 imd->metadata_lte = NULL;
238         }
239         if (table == NULL) {
240                 struct wim_lookup_table_entry *lte, *tmp;
241                 list_for_each_entry_safe(lte, tmp, &imd->unhashed_streams, unhashed_list)
242                         free_lookup_table_entry(lte);
243         }
244         INIT_LIST_HEAD(&imd->unhashed_streams);
245         INIT_LIST_HEAD(&imd->inode_list);
246 #ifdef WITH_NTFS_3G
247         if (imd->ntfs_vol) {
248                 do_ntfs_umount(imd->ntfs_vol);
249                 imd->ntfs_vol = NULL;
250         }
251 #endif
252 }
253
254 void
255 put_image_metadata(struct wim_image_metadata *imd,
256                    struct wim_lookup_table *table)
257 {
258         if (imd && --imd->refcnt == 0) {
259                 destroy_image_metadata(imd, table, true);
260                 FREE(imd);
261         }
262 }
263
264 /* Appends the specified image metadata structure to the array of image metadata
265  * for a WIM, and increments the image count. */
266 int
267 append_image_metadata(WIMStruct *wim, struct wim_image_metadata *imd)
268 {
269         struct wim_image_metadata **imd_array;
270
271         DEBUG("Reallocating image metadata array for image_count = %u",
272               wim->hdr.image_count + 1);
273         imd_array = REALLOC(wim->image_metadata,
274                             sizeof(wim->image_metadata[0]) * (wim->hdr.image_count + 1));
275
276         if (imd_array == NULL)
277                 return WIMLIB_ERR_NOMEM;
278         wim->image_metadata = imd_array;
279         imd_array[wim->hdr.image_count++] = imd;
280         return 0;
281 }
282
283 struct wim_image_metadata *
284 new_image_metadata(void)
285 {
286         struct wim_image_metadata *imd;
287
288         imd = CALLOC(1, sizeof(*imd));
289         if (imd) {
290                 imd->refcnt = 1;
291                 INIT_LIST_HEAD(&imd->inode_list);
292                 INIT_LIST_HEAD(&imd->unhashed_streams);
293                 DEBUG("Created new image metadata (refcnt=1)");
294         } else {
295                 ERROR_WITH_ERRNO("Failed to allocate new image metadata structure");
296         }
297         return imd;
298 }
299
300 static struct wim_image_metadata **
301 new_image_metadata_array(unsigned num_images)
302 {
303         struct wim_image_metadata **imd_array;
304
305         DEBUG("Creating new image metadata array for %u images",
306               num_images);
307
308         imd_array = CALLOC(num_images, sizeof(imd_array[0]));
309
310         if (imd_array == NULL) {
311                 ERROR("Failed to allocate memory for %u image metadata structures",
312                       num_images);
313                 return NULL;
314         }
315         for (unsigned i = 0; i < num_images; i++) {
316                 imd_array[i] = new_image_metadata();
317                 if (imd_array[i] == NULL) {
318                         for (unsigned j = 0; j < i; j++)
319                                 put_image_metadata(imd_array[j], NULL);
320                         FREE(imd_array);
321                         return NULL;
322                 }
323         }
324         return imd_array;
325 }
326
327
328 /*
329  * Load the metadata for the specified WIM image into memory and set it
330  * as the WIMStruct's currently selected image.
331  *
332  * @wim
333  *      The WIMStruct for the WIM.
334  * @image
335  *      The 1-based index of the image in the WIM to select.
336  *
337  * On success, 0 will be returned, wim->current_image will be set to
338  * @image, and wim_get_current_image_metadata() can be used to retrieve
339  * metadata information for the image.
340  *
341  * On failure, WIMLIB_ERR_INVALID_IMAGE, WIMLIB_ERR_METADATA_NOT_FOUND,
342  * or another error code will be returned.
343  */
344 int
345 select_wim_image(WIMStruct *wim, int image)
346 {
347         struct wim_image_metadata *imd;
348         int ret;
349
350         DEBUG("Selecting image %d", image);
351
352         if (image == WIMLIB_NO_IMAGE) {
353                 ERROR("Invalid image: %d", WIMLIB_NO_IMAGE);
354                 return WIMLIB_ERR_INVALID_IMAGE;
355         }
356
357         if (image == wim->current_image)
358                 return 0;
359
360         if (image < 1 || image > wim->hdr.image_count) {
361                 ERROR("Cannot select image %d: There are only %u images",
362                       image, wim->hdr.image_count);
363                 return WIMLIB_ERR_INVALID_IMAGE;
364         }
365
366         if (!wim_has_metadata(wim)) {
367                 ERROR("\"%"TS"\" does not contain metadata resources!", wim->filename);
368                 if (wim->hdr.part_number != 1)
369                         ERROR("Specify the first part of the split WIM instead.");
370                 return WIMLIB_ERR_METADATA_NOT_FOUND;
371         }
372
373         /* If a valid image is currently selected, its metadata can be freed if
374          * it has not been modified.  */
375         if (wim->current_image != WIMLIB_NO_IMAGE) {
376                 imd = wim_get_current_image_metadata(wim);
377                 if (!imd->modified) {
378                         wimlib_assert(list_empty(&imd->unhashed_streams));
379                         DEBUG("Freeing image %u", wim->current_image);
380                         destroy_image_metadata(imd, NULL, false);
381                 }
382         }
383         wim->current_image = image;
384         imd = wim_get_current_image_metadata(wim);
385         if (imd->root_dentry || imd->modified) {
386                 ret = 0;
387         } else {
388                 ret = read_metadata_resource(wim, imd);
389                 if (ret)
390                         wim->current_image = WIMLIB_NO_IMAGE;
391         }
392         return ret;
393 }
394
395
396 /* API function documented in wimlib.h  */
397 WIMLIBAPI const tchar *
398 wimlib_get_compression_type_string(int ctype)
399 {
400         switch (ctype) {
401                 case WIMLIB_COMPRESSION_TYPE_NONE:
402                         return T("None");
403                 case WIMLIB_COMPRESSION_TYPE_LZX:
404                         return T("LZX");
405                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
406                         return T("XPRESS");
407                 case WIMLIB_COMPRESSION_TYPE_LZMS:
408                         return T("LZMS");
409                 default:
410                         return T("Invalid");
411         }
412 }
413
414 /* API function documented in wimlib.h  */
415 WIMLIBAPI int
416 wimlib_resolve_image(WIMStruct *wim, const tchar *image_name_or_num)
417 {
418         tchar *p;
419         long image;
420         int i;
421
422         if (!image_name_or_num || !*image_name_or_num)
423                 return WIMLIB_NO_IMAGE;
424
425         if (!tstrcasecmp(image_name_or_num, T("all"))
426             || !tstrcasecmp(image_name_or_num, T("*")))
427                 return WIMLIB_ALL_IMAGES;
428         image = tstrtol(image_name_or_num, &p, 10);
429         if (p != image_name_or_num && *p == T('\0') && image > 0) {
430                 if (image > wim->hdr.image_count)
431                         return WIMLIB_NO_IMAGE;
432                 return image;
433         } else {
434                 for (i = 1; i <= wim->hdr.image_count; i++) {
435                         if (!tstrcmp(image_name_or_num,
436                                      wimlib_get_image_name(wim, i)))
437                                 return i;
438                 }
439                 return WIMLIB_NO_IMAGE;
440         }
441 }
442
443 /* API function documented in wimlib.h  */
444 WIMLIBAPI void
445 wimlib_print_available_images(const WIMStruct *wim, int image)
446 {
447         int first;
448         int last;
449         int i;
450         int n;
451         if (image == WIMLIB_ALL_IMAGES) {
452                 n = tprintf(T("Available Images:\n"));
453                 first = 1;
454                 last = wim->hdr.image_count;
455         } else if (image >= 1 && image <= wim->hdr.image_count) {
456                 n = tprintf(T("Information for Image %d\n"), image);
457                 first = image;
458                 last = image;
459         } else {
460                 tprintf(T("wimlib_print_available_images(): Invalid image %d"),
461                         image);
462                 return;
463         }
464         for (i = 0; i < n - 1; i++)
465                 tputchar(T('-'));
466         tputchar(T('\n'));
467         for (i = first; i <= last; i++)
468                 print_image_info(wim->wim_info, i);
469 }
470
471 /* API function documented in wimlib.h  */
472 WIMLIBAPI int
473 wimlib_get_wim_info(WIMStruct *wim, struct wimlib_wim_info *info)
474 {
475         memset(info, 0, sizeof(struct wimlib_wim_info));
476         memcpy(info->guid, wim->hdr.guid, WIMLIB_GUID_LEN);
477         info->image_count = wim->hdr.image_count;
478         info->boot_index = wim->hdr.boot_idx;
479         info->wim_version = wim->hdr.wim_version;
480         info->chunk_size = wim->chunk_size;
481         info->part_number = wim->hdr.part_number;
482         info->total_parts = wim->hdr.total_parts;
483         info->compression_type = wim->compression_type;
484         info->total_bytes = wim_info_get_total_bytes(wim->wim_info);
485         info->has_integrity_table = wim_has_integrity_table(wim);
486         info->opened_from_file = (wim->filename != NULL);
487         info->is_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) ||
488                              (wim->hdr.total_parts != 1) ||
489                              (wim->filename && taccess(wim->filename, W_OK));
490         info->has_rpfix = (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX) != 0;
491         info->is_marked_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) != 0;
492         info->write_in_progress = (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) != 0;
493         info->metadata_only = (wim->hdr.flags & WIM_HDR_FLAG_METADATA_ONLY) != 0;
494         info->resource_only = (wim->hdr.flags & WIM_HDR_FLAG_RESOURCE_ONLY) != 0;
495         info->spanned = (wim->hdr.flags & WIM_HDR_FLAG_SPANNED) != 0;
496         info->pipable = wim_is_pipable(wim);
497         return 0;
498 }
499
500 /* API function documented in wimlib.h  */
501 WIMLIBAPI int
502 wimlib_set_wim_info(WIMStruct *wim, const struct wimlib_wim_info *info, int which)
503 {
504         int ret;
505
506         if (which & ~(WIMLIB_CHANGE_READONLY_FLAG |
507                       WIMLIB_CHANGE_GUID |
508                       WIMLIB_CHANGE_BOOT_INDEX |
509                       WIMLIB_CHANGE_RPFIX_FLAG))
510                 return WIMLIB_ERR_INVALID_PARAM;
511
512         if (which & WIMLIB_CHANGE_READONLY_FLAG) {
513                 if (info->is_marked_readonly)
514                         wim->hdr.flags |= WIM_HDR_FLAG_READONLY;
515                 else
516                         wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
517         }
518
519         if ((which & ~WIMLIB_CHANGE_READONLY_FLAG) == 0)
520                 return 0;
521
522         ret = can_modify_wim(wim);
523         if (ret)
524                 return ret;
525
526         if (which & WIMLIB_CHANGE_GUID)
527                 memcpy(wim->hdr.guid, info->guid, WIM_GUID_LEN);
528
529         if (which & WIMLIB_CHANGE_BOOT_INDEX) {
530                 if (info->boot_index > wim->hdr.image_count) {
531                         ERROR("%u is not 0 or a valid image in the WIM to mark as bootable",
532                               info->boot_index);
533                         return WIMLIB_ERR_INVALID_IMAGE;
534                 }
535                 wim->hdr.boot_idx = info->boot_index;
536         }
537
538         if (which & WIMLIB_CHANGE_RPFIX_FLAG) {
539                 if (info->has_rpfix)
540                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
541                 else
542                         wim->hdr.flags &= ~WIM_HDR_FLAG_RP_FIX;
543         }
544         return 0;
545 }
546
547 static int
548 set_out_ctype(int ctype, u8 *out_ctype_p)
549 {
550         switch (ctype) {
551         case WIMLIB_COMPRESSION_TYPE_NONE:
552         case WIMLIB_COMPRESSION_TYPE_LZX:
553         case WIMLIB_COMPRESSION_TYPE_XPRESS:
554         case WIMLIB_COMPRESSION_TYPE_LZMS:
555                 *out_ctype_p = ctype;
556                 return 0;
557         }
558         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
559 }
560
561 /* API function documented in wimlib.h  */
562 WIMLIBAPI int
563 wimlib_set_output_compression_type(WIMStruct *wim, int ctype)
564 {
565         int ret = set_out_ctype(ctype, &wim->out_compression_type);
566         if (ret)
567                 return ret;
568
569         /* Reset the chunk size if it's no longer valid.  */
570         if (!wim_chunk_size_valid(wim->out_chunk_size, ctype))
571                 wim->out_chunk_size = wim_default_chunk_size(ctype);
572         return 0;
573 }
574
575 /* API function documented in wimlib.h  */
576 WIMLIBAPI int
577 wimlib_set_output_pack_compression_type(WIMStruct *wim, int ctype)
578 {
579         int ret = set_out_ctype(ctype, &wim->out_pack_compression_type);
580         if (ret)
581                 return ret;
582
583         /* Reset the chunk size if it's no longer valid.  */
584         if (!wim_chunk_size_valid(wim->out_pack_chunk_size, ctype))
585                 wim->out_pack_chunk_size = wim_default_pack_chunk_size(ctype);
586         return 0;
587 }
588
589 static int
590 set_out_chunk_size(u32 chunk_size, int ctype, u32 *out_chunk_size_p)
591 {
592         if (!wim_chunk_size_valid(chunk_size, ctype)) {
593                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
594                       "for compression type %"TS"!",
595                       chunk_size,
596                       wimlib_get_compression_type_string(ctype));
597                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
598         }
599
600         *out_chunk_size_p = chunk_size;
601         return 0;
602 }
603
604 /* API function documented in wimlib.h  */
605 WIMLIBAPI int
606 wimlib_set_output_chunk_size(WIMStruct *wim, uint32_t chunk_size)
607 {
608         if (chunk_size == 0) {
609                 wim->out_chunk_size =
610                         wim_default_chunk_size(wim->out_compression_type);
611                 return 0;
612         }
613
614         return set_out_chunk_size(chunk_size,
615                                   wim->out_compression_type,
616                                   &wim->out_chunk_size);
617 }
618
619 /* API function documented in wimlib.h  */
620 WIMLIBAPI int
621 wimlib_set_output_pack_chunk_size(WIMStruct *wim, uint32_t chunk_size)
622 {
623         if (chunk_size == 0) {
624                 wim->out_pack_chunk_size =
625                         wim_default_pack_chunk_size(wim->out_pack_compression_type);
626                 return 0;
627         }
628
629         return set_out_chunk_size(chunk_size,
630                                   wim->out_pack_compression_type,
631                                   &wim->out_pack_chunk_size);
632 }
633
634 WIMLIBAPI void
635 wimlib_register_progress_function(WIMStruct *wim,
636                                   wimlib_progress_func_t progfunc,
637                                   void *progctx)
638 {
639         wim->progfunc = progfunc;
640         wim->progctx = progctx;
641 }
642
643 static int
644 open_wim_file(const tchar *filename, struct filedes *fd_ret)
645 {
646         int raw_fd;
647
648         raw_fd = topen(filename, O_RDONLY | O_BINARY);
649         if (raw_fd < 0) {
650                 ERROR_WITH_ERRNO("Can't open \"%"TS"\" read-only", filename);
651                 return WIMLIB_ERR_OPEN;
652         }
653         filedes_init(fd_ret, raw_fd);
654         return 0;
655 }
656
657 /*
658  * Begins the reading of a WIM file; opens the file and reads its header and
659  * lookup table, and optionally checks the integrity.
660  */
661 static int
662 begin_read(WIMStruct *wim, const void *wim_filename_or_fd, int open_flags)
663 {
664         int ret;
665         int xml_num_images;
666         const tchar *wimfile;
667
668         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
669                 wimfile = NULL;
670                 filedes_init(&wim->in_fd, *(const int*)wim_filename_or_fd);
671                 wim->in_fd.is_pipe = 1;
672         } else {
673                 wimfile = wim_filename_or_fd;
674                 ret = open_wim_file(wimfile, &wim->in_fd);
675                 if (ret)
676                         return ret;
677
678                 /* The absolute path to the WIM is requested so that
679                  * wimlib_overwrite() still works even if the process changes
680                  * its working directory.  This actually happens if a WIM is
681                  * mounted read-write, since the FUSE thread changes directory
682                  * to "/", and it needs to be able to find the WIM file again.
683                  *
684                  * This will break if the full path to the WIM changes in the
685                  * intervening time...
686                  *
687                  * Warning: in Windows native builds, realpath() calls the
688                  * replacement function in win32_replacements.c.
689                  */
690                 wim->filename = realpath(wimfile, NULL);
691                 if (wim->filename == NULL) {
692                         ERROR_WITH_ERRNO("Failed to resolve WIM filename");
693                         if (errno == ENOMEM)
694                                 return WIMLIB_ERR_NOMEM;
695                         else
696                                 return WIMLIB_ERR_OPEN;
697                 }
698         }
699
700         ret = read_wim_header(wim, &wim->hdr);
701         if (ret)
702                 return ret;
703
704         if (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) {
705                 WARNING("The WIM_HDR_FLAG_WRITE_IN_PROGRESS flag is set in the header of\n"
706                         "          \"%"TS"\".  It may be being changed by another process,\n"
707                         "          or a process may have crashed while writing the WIM.",
708                         wimfile);
709         }
710
711         if (open_flags & WIMLIB_OPEN_FLAG_WRITE_ACCESS) {
712                 ret = can_modify_wim(wim);
713                 if (ret)
714                         return ret;
715         }
716
717         if ((open_flags & WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT) &&
718             (wim->hdr.total_parts != 1))
719                 return WIMLIB_ERR_IS_SPLIT_WIM;
720
721         DEBUG("According to header, WIM contains %u images", wim->hdr.image_count);
722
723         /* If the boot index is invalid, print a warning and set it to 0 */
724         if (wim->hdr.boot_idx > wim->hdr.image_count) {
725                 WARNING("In `%"TS"', image %u is marked as bootable, "
726                         "but there are only %u images in the WIM",
727                         wimfile, wim->hdr.boot_idx, wim->hdr.image_count);
728                 wim->hdr.boot_idx = 0;
729         }
730
731         /* Check and cache the compression type */
732         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESSION) {
733                 if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZX) {
734                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
735                 } else if (wim->hdr.flags & (WIM_HDR_FLAG_COMPRESS_XPRESS |
736                                              WIM_HDR_FLAG_COMPRESS_XPRESS_2)) {
737                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
738                 } else if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZMS) {
739                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZMS;
740                 } else {
741                         ERROR("The compression flag is set on \"%"TS"\", but "
742                               "a flag for a recognized format is not",
743                               wimfile);
744                         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
745                 }
746         } else {
747                 wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
748         }
749         wim->out_compression_type = wim->compression_type;
750
751         /* Check and cache the chunk size.  */
752         wim->chunk_size = wim->hdr.chunk_size;
753         wim->out_chunk_size = wim->chunk_size;
754         if (!wim_chunk_size_valid(wim->chunk_size, wim->compression_type)) {
755                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
756                       "for compression type %"TS"!",
757                       wim->chunk_size,
758                       wimlib_get_compression_type_string(wim->compression_type));
759                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
760         }
761
762         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
763                 ret = check_wim_integrity(wim);
764                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
765                         WARNING("No integrity information for `%"TS"'; skipping "
766                                 "integrity check.", wimfile);
767                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
768                         ERROR("WIM is not intact! (Failed integrity check)");
769                         return WIMLIB_ERR_INTEGRITY;
770                 } else if (ret != WIM_INTEGRITY_OK) {
771                         return ret;
772                 }
773         }
774
775         if (wim->hdr.image_count != 0 && wim->hdr.part_number == 1) {
776                 wim->image_metadata = new_image_metadata_array(wim->hdr.image_count);
777                 if (wim->image_metadata == NULL)
778                         return WIMLIB_ERR_NOMEM;
779         }
780
781         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
782                 wim->lookup_table = new_lookup_table(9001);
783                 if (wim->lookup_table == NULL)
784                         return WIMLIB_ERR_NOMEM;
785         } else {
786
787                 ret = read_wim_xml_data(wim);
788                 if (ret)
789                         return ret;
790
791                 xml_num_images = wim_info_get_num_images(wim->wim_info);
792                 if (xml_num_images != wim->hdr.image_count) {
793                         ERROR("In the file `%"TS"', there are %u <IMAGE> elements "
794                               "in the XML data,", wimfile, xml_num_images);
795                         ERROR("but %u images in the WIM!  There must be exactly one "
796                               "<IMAGE> element per image.", wim->hdr.image_count);
797                         return WIMLIB_ERR_IMAGE_COUNT;
798                 }
799
800                 ret = read_wim_lookup_table(wim);
801                 if (ret)
802                         return ret;
803
804                 DEBUG("Done beginning read of WIM file `%"TS"'.", wimfile);
805         }
806         return 0;
807 }
808
809 int
810 open_wim_as_WIMStruct(const void *wim_filename_or_fd, int open_flags,
811                       WIMStruct **wim_ret,
812                       wimlib_progress_func_t progfunc, void *progctx)
813 {
814         WIMStruct *wim;
815         int ret;
816
817         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE)
818                 DEBUG("Opening pipable WIM from file descriptor %d.", *(const int*)wim_filename_or_fd);
819         else
820                 DEBUG("Opening WIM file \"%"TS"\"", (const tchar*)wim_filename_or_fd);
821
822         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
823         if (ret)
824                 return ret;
825
826         if (wim_ret == NULL)
827                 return WIMLIB_ERR_INVALID_PARAM;
828
829         wim = new_wim_struct();
830         if (wim == NULL)
831                 return WIMLIB_ERR_NOMEM;
832
833         wim->progfunc = progfunc;
834         wim->progctx = progctx;
835
836         ret = begin_read(wim, wim_filename_or_fd, open_flags);
837         if (ret) {
838                 wimlib_free(wim);
839                 return ret;
840         }
841
842         DEBUG("Successfully opened WIM and created WIMStruct.");
843         *wim_ret = wim;
844         return 0;
845 }
846
847 /* API function documented in wimlib.h  */
848 WIMLIBAPI int
849 wimlib_open_wim_with_progress(const tchar *wimfile, int open_flags,
850                               WIMStruct **wim_ret,
851                               wimlib_progress_func_t progfunc, void *progctx)
852 {
853         if (open_flags & ~(WIMLIB_OPEN_FLAG_CHECK_INTEGRITY |
854                            WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT |
855                            WIMLIB_OPEN_FLAG_WRITE_ACCESS))
856                 return WIMLIB_ERR_INVALID_PARAM;
857
858         return open_wim_as_WIMStruct(wimfile, open_flags, wim_ret,
859                                      progfunc, progctx);
860 }
861
862 /* API function documented in wimlib.h  */
863 WIMLIBAPI int
864 wimlib_open_wim(const tchar *wimfile, int open_flags, WIMStruct **wim_ret)
865 {
866         return wimlib_open_wim_with_progress(wimfile, open_flags, wim_ret,
867                                              NULL, NULL);
868 }
869
870 /* Checksum all streams that are unhashed (other than the metadata streams),
871  * merging them into the lookup table as needed.  This is a no-op unless the
872  * library has previously used to add or mount an image using the same
873  * WIMStruct. */
874 int
875 wim_checksum_unhashed_streams(WIMStruct *wim)
876 {
877         int ret;
878
879         if (!wim_has_metadata(wim))
880                 return 0;
881         for (int i = 0; i < wim->hdr.image_count; i++) {
882                 struct wim_lookup_table_entry *lte, *tmp;
883                 struct wim_image_metadata *imd = wim->image_metadata[i];
884                 image_for_each_unhashed_stream_safe(lte, tmp, imd) {
885                         struct wim_lookup_table_entry *new_lte;
886                         ret = hash_unhashed_stream(lte, wim->lookup_table, &new_lte);
887                         if (ret)
888                                 return ret;
889                         if (new_lte != lte)
890                                 free_lookup_table_entry(lte);
891                 }
892         }
893         return 0;
894 }
895
896 /*
897  * can_modify_wim - Check if a given WIM is writeable.  This is only the case if
898  * it meets the following three conditions:
899  *
900  * 1. Write access is allowed to the underlying file (if any) at the filesystem level.
901  * 2. The WIM is not part of a spanned set.
902  * 3. The WIM_HDR_FLAG_READONLY flag is not set in the WIM header.
903  *
904  * Return value is 0 if writable; WIMLIB_ERR_WIM_IS_READONLY otherwise.
905  */
906 int
907 can_modify_wim(WIMStruct *wim)
908 {
909         if (wim->filename) {
910                 if (taccess(wim->filename, W_OK)) {
911                         ERROR_WITH_ERRNO("Can't modify \"%"TS"\"", wim->filename);
912                         return WIMLIB_ERR_WIM_IS_READONLY;
913                 }
914         }
915         if (wim->hdr.total_parts != 1) {
916                 ERROR("Cannot modify \"%"TS"\": is part of a split WIM",
917                       wim->filename);
918                 return WIMLIB_ERR_WIM_IS_READONLY;
919         }
920         if (wim->hdr.flags & WIM_HDR_FLAG_READONLY) {
921                 ERROR("Cannot modify \"%"TS"\": is marked read-only",
922                       wim->filename);
923                 return WIMLIB_ERR_WIM_IS_READONLY;
924         }
925         return 0;
926 }
927
928 /*
929  * can_delete_from_wim - Check if files or images can be deleted from a given
930  * WIM file.
931  *
932  * This theoretically should be exactly the same as can_modify_wim(), but
933  * unfortunately, due to bugs in Microsoft's software that generate incorrect
934  * reference counts for some WIM resources, we need to run expensive
935  * verifications to make sure the reference counts are correct on all WIM
936  * resources.  Otherwise we might delete a WIM resource whose reference count
937  * has fallen to 0, but is actually still referenced somewhere.
938  */
939 int
940 can_delete_from_wim(WIMStruct *wim)
941 {
942         int ret;
943
944         ret = can_modify_wim(wim);
945         if (ret)
946                 return ret;
947         if (!wim->refcnts_ok) {
948                 ret = wim_recalculate_refcnts(wim);
949                 if (ret)
950                         return ret;
951         }
952         return 0;
953 }
954
955 /* API function documented in wimlib.h  */
956 WIMLIBAPI void
957 wimlib_free(WIMStruct *wim)
958 {
959         if (wim == NULL)
960                 return;
961
962         DEBUG("Freeing WIMStruct (filename=\"%"TS"\", image_count=%u)",
963               wim->filename, wim->hdr.image_count);
964
965         while (!list_empty(&wim->subwims)) {
966                 WIMStruct *subwim;
967
968                 subwim = list_entry(wim->subwims.next, WIMStruct, subwim_node);
969                 list_del(&subwim->subwim_node);
970                 DEBUG("Freeing subwim.");
971                 wimlib_free(subwim);
972         }
973
974         if (filedes_valid(&wim->in_fd))
975                 filedes_close(&wim->in_fd);
976         if (filedes_valid(&wim->out_fd))
977                 filedes_close(&wim->out_fd);
978
979         free_lookup_table(wim->lookup_table);
980
981         wimlib_free_decompressor(wim->decompressor);
982
983         FREE(wim->filename);
984         free_wim_info(wim->wim_info);
985         if (wim->image_metadata) {
986                 for (unsigned i = 0; i < wim->hdr.image_count; i++)
987                         put_image_metadata(wim->image_metadata[i], NULL);
988                 FREE(wim->image_metadata);
989         }
990         FREE(wim);
991 }
992
993 static bool
994 test_locale_ctype_utf8(void)
995 {
996 #ifdef __WIN32__
997         return false;
998 #else
999         char *ctype = nl_langinfo(CODESET);
1000
1001         return (!strstr(ctype, "UTF-8") ||
1002                 !strstr(ctype, "UTF8") ||
1003                 !strstr(ctype, "utf8") ||
1004                 !strstr(ctype, "utf-8"));
1005 #endif
1006 }
1007
1008 /* API function documented in wimlib.h  */
1009 WIMLIBAPI u32
1010 wimlib_get_version(void)
1011 {
1012         return WIMLIB_VERSION_CODE;
1013 }
1014
1015 static bool lib_initialized = false;
1016
1017 /* API function documented in wimlib.h  */
1018 WIMLIBAPI int
1019 wimlib_global_init(int init_flags)
1020 {
1021         if (lib_initialized)
1022                 return 0;
1023
1024 #ifdef ENABLE_ERROR_MESSAGES
1025         if (wimlib_error_file == NULL)
1026                 wimlib_error_file = stderr;
1027 #endif
1028
1029         if (init_flags & ~(WIMLIB_INIT_FLAG_ASSUME_UTF8 |
1030                            WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES |
1031                            WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES |
1032                            WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES |
1033                            WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
1034                            WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
1035                 return WIMLIB_ERR_INVALID_PARAM;
1036
1037         libxml_global_init();
1038         if (!(init_flags & WIMLIB_INIT_FLAG_ASSUME_UTF8)) {
1039                 wimlib_mbs_is_utf8 = test_locale_ctype_utf8();
1040         #ifdef WITH_NTFS_3G
1041                 if (!wimlib_mbs_is_utf8)
1042                         libntfs3g_global_init();
1043         #endif
1044         }
1045 #ifdef __WIN32__
1046         {
1047                 int ret = win32_global_init(init_flags);
1048                 if (ret)
1049                         return ret;
1050         }
1051 #endif
1052         iconv_global_init();
1053         init_upcase();
1054         if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE)
1055                 default_ignore_case = false;
1056         else if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE)
1057                 default_ignore_case = true;
1058         lib_initialized = true;
1059         return 0;
1060 }
1061
1062 /* API function documented in wimlib.h  */
1063 WIMLIBAPI void
1064 wimlib_global_cleanup(void)
1065 {
1066         if (!lib_initialized)
1067                 return;
1068         libxml_global_cleanup();
1069         iconv_global_cleanup();
1070 #ifdef __WIN32__
1071         win32_global_cleanup();
1072 #endif
1073
1074         wimlib_set_error_file(NULL);
1075         lib_initialized = false;
1076 }