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