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