]> wimlib.net Git - wimlib/blob - src/wim.c
avl_tree: replace 'AVL_INLINE' with 'forceinline'
[wimlib] / src / wim.c
1 /*
2  * wim.c - High-level code dealing with WIMStructs and images.
3  */
4
5 /*
6  * Copyright (C) 2012-2016 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #ifndef __WIN32__
29 #  include <langinfo.h>
30 #endif
31 #include <pthread.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34
35 #include "wimlib.h"
36 #include "wimlib/assert.h"
37 #include "wimlib/blob_table.h"
38 #include "wimlib/dentry.h"
39 #include "wimlib/encoding.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/integrity.h"
42 #include "wimlib/metadata.h"
43 #include "wimlib/security.h"
44 #include "wimlib/wim.h"
45 #include "wimlib/xml.h"
46 #include "wimlib/win32.h"
47
48 /* Information about the available compression types for the WIM format.  */
49 static const struct {
50         const tchar *name;
51         u32 min_chunk_size;
52         u32 max_chunk_size;
53         u32 default_nonsolid_chunk_size;
54         u32 default_solid_chunk_size;
55 } wim_ctype_info[] = {
56         [WIMLIB_COMPRESSION_TYPE_NONE] = {
57                 .name = T("None"),
58                 .min_chunk_size = 0,
59                 .max_chunk_size = 0,
60                 .default_nonsolid_chunk_size = 0,
61                 .default_solid_chunk_size = 0,
62         },
63         [WIMLIB_COMPRESSION_TYPE_XPRESS] = {
64                 .name = T("XPRESS"),
65                 .min_chunk_size = 4096,
66                 .max_chunk_size = 65536,
67                 .default_nonsolid_chunk_size = 32768,
68                 .default_solid_chunk_size = 32768,
69         },
70         [WIMLIB_COMPRESSION_TYPE_LZX] = {
71                 .name = T("LZX"),
72                 .min_chunk_size = 32768,
73                 .max_chunk_size = 2097152,
74                 .default_nonsolid_chunk_size = 32768,
75                 .default_solid_chunk_size = 32768,
76         },
77         [WIMLIB_COMPRESSION_TYPE_LZMS] = {
78                 .name = T("LZMS"),
79                 .min_chunk_size = 32768,
80                 .max_chunk_size = 1073741824,
81                 .default_nonsolid_chunk_size = 131072,
82                 .default_solid_chunk_size = 67108864,
83         },
84 };
85
86 /* Is the specified compression type valid?  */
87 static bool
88 wim_compression_type_valid(enum wimlib_compression_type ctype)
89 {
90         return (unsigned)ctype < ARRAY_LEN(wim_ctype_info) &&
91                wim_ctype_info[(unsigned)ctype].name != NULL;
92 }
93
94 /* Is the specified chunk size valid for the compression type?  */
95 static bool
96 wim_chunk_size_valid(u32 chunk_size, enum wimlib_compression_type ctype)
97 {
98         if (!(chunk_size == 0 || is_power_of_2(chunk_size)))
99                 return false;
100
101         return chunk_size >= wim_ctype_info[(unsigned)ctype].min_chunk_size &&
102                chunk_size <= wim_ctype_info[(unsigned)ctype].max_chunk_size;
103 }
104
105 /* Return the default chunk size to use for the specified compression type in
106  * non-solid resources.  */
107 static u32
108 wim_default_nonsolid_chunk_size(enum wimlib_compression_type ctype)
109 {
110         return wim_ctype_info[(unsigned)ctype].default_nonsolid_chunk_size;
111 }
112
113 /* Return the default chunk size to use for the specified compression type in
114  * solid resources.  */
115 static u32
116 wim_default_solid_chunk_size(enum wimlib_compression_type ctype)
117 {
118         return wim_ctype_info[(unsigned)ctype].default_solid_chunk_size;
119 }
120
121 /* Return the default compression type to use in solid resources.  */
122 static enum wimlib_compression_type
123 wim_default_solid_compression_type(void)
124 {
125         return WIMLIB_COMPRESSION_TYPE_LZMS;
126 }
127
128 static int
129 is_blob_in_solid_resource(struct blob_descriptor *blob, void *_ignore)
130 {
131         return blob->blob_location == BLOB_IN_WIM &&
132                 (blob->rdesc->flags & WIM_RESHDR_FLAG_SOLID);
133 }
134
135 bool
136 wim_has_solid_resources(const WIMStruct *wim)
137 {
138         return for_blob_in_table(wim->blob_table, is_blob_in_solid_resource, NULL);
139 }
140
141 static WIMStruct *
142 new_wim_struct(void)
143 {
144         WIMStruct *wim = CALLOC(1, sizeof(WIMStruct));
145         if (!wim)
146                 return NULL;
147
148         wim->refcnt = 1;
149         filedes_invalidate(&wim->in_fd);
150         filedes_invalidate(&wim->out_fd);
151         wim->out_solid_compression_type = wim_default_solid_compression_type();
152         wim->out_solid_chunk_size = wim_default_solid_chunk_size(
153                                         wim->out_solid_compression_type);
154         return wim;
155 }
156
157 /* API function documented in wimlib.h  */
158 WIMLIBAPI int
159 wimlib_create_new_wim(enum wimlib_compression_type ctype, WIMStruct **wim_ret)
160 {
161         int ret;
162         WIMStruct *wim;
163
164         ret = wimlib_global_init(0);
165         if (ret)
166                 return ret;
167
168         if (!wim_ret)
169                 return WIMLIB_ERR_INVALID_PARAM;
170
171         if (!wim_compression_type_valid(ctype))
172                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
173
174         wim = new_wim_struct();
175         if (!wim)
176                 return WIMLIB_ERR_NOMEM;
177
178         wim->xml_info = xml_new_info_struct();
179         wim->blob_table = new_blob_table(64);
180         if (!wim->xml_info || !wim->blob_table) {
181                 wimlib_free(wim);
182                 return WIMLIB_ERR_NOMEM;
183         }
184
185         /* Fill in wim->hdr with default values  */
186         wim->hdr.magic = WIM_MAGIC;
187         wim->hdr.wim_version = WIM_VERSION_DEFAULT;
188         wim->hdr.flags = 0;
189         wim->hdr.chunk_size = 0;
190         generate_guid(wim->hdr.guid);
191         wim->hdr.part_number = 1;
192         wim->hdr.total_parts = 1;
193         wim->hdr.image_count = 0;
194         wim->hdr.boot_idx = 0;
195
196         wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
197         wim->chunk_size = wim->hdr.chunk_size;
198
199         /* Set the output compression type  */
200         wim->out_compression_type = ctype;
201         wim->out_chunk_size = wim_default_nonsolid_chunk_size(ctype);
202
203         *wim_ret = wim;
204         return 0;
205 }
206
207 static void
208 unload_image_metadata(struct wim_image_metadata *imd)
209 {
210         free_dentry_tree(imd->root_dentry, NULL);
211         imd->root_dentry = NULL;
212         free_wim_security_data(imd->security_data);
213         imd->security_data = NULL;
214         INIT_HLIST_HEAD(&imd->inode_list);
215 }
216
217 /* Release a reference to the specified image metadata.  This assumes that no
218  * WIMStruct has the image selected.  */
219 void
220 put_image_metadata(struct wim_image_metadata *imd)
221 {
222         struct blob_descriptor *blob, *tmp;
223
224         if (!imd)
225                 return;
226         wimlib_assert(imd->refcnt > 0);
227         if (--imd->refcnt != 0)
228                 return;
229         wimlib_assert(imd->selected_refcnt == 0);
230         unload_image_metadata(imd);
231         list_for_each_entry_safe(blob, tmp, &imd->unhashed_blobs, unhashed_list)
232                 free_blob_descriptor(blob);
233         free_blob_descriptor(imd->metadata_blob);
234         FREE(imd);
235 }
236
237 /* Appends the specified image metadata structure to the array of image metadata
238  * for a WIM, and increments the image count. */
239 int
240 append_image_metadata(WIMStruct *wim, struct wim_image_metadata *imd)
241 {
242         struct wim_image_metadata **imd_array;
243
244         if (!wim_has_metadata(wim))
245                 return WIMLIB_ERR_METADATA_NOT_FOUND;
246
247         if (wim->hdr.image_count >= MAX_IMAGES)
248                 return WIMLIB_ERR_IMAGE_COUNT;
249
250         imd_array = REALLOC(wim->image_metadata,
251                             sizeof(wim->image_metadata[0]) * (wim->hdr.image_count + 1));
252
253         if (!imd_array)
254                 return WIMLIB_ERR_NOMEM;
255         wim->image_metadata = imd_array;
256         imd_array[wim->hdr.image_count++] = imd;
257         return 0;
258 }
259
260 static struct wim_image_metadata *
261 new_image_metadata(struct blob_descriptor *metadata_blob,
262                    struct wim_security_data *security_data)
263 {
264         struct wim_image_metadata *imd;
265
266         imd = CALLOC(1, sizeof(*imd));
267         if (!imd)
268                 return NULL;
269
270         metadata_blob->is_metadata = 1;
271         imd->refcnt = 1;
272         imd->selected_refcnt = 0;
273         imd->root_dentry = NULL;
274         imd->security_data = security_data;
275         imd->metadata_blob = metadata_blob;
276         INIT_HLIST_HEAD(&imd->inode_list);
277         INIT_LIST_HEAD(&imd->unhashed_blobs);
278         imd->stats_outdated = false;
279         return imd;
280 }
281
282 /* Create an image metadata structure for a new empty image.  */
283 struct wim_image_metadata *
284 new_empty_image_metadata(void)
285 {
286         struct blob_descriptor *metadata_blob;
287         struct wim_security_data *security_data;
288         struct wim_image_metadata *imd;
289
290         metadata_blob = new_blob_descriptor();
291         security_data = new_wim_security_data();
292         if (metadata_blob && security_data) {
293                 metadata_blob->refcnt = 1;
294                 imd = new_image_metadata(metadata_blob, security_data);
295                 if (imd)
296                         return imd;
297         }
298         free_blob_descriptor(metadata_blob);
299         FREE(security_data);
300         return NULL;
301 }
302
303 /* Create an image metadata structure that refers to the specified metadata
304  * resource and is initially not loaded.  */
305 struct wim_image_metadata *
306 new_unloaded_image_metadata(struct blob_descriptor *metadata_blob)
307 {
308         wimlib_assert(metadata_blob->blob_location == BLOB_IN_WIM);
309         return new_image_metadata(metadata_blob, NULL);
310 }
311
312 /*
313  * Load the metadata for the specified WIM image into memory and set it
314  * as the WIMStruct's currently selected image.
315  *
316  * @wim
317  *      The WIMStruct for the WIM.
318  * @image
319  *      The 1-based index of the image in the WIM to select.
320  *
321  * On success, 0 will be returned, wim->current_image will be set to
322  * @image, and wim_get_current_image_metadata() can be used to retrieve
323  * metadata information for the image.
324  *
325  * On failure, WIMLIB_ERR_INVALID_IMAGE, WIMLIB_ERR_METADATA_NOT_FOUND,
326  * or another error code will be returned.
327  */
328 int
329 select_wim_image(WIMStruct *wim, int image)
330 {
331         struct wim_image_metadata *imd;
332         int ret;
333
334         if (image == WIMLIB_NO_IMAGE)
335                 return WIMLIB_ERR_INVALID_IMAGE;
336
337         if (image == wim->current_image)
338                 return 0;
339
340         if (image < 1 || image > wim->hdr.image_count)
341                 return WIMLIB_ERR_INVALID_IMAGE;
342
343         if (!wim_has_metadata(wim))
344                 return WIMLIB_ERR_METADATA_NOT_FOUND;
345
346         deselect_current_wim_image(wim);
347
348         imd = wim->image_metadata[image - 1];
349         if (!is_image_loaded(imd)) {
350                 ret = read_metadata_resource(imd);
351                 if (ret)
352                         return ret;
353         }
354         wim->current_image = image;
355         imd->selected_refcnt++;
356         return 0;
357 }
358
359 /*
360  * Deselect the WIMStruct's currently selected image, if any.  To reduce memory
361  * usage, possibly unload the newly deselected image's metadata from memory.
362  */
363 void
364 deselect_current_wim_image(WIMStruct *wim)
365 {
366         struct wim_image_metadata *imd;
367
368         if (wim->current_image == WIMLIB_NO_IMAGE)
369                 return;
370         imd = wim_get_current_image_metadata(wim);
371         wimlib_assert(imd->selected_refcnt > 0);
372         imd->selected_refcnt--;
373         wim->current_image = WIMLIB_NO_IMAGE;
374
375         if (can_unload_image(imd)) {
376                 wimlib_assert(list_empty(&imd->unhashed_blobs));
377                 unload_image_metadata(imd);
378         }
379 }
380
381 /*
382  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES,
383  * @visitor is called on the WIM once for each image, with each image selected
384  * as the current image in turn.  If @image is a certain image, @visitor is
385  * called on the WIM only once, with that image selected.
386  */
387 int
388 for_image(WIMStruct *wim, int image, int (*visitor)(WIMStruct *))
389 {
390         int ret;
391         int start;
392         int end;
393         int i;
394
395         if (image == WIMLIB_ALL_IMAGES) {
396                 start = 1;
397                 end = wim->hdr.image_count;
398         } else if (image >= 1 && image <= wim->hdr.image_count) {
399                 start = image;
400                 end = image;
401         } else {
402                 return WIMLIB_ERR_INVALID_IMAGE;
403         }
404         for (i = start; i <= end; i++) {
405                 ret = select_wim_image(wim, i);
406                 if (ret != 0)
407                         return ret;
408                 ret = visitor(wim);
409                 if (ret != 0)
410                         return ret;
411         }
412         return 0;
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                 xml_print_image_info(wim->xml_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         copy_guid(info->guid, wim->hdr.guid);
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 = xml_get_total_bytes(wim->xml_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         if (which & ~(WIMLIB_CHANGE_READONLY_FLAG |
506                       WIMLIB_CHANGE_GUID |
507                       WIMLIB_CHANGE_BOOT_INDEX |
508                       WIMLIB_CHANGE_RPFIX_FLAG))
509                 return WIMLIB_ERR_INVALID_PARAM;
510
511         if ((which & WIMLIB_CHANGE_BOOT_INDEX) &&
512             info->boot_index > wim->hdr.image_count)
513                 return WIMLIB_ERR_INVALID_IMAGE;
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_GUID)
523                 copy_guid(wim->hdr.guid, info->guid);
524
525         if (which & WIMLIB_CHANGE_BOOT_INDEX)
526                 wim->hdr.boot_idx = info->boot_index;
527
528         if (which & WIMLIB_CHANGE_RPFIX_FLAG) {
529                 if (info->has_rpfix)
530                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
531                 else
532                         wim->hdr.flags &= ~WIM_HDR_FLAG_RP_FIX;
533         }
534         return 0;
535 }
536
537 /* API function documented in wimlib.h  */
538 WIMLIBAPI int
539 wimlib_set_output_compression_type(WIMStruct *wim,
540                                    enum wimlib_compression_type ctype)
541 {
542         if (!wim_compression_type_valid(ctype))
543                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
544
545         wim->out_compression_type = ctype;
546
547         /* Reset the chunk size if it's no longer valid.  */
548         if (!wim_chunk_size_valid(wim->out_chunk_size, ctype))
549                 wim->out_chunk_size = wim_default_nonsolid_chunk_size(ctype);
550         return 0;
551 }
552
553 /* API function documented in wimlib.h  */
554 WIMLIBAPI int
555 wimlib_set_output_pack_compression_type(WIMStruct *wim,
556                                         enum wimlib_compression_type ctype)
557 {
558         if (!wim_compression_type_valid(ctype))
559                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
560
561         /* Solid resources can't be uncompressed.  */
562         if (ctype == WIMLIB_COMPRESSION_TYPE_NONE)
563                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
564
565         wim->out_solid_compression_type = ctype;
566
567         /* Reset the chunk size if it's no longer valid.  */
568         if (!wim_chunk_size_valid(wim->out_solid_chunk_size, ctype))
569                 wim->out_solid_chunk_size = wim_default_solid_chunk_size(ctype);
570         return 0;
571 }
572
573 /* API function documented in wimlib.h  */
574 WIMLIBAPI int
575 wimlib_set_output_chunk_size(WIMStruct *wim, u32 chunk_size)
576 {
577         if (chunk_size == 0) {
578                 wim->out_chunk_size =
579                         wim_default_nonsolid_chunk_size(wim->out_compression_type);
580                 return 0;
581         }
582
583         if (!wim_chunk_size_valid(chunk_size, wim->out_compression_type))
584                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
585
586         wim->out_chunk_size = chunk_size;
587         return 0;
588 }
589
590 /* API function documented in wimlib.h  */
591 WIMLIBAPI int
592 wimlib_set_output_pack_chunk_size(WIMStruct *wim, u32 chunk_size)
593 {
594         if (chunk_size == 0) {
595                 wim->out_solid_chunk_size =
596                         wim_default_solid_chunk_size(wim->out_solid_compression_type);
597                 return 0;
598         }
599
600         if (!wim_chunk_size_valid(chunk_size, wim->out_solid_compression_type))
601                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
602
603         wim->out_solid_chunk_size = chunk_size;
604         return 0;
605 }
606
607 /* API function documented in wimlib.h  */
608 WIMLIBAPI const tchar *
609 wimlib_get_compression_type_string(enum wimlib_compression_type ctype)
610 {
611         if (!wim_compression_type_valid(ctype))
612                 return T("Invalid");
613
614         return wim_ctype_info[(unsigned)ctype].name;
615 }
616
617 WIMLIBAPI void
618 wimlib_register_progress_function(WIMStruct *wim,
619                                   wimlib_progress_func_t progfunc,
620                                   void *progctx)
621 {
622         wim->progfunc = progfunc;
623         wim->progctx = progctx;
624 }
625
626 static int
627 open_wim_file(const tchar *filename, struct filedes *fd_ret)
628 {
629         int raw_fd;
630
631         raw_fd = topen(filename, O_RDONLY | O_BINARY);
632         if (raw_fd < 0) {
633                 ERROR_WITH_ERRNO("Can't open \"%"TS"\" read-only", filename);
634                 return WIMLIB_ERR_OPEN;
635         }
636         filedes_init(fd_ret, raw_fd);
637         return 0;
638 }
639
640 /*
641  * Begins the reading of a WIM file; opens the file and reads its header and
642  * blob table, and optionally checks the integrity.
643  */
644 static int
645 begin_read(WIMStruct *wim, const void *wim_filename_or_fd, int open_flags)
646 {
647         int ret;
648         const tchar *wimfile;
649
650         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
651                 wimfile = NULL;
652                 filedes_init(&wim->in_fd, *(const int*)wim_filename_or_fd);
653                 wim->in_fd.is_pipe = 1;
654         } else {
655                 wimfile = wim_filename_or_fd;
656                 ret = open_wim_file(wimfile, &wim->in_fd);
657                 if (ret)
658                         return ret;
659
660                 /* The absolute path to the WIM is requested so that
661                  * wimlib_overwrite() still works even if the process changes
662                  * its working directory.  This actually happens if a WIM is
663                  * mounted read-write, since the FUSE thread changes directory
664                  * to "/", and it needs to be able to find the WIM file again.
665                  *
666                  * This will break if the full path to the WIM changes in the
667                  * intervening time...
668                  *
669                  * Warning: in Windows native builds, realpath() calls the
670                  * replacement function in win32_replacements.c.
671                  */
672                 wim->filename = realpath(wimfile, NULL);
673                 if (!wim->filename) {
674                         ERROR_WITH_ERRNO("Failed to get full path to file "
675                                          "\"%"TS"\"", wimfile);
676                         if (errno == ENOMEM)
677                                 return WIMLIB_ERR_NOMEM;
678                         else
679                                 return WIMLIB_ERR_NO_FILENAME;
680                 }
681         }
682
683         ret = read_wim_header(wim, &wim->hdr);
684         if (ret)
685                 return ret;
686
687         if (wim->hdr.flags & WIM_HDR_FLAG_WRITE_IN_PROGRESS) {
688                 WARNING("The WIM_HDR_FLAG_WRITE_IN_PROGRESS flag is set in the header of\n"
689                         "          \"%"TS"\".  It may be being changed by another process,\n"
690                         "          or a process may have crashed while writing the WIM.",
691                         wimfile);
692         }
693
694         if (open_flags & WIMLIB_OPEN_FLAG_WRITE_ACCESS) {
695                 ret = can_modify_wim(wim);
696                 if (ret)
697                         return ret;
698         }
699
700         if ((open_flags & WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT) &&
701             (wim->hdr.total_parts != 1))
702                 return WIMLIB_ERR_IS_SPLIT_WIM;
703
704         /* If the boot index is invalid, print a warning and set it to 0 */
705         if (wim->hdr.boot_idx > wim->hdr.image_count) {
706                 WARNING("Ignoring invalid boot index.");
707                 wim->hdr.boot_idx = 0;
708         }
709
710         /* Check and cache the compression type */
711         if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESSION) {
712                 if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZX) {
713                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
714                 } else if (wim->hdr.flags & (WIM_HDR_FLAG_COMPRESS_XPRESS |
715                                              WIM_HDR_FLAG_COMPRESS_XPRESS_2)) {
716                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
717                 } else if (wim->hdr.flags & WIM_HDR_FLAG_COMPRESS_LZMS) {
718                         wim->compression_type = WIMLIB_COMPRESSION_TYPE_LZMS;
719                 } else {
720                         return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
721                 }
722         } else {
723                 wim->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
724         }
725         wim->out_compression_type = wim->compression_type;
726
727         /* Check and cache the chunk size.  */
728         wim->chunk_size = wim->hdr.chunk_size;
729         wim->out_chunk_size = wim->chunk_size;
730         if (!wim_chunk_size_valid(wim->chunk_size, wim->compression_type)) {
731                 ERROR("Invalid chunk size (%"PRIu32" bytes) "
732                       "for compression type %"TS"!", wim->chunk_size,
733                       wimlib_get_compression_type_string(wim->compression_type));
734                 return WIMLIB_ERR_INVALID_CHUNK_SIZE;
735         }
736
737         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
738                 ret = check_wim_integrity(wim);
739                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
740                         WARNING("\"%"TS"\" does not contain integrity "
741                                 "information.  Skipping integrity check.",
742                                 wimfile);
743                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
744                         return WIMLIB_ERR_INTEGRITY;
745                 } else if (ret != WIM_INTEGRITY_OK) {
746                         return ret;
747                 }
748         }
749
750         if (wim->hdr.image_count != 0 && wim->hdr.part_number == 1) {
751                 wim->image_metadata = CALLOC(wim->hdr.image_count,
752                                              sizeof(wim->image_metadata[0]));
753                 if (!wim->image_metadata)
754                         return WIMLIB_ERR_NOMEM;
755         }
756
757         if (open_flags & WIMLIB_OPEN_FLAG_FROM_PIPE) {
758                 wim->blob_table = new_blob_table(64);
759                 if (!wim->blob_table)
760                         return WIMLIB_ERR_NOMEM;
761         } else {
762                 if (wim->hdr.blob_table_reshdr.uncompressed_size == 0 &&
763                     wim->hdr.xml_data_reshdr.uncompressed_size == 0)
764                         return WIMLIB_ERR_WIM_IS_INCOMPLETE;
765
766                 ret = read_wim_xml_data(wim);
767                 if (ret)
768                         return ret;
769
770                 if (xml_get_image_count(wim->xml_info) != wim->hdr.image_count) {
771                         ERROR("The WIM's header is inconsistent with its XML data.\n"
772                               "        Please submit a bug report if you believe this "
773                               "WIM file should be considered valid.");
774                         return WIMLIB_ERR_IMAGE_COUNT;
775                 }
776
777                 ret = read_blob_table(wim);
778                 if (ret)
779                         return ret;
780         }
781         return 0;
782 }
783
784 int
785 open_wim_as_WIMStruct(const void *wim_filename_or_fd, int open_flags,
786                       WIMStruct **wim_ret,
787                       wimlib_progress_func_t progfunc, void *progctx)
788 {
789         WIMStruct *wim;
790         int ret;
791
792         ret = wimlib_global_init(0);
793         if (ret)
794                 return ret;
795
796         wim = new_wim_struct();
797         if (!wim)
798                 return WIMLIB_ERR_NOMEM;
799
800         wim->progfunc = progfunc;
801         wim->progctx = progctx;
802
803         ret = begin_read(wim, wim_filename_or_fd, open_flags);
804         if (ret) {
805                 wimlib_free(wim);
806                 return ret;
807         }
808
809         *wim_ret = wim;
810         return 0;
811 }
812
813 /* API function documented in wimlib.h  */
814 WIMLIBAPI int
815 wimlib_open_wim_with_progress(const tchar *wimfile, int open_flags,
816                               WIMStruct **wim_ret,
817                               wimlib_progress_func_t progfunc, void *progctx)
818 {
819         if (open_flags & ~(WIMLIB_OPEN_FLAG_CHECK_INTEGRITY |
820                            WIMLIB_OPEN_FLAG_ERROR_IF_SPLIT |
821                            WIMLIB_OPEN_FLAG_WRITE_ACCESS))
822                 return WIMLIB_ERR_INVALID_PARAM;
823
824         if (!wimfile || !*wimfile || !wim_ret)
825                 return WIMLIB_ERR_INVALID_PARAM;
826
827         return open_wim_as_WIMStruct(wimfile, open_flags, wim_ret,
828                                      progfunc, progctx);
829 }
830
831 /* API function documented in wimlib.h  */
832 WIMLIBAPI int
833 wimlib_open_wim(const tchar *wimfile, int open_flags, WIMStruct **wim_ret)
834 {
835         return wimlib_open_wim_with_progress(wimfile, open_flags, wim_ret,
836                                              NULL, NULL);
837 }
838
839 /* Checksum all blobs that are unhashed (other than the metadata blobs), merging
840  * them into the blob table as needed.  This is a no-op unless files have been
841  * added to an image in the same WIMStruct.  */
842 int
843 wim_checksum_unhashed_blobs(WIMStruct *wim)
844 {
845         int ret;
846
847         if (!wim_has_metadata(wim))
848                 return 0;
849         for (int i = 0; i < wim->hdr.image_count; i++) {
850                 struct blob_descriptor *blob, *tmp;
851                 struct wim_image_metadata *imd = wim->image_metadata[i];
852                 image_for_each_unhashed_blob_safe(blob, tmp, imd) {
853                         struct blob_descriptor *new_blob;
854                         ret = hash_unhashed_blob(blob, wim->blob_table, &new_blob);
855                         if (ret)
856                                 return ret;
857                         if (new_blob != blob)
858                                 free_blob_descriptor(blob);
859                 }
860         }
861         return 0;
862 }
863
864 /*
865  * can_modify_wim - Check if a given WIM is writeable.  This is only the case if
866  * it meets the following three conditions:
867  *
868  * 1. Write access is allowed to the underlying file (if any) at the filesystem level.
869  * 2. The WIM is not part of a spanned set.
870  * 3. The WIM_HDR_FLAG_READONLY flag is not set in the WIM header.
871  *
872  * Return value is 0 if writable; WIMLIB_ERR_WIM_IS_READONLY otherwise.
873  */
874 int
875 can_modify_wim(WIMStruct *wim)
876 {
877         if (wim->filename) {
878                 if (taccess(wim->filename, W_OK)) {
879                         ERROR_WITH_ERRNO("Can't modify \"%"TS"\"", wim->filename);
880                         return WIMLIB_ERR_WIM_IS_READONLY;
881                 }
882         }
883         if (wim->hdr.total_parts != 1) {
884                 ERROR("Cannot modify \"%"TS"\": is part of a split WIM",
885                       wim->filename);
886                 return WIMLIB_ERR_WIM_IS_READONLY;
887         }
888         if (wim->hdr.flags & WIM_HDR_FLAG_READONLY) {
889                 ERROR("Cannot modify \"%"TS"\": is marked read-only",
890                       wim->filename);
891                 return WIMLIB_ERR_WIM_IS_READONLY;
892         }
893         return 0;
894 }
895
896 /* Release a reference to a WIMStruct.  If the reference count reaches 0, the
897  * WIMStruct is freed.  */
898 void
899 wim_decrement_refcnt(WIMStruct *wim)
900 {
901         wimlib_assert(wim->refcnt > 0);
902         if (--wim->refcnt != 0)
903                 return;
904         if (filedes_valid(&wim->in_fd))
905                 filedes_close(&wim->in_fd);
906         if (filedes_valid(&wim->out_fd))
907                 filedes_close(&wim->out_fd);
908         wimlib_free_decompressor(wim->decompressor);
909         xml_free_info_struct(wim->xml_info);
910         FREE(wim->filename);
911         FREE(wim);
912 }
913
914 /* API function documented in wimlib.h  */
915 WIMLIBAPI void
916 wimlib_free(WIMStruct *wim)
917 {
918         if (!wim)
919                 return;
920
921         /* The blob table and image metadata are freed immediately, but other
922          * members of the WIMStruct such as the input file descriptor are
923          * retained until no more exported resources reference the WIMStruct. */
924
925         free_blob_table(wim->blob_table);
926         wim->blob_table = NULL;
927         if (wim->image_metadata != NULL) {
928                 deselect_current_wim_image(wim);
929                 for (int i = 0; i < wim->hdr.image_count; i++)
930                         put_image_metadata(wim->image_metadata[i]);
931                 FREE(wim->image_metadata);
932                 wim->image_metadata = NULL;
933         }
934
935         wim_decrement_refcnt(wim);
936 }
937
938 /* API function documented in wimlib.h  */
939 WIMLIBAPI u32
940 wimlib_get_version(void)
941 {
942         return (WIMLIB_MAJOR_VERSION << 20) |
943                (WIMLIB_MINOR_VERSION << 10) |
944                 WIMLIB_PATCH_VERSION;
945 }
946
947 static bool lib_initialized = false;
948 static pthread_mutex_t lib_initialization_mutex = PTHREAD_MUTEX_INITIALIZER;
949
950 /* API function documented in wimlib.h  */
951 WIMLIBAPI int
952 wimlib_global_init(int init_flags)
953 {
954         int ret = 0;
955
956         if (lib_initialized)
957                 goto out;
958
959         pthread_mutex_lock(&lib_initialization_mutex);
960
961         if (lib_initialized)
962                 goto out_unlock;
963
964 #ifdef ENABLE_ERROR_MESSAGES
965         if (!wimlib_error_file)
966                 wimlib_error_file = stderr;
967 #endif
968
969         ret = WIMLIB_ERR_INVALID_PARAM;
970         if (init_flags & ~(WIMLIB_INIT_FLAG_ASSUME_UTF8 |
971                            WIMLIB_INIT_FLAG_DONT_ACQUIRE_PRIVILEGES |
972                            WIMLIB_INIT_FLAG_STRICT_CAPTURE_PRIVILEGES |
973                            WIMLIB_INIT_FLAG_STRICT_APPLY_PRIVILEGES |
974                            WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
975                            WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
976                 goto out_unlock;
977
978         ret = WIMLIB_ERR_INVALID_PARAM;
979         if ((init_flags & (WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
980                            WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
981                         == (WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE |
982                             WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE))
983                 goto out_unlock;
984
985         xml_global_init();
986 #ifdef __WIN32__
987         ret = win32_global_init(init_flags);
988         if (ret)
989                 goto out_unlock;
990 #endif
991         init_upcase();
992         if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE)
993                 default_ignore_case = false;
994         else if (init_flags & WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE)
995                 default_ignore_case = true;
996         lib_initialized = true;
997         ret = 0;
998 out_unlock:
999         pthread_mutex_unlock(&lib_initialization_mutex);
1000 out:
1001         return ret;
1002 }
1003
1004 /* API function documented in wimlib.h  */
1005 WIMLIBAPI void
1006 wimlib_global_cleanup(void)
1007 {
1008         if (!lib_initialized)
1009                 return;
1010
1011         pthread_mutex_lock(&lib_initialization_mutex);
1012
1013         if (!lib_initialized)
1014                 goto out_unlock;
1015
1016         xml_global_cleanup();
1017 #ifdef __WIN32__
1018         win32_global_cleanup();
1019 #endif
1020
1021         wimlib_set_error_file(NULL);
1022         lib_initialized = false;
1023
1024 out_unlock:
1025         pthread_mutex_unlock(&lib_initialization_mutex);
1026 }