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