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