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