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