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