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