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