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