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