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