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