500fc1ebc08f7407028be9041fb9f2defe7fbbe2
[wimlib] / src / wim.c
1 /*
2  * wim.c
3  */
4
5 /*
6  * Copyright (C) 2010 Carl Thijssen
7  * Copyright (C) 2012 Eric Biggers
8  *
9  * wimlib - Library for working with WIM files
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #include "config.h"
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31
32 #include "dentry.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35
36 #ifdef WITH_NTFS_3G
37 #include <time.h>
38 #include <ntfs-3g/volume.h>
39 #endif
40
41 #include "wimlib_internal.h"
42 #include "io.h"
43 #include "lookup_table.h"
44 #include "xml.h"
45
46
47 static int print_metadata(WIMStruct *w)
48 {
49         DEBUG("Printing metadata for image %d", w->current_image);
50         print_security_data(wim_security_data(w));
51         return for_dentry_in_tree(wim_root_dentry(w), print_dentry,
52                                   w->lookup_table);
53 }
54
55
56 static int print_files(WIMStruct *w)
57 {
58         return for_dentry_in_tree(wim_root_dentry(w), print_dentry_full_path,
59                                   NULL);
60 }
61
62 WIMStruct *new_wim_struct()
63 {
64         WIMStruct *w = CALLOC(1, sizeof(WIMStruct));
65 #ifdef WITH_FUSE
66         if (pthread_mutex_init(&w->fp_tab_mutex, NULL) != 0) {
67                 ERROR_WITH_ERRNO("Failed to initialize mutex");
68                 FREE(w);
69                 w = NULL;
70         }
71 #endif
72         return w;
73
74 }
75
76 /*
77  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES, @visitor
78  * is called on the WIM once for each image, with each image selected as the
79  * current image in turn.  If @image is a certain image, @visitor is called on
80  * the WIM only once, with that image selected.
81  */
82 int for_image(WIMStruct *w, int image, int (*visitor)(WIMStruct *))
83 {
84         int ret;
85         int start;
86         int end;
87         int i;
88
89         if (image == WIMLIB_ALL_IMAGES) {
90                 start = 1;
91                 end = w->hdr.image_count;
92         } else if (image >= 1 && image <= w->hdr.image_count) {
93                 start = image;
94                 end = image;
95         } else {
96                 return WIMLIB_ERR_INVALID_IMAGE;
97         }
98         for (i = start; i <= end; i++) {
99                 ret = select_wim_image(w, i);
100                 if (ret != 0)
101                         return ret;
102                 ret = visitor(w);
103                 if (ret != 0)
104                         return ret;
105         }
106         return 0;
107 }
108
109 static int sort_image_metadata_by_position(const void *p1, const void *p2)
110 {
111         const struct image_metadata *imd1 = p1;
112         const struct image_metadata *imd2 = p2;
113         u64 offset1 = imd1->metadata_lte->resource_entry.offset;
114         u64 offset2 = imd2->metadata_lte->resource_entry.offset;
115         if (offset1 < offset2)
116                 return -1;
117         else if (offset1 > offset2)
118                 return 1;
119         else
120                 return 0;
121 }
122
123 /*
124  * If @lte points to a metadata resource, append it to the list of metadata
125  * resources in the WIMStruct.  Otherwise, do nothing.
126  */
127 static int append_metadata_resource_entry(struct lookup_table_entry *lte,
128                                           void *wim_p)
129 {
130         WIMStruct *w = wim_p;
131         int ret = 0;
132
133         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
134                 if (w->current_image == w->hdr.image_count) {
135                         ERROR("The WIM header says there are %u images in the WIM,\n"
136                               "        but we found more metadata resources than this",
137                               w->hdr.image_count);
138                         ret = WIMLIB_ERR_IMAGE_COUNT;
139                 } else {
140                         DEBUG("Found metadata resource for image %u at "
141                               "offset %"PRIu64".",
142                               w->current_image + 1,
143                               lte->resource_entry.offset);
144                         w->image_metadata[
145                                 w->current_image++].metadata_lte = lte;
146                 }
147         }
148         return ret;
149 }
150
151 /* Returns the compression type given in the flags of a WIM header. */
152 int wim_hdr_flags_compression_type(int wim_hdr_flags)
153 {
154         if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESSION) {
155                 if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_LZX)
156                         return WIMLIB_COMPRESSION_TYPE_LZX;
157                 else if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_XPRESS)
158                         return WIMLIB_COMPRESSION_TYPE_XPRESS;
159                 else
160                         return WIMLIB_COMPRESSION_TYPE_INVALID;
161         } else {
162                 return WIMLIB_COMPRESSION_TYPE_NONE;
163         }
164 }
165
166 /*
167  * Creates a WIMStruct for a new WIM file.
168  */
169 WIMLIBAPI int wimlib_create_new_wim(int ctype, WIMStruct **w_ret)
170 {
171         WIMStruct *w;
172         struct lookup_table *table;
173         int ret;
174
175         DEBUG("Creating new WIM with %s compression.",
176               wimlib_get_compression_type_string(ctype));
177
178         /* Allocate the WIMStruct. */
179         w = new_wim_struct();
180         if (!w)
181                 return WIMLIB_ERR_NOMEM;
182
183         ret = init_header(&w->hdr, ctype);
184         if (ret != 0)
185                 goto out_free;
186
187         table = new_lookup_table(9001);
188         if (!table) {
189                 ret = WIMLIB_ERR_NOMEM;
190                 goto out_free;
191         }
192         w->lookup_table = table;
193         *w_ret = w;
194         return 0;
195 out_free:
196         FREE(w);
197         return ret;
198 }
199
200 WIMLIBAPI int wimlib_get_num_images(const WIMStruct *w)
201 {
202         return w->hdr.image_count;
203 }
204
205 int select_wim_image(WIMStruct *w, int image)
206 {
207         struct image_metadata *imd;
208
209         DEBUG("Selecting image %d", image);
210
211         if (image == w->current_image)
212                 return 0;
213
214         if (image < 1 || image > w->hdr.image_count) {
215                 ERROR("Cannot select image %d: There are only %u images",
216                       image, w->hdr.image_count);
217                 return WIMLIB_ERR_INVALID_IMAGE;
218         }
219
220         /* If a valid image is currently selected, it can be freed if it is not
221          * modified.  */
222         if (w->current_image != WIMLIB_NO_IMAGE) {
223                 imd = wim_get_current_image_metadata(w);
224                 if (!imd->modified) {
225                         DEBUG("Freeing image %u", w->current_image);
226                         destroy_image_metadata(imd, NULL);
227                         imd->root_dentry = NULL;
228                         imd->security_data = NULL;
229                 }
230         }
231
232         w->current_image = image;
233         imd = wim_get_current_image_metadata(w);
234
235         if (imd->root_dentry) {
236                 return 0;
237         } else {
238                 #ifdef ENABLE_DEBUG
239                 DEBUG("Reading metadata resource specified by the following "
240                       "lookup table entry:");
241                 print_lookup_table_entry(imd->metadata_lte);
242                 #endif
243                 return read_metadata_resource(w, imd);
244         }
245 }
246
247
248 /* Returns the compression type of the WIM file. */
249 WIMLIBAPI int wimlib_get_compression_type(const WIMStruct *w)
250 {
251         return wim_hdr_flags_compression_type(w->hdr.flags);
252 }
253
254 WIMLIBAPI const char *wimlib_get_compression_type_string(int ctype)
255 {
256         switch (ctype) {
257                 case WIMLIB_COMPRESSION_TYPE_NONE:
258                         return "None";
259                 case WIMLIB_COMPRESSION_TYPE_LZX:
260                         return "LZX";
261                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
262                         return "XPRESS";
263                 default:
264                         return "Invalid";
265         }
266 }
267
268 /*
269  * Returns the number of an image in the WIM file, given a string that is either
270  * the number of the image, or the name of the image.  The images are numbered
271  * starting at 1.
272  */
273 WIMLIBAPI int wimlib_resolve_image(WIMStruct *w, const char *image_name_or_num)
274 {
275         char *p;
276         int image;
277         int i;
278
279         if (!image_name_or_num || !*image_name_or_num)
280                 return WIMLIB_NO_IMAGE;
281
282         if (strcmp(image_name_or_num, "all") == 0
283             || strcmp(image_name_or_num, "*") == 0)
284                 return WIMLIB_ALL_IMAGES;
285         image = strtol(image_name_or_num, &p, 10);
286         if (p != image_name_or_num && *p == '\0' && image > 0) {
287                 if (image > w->hdr.image_count)
288                         return WIMLIB_NO_IMAGE;
289                 return image;
290         } else {
291                 for (i = 1; i <= w->hdr.image_count; i++) {
292                         if (strcmp(image_name_or_num,
293                                    wimlib_get_image_name(w, i)) == 0)
294                                 return i;
295                 }
296                 return WIMLIB_NO_IMAGE;
297         }
298 }
299
300
301 /* Prints some basic information about a WIM file. */
302 WIMLIBAPI void wimlib_print_wim_information(const WIMStruct *w)
303 {
304         const struct wim_header *hdr;
305
306         hdr = &w->hdr;
307         puts("WIM Information:");
308         puts("----------------");
309         printf("Path:           %s\n", w->filename);
310         fputs ("GUID:           0x", stdout);
311         print_byte_field(hdr->guid, WIM_GID_LEN);
312         putchar('\n');
313         printf("Image Count:    %d\n", hdr->image_count);
314         printf("Compression:    %s\n", wimlib_get_compression_type_string(
315                                                 wimlib_get_compression_type(w)));
316         printf("Part Number:    %d/%d\n", hdr->part_number, hdr->total_parts);
317         printf("Boot Index:     %d\n", hdr->boot_idx);
318         printf("Size:           %"PRIu64" bytes\n",
319                                 wim_info_get_total_bytes(w->wim_info));
320         printf("Integrity Info: %s\n", (w->hdr.integrity.size != 0) ? "yes" : "no");
321         putchar('\n');
322 }
323
324 WIMLIBAPI bool wimlib_has_integrity_table(const WIMStruct *w)
325 {
326         return w->hdr.integrity.size != 0;
327 }
328
329 WIMLIBAPI void wimlib_print_available_images(const WIMStruct *w, int image)
330 {
331         int first;
332         int last;
333         int i;
334         int n;
335         if (image == WIMLIB_ALL_IMAGES) {
336                 n = printf("Available Images:\n");
337                 first = 1;
338                 last = w->hdr.image_count;
339         } else if (image >= 1 && image <= w->hdr.image_count) {
340                 n = printf("Information for Image %d\n", image);
341                 first = image;
342                 last = image;
343         } else {
344                 printf("wimlib_print_available_images(): Invalid image %d",
345                        image);
346                 return;
347         }
348         for (i = 0; i < n - 1; i++)
349                 putchar('-');
350         putchar('\n');
351         for (i = first; i <= last; i++)
352                 print_image_info(w->wim_info, i);
353 }
354
355
356 /* Prints the metadata for the specified image, which may be WIMLIB_ALL_IMAGES, but
357  * not WIMLIB_NO_IMAGE. */
358 WIMLIBAPI int wimlib_print_metadata(WIMStruct *w, int image)
359 {
360         if (!w)
361                 return WIMLIB_ERR_INVALID_PARAM;
362         if (w->hdr.part_number != 1) {
363                 ERROR("Cannot show the metadata from part %hu of a %hu-part split WIM!",
364                        w->hdr.part_number, w->hdr.total_parts);
365                 ERROR("Select the first part of the split WIM to see the metadata.");
366                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
367         }
368         return for_image(w, image, print_metadata);
369 }
370
371 WIMLIBAPI int wimlib_print_files(WIMStruct *w, int image)
372 {
373         if (!w)
374                 return WIMLIB_ERR_INVALID_PARAM;
375         if (w->hdr.part_number != 1) {
376                 ERROR("Cannot list the files from part %hu of a %hu-part split WIM!",
377                        w->hdr.part_number, w->hdr.total_parts);
378                 ERROR("Select the first part of the split WIM if you'd like to list the files.");
379                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
380         }
381         return for_image(w, image, print_files);
382 }
383
384 /* Sets the index of the bootable image. */
385 WIMLIBAPI int wimlib_set_boot_idx(WIMStruct *w, int boot_idx)
386 {
387         if (!w)
388                 return WIMLIB_ERR_INVALID_PARAM;
389         if (w->hdr.total_parts != 1) {
390                 ERROR("Cannot modify the boot index of a split WIM!");
391                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
392         }
393         if (boot_idx < 0 || boot_idx > w->hdr.image_count)
394                 return WIMLIB_ERR_INVALID_IMAGE;
395         w->hdr.boot_idx = boot_idx;
396
397         if (boot_idx == 0) {
398                 memset(&w->hdr.boot_metadata_res_entry, 0,
399                        sizeof(struct resource_entry));
400         } else {
401                 memcpy(&w->hdr.boot_metadata_res_entry,
402                        &w->image_metadata[
403                           boot_idx - 1].metadata_lte->resource_entry,
404                        sizeof(struct resource_entry));
405         }
406
407         return 0;
408 }
409
410 WIMLIBAPI int wimlib_get_part_number(const WIMStruct *w, int *total_parts_ret)
411 {
412         if (total_parts_ret)
413                 *total_parts_ret = w->hdr.total_parts;
414         return w->hdr.part_number;
415 }
416
417
418 WIMLIBAPI int wimlib_get_boot_idx(const WIMStruct *w)
419 {
420         return w->hdr.boot_idx;
421 }
422
423 /* Opens a WIM readable */
424 int open_wim_readable(WIMStruct *w, const char *path)
425 {
426         if (w->fp != NULL)
427                 fclose(w->fp);
428         wimlib_assert(path != NULL);
429         w->fp = fopen(path, "rb");
430         if (!w->fp) {
431                 ERROR_WITH_ERRNO("Failed to open `%s' for reading",
432                                  path);
433                 return WIMLIB_ERR_OPEN;
434         }
435         return 0;
436 }
437
438 /* Opens a WIM writable */
439 int open_wim_writable(WIMStruct *w, const char *path,
440                       bool trunc, bool readable)
441 {
442         const char *mode;
443         if (trunc)
444                 if (readable)
445                         mode = "w+b";
446                 else
447                         mode = "wb";
448         else
449                 mode = "r+b";
450
451         DEBUG("Opening `%s' read-write", path);
452         wimlib_assert(w->out_fp == NULL);
453         wimlib_assert(path != NULL);
454         w->out_fp = fopen(path, mode);
455         if (!w->out_fp) {
456                 ERROR_WITH_ERRNO("Failed to open `%s' for writing", path);
457                 return WIMLIB_ERR_OPEN;
458         }
459         return 0;
460 }
461
462 /*
463  * Begins the reading of a WIM file; opens the file and reads its header and
464  * lookup table, and optionally checks the integrity.
465  */
466 static int begin_read(WIMStruct *w, const char *in_wim_path, int open_flags,
467                       wimlib_progress_func_t progress_func)
468 {
469         int ret;
470         uint xml_num_images;
471
472         DEBUG("Reading the WIM file `%s'", in_wim_path);
473
474         ret = open_wim_readable(w, in_wim_path);
475         if (ret != 0)
476                 goto out;
477
478         w->filename = realpath(in_wim_path, NULL);
479         if (!w->filename) {
480                 ERROR_WITH_ERRNO("Failed to resolve WIM filename");
481                 ret = WIMLIB_ERR_NOMEM;
482                 goto out_close;
483         }
484
485         ret = read_header(w->fp, &w->hdr, open_flags);
486         if (ret != 0)
487                 goto out_close;
488
489         DEBUG("Wim file contains %u images", w->hdr.image_count);
490
491         /* If the boot index is invalid, print a warning and set it to 0 */
492         if (w->hdr.boot_idx > w->hdr.image_count) {
493                 WARNING("In `%s', image %u is marked as bootable, "
494                         "but there are only %u images in the WIM",
495                         in_wim_path, w->hdr.boot_idx, w->hdr.image_count);
496                 w->hdr.boot_idx = 0;
497         }
498
499         if (wimlib_get_compression_type(w) == WIMLIB_COMPRESSION_TYPE_INVALID) {
500                 ERROR("Invalid compression type (WIM header flags = %x)",
501                       w->hdr.flags);
502                 ret = WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
503                 goto out_close;
504         }
505
506         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
507                 ret = check_wim_integrity(w, progress_func);
508                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
509                         WARNING("No integrity information for `%s'; skipping "
510                                 "integrity check.", w->filename);
511                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
512                         ERROR("WIM is not intact! (Failed integrity check)");
513                         ret = WIMLIB_ERR_INTEGRITY;
514                         goto out_close;
515                 } else if (ret != 0) {
516                         goto out_close;
517                 }
518         }
519
520         if (resource_is_compressed(&w->hdr.lookup_table_res_entry)) {
521                 ERROR("Didn't expect a compressed lookup table!");
522                 ERROR("Ask the author to implement support for this.");
523                 ret = WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE;
524                 goto out_close;
525         }
526
527         ret = read_lookup_table(w);
528         if (ret != 0)
529                 goto out_close;
530
531         w->image_metadata = CALLOC(w->hdr.image_count,
532                                    sizeof(struct image_metadata));
533
534         if (!w->image_metadata) {
535                 ERROR("Failed to allocate memory for %u metadata structures",
536                       w->hdr.image_count);
537                 ret = WIMLIB_ERR_NOMEM;
538                 goto out_free_lookup_table;
539         }
540         w->current_image = 0;
541
542         DEBUG("Looking for metadata resources in the lookup table.");
543
544         /* Find the images in the WIM by searching the lookup table. */
545         ret = for_lookup_table_entry(w->lookup_table,
546                                      append_metadata_resource_entry, w);
547
548         if (ret != 0)
549                 goto out_free_image_metadata;
550
551         /* Make sure all the expected images were found.  (We already have
552          * returned false if *extra* images were found) */
553         if (w->current_image != w->hdr.image_count &&
554             w->hdr.part_number == 1)
555         {
556                 ERROR("Only found %u images in WIM, but expected %u",
557                       w->current_image, w->hdr.image_count);
558                 ret = WIMLIB_ERR_IMAGE_COUNT;
559                 goto out_free_image_metadata;
560         }
561
562         /* Sort images by the position of their metadata resources.  I'm
563          * assuming that is what determines the other of the images in the WIM
564          * file, rather than their order in the lookup table, which is random
565          * because of hashing. */
566         qsort(w->image_metadata, w->current_image,
567               sizeof(struct image_metadata), sort_image_metadata_by_position);
568
569         w->current_image = WIMLIB_NO_IMAGE;
570
571         /* Read the XML data. */
572         ret = read_xml_data(w->fp, &w->hdr.xml_res_entry,
573                             &w->xml_data, &w->wim_info);
574
575         if (ret != 0)
576                 goto out_free_image_metadata;
577
578         xml_num_images = wim_info_get_num_images(w->wim_info);
579         if (xml_num_images != w->hdr.image_count) {
580                 ERROR("In the file `%s', there are %u <IMAGE> elements "
581                       "in the XML data,", in_wim_path, xml_num_images);
582                 ERROR("but %u images in the WIM!  There must be exactly one "
583                       "<IMAGE> element per image.", w->hdr.image_count);
584                 ret = WIMLIB_ERR_IMAGE_COUNT;
585                 goto out_free_xml_data;
586         }
587
588         DEBUG("Done beginning read of WIM file `%s'.", in_wim_path);
589         return 0;
590
591         //
592         // Everything is freed in wimlib_free() anyway, so no need to roll back
593         // changes here.
594         //
595 out_free_xml_data:
596         /*FREE(w->xml_data);*/
597         /*w->xml_data = NULL;*/
598         /*free_wim_info(w->wim_info);*/
599         /*w->wim_info = NULL;*/
600 out_free_image_metadata:
601         /*FREE(w->image_metadata);*/
602         /*w->image_metadata = NULL;*/
603         /*w->current_image = WIMLIB_NO_IMAGE;*/
604 out_free_lookup_table:
605         /*free_lookup_table(w->lookup_table);*/
606         /*w->lookup_table = NULL;*/
607 out_close:
608         /*fclose(w->fp);*/
609         /*w->fp = NULL;*/
610 out:
611         return ret;
612 }
613
614
615 /*
616  * Opens a WIM file and creates a WIMStruct for it.
617  */
618 WIMLIBAPI int wimlib_open_wim(const char *wim_file, int open_flags,
619                               WIMStruct **w_ret,
620                               wimlib_progress_func_t progress_func)
621 {
622         WIMStruct *w;
623         int ret;
624
625         DEBUG("wim_file = `%s', open_flags = %#x", wim_file, open_flags);
626         w = new_wim_struct();
627         if (!w) {
628                 ERROR("Failed to allocate memory for WIMStruct");
629                 return WIMLIB_ERR_NOMEM;
630         }
631
632         ret = begin_read(w, wim_file, open_flags, progress_func);
633         if (ret == 0) {
634                 *w_ret = w;
635         } else {
636                 DEBUG("Could not begin reading the WIM file `%s'", wim_file);
637                 wimlib_free(w);
638         }
639         return ret;
640 }
641
642 /* Frees the memory for the WIMStruct, including all internal memory; also
643  * closes all files associated with the WIMStruct.  */
644 WIMLIBAPI void wimlib_free(WIMStruct *w)
645 {
646         DEBUG2("Freeing WIMStruct");
647
648         if (!w)
649                 return;
650         if (w->fp)
651                 fclose(w->fp);
652         if (w->out_fp)
653                 fclose(w->out_fp);
654
655 #ifdef WITH_FUSE
656         if (w->fp_tab) {
657                 for (size_t i = 0; i < w->num_allocated_fps; i++)
658                         if (w->fp_tab[i])
659                                 fclose(w->fp_tab[i]);
660                 FREE(w->fp_tab);
661         }
662         pthread_mutex_destroy(&w->fp_tab_mutex);
663 #endif
664
665         free_lookup_table(w->lookup_table);
666
667         FREE(w->filename);
668         FREE(w->xml_data);
669         free_wim_info(w->wim_info);
670         if (w->image_metadata) {
671                 for (uint i = 0; i < w->hdr.image_count; i++)
672                         destroy_image_metadata(&w->image_metadata[i], NULL);
673                 FREE(w->image_metadata);
674         }
675 #ifdef WITH_NTFS_3G
676         if (w->ntfs_vol) {
677                 DEBUG("Unmounting NTFS volume");
678                 ntfs_umount(w->ntfs_vol, FALSE);
679         }
680 #endif
681         FREE(w);
682 }