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