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