]> wimlib.net Git - wimlib/blob - src/wim.c
Remove some dead assignments
[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 #include "wimlib/compressor_ops.h"
42 #include "wimlib/decompressor_ops.h"
43 #include "wimlib/version.h"
44
45 #ifdef __WIN32__
46 #  include "wimlib/win32.h" /* for realpath() replacement */
47 #endif
48
49 #include <errno.h>
50 #include <fcntl.h>
51 #ifndef __WIN32__
52 #  include <langinfo.h>
53 #endif
54 #include <limits.h>
55 #include <stdarg.h>
56 #include <stdlib.h>
57 #include <unistd.h>
58
59 static int
60 wim_default_pack_compression_type(void)
61 {
62         return WIMLIB_COMPRESSION_TYPE_LZMS;
63 }
64
65 static u32
66 wim_default_pack_chunk_size(int ctype) {
67         switch (ctype) {
68         case WIMLIB_COMPRESSION_TYPE_LZMS:
69                 return 1U << 26; /* 67108864  */
70         default:
71                 return 1U << 15; /* 32768     */
72         }
73 }
74
75 static WIMStruct *
76 new_wim_struct(void)
77 {
78         WIMStruct *wim = CALLOC(1, sizeof(WIMStruct));
79         if (wim) {
80                 filedes_invalidate(&wim->in_fd);
81                 filedes_invalidate(&wim->out_fd);
82                 wim->out_pack_compression_type = wim_default_pack_compression_type();
83                 wim->out_pack_chunk_size = wim_default_pack_chunk_size(
84                                                 wim->out_pack_compression_type);
85                 INIT_LIST_HEAD(&wim->subwims);
86         }
87         return wim;
88 }
89
90 /* Determine if the chunk size is valid for the specified compression type.  */
91 static bool
92 wim_chunk_size_valid(u32 chunk_size, int ctype)
93 {
94         u32 order;
95
96         /* Chunk size is meaningless for uncompressed WIMs --- any value is
97          * okay.  */
98         if (ctype == WIMLIB_COMPRESSION_TYPE_NONE)
99                 return true;
100
101         /* Chunk size must be power of 2.  */
102         if (chunk_size == 0)
103                 return false;
104         order = bsr32(chunk_size);
105         if (chunk_size != 1U << order)
106                 return false;
107
108         /* Order        Size
109          * =====        ====
110          * 15           32768
111          * 16           65536
112          * 17           131072
113          * 18           262144
114          * 19           524288
115          * 20           1048576
116          * 21           2097152
117          * 22           4194304
118          * 23           8388608
119          * 24           16777216
120          * 25           33554432
121          * 26           67108864
122          */
123
124         /* See the documentation for the --chunk-size option of `wimlib-imagex
125          * capture' for information about allowed chunk sizes.  */
126         switch (ctype) {
127         case WIMLIB_COMPRESSION_TYPE_LZX:
128                 return order >= 15 && order <= 21;
129
130         case WIMLIB_COMPRESSION_TYPE_XPRESS:
131                 return order >= 12 && order <= 26;
132         case WIMLIB_COMPRESSION_TYPE_LZMS:
133                 return order >= 15 && order <= 30;
134         }
135         return false;
136 }
137
138 /* Return the default chunk size to use for the specified compression type.
139  *
140  * See notes above in wim_chunk_size_valid().  */
141 static u32
142 wim_default_chunk_size(int ctype)
143 {
144         switch (ctype) {
145         case WIMLIB_COMPRESSION_TYPE_LZMS:
146                 return 1U << 17; /* 131072  */
147         default:
148                 return 1U << 15; /* 32768   */
149         }
150 }
151
152 /*
153  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES,
154  * @visitor is called on the WIM once for each image, with each image selected
155  * as the current image in turn.  If @image is a certain image, @visitor is
156  * called on the WIM only once, with that image selected.
157  */
158 int
159 for_image(WIMStruct *wim, int image, int (*visitor)(WIMStruct *))
160 {
161         int ret;
162         int start;
163         int end;
164         int i;
165
166         if (image == WIMLIB_ALL_IMAGES) {
167                 start = 1;
168                 end = wim->hdr.image_count;
169         } else if (image >= 1 && image <= wim->hdr.image_count) {
170                 start = image;
171                 end = image;
172         } else {
173                 return WIMLIB_ERR_INVALID_IMAGE;
174         }
175         for (i = start; i <= end; i++) {
176                 ret = select_wim_image(wim, i);
177                 if (ret != 0)
178                         return ret;
179                 ret = visitor(wim);
180                 if (ret != 0)
181                         return ret;
182         }
183         return 0;
184 }
185
186 /* API function documented in wimlib.h  */
187 WIMLIBAPI int
188 wimlib_create_new_wim(int ctype, WIMStruct **wim_ret)
189 {
190         WIMStruct *wim;
191         struct wim_lookup_table *table;
192         int ret;
193
194         wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
195
196         DEBUG("Creating new WIM with %"TS" compression.",
197               wimlib_get_compression_type_string(ctype));
198
199         /* Allocate the WIMStruct. */
200         wim = new_wim_struct();
201         if (wim == NULL)
202                 return WIMLIB_ERR_NOMEM;
203
204         ret = init_wim_header(&wim->hdr, ctype, wim_default_chunk_size(ctype));
205         if (ret)
206                 goto out_free;
207
208         table = new_lookup_table(9001);
209         if (table == NULL) {
210                 ret = WIMLIB_ERR_NOMEM;
211                 goto out_free;
212         }
213         wim->lookup_table = table;
214         wim->refcnts_ok = 1;
215         wim->compression_type = ctype;
216         wim->out_compression_type = ctype;
217         wim->chunk_size = wim->hdr.chunk_size;
218         wim->out_chunk_size = wim->hdr.chunk_size;
219         *wim_ret = wim;
220         return 0;
221 out_free:
222         FREE(wim);
223         return ret;
224 }
225
226 static void
227 destroy_image_metadata(struct wim_image_metadata *imd,
228                        struct wim_lookup_table *table,
229                        bool free_metadata_lte)
230 {
231         free_dentry_tree(imd->root_dentry, table);
232         imd->root_dentry = NULL;
233         free_wim_security_data(imd->security_data);
234         imd->security_data = NULL;
235
236         if (free_metadata_lte) {
237                 free_lookup_table_entry(imd->metadata_lte);
238                 imd->metadata_lte = NULL;
239         }
240         if (table == NULL) {
241                 struct wim_lookup_table_entry *lte, *tmp;
242                 list_for_each_entry_safe(lte, tmp, &imd->unhashed_streams, unhashed_list)
243                         free_lookup_table_entry(lte);
244         }
245         INIT_LIST_HEAD(&imd->unhashed_streams);
246         INIT_LIST_HEAD(&imd->inode_list);
247 #ifdef WITH_NTFS_3G
248         if (imd->ntfs_vol) {
249                 do_ntfs_umount(imd->ntfs_vol);
250                 imd->ntfs_vol = NULL;
251         }
252 #endif
253 }
254
255 void
256 put_image_metadata(struct wim_image_metadata *imd,
257                    struct wim_lookup_table *table)
258 {
259         if (imd && --imd->refcnt == 0) {
260                 destroy_image_metadata(imd, table, true);
261                 FREE(imd);
262         }
263 }
264
265 /* Appends the specified image metadata structure to the array of image metadata
266  * for a WIM, and increments the image count. */
267 int
268 append_image_metadata(WIMStruct *wim, struct wim_image_metadata *imd)
269 {
270         struct wim_image_metadata **imd_array;
271
272         DEBUG("Reallocating image metadata array for image_count = %u",
273               wim->hdr.image_count + 1);
274         imd_array = REALLOC(wim->image_metadata,
275                             sizeof(wim->image_metadata[0]) * (wim->hdr.image_count + 1));
276
277         if (imd_array == NULL)
278                 return WIMLIB_ERR_NOMEM;
279         wim->image_metadata = imd_array;
280         imd_array[wim->hdr.image_count++] = imd;
281         return 0;
282 }
283
284 struct wim_image_metadata *
285 new_image_metadata(void)
286 {
287         struct wim_image_metadata *imd;
288
289         imd = CALLOC(1, sizeof(*imd));
290         if (imd) {
291                 imd->refcnt = 1;
292                 INIT_LIST_HEAD(&imd->inode_list);
293                 INIT_LIST_HEAD(&imd->unhashed_streams);
294                 DEBUG("Created new image metadata (refcnt=1)");
295         } else {
296                 ERROR_WITH_ERRNO("Failed to allocate new image metadata structure");
297         }
298         return imd;
299 }
300
301 static struct wim_image_metadata **
302 new_image_metadata_array(unsigned num_images)
303 {
304         struct wim_image_metadata **imd_array;
305
306         DEBUG("Creating new image metadata array for %u images",
307               num_images);
308
309         imd_array = CALLOC(num_images, sizeof(imd_array[0]));
310
311         if (imd_array == NULL) {
312                 ERROR("Failed to allocate memory for %u image metadata structures",
313                       num_images);
314                 return NULL;
315         }
316         for (unsigned i = 0; i < num_images; i++) {
317                 imd_array[i] = new_image_metadata();
318                 if (imd_array[i] == NULL) {
319                         for (unsigned j = 0; j < i; j++)
320                                 put_image_metadata(imd_array[j], NULL);
321                         FREE(imd_array);
322                         return NULL;
323                 }
324         }
325         return imd_array;
326 }
327
328
329 /*
330  * Load the metadata for the specified WIM image into memory and set it
331  * as the WIMStruct's currently selected image.
332  *
333  * @wim
334  *      The WIMStruct for the WIM.
335  * @image
336  *      The 1-based index of the image in the WIM to select.
337  *
338  * On success, 0 will be returned, wim->current_image will be set to
339  * @image, and wim_get_current_image_metadata() can be used to retrieve
340  * metadata information for the image.
341  *
342  * On failure, WIMLIB_ERR_INVALID_IMAGE, WIMLIB_ERR_METADATA_NOT_FOUND,
343  * or another error code will be returned.
344  */
345 int
346 select_wim_image(WIMStruct *wim, int image)
347 {
348         struct wim_image_metadata *imd;
349         int ret;
350
351         DEBUG("Selecting image %d", image);
352
353         if (image == WIMLIB_NO_IMAGE) {
354                 ERROR("Invalid image: %d", WIMLIB_NO_IMAGE);
355                 return WIMLIB_ERR_INVALID_IMAGE;
356         }
357
358         if (image == wim->current_image)
359                 return 0;
360
361         if (image < 1 || image > wim->hdr.image_count) {
362                 ERROR("Cannot select image %d: There are only %u images",
363                       image, wim->hdr.image_count);
364                 return WIMLIB_ERR_INVALID_IMAGE;
365         }
366
367         if (!wim_has_metadata(wim)) {
368                 ERROR("\"%"TS"\" does not contain metadata resources!", wim->filename);
369                 if (wim->hdr.part_number != 1)
370                         ERROR("Specify the first part of the split WIM instead.");
371                 return WIMLIB_ERR_METADATA_NOT_FOUND;
372         }
373
374         /* If a valid image is currently selected, its metadata can be freed if
375          * it has not been modified.  */
376         if (wim->current_image != WIMLIB_NO_IMAGE) {
377                 imd = wim_get_current_image_metadata(wim);
378                 if (!imd->modified) {
379                         wimlib_assert(list_empty(&imd->unhashed_streams));
380                         DEBUG("Freeing image %u", wim->current_image);
381                         destroy_image_metadata(imd, NULL, false);
382                 }
383         }
384         wim->current_image = image;
385         imd = wim_get_current_image_metadata(wim);
386         if (imd->root_dentry || imd->modified) {
387                 ret = 0;
388         } else {
389                 ret = read_metadata_resource(wim, imd);
390                 if (ret)
391                         wim->current_image = WIMLIB_NO_IMAGE;
392         }
393         return ret;
394 }
395
396
397 /* API function documented in wimlib.h  */
398 WIMLIBAPI const tchar *
399 wimlib_get_compression_type_string(int ctype)
400 {
401         switch (ctype) {
402                 case WIMLIB_COMPRESSION_TYPE_NONE:
403                         return T("None");
404                 case WIMLIB_COMPRESSION_TYPE_LZX:
405                         return T("LZX");
406                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
407                         return T("XPRESS");
408                 case WIMLIB_COMPRESSION_TYPE_LZMS:
409                         return T("LZMS");
410                 default:
411                         return T("Invalid");
412         }
413 }
414
415 /* API function documented in wimlib.h  */
416 WIMLIBAPI int
417 wimlib_resolve_image(WIMStruct *wim, const tchar *image_name_or_num)
418 {
419         tchar *p;
420         long image;
421         int i;
422
423         if (!image_name_or_num || !*image_name_or_num)
424                 return WIMLIB_NO_IMAGE;
425
426         if (!tstrcasecmp(image_name_or_num, T("all"))
427             || !tstrcasecmp(image_name_or_num, T("*")))
428                 return WIMLIB_ALL_IMAGES;
429         image = tstrtol(image_name_or_num, &p, 10);
430         if (p != image_name_or_num && *p == T('\0') && image > 0) {
431                 if (image > wim->hdr.image_count)
432                         return WIMLIB_NO_IMAGE;
433                 return image;
434         } else {
435                 for (i = 1; i <= wim->hdr.image_count; i++) {
436                         if (!tstrcmp(image_name_or_num,
437                                      wimlib_get_image_name(wim, i)))
438                                 return i;
439                 }
440                 return WIMLIB_NO_IMAGE;
441         }
442 }
443
444 /* API function documented in wimlib.h  */
445 WIMLIBAPI void
446 wimlib_print_available_images(const WIMStruct *wim, int image)
447 {
448         int first;
449         int last;
450         int i;
451         int n;
452         if (image == WIMLIB_ALL_IMAGES) {
453                 n = tprintf(T("Available Images:\n"));
454                 first = 1;
455                 last = wim->hdr.image_count;
456         } else if (image >= 1 && image <= wim->hdr.image_count) {
457                 n = tprintf(T("Information for Image %d\n"), image);
458                 first = image;
459                 last = image;
460         } else {
461                 tprintf(T("wimlib_print_available_images(): Invalid image %d"),
462                         image);
463                 return;
464         }
465         for (i = 0; i < n - 1; i++)
466                 tputchar(T('-'));
467         tputchar(T('\n'));
468         for (i = first; i <= last; i++)
469                 print_image_info(wim->wim_info, i);
470 }
471
472 /* API function documented in wimlib.h  */
473 WIMLIBAPI int
474 wimlib_get_wim_info(WIMStruct *wim, struct wimlib_wim_info *info)
475 {
476         memset(info, 0, sizeof(struct wimlib_wim_info));
477         memcpy(info->guid, wim->hdr.guid, WIMLIB_GUID_LEN);
478         info->image_count = wim->hdr.image_count;
479         info->boot_index = wim->hdr.boot_idx;
480         info->wim_version = wim->hdr.wim_version;
481         info->chunk_size = wim->chunk_size;
482         info->part_number = wim->hdr.part_number;
483         info->total_parts = wim->hdr.total_parts;
484         info->compression_type = wim->compression_type;
485         info->total_bytes = wim_info_get_total_bytes(wim->wim_info);
486         info->has_integrity_table = wim_has_integrity_table(wim);
487         info->opened_from_file = (wim->filename != NULL);
488         info->is_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) ||
489                              (wim->hdr.total_parts != 1) ||
490                              (wim->filename && taccess(wim->filename, W_OK));
491         info->has_rpfix = (wim->hdr.flags & WIM_HDR_FLAG_RP_FIX) != 0;
492         info->is_marked_readonly = (wim->hdr.flags & WIM_HDR_FLAG_READONLY) != 0;
493         info->write_in_progress = (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) != 0;
494         info->metadata_only = (wim->hdr.flags & WIM_HDR_FLAG_METADATA_ONLY) != 0;
495         info->resource_only = (wim->hdr.flags & WIM_HDR_FLAG_RESOURCE_ONLY) != 0;
496         info->spanned = (wim->hdr.flags & WIM_HDR_FLAG_SPANNED) != 0;
497         info->pipable = wim_is_pipable(wim);
498         return 0;
499 }
500
501 /* API function documented in wimlib.h  */
502 WIMLIBAPI int
503 wimlib_set_wim_info(WIMStruct *wim, const struct wimlib_wim_info *info, int which)
504 {
505         int ret;
506
507         if (which & ~(WIMLIB_CHANGE_READONLY_FLAG |
508                       WIMLIB_CHANGE_GUID |
509                       WIMLIB_CHANGE_BOOT_INDEX |
510                       WIMLIB_CHANGE_RPFIX_FLAG))
511                 return WIMLIB_ERR_INVALID_PARAM;
512
513         if (which & WIMLIB_CHANGE_READONLY_FLAG) {
514                 if (info->is_marked_readonly)
515                         wim->hdr.flags |= WIM_HDR_FLAG_READONLY;
516                 else
517                         wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
518         }
519
520         if ((which & ~WIMLIB_CHANGE_READONLY_FLAG) == 0)
521                 return 0;
522
523         ret = can_modify_wim(wim);
524         if (ret)
525                 return ret;
526
527         if (which & WIMLIB_CHANGE_GUID)
528                 memcpy(wim->hdr.guid, info->guid, WIM_GUID_LEN);
529
530         if (which & WIMLIB_CHANGE_BOOT_INDEX) {
531                 if (info->boot_index > wim->hdr.image_count) {
532                         ERROR("%u is not 0 or a valid image in the WIM to mark as bootable",
533                               info->boot_index);
534                         return WIMLIB_ERR_INVALID_IMAGE;
535                 }
536                 wim->hdr.boot_idx = info->boot_index;
537         }
538
539         if (which & WIMLIB_CHANGE_RPFIX_FLAG) {
540                 if (info->has_rpfix)
541                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
542                 else
543                         wim->hdr.flags &= ~WIM_HDR_FLAG_RP_FIX;
544         }
545         return 0;
546 }
547
548 static int
549 set_out_ctype(int ctype, u8 *out_ctype_p)
550 {
551         switch (ctype) {
552         case WIMLIB_COMPRESSION_TYPE_INVALID:
553                 break;
554         case WIMLIB_COMPRESSION_TYPE_NONE:
555         case WIMLIB_COMPRESSION_TYPE_LZX:
556         case WIMLIB_COMPRESSION_TYPE_XPRESS:
557         case WIMLIB_COMPRESSION_TYPE_LZMS:
558                 *out_ctype_p = ctype;
559                 return 0;
560         }
561         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
562 }
563
564 /* API function documented in wimlib.h  */
565 WIMLIBAPI int
566 wimlib_set_output_compression_type(WIMStruct *wim, int ctype)
567 {
568         int ret = set_out_ctype(ctype, &wim->out_compression_type);
569         if (ret)
570                 return ret;
571
572         /* Reset the chunk size if it's no longer valid.  */
573         if (!wim_chunk_size_valid(wim->out_chunk_size, ctype))
574                 wim->out_chunk_size = wim_default_chunk_size(ctype);
575         return 0;
576 }
577
578 /* API function documented in wimlib.h  */
579 WIMLIBAPI int
580 wimlib_set_output_pack_compression_type(WIMStruct *wim, int ctype)
581 {
582         int ret = set_out_ctype(ctype, &wim->out_pack_compression_type);
583         if (ret)
584                 return ret;
585
586         /* Reset the chunk size if it's no longer valid.  */
587         if (!wim_chunk_size_valid(wim->out_pack_chunk_size, ctype))
588                 wim->out_pack_chunk_size = wim_default_pack_chunk_size(ctype);
589         return 0;
590 }
591
592 static int
593 set_out_chunk_size(u32 chunk_size, int ctype, u32 *out_chunk_size_p)
594 {
595         if (!wim_chunk_size_valid(chunk_size, ctype)) {
596                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
597                       "for compression type %"TS"!",
598                       chunk_size,
599                       wimlib_get_compression_type_string(ctype));
600                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
601         }
602
603         *out_chunk_size_p = chunk_size;
604         return 0;
605 }
606
607 /* API function documented in wimlib.h  */
608 WIMLIBAPI int
609 wimlib_set_output_chunk_size(WIMStruct *wim, uint32_t chunk_size)
610 {
611         if (chunk_size == 0) {
612                 wim->out_chunk_size =
613                         wim_default_chunk_size(wim->out_compression_type);
614                 return 0;
615         }
616
617         return set_out_chunk_size(chunk_size,
618                                   wim->out_compression_type,
619                                   &wim->out_chunk_size);
620 }
621
622 /* API function documented in wimlib.h  */
623 WIMLIBAPI int
624 wimlib_set_output_pack_chunk_size(WIMStruct *wim, uint32_t chunk_size)
625 {
626         if (chunk_size == 0) {
627                 wim->out_pack_chunk_size =
628                         wim_default_pack_chunk_size(wim->out_pack_compression_type);
629                 return 0;
630         }
631
632         return set_out_chunk_size(chunk_size,
633                                   wim->out_pack_compression_type,
634                                   &wim->out_pack_chunk_size);
635 }
636
637 WIMLIBAPI void
638 wimlib_register_progress_function(WIMStruct *wim,
639                                   wimlib_progress_func_t progfunc,
640                                   void *progctx)
641 {
642         wim->progfunc = progfunc;
643         wim->progctx = progctx;
644 }
645
646 static int
647 open_wim_file(const tchar *filename, struct filedes *fd_ret)
648 {
649         int raw_fd;
650
651         raw_fd = topen(filename, O_RDONLY | O_BINARY);
652         if (raw_fd < 0) {
653                 ERROR_WITH_ERRNO("Can't open \"%"TS"\" read-only", filename);
654                 return WIMLIB_ERR_OPEN;
655         }
656         filedes_init(fd_ret, raw_fd);
657         return 0;
658 }
659
660 /*
661  * Begins the reading of a WIM file; opens the file and reads its header and
662  * lookup table, and optionally checks the integrity.
663  */
664 static int
665 begin_read(WIMStruct *wim, const void *wim_filename_or_fd, int open_flags)
666 {
667         int ret;
668         int xml_num_images;
669         const tchar *wimfile;
670
671         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
672                 wimfile = NULL;
673                 filedes_init(&wim->in_fd, *(const int*)wim_filename_or_fd);
674                 wim->in_fd.is_pipe = 1;
675         } else {
676                 wimfile = wim_filename_or_fd;
677                 ret = open_wim_file(wimfile, &wim->in_fd);
678                 if (ret)
679                         return ret;
680
681                 /* The absolute path to the WIM is requested so that
682                  * wimlib_overwrite() still works even if the process changes
683                  * its working directory.  This actually happens if a WIM is
684                  * mounted read-write, since the FUSE thread changes directory
685                  * to "/", and it needs to be able to find the WIM file again.
686                  *
687                  * This will break if the full path to the WIM changes in the
688                  * intervening time...
689                  *
690                  * Warning: in Windows native builds, realpath() calls the
691                  * replacement function in win32_replacements.c.
692                  */
693                 wim->filename = realpath(wimfile, NULL);
694                 if (wim->filename == NULL) {
695                         ERROR_WITH_ERRNO("Failed to resolve WIM filename");
696                         if (errno == ENOMEM)
697                                 return WIMLIB_ERR_NOMEM;
698                         else
699                                 return WIMLIB_ERR_OPEN;
700                 }
701         }
702
703         ret = read_wim_header(wim, &wim->hdr);
704         if (ret)
705                 return ret;
706
707         if (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) {
708                 WARNING("The WIM_HDR_FLAG_WRITE_IN_PROGRESS flag is set in the header of\n"
709                         "          \"%"TS"\".  It may be being changed by another process,\n"
710                         "          or a process may have crashed while writing the WIM.",
711                         wimfile);
712         }
713
714         if (open_flags & WIMLIB_OPEN_FLAG_WRITE_ACCESS) {
715                 ret = can_modify_wim(wim);
716                 if (ret)
717                         return ret;
718         }
719
720         if ((open_flags & WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT) &&
721             (wim->hdr.total_parts != 1))
722                 return WIMLIB_ERR_IS_SPLIT_WIM;
723
724         DEBUG("According to header, WIM contains %u images", wim->hdr.image_count);
725
726         /* If the boot index is invalid, print a warning and set it to 0 */
727         if (wim->hdr.boot_idx > wim->hdr.image_count) {
728                 WARNING("In `%"TS"', image %u is marked as bootable, "
729                         "but there are only %u images in the WIM",
730                         wimfile, wim->hdr.boot_idx, wim->hdr.image_count);
731                 wim->hdr.boot_idx = 0;
732         }
733
734         /* Check and cache the compression type */
735         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESSION) {
736                 if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZX) {
737                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
738                 } else if (wim->hdr.flags & (WIM_HDR_FLAG_COMPRESS_XPRESS |
739                                              WIM_HDR_FLAG_COMPRESS_XPRESS_2)) {
740                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
741                 } else if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZMS) {
742                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZMS;
743                 } else {
744                         ERROR("The compression flag is set on \"%"TS"\", but "
745                               "a flag for a recognized format is not",
746                               wimfile);
747                         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
748                 }
749         } else {
750                 wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
751         }
752         wim->out_compression_type = wim->compression_type;
753
754         /* Check and cache the chunk size.  */
755         wim->chunk_size = wim->hdr.chunk_size;
756         wim->out_chunk_size = wim->chunk_size;
757         if (!wim_chunk_size_valid(wim->chunk_size, wim->compression_type)) {
758                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
759                       "for compression type %"TS"!",
760                       wim->chunk_size,
761                       wimlib_get_compression_type_string(wim->compression_type));
762                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
763         }
764
765         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
766                 ret = check_wim_integrity(wim);
767                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
768                         WARNING("No integrity information for `%"TS"'; skipping "
769                                 "integrity check.", wimfile);
770                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
771                         ERROR("WIM is not intact! (Failed integrity check)");
772                         return WIMLIB_ERR_INTEGRITY;
773                 } else if (ret != WIM_INTEGRITY_OK) {
774                         return ret;
775                 }
776         }
777
778         if (wim->hdr.image_count != 0 && wim->hdr.part_number == 1) {
779                 wim->image_metadata = new_image_metadata_array(wim->hdr.image_count);
780                 if (wim->image_metadata == NULL)
781                         return WIMLIB_ERR_NOMEM;
782         }
783
784         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
785                 wim->lookup_table = new_lookup_table(9001);
786                 if (wim->lookup_table == NULL)
787                         return WIMLIB_ERR_NOMEM;
788         } else {
789
790                 ret = read_wim_xml_data(wim);
791                 if (ret)
792                         return ret;
793
794                 xml_num_images = wim_info_get_num_images(wim->wim_info);
795                 if (xml_num_images != wim->hdr.image_count) {
796                         ERROR("In the file `%"TS"', there are %u <IMAGE> elements "
797                               "in the XML data,", wimfile, xml_num_images);
798                         ERROR("but %u images in the WIM!  There must be exactly one "
799                               "<IMAGE> element per image.", wim->hdr.image_count);
800                         return WIMLIB_ERR_IMAGE_COUNT;
801                 }
802
803                 ret = read_wim_lookup_table(wim);
804                 if (ret)
805                         return ret;
806
807                 DEBUG("Done beginning read of WIM file `%"TS"'.", wimfile);
808         }
809         return 0;
810 }
811
812 int
813 open_wim_as_WIMStruct(const void *wim_filename_or_fd, int open_flags,
814                       WIMStruct **wim_ret,
815                       wimlib_progress_func_t progfunc, void *progctx)
816 {
817         WIMStruct *wim;
818         int ret;
819
820         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE)
821                 DEBUG("Opening pipable WIM from file descriptor %d.", *(const int*)wim_filename_or_fd);
822         else
823                 DEBUG("Opening WIM file \"%"TS"\"", (const tchar*)wim_filename_or_fd);
824
825         wimlib_global_init(WIMLIB_INIT_FLAG_ASSUME_UTF8);
826
827         if (wim_ret == NULL)
828                 return WIMLIB_ERR_INVALID_PARAM;
829
830         wim = new_wim_struct();
831         if (wim == NULL)
832                 return WIMLIB_ERR_NOMEM;
833
834         wim->progfunc = progfunc;
835         wim->progctx = progctx;
836
837         ret = begin_read(wim, wim_filename_or_fd, open_flags);
838         if (ret) {
839                 wimlib_free(wim);
840                 return ret;
841         }
842
843         DEBUG("Successfully opened WIM and created WIMStruct.");
844         *wim_ret = wim;
845         return 0;
846 }
847
848 /* API function documented in wimlib.h  */
849 WIMLIBAPI int
850 wimlib_open_wim_with_progress(const tchar *wimfile, int open_flags,
851                               WIMStruct **wim_ret,
852                               wimlib_progress_func_t progfunc, void *progctx)
853 {
854         if (open_flags & ~(WIMLIB_OPEN_FLAG_CHECK_INTEGRITY |
855                            WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT |
856                            WIMLIB_OPEN_FLAG_WRITE_ACCESS))
857                 return WIMLIB_ERR_INVALID_PARAM;
858
859         return open_wim_as_WIMStruct(wimfile, open_flags, wim_ret,
860                                      progfunc, progctx);
861 }
862
863 /* API function documented in wimlib.h  */
864 WIMLIBAPI int
865 wimlib_open_wim(const tchar *wimfile, int open_flags, WIMStruct **wim_ret)
866 {
867         return wimlib_open_wim_with_progress(wimfile, open_flags, wim_ret,
868                                              NULL, NULL);
869 }
870
871 /* Checksum all streams that are unhashed (other than the metadata streams),
872  * merging them into the lookup table as needed.  This is a no-op unless the
873  * library has previously used to add or mount an image using the same
874  * WIMStruct. */
875 int
876 wim_checksum_unhashed_streams(WIMStruct *wim)
877 {
878         int ret;
879
880         if (!wim_has_metadata(wim))
881                 return 0;
882         for (int i = 0; i < wim->hdr.image_count; i++) {
883                 struct wim_lookup_table_entry *lte, *tmp;
884                 struct wim_image_metadata *imd = wim->image_metadata[i];
885                 image_for_each_unhashed_stream_safe(lte, tmp, imd) {
886                         struct wim_lookup_table_entry *new_lte;
887                         ret = hash_unhashed_stream(lte, wim->lookup_table, &new_lte);
888                         if (ret)
889                                 return ret;
890                         if (new_lte != lte)
891                                 free_lookup_table_entry(lte);
892                 }
893         }
894         return 0;
895 }
896
897 /*
898  * can_modify_wim - Check if a given WIM is writeable.  This is only the case if
899  * it meets the following three conditions:
900  *
901  * 1. Write access is allowed to the underlying file (if any) at the filesystem level.
902  * 2. The WIM is not part of a spanned set.
903  * 3. The WIM_HDR_FLAG_READONLY flag is not set in the WIM header.
904  *
905  * Return value is 0 if writable; WIMLIB_ERR_WIM_IS_READONLY otherwise.
906  */
907 int
908 can_modify_wim(WIMStruct *wim)
909 {
910         if (wim->filename) {
911                 if (taccess(wim->filename, W_OK)) {
912                         ERROR_WITH_ERRNO("Can't modify \"%"TS"\"", wim->filename);
913                         return WIMLIB_ERR_WIM_IS_READONLY;
914                 }
915         }
916         if (wim->hdr.total_parts != 1) {
917                 ERROR("Cannot modify \"%"TS"\": is part of a split WIM",
918                       wim->filename);
919                 return WIMLIB_ERR_WIM_IS_READONLY;
920         }
921         if (wim->hdr.flags & WIM_HDR_FLAG_READONLY) {
922                 ERROR("Cannot modify \"%"TS"\": is marked read-only",
923                       wim->filename);
924                 return WIMLIB_ERR_WIM_IS_READONLY;
925         }
926         return 0;
927 }
928
929 /*
930  * can_delete_from_wim - Check if files or images can be deleted from a given
931  * WIM file.
932  *
933  * This theoretically should be exactly the same as can_modify_wim(), but
934  * unfortunately, due to bugs in Microsoft's software that generate incorrect
935  * reference counts for some WIM resources, we need to run expensive
936  * verifications to make sure the reference counts are correct on all WIM
937  * resources.  Otherwise we might delete a WIM resource whose reference count
938  * has fallen to 0, but is actually still referenced somewhere.
939  */
940 int
941 can_delete_from_wim(WIMStruct *wim)
942 {
943         int ret;
944
945         ret = can_modify_wim(wim);
946         if (ret)
947                 return ret;
948         if (!wim->refcnts_ok) {
949                 ret = wim_recalculate_refcnts(wim);
950                 if (ret)
951                         return ret;
952         }
953         return 0;
954 }
955
956 /* API function documented in wimlib.h  */
957 WIMLIBAPI void
958 wimlib_free(WIMStruct *wim)
959 {
960         if (wim == NULL)
961                 return;
962
963         DEBUG("Freeing WIMStruct (filename=\"%"TS"\", image_count=%u)",
964               wim->filename, wim->hdr.image_count);
965
966         while (!list_empty(&wim->subwims)) {
967                 WIMStruct *subwim;
968
969                 subwim = list_entry(wim->subwims.next, WIMStruct, subwim_node);
970                 list_del(&subwim->subwim_node);
971                 DEBUG("Freeing subwim.");
972                 wimlib_free(subwim);
973         }
974
975         if (filedes_valid(&wim->in_fd))
976                 filedes_close(&wim->in_fd);
977         if (filedes_valid(&wim->out_fd))
978                 filedes_close(&wim->out_fd);
979
980         free_lookup_table(wim->lookup_table);
981
982         wimlib_free_decompressor(wim->decompressor);
983
984         FREE(wim->filename);
985         free_wim_info(wim->wim_info);
986         if (wim->image_metadata) {
987                 for (unsigned i = 0; i < wim->hdr.image_count; i++)
988                         put_image_metadata(wim->image_metadata[i], NULL);
989                 FREE(wim->image_metadata);
990         }
991         FREE(wim);
992 }
993
994 static bool
995 test_locale_ctype_utf8(void)
996 {
997 #ifdef __WIN32__
998         return false;
999 #else
1000         char *ctype = nl_langinfo(CODESET);
1001
1002         return (!strstr(ctype, "UTF-8") ||
1003                 !strstr(ctype, "UTF8") ||
1004                 !strstr(ctype, "utf8") ||
1005                 !strstr(ctype, "utf-8"));
1006 #endif
1007 }
1008
1009 /* API function documented in wimlib.h  */
1010 WIMLIBAPI u32
1011 wimlib_get_version(void)
1012 {
1013         return WIMLIB_VERSION_CODE;
1014 }
1015
1016 /* API function documented in wimlib.h  */
1017 WIMLIBAPI int
1018 wimlib_global_init(int init_flags)
1019 {
1020         static bool already_inited = false;
1021
1022         if (already_inited)
1023                 return 0;
1024
1025         if (init_flags & ~(WIMLIB_INIT_FLAG_ASSUME_UTF8 |
1026                            WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES |
1027                            WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES |
1028                            WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES |
1029                            WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
1030                            WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
1031                 return WIMLIB_ERR_INVALID_PARAM;
1032
1033         libxml_global_init();
1034         if (!(init_flags & WIMLIB_INIT_FLAG_ASSUME_UTF8)) {
1035                 wimlib_mbs_is_utf8 = test_locale_ctype_utf8();
1036         #ifdef WITH_NTFS_3G
1037                 if (!wimlib_mbs_is_utf8)
1038                         libntfs3g_global_init();
1039         #endif
1040         }
1041 #ifdef __WIN32__
1042         {
1043                 int ret = win32_global_init(init_flags);
1044                 if (ret)
1045                         return ret;
1046         }
1047 #endif
1048         init_upcase();
1049         if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE)
1050                 default_ignore_case = false;
1051         else if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE)
1052                 default_ignore_case = true;
1053         already_inited = true;
1054         return 0;
1055 }
1056
1057 /* API function documented in wimlib.h  */
1058 WIMLIBAPI void
1059 wimlib_global_cleanup(void)
1060 {
1061         libxml_global_cleanup();
1062         iconv_global_cleanup();
1063 #ifdef __WIN32__
1064         win32_global_cleanup();
1065 #endif
1066         cleanup_decompressor_params();
1067         cleanup_compressor_params();
1068 }