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