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