]> wimlib.net Git - wimlib/blob - src/wim.c
Use LGPLv3+ for src/*.c
[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/dentry.h"
28 #include "wimlib/encoding.h"
29 #include "wimlib/file_io.h"
30 #include "wimlib/integrity.h"
31 #include "wimlib/lookup_table.h"
32 #include "wimlib/metadata.h"
33 #ifdef WITH_NTFS_3G
34 #  include "wimlib/ntfs_3g.h" /* for do_ntfs_umount() */
35 #endif
36 #include "wimlib/security.h"
37 #include "wimlib/wim.h"
38 #include "wimlib/xml.h"
39 #include "wimlib/version.h"
40
41 #ifdef __WIN32__
42 #  include "wimlib/win32.h" /* for realpath() replacement */
43 #endif
44
45 #include <errno.h>
46 #include <fcntl.h>
47 #ifndef __WIN32__
48 #  include <langinfo.h>
49 #endif
50 #include <stdlib.h>
51 #include <unistd.h>
52
53 static int
54 wim_default_pack_compression_type(void)
55 {
56         return WIMLIB_COMPRESSION_TYPE_LZMS;
57 }
58
59 static u32
60 wim_default_pack_chunk_size(int ctype) {
61         switch (ctype) {
62         case WIMLIB_COMPRESSION_TYPE_LZMS:
63                 return 1U << 25; /* 33554432  */
64         default:
65                 return 1U << 15; /* 32768     */
66         }
67 }
68
69 static WIMStruct *
70 new_wim_struct(void)
71 {
72         WIMStruct *wim = CALLOC(1, sizeof(WIMStruct));
73         if (!wim)
74                 return NULL;
75
76         filedes_invalidate(&wim->in_fd);
77         filedes_invalidate(&wim->out_fd);
78         wim->out_pack_compression_type = wim_default_pack_compression_type();
79         wim->out_pack_chunk_size = wim_default_pack_chunk_size(
80                                         wim->out_pack_compression_type);
81         INIT_LIST_HEAD(&wim->subwims);
82         return wim;
83 }
84
85 /* Determine if the chunk size is valid for the specified compression type.  */
86 static bool
87 wim_chunk_size_valid(u32 chunk_size, int ctype)
88 {
89         u32 order;
90
91         /* Chunk size is meaningless for uncompressed WIMs --- any value is
92          * okay.  */
93         if (ctype == WIMLIB_COMPRESSION_TYPE_NONE)
94                 return true;
95
96         /* Chunk size must be power of 2.  */
97         if (chunk_size == 0)
98                 return false;
99         order = bsr32(chunk_size);
100         if (chunk_size != 1U << order)
101                 return false;
102
103         /* Order        Size
104          * =====        ====
105          * 15           32768
106          * 16           65536
107          * 17           131072
108          * 18           262144
109          * 19           524288
110          * 20           1048576
111          * 21           2097152
112          * 22           4194304
113          * 23           8388608
114          * 24           16777216
115          * 25           33554432
116          * 26           67108864
117          */
118
119         /* See the documentation for the --chunk-size option of `wimlib-imagex
120          * capture' for information about allowed chunk sizes.  */
121         switch (ctype) {
122         case WIMLIB_COMPRESSION_TYPE_LZX:
123                 return order >= 15 && order <= 21;
124         case WIMLIB_COMPRESSION_TYPE_XPRESS:
125                 return order >= 12 && order <= 16;
126         case WIMLIB_COMPRESSION_TYPE_LZMS:
127                 return order >= 15 && order <= 30;
128         }
129         return false;
130 }
131
132 /* Return the default chunk size to use for the specified compression type.
133  *
134  * See notes above in wim_chunk_size_valid().  */
135 static u32
136 wim_default_chunk_size(int ctype)
137 {
138         switch (ctype) {
139         case WIMLIB_COMPRESSION_TYPE_LZMS:
140                 return 1U << 17; /* 131072  */
141         default:
142                 return 1U << 15; /* 32768   */
143         }
144 }
145
146 /*
147  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES,
148  * @visitor is called on the WIM once for each image, with each image selected
149  * as the current image in turn.  If @image is a certain image, @visitor is
150  * called on the WIM only once, with that image selected.
151  */
152 int
153 for_image(WIMStruct *wim, int image, int (*visitor)(WIMStruct *))
154 {
155         int ret;
156         int start;
157         int end;
158         int i;
159
160         if (image == WIMLIB_ALL_IMAGES) {
161                 start = 1;
162                 end = wim->hdr.image_count;
163         } else if (image >= 1 && image <= wim->hdr.image_count) {
164                 start = image;
165                 end = image;
166         } else {
167                 return WIMLIB_ERR_INVALID_IMAGE;
168         }
169         for (i = start; i <= end; i++) {
170                 ret = select_wim_image(wim, i);
171                 if (ret != 0)
172                         return ret;
173                 ret = visitor(wim);
174                 if (ret != 0)
175                         return ret;
176         }
177         return 0;
178 }
179
180 /* API function documented in wimlib.h  */
181 WIMLIBAPI int
182 wimlib_create_new_wim(int ctype, WIMStruct **wim_ret)
183 {
184         WIMStruct *wim;
185         struct wim_lookup_table *table;
186         int ret;
187
188         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
189         if (ret)
190                 return ret;
191
192         wim = new_wim_struct();
193         if (!wim)
194                 return WIMLIB_ERR_NOMEM;
195
196         ret = init_wim_header(&wim->hdr, ctype, wim_default_chunk_size(ctype));
197         if (ret)
198                 goto out_free_wim;
199
200         table = new_lookup_table(9001);
201         if (!table) {
202                 ret = WIMLIB_ERR_NOMEM;
203                 goto out_free_wim;
204         }
205         wim->lookup_table = table;
206         wim->refcnts_ok = 1;
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(wim, 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         int ret;
476
477         if (which & ~(WIMLIB_CHANGE_READONLY_FLAG |
478                       WIMLIB_CHANGE_GUID |
479                       WIMLIB_CHANGE_BOOT_INDEX |
480                       WIMLIB_CHANGE_RPFIX_FLAG))
481                 return WIMLIB_ERR_INVALID_PARAM;
482
483         if (which & WIMLIB_CHANGE_READONLY_FLAG) {
484                 if (info->is_marked_readonly)
485                         wim->hdr.flags |= WIM_HDR_FLAG_READONLY;
486                 else
487                         wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
488         }
489
490         if ((which & ~WIMLIB_CHANGE_READONLY_FLAG) == 0)
491                 return 0;
492
493         ret = can_modify_wim(wim);
494         if (ret)
495                 return ret;
496
497         if (which & WIMLIB_CHANGE_GUID)
498                 memcpy(wim->hdr.guid, info->guid, WIM_GUID_LEN);
499
500         if (which & WIMLIB_CHANGE_BOOT_INDEX) {
501                 if (info->boot_index > wim->hdr.image_count)
502                         return WIMLIB_ERR_INVALID_IMAGE;
503                 wim->hdr.boot_idx = info->boot_index;
504         }
505
506         if (which & WIMLIB_CHANGE_RPFIX_FLAG) {
507                 if (info->has_rpfix)
508                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
509                 else
510                         wim->hdr.flags &= ~WIM_HDR_FLAG_RP_FIX;
511         }
512         return 0;
513 }
514
515 static int
516 set_out_ctype(int ctype, u8 *out_ctype_p)
517 {
518         switch (ctype) {
519         case WIMLIB_COMPRESSION_TYPE_NONE:
520         case WIMLIB_COMPRESSION_TYPE_LZX:
521         case WIMLIB_COMPRESSION_TYPE_XPRESS:
522         case WIMLIB_COMPRESSION_TYPE_LZMS:
523                 *out_ctype_p = ctype;
524                 return 0;
525         }
526         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
527 }
528
529 /* API function documented in wimlib.h  */
530 WIMLIBAPI int
531 wimlib_set_output_compression_type(WIMStruct *wim, int ctype)
532 {
533         int ret = set_out_ctype(ctype, &wim->out_compression_type);
534         if (ret)
535                 return ret;
536
537         /* Reset the chunk size if it's no longer valid.  */
538         if (!wim_chunk_size_valid(wim->out_chunk_size, ctype))
539                 wim->out_chunk_size = wim_default_chunk_size(ctype);
540         return 0;
541 }
542
543 /* API function documented in wimlib.h  */
544 WIMLIBAPI int
545 wimlib_set_output_pack_compression_type(WIMStruct *wim, int ctype)
546 {
547         int ret = set_out_ctype(ctype, &wim->out_pack_compression_type);
548         if (ret)
549                 return ret;
550
551         /* Reset the chunk size if it's no longer valid.  */
552         if (!wim_chunk_size_valid(wim->out_pack_chunk_size, ctype))
553                 wim->out_pack_chunk_size = wim_default_pack_chunk_size(ctype);
554         return 0;
555 }
556
557 static int
558 set_out_chunk_size(u32 chunk_size, int ctype, u32 *out_chunk_size_p)
559 {
560         if (!wim_chunk_size_valid(chunk_size, ctype))
561                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
562
563         *out_chunk_size_p = chunk_size;
564         return 0;
565 }
566
567 /* API function documented in wimlib.h  */
568 WIMLIBAPI int
569 wimlib_set_output_chunk_size(WIMStruct *wim, uint32_t chunk_size)
570 {
571         if (chunk_size == 0) {
572                 wim->out_chunk_size =
573                         wim_default_chunk_size(wim->out_compression_type);
574                 return 0;
575         }
576
577         return set_out_chunk_size(chunk_size,
578                                   wim->out_compression_type,
579                                   &wim->out_chunk_size);
580 }
581
582 /* API function documented in wimlib.h  */
583 WIMLIBAPI int
584 wimlib_set_output_pack_chunk_size(WIMStruct *wim, uint32_t chunk_size)
585 {
586         if (chunk_size == 0) {
587                 wim->out_pack_chunk_size =
588                         wim_default_pack_chunk_size(wim->out_pack_compression_type);
589                 return 0;
590         }
591
592         return set_out_chunk_size(chunk_size,
593                                   wim->out_pack_compression_type,
594                                   &wim->out_pack_chunk_size);
595 }
596
597 WIMLIBAPI void
598 wimlib_register_progress_function(WIMStruct *wim,
599                                   wimlib_progress_func_t progfunc,
600                                   void *progctx)
601 {
602         wim->progfunc = progfunc;
603         wim->progctx = progctx;
604 }
605
606 static int
607 open_wim_file(const tchar *filename, struct filedes *fd_ret)
608 {
609         int raw_fd;
610
611         raw_fd = topen(filename, O_RDONLY | O_BINARY);
612         if (raw_fd < 0) {
613                 ERROR_WITH_ERRNO("Can't open \"%"TS"\" read-only", filename);
614                 return WIMLIB_ERR_OPEN;
615         }
616         filedes_init(fd_ret, raw_fd);
617         return 0;
618 }
619
620 /*
621  * Begins the reading of a WIM file; opens the file and reads its header and
622  * lookup table, and optionally checks the integrity.
623  */
624 static int
625 begin_read(WIMStruct *wim, const void *wim_filename_or_fd, int open_flags)
626 {
627         int ret;
628         int xml_num_images;
629         const tchar *wimfile;
630
631         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
632                 wimfile = NULL;
633                 filedes_init(&wim->in_fd, *(const int*)wim_filename_or_fd);
634                 wim->in_fd.is_pipe = 1;
635         } else {
636                 wimfile = wim_filename_or_fd;
637                 ret = open_wim_file(wimfile, &wim->in_fd);
638                 if (ret)
639                         return ret;
640
641                 /* The absolute path to the WIM is requested so that
642                  * wimlib_overwrite() still works even if the process changes
643                  * its working directory.  This actually happens if a WIM is
644                  * mounted read-write, since the FUSE thread changes directory
645                  * to "/", and it needs to be able to find the WIM file again.
646                  *
647                  * This will break if the full path to the WIM changes in the
648                  * intervening time...
649                  *
650                  * Warning: in Windows native builds, realpath() calls the
651                  * replacement function in win32_replacements.c.
652                  */
653                 wim->filename = realpath(wimfile, NULL);
654                 if (!wim->filename) {
655                         ERROR_WITH_ERRNO("Failed to get full path to file "
656                                          "\"%"TS"\"", wimfile);
657                         if (errno == ENOMEM)
658                                 return WIMLIB_ERR_NOMEM;
659                         else
660                                 return WIMLIB_ERR_NO_FILENAME;
661                 }
662         }
663
664         ret = read_wim_header(wim, &wim->hdr);
665         if (ret)
666                 return ret;
667
668         if (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) {
669                 WARNING("The WIM_HDR_FLAG_WRITE_IN_PROGRESS flag is set in the header of\n"
670                         "          \"%"TS"\".  It may be being changed by another process,\n"
671                         "          or a process may have crashed while writing the WIM.",
672                         wimfile);
673         }
674
675         if (open_flags & WIMLIB_OPEN_FLAG_WRITE_ACCESS) {
676                 ret = can_modify_wim(wim);
677                 if (ret)
678                         return ret;
679         }
680
681         if ((open_flags & WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT) &&
682             (wim->hdr.total_parts != 1))
683                 return WIMLIB_ERR_IS_SPLIT_WIM;
684
685         /* If the boot index is invalid, print a warning and set it to 0 */
686         if (wim->hdr.boot_idx > wim->hdr.image_count) {
687                 WARNING("Ignoring invalid boot index.");
688                 wim->hdr.boot_idx = 0;
689         }
690
691         /* Check and cache the compression type */
692         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESSION) {
693                 if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZX) {
694                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
695                 } else if (wim->hdr.flags & (WIM_HDR_FLAG_COMPRESS_XPRESS |
696                                              WIM_HDR_FLAG_COMPRESS_XPRESS_2)) {
697                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
698                 } else if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZMS) {
699                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZMS;
700                 } else {
701                         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
702                 }
703         } else {
704                 wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
705         }
706         wim->out_compression_type = wim->compression_type;
707
708         /* Check and cache the chunk size.  */
709         wim->chunk_size = wim->hdr.chunk_size;
710         wim->out_chunk_size = wim->chunk_size;
711         if (!wim_chunk_size_valid(wim->chunk_size, wim->compression_type)) {
712                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
713                       "for compression type %"TS"!", wim->chunk_size,
714                       wimlib_get_compression_type_string(wim->compression_type));
715                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
716         }
717
718         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
719                 ret = check_wim_integrity(wim);
720                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
721                         WARNING("\"%"TS"\" does not contain integrity "
722                                 "information.  Skipping integrity check.",
723                                 wimfile);
724                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
725                         return WIMLIB_ERR_INTEGRITY;
726                 } else if (ret != WIM_INTEGRITY_OK) {
727                         return ret;
728                 }
729         }
730
731         if (wim->hdr.image_count != 0 && wim->hdr.part_number == 1) {
732                 wim->image_metadata = new_image_metadata_array(wim->hdr.image_count);
733                 if (!wim->image_metadata)
734                         return WIMLIB_ERR_NOMEM;
735         }
736
737         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
738                 wim->lookup_table = new_lookup_table(9001);
739                 if (!wim->lookup_table)
740                         return WIMLIB_ERR_NOMEM;
741         } else {
742
743                 ret = read_wim_xml_data(wim);
744                 if (ret)
745                         return ret;
746
747                 xml_num_images = wim_info_get_num_images(wim->wim_info);
748                 if (xml_num_images != wim->hdr.image_count) {
749                         ERROR("The WIM's header is inconsistent with its XML data.\n"
750                               "        Please submit a bug report if you believe this "
751                               "WIM file should be considered valid.");
752                         return WIMLIB_ERR_IMAGE_COUNT;
753                 }
754
755                 ret = read_wim_lookup_table(wim);
756                 if (ret)
757                         return ret;
758         }
759         return 0;
760 }
761
762 int
763 open_wim_as_WIMStruct(const void *wim_filename_or_fd, int open_flags,
764                       WIMStruct **wim_ret,
765                       wimlib_progress_func_t progfunc, void *progctx)
766 {
767         WIMStruct *wim;
768         int ret;
769
770         ret = wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
771         if (ret)
772                 return ret;
773
774         wim = new_wim_struct();
775         if (!wim)
776                 return WIMLIB_ERR_NOMEM;
777
778         wim->progfunc = progfunc;
779         wim->progctx = progctx;
780
781         ret = begin_read(wim, wim_filename_or_fd, open_flags);
782         if (ret) {
783                 wimlib_free(wim);
784                 return ret;
785         }
786
787         *wim_ret = wim;
788         return 0;
789 }
790
791 /* API function documented in wimlib.h  */
792 WIMLIBAPI int
793 wimlib_open_wim_with_progress(const tchar *wimfile, int open_flags,
794                               WIMStruct **wim_ret,
795                               wimlib_progress_func_t progfunc, void *progctx)
796 {
797         if (open_flags & ~(WIMLIB_OPEN_FLAG_CHECK_INTEGRITY |
798                            WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT |
799                            WIMLIB_OPEN_FLAG_WRITE_ACCESS))
800                 return WIMLIB_ERR_INVALID_PARAM;
801
802         if (!wimfile || !*wimfile || !wim_ret)
803                 return WIMLIB_ERR_INVALID_PARAM;
804
805         return open_wim_as_WIMStruct(wimfile, open_flags, wim_ret,
806                                      progfunc, progctx);
807 }
808
809 /* API function documented in wimlib.h  */
810 WIMLIBAPI int
811 wimlib_open_wim(const tchar *wimfile, int open_flags, WIMStruct **wim_ret)
812 {
813         return wimlib_open_wim_with_progress(wimfile, open_flags, wim_ret,
814                                              NULL, NULL);
815 }
816
817 /* Checksum all streams that are unhashed (other than the metadata streams),
818  * merging them into the lookup table as needed.  This is a no-op unless the
819  * library has previously used to add or mount an image using the same
820  * WIMStruct. */
821 int
822 wim_checksum_unhashed_streams(WIMStruct *wim)
823 {
824         int ret;
825
826         if (!wim_has_metadata(wim))
827                 return 0;
828         for (int i = 0; i < wim->hdr.image_count; i++) {
829                 struct wim_lookup_table_entry *lte, *tmp;
830                 struct wim_image_metadata *imd = wim->image_metadata[i];
831                 image_for_each_unhashed_stream_safe(lte, tmp, imd) {
832                         struct wim_lookup_table_entry *new_lte;
833                         ret = hash_unhashed_stream(lte, wim->lookup_table, &new_lte);
834                         if (ret)
835                                 return ret;
836                         if (new_lte != lte)
837                                 free_lookup_table_entry(lte);
838                 }
839         }
840         return 0;
841 }
842
843 /*
844  * can_modify_wim - Check if a given WIM is writeable.  This is only the case if
845  * it meets the following three conditions:
846  *
847  * 1. Write access is allowed to the underlying file (if any) at the filesystem level.
848  * 2. The WIM is not part of a spanned set.
849  * 3. The WIM_HDR_FLAG_READONLY flag is not set in the WIM header.
850  *
851  * Return value is 0 if writable; WIMLIB_ERR_WIM_IS_READONLY otherwise.
852  */
853 int
854 can_modify_wim(WIMStruct *wim)
855 {
856         if (wim->filename) {
857                 if (taccess(wim->filename, W_OK)) {
858                         ERROR_WITH_ERRNO("Can't modify \"%"TS"\"", wim->filename);
859                         return WIMLIB_ERR_WIM_IS_READONLY;
860                 }
861         }
862         if (wim->hdr.total_parts != 1) {
863                 ERROR("Cannot modify \"%"TS"\": is part of a split WIM",
864                       wim->filename);
865                 return WIMLIB_ERR_WIM_IS_READONLY;
866         }
867         if (wim->hdr.flags & WIM_HDR_FLAG_READONLY) {
868                 ERROR("Cannot modify \"%"TS"\": is marked read-only",
869                       wim->filename);
870                 return WIMLIB_ERR_WIM_IS_READONLY;
871         }
872         return 0;
873 }
874
875 /*
876  * can_delete_from_wim - Check if files or images can be deleted from a given
877  * WIM file.
878  *
879  * This theoretically should be exactly the same as can_modify_wim(), but
880  * unfortunately, due to bugs in Microsoft's software that generate incorrect
881  * reference counts for some WIM resources, we need to run expensive
882  * verifications to make sure the reference counts are correct on all WIM
883  * resources.  Otherwise we might delete a WIM resource whose reference count
884  * has fallen to 0, but is actually still referenced somewhere.
885  */
886 int
887 can_delete_from_wim(WIMStruct *wim)
888 {
889         int ret;
890
891         ret = can_modify_wim(wim);
892         if (ret)
893                 return ret;
894         if (!wim->refcnts_ok) {
895                 ret = wim_recalculate_refcnts(wim);
896                 if (ret)
897                         return ret;
898         }
899         return 0;
900 }
901
902 /* API function documented in wimlib.h  */
903 WIMLIBAPI void
904 wimlib_free(WIMStruct *wim)
905 {
906         if (!wim)
907                 return;
908
909         while (!list_empty(&wim->subwims)) {
910                 WIMStruct *subwim;
911
912                 subwim = list_entry(wim->subwims.next, WIMStruct, subwim_node);
913                 list_del(&subwim->subwim_node);
914                 wimlib_free(subwim);
915         }
916
917         if (filedes_valid(&wim->in_fd))
918                 filedes_close(&wim->in_fd);
919         if (filedes_valid(&wim->out_fd))
920                 filedes_close(&wim->out_fd);
921
922         free_lookup_table(wim->lookup_table);
923
924         wimlib_free_decompressor(wim->decompressor);
925
926         FREE(wim->filename);
927         free_wim_info(wim->wim_info);
928         if (wim->image_metadata) {
929                 for (unsigned i = 0; i < wim->hdr.image_count; i++)
930                         put_image_metadata(wim->image_metadata[i], NULL);
931                 FREE(wim->image_metadata);
932         }
933         FREE(wim);
934 }
935
936 static bool
937 test_locale_ctype_utf8(void)
938 {
939 #ifdef __WIN32__
940         return false;
941 #else
942         char *ctype = nl_langinfo(CODESET);
943
944         return (!strstr(ctype, "UTF-8") ||
945                 !strstr(ctype, "UTF8") ||
946                 !strstr(ctype, "utf8") ||
947                 !strstr(ctype, "utf-8"));
948 #endif
949 }
950
951 /* API function documented in wimlib.h  */
952 WIMLIBAPI u32
953 wimlib_get_version(void)
954 {
955         return WIMLIB_VERSION_CODE;
956 }
957
958 static bool lib_initialized = false;
959
960 /* API function documented in wimlib.h  */
961 WIMLIBAPI int
962 wimlib_global_init(int init_flags)
963 {
964         if (lib_initialized)
965                 return 0;
966
967 #ifdef ENABLE_ERROR_MESSAGES
968         if (!wimlib_error_file)
969                 wimlib_error_file = stderr;
970 #endif
971
972         if (init_flags & ~(WIMLIB_INIT_FLAG_ASSUME_UTF8 |
973                            WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES |
974                            WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES |
975                            WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES |
976                            WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
977                            WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
978                 return WIMLIB_ERR_INVALID_PARAM;
979
980         libxml_global_init();
981         if (!(init_flags & WIMLIB_INIT_FLAG_ASSUME_UTF8)) {
982                 wimlib_mbs_is_utf8 = test_locale_ctype_utf8();
983         #ifdef WITH_NTFS_3G
984                 if (!wimlib_mbs_is_utf8)
985                         libntfs3g_global_init();
986         #endif
987         }
988 #ifdef __WIN32__
989         {
990                 int ret = win32_global_init(init_flags);
991                 if (ret)
992                         return ret;
993         }
994 #endif
995         iconv_global_init();
996         init_upcase();
997         if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE)
998                 default_ignore_case = false;
999         else if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE)
1000                 default_ignore_case = true;
1001         lib_initialized = true;
1002         return 0;
1003 }
1004
1005 /* API function documented in wimlib.h  */
1006 WIMLIBAPI void
1007 wimlib_global_cleanup(void)
1008 {
1009         if (!lib_initialized)
1010                 return;
1011         libxml_global_cleanup();
1012         iconv_global_cleanup();
1013 #ifdef __WIN32__
1014         win32_global_cleanup();
1015 #endif
1016
1017         wimlib_set_error_file(NULL);
1018         lib_initialized = false;
1019 }