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