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