imagex capture and append consolidation
[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 "wimlib_internal.h"
28 #include "io.h"
29 #include "lookup_table.h"
30 #include "xml.h"
31 #include <stdlib.h>
32
33 #ifdef WITH_NTFS_3G
34 #include <ntfs-3g/volume.h>
35 #endif
36
37 static int print_metadata(WIMStruct *w)
38 {
39         print_security_data(wim_security_data(w));
40         return for_dentry_in_tree(wim_root_dentry(w), print_dentry, 
41                                   w->lookup_table);
42 }
43
44
45 static int print_files(WIMStruct *w)
46 {
47         return for_dentry_in_tree(wim_root_dentry(w), print_dentry_full_path, 
48                                   NULL);
49 }
50
51 WIMStruct *new_wim_struct()
52 {
53         return CALLOC(1, sizeof(WIMStruct));
54 }
55
56 /* 
57  * Calls a function on images in the WIM.  If @image is WIM_ALL_IMAGES, @visitor
58  * is called on the WIM once for each image, with each image selected as the
59  * current image in turn.  If @image is a certain image, @visitor is called on
60  * the WIM only once, with that image selected.
61  */
62 int for_image(WIMStruct *w, int image, int (*visitor)(WIMStruct *))
63 {
64         int ret;
65         int i;
66         int end;
67
68         if (image == WIM_ALL_IMAGES) {
69                 i = 1;
70                 end = w->hdr.image_count;
71         } else {
72                 if (image < 1 || image > w->hdr.image_count)
73                         return WIMLIB_ERR_INVALID_IMAGE;
74                 i = image;
75                 end = image;
76         }
77         for (; i <= end; i++) {
78                 ret = wimlib_select_image(w, i);
79                 if (ret != 0)
80                         return ret;
81                 ret = visitor(w);
82                 if (ret != 0)
83                         return ret;
84         }
85         return 0;
86 }
87
88 static int sort_image_metadata_by_position(const void *p1, const void *p2)
89 {
90         struct image_metadata *bmd1 = (struct image_metadata*)p1;
91         struct image_metadata *bmd2 = (struct image_metadata*)p2;
92         u64 offset1 = bmd1->metadata_lte->resource_entry.offset;
93         u64 offset2 = bmd2->metadata_lte->resource_entry.offset;
94         if (offset1 < offset2)
95                 return -1;
96         else if (offset1 > offset2)
97                 return 1;
98         else
99                 return 0;
100 }
101
102 /* 
103  * If @lte points to a metadata resource, append it to the list of metadata
104  * resources in the WIMStruct.  Otherwise, do nothing.
105  */
106 static int append_metadata_resource_entry(struct lookup_table_entry *lte, 
107                                           void *wim_p)
108 {
109         WIMStruct *w = wim_p;
110
111         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
112                 /*fprintf(stderr, "found mlte at %u\n", lte->resource_entry.offset);*/
113                 if (w->current_image == w->hdr.image_count) {
114                         ERROR("Expected only %u images, but found more",
115                               w->hdr.image_count);
116                         return WIMLIB_ERR_IMAGE_COUNT;
117                 } else {
118                         DEBUG("Found metadata resource for image %u at "
119                               "offset %"PRIu64".",
120                               w->current_image + 1, 
121                               lte->resource_entry.offset);
122                         w->image_metadata[
123                                 w->current_image++].metadata_lte = lte;
124                 }
125         }
126         return 0;
127 }
128
129 /* Returns the compression type given in the flags of a WIM header. */
130 int wim_hdr_flags_compression_type(int wim_hdr_flags)
131 {
132         if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESSION) {
133                 if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_LZX)
134                         return WIM_COMPRESSION_TYPE_LZX;
135                 else if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_XPRESS)
136                         return WIM_COMPRESSION_TYPE_XPRESS;
137                 else
138                         return WIM_COMPRESSION_TYPE_INVALID;
139         } else {
140                 return WIM_COMPRESSION_TYPE_NONE;
141         }
142 }
143
144 /*
145  * Creates a WIMStruct for a new WIM file.
146  */
147 WIMLIBAPI int wimlib_create_new_wim(int ctype, WIMStruct **w_ret)
148 {
149         WIMStruct *w;
150         struct lookup_table *table;
151         int ret;
152
153         DEBUG("Creating new WIM with %s compression.",
154               wimlib_get_compression_type_string(ctype));
155
156         /* Allocate the WIMStruct. */
157         w = new_wim_struct();
158         if (!w)
159                 return WIMLIB_ERR_NOMEM;
160
161         ret = init_header(&w->hdr, ctype);
162         if (ret != 0)
163                 goto out_free;
164
165         table = new_lookup_table(9001);
166         if (!table) {
167                 ret = WIMLIB_ERR_NOMEM;
168                 goto out_free;
169         }
170         w->lookup_table = table;
171         *w_ret = w;
172         return 0;
173 out_free:
174         FREE(w);
175         return ret;
176 }
177
178 WIMLIBAPI int wimlib_get_num_images(const WIMStruct *w)
179 {
180         return w->hdr.image_count;
181 }
182
183 int wimlib_select_image(WIMStruct *w, int image)
184 {
185         struct image_metadata *imd;
186
187         DEBUG("Selecting image %d", image);
188
189         if (image == w->current_image)
190                 return 0;
191
192         if (image < 1 || image > w->hdr.image_count) {
193                 ERROR("Cannot select image %d: There are only %u images",
194                       image, w->hdr.image_count);
195                 return WIMLIB_ERR_INVALID_IMAGE;
196         }
197
198
199         /* If a valid image is currently selected, it can be freed if it is not
200          * modified.  */
201         if (w->current_image != WIM_NO_IMAGE) {
202                 imd = wim_get_current_image_metadata(w);
203                 if (!imd->modified) {
204                         DEBUG("Freeing image %u", w->current_image);
205                         destroy_image_metadata(imd, NULL);
206                         imd->root_dentry = NULL;
207                         imd->security_data = NULL;
208                         imd->lgt = NULL;
209                 }
210         }
211
212         w->current_image = image;
213         imd = wim_get_current_image_metadata(w);
214
215         if (imd->root_dentry) {
216                 return 0;
217         } else {
218                 #ifdef ENABLE_DEBUG
219                 DEBUG("Reading metadata resource specified by the following "
220                       "lookup table entry:");
221                 print_lookup_table_entry(imd->metadata_lte);
222                 #endif
223                 return read_metadata_resource(w, imd);
224         }
225 }
226
227
228 /* Returns the compression type of the WIM file. */
229 WIMLIBAPI int wimlib_get_compression_type(const WIMStruct *w)
230 {
231         return wim_hdr_flags_compression_type(w->hdr.flags);
232 }
233
234 WIMLIBAPI const char *wimlib_get_compression_type_string(int ctype)
235 {
236         switch (ctype) {
237                 case WIM_COMPRESSION_TYPE_NONE:
238                         return "None";
239                 case WIM_COMPRESSION_TYPE_LZX:
240                         return "LZX";
241                 case WIM_COMPRESSION_TYPE_XPRESS:
242                         return "XPRESS";
243                 default:
244                         return "Invalid";
245         }
246 }
247
248 /*
249  * Returns the number of an image in the WIM file, given a string that is either
250  * the number of the image, or the name of the image.  The images are numbered
251  * starting at 1.
252  */
253 WIMLIBAPI int wimlib_resolve_image(WIMStruct *w, const char *image_name_or_num)
254 {
255         char *p;
256         int image;
257         int i;
258
259         if (!image_name_or_num)
260                 return WIM_NO_IMAGE;
261
262         if (strcmp(image_name_or_num, "all") == 0)
263                 return WIM_ALL_IMAGES;
264         image = strtol(image_name_or_num, &p, 10);
265         if (p != image_name_or_num && *p == '\0') {
266                 if (image < 1 || image > w->hdr.image_count)
267                         return WIM_NO_IMAGE;
268                 return image;
269         } else {
270                 for (i = 1; i <= w->hdr.image_count; i++) {
271                         if (strcmp(image_name_or_num,
272                                    wimlib_get_image_name(w, i)) == 0)
273                                 return i;
274                 }
275                 return WIM_NO_IMAGE;
276         }
277 }
278
279
280 /* Prints some basic information about a WIM file. */
281 WIMLIBAPI void wimlib_print_wim_information(const WIMStruct *w)
282 {
283         const struct wim_header *hdr;
284         
285         hdr = &w->hdr;
286         puts("WIM Information:");
287         puts("----------------");
288         printf("Path:           %s\n", w->filename);
289         fputs ("GUID:           0x", stdout);
290         print_byte_field(hdr->guid, WIM_GID_LEN);
291         putchar('\n');
292         printf("Image Count:    %d\n", hdr->image_count);
293         printf("Compression:    %s\n", wimlib_get_compression_type_string(
294                                                 wimlib_get_compression_type(w)));
295         printf("Part Number:    %d/%d\n", hdr->part_number, hdr->total_parts);
296         printf("Boot Index:     %d\n", hdr->boot_idx);
297         printf("Size:           %"PRIu64" bytes\n", 
298                                 wim_info_get_total_bytes(w->wim_info));
299         printf("Integrity Info: %s\n", (w->hdr.integrity.size != 0) ? "yes" : "no");
300         putchar('\n');
301 }
302
303 WIMLIBAPI bool wimlib_has_integrity_table(const WIMStruct *w)
304 {
305         return w->hdr.integrity.size != 0;
306 }
307
308 WIMLIBAPI void wimlib_print_available_images(const WIMStruct *w, int image)
309 {
310         if (image == WIM_ALL_IMAGES) {
311                 puts("Available Images:");
312                 puts("-----------------");
313         } else {
314                 int n;
315                 int i;
316
317                 n = printf("Information for Image %d\n", image);
318                 for (i = 0; i < n - 1; i++)
319                         putchar('-');
320                 putchar('\n');
321
322         }
323         print_image_info(w->wim_info, image);
324 }
325
326
327 /* Prints the metadata for the specified image, which may be WIM_ALL_IMAGES, but
328  * not WIM_NO_IMAGE. */
329 WIMLIBAPI int wimlib_print_metadata(WIMStruct *w, int image)
330 {
331         if (!w)
332                 return WIMLIB_ERR_INVALID_PARAM;
333         if (w->hdr.part_number != 1) {
334                 ERROR("We cannot show the metadata from part %hu of a %hu-part split WIM.",
335                        w->hdr.part_number, w->hdr.total_parts);
336                 ERROR("Select the first part of the split WIM to see the metadata.");
337                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
338         }
339         if (image == WIM_ALL_IMAGES)
340                 DEBUG("Printing metadata for all images");
341         else
342                 DEBUG("Printing metadata for image %d", image);
343         return for_image(w, image, print_metadata);
344 }
345
346 WIMLIBAPI int wimlib_print_files(WIMStruct *w, int image)
347 {
348         if (!w)
349                 return WIMLIB_ERR_INVALID_PARAM;
350         if (w->hdr.part_number != 1) {
351                 ERROR("We cannot list the files from part %hu of a %hu-part split WIM",
352                        w->hdr.part_number, w->hdr.total_parts);
353                 ERROR("Select the first part of the split WIM if you'd like to list the files.");
354                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
355         }
356         return for_image(w, image, print_files);
357 }
358
359 /* Sets the index of the bootable image. */
360 WIMLIBAPI int wimlib_set_boot_idx(WIMStruct *w, int boot_idx)
361 {
362         if (!w)
363                 return WIMLIB_ERR_INVALID_PARAM;
364         if (w->hdr.total_parts != 1) {
365                 ERROR("We cannot modify the boot index of a split WIM");
366                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
367         }
368         if (boot_idx < 0 || boot_idx > w->hdr.image_count)
369                 return WIMLIB_ERR_INVALID_IMAGE;
370         w->hdr.boot_idx = boot_idx;
371         if (boot_idx == 0) {
372                 memset(&w->hdr.boot_metadata_res_entry, 0, 
373                        sizeof(struct resource_entry));
374         } else {
375                 memcpy(&w->hdr.boot_metadata_res_entry,
376                        &w->image_metadata[
377                                 boot_idx - 1].metadata_lte->resource_entry, 
378                        sizeof(struct resource_entry));
379         }
380         return 0;
381 }
382
383 WIMLIBAPI int wimlib_get_part_number(const WIMStruct *w, int *total_parts_ret)
384 {
385         if (total_parts_ret)
386                 *total_parts_ret = w->hdr.total_parts;
387         return w->hdr.part_number;
388 }
389                                     
390
391 WIMLIBAPI int wimlib_get_boot_idx(const WIMStruct *w)
392 {
393         return w->hdr.boot_idx;
394 }
395
396 /* 
397  * Begins the reading of a WIM file; opens the file and reads its header and
398  * lookup table, and optionally checks the integrity.
399  */
400 static int begin_read(WIMStruct *w, const char *in_wim_path, int flags)
401 {
402         int ret;
403         uint xml_num_images;
404
405         DEBUG("Reading the WIM file `%s'", in_wim_path);
406
407         w->filename = STRDUP(in_wim_path);
408         if (!w->filename) {
409                 ERROR("Failed to allocate memory for WIM filename");
410                 return WIMLIB_ERR_NOMEM;
411         }
412
413         w->fp = fopen(in_wim_path, "rb");
414
415         if (!w->fp) {
416                 ERROR_WITH_ERRNO("Failed to open the file `%s' for reading",
417                                  in_wim_path);
418                 return WIMLIB_ERR_OPEN;
419         }
420
421         ret = read_header(w->fp, &w->hdr, flags & WIMLIB_OPEN_FLAG_SPLIT_OK);
422         if (ret != 0)
423                 return ret;
424
425         DEBUG("Wim file contains %u images", w->hdr.image_count);
426
427         /* If the boot index is invalid, print a warning and set it to 0 */
428         if (w->hdr.boot_idx > w->hdr.image_count) {
429                 WARNING("In `%s', image %u is marked as bootable, "
430                         "but there are only %u images",
431                          in_wim_path, w->hdr.boot_idx, w->hdr.image_count);
432                 w->hdr.boot_idx = 0;
433         }
434
435         if (wimlib_get_compression_type(w) == WIM_COMPRESSION_TYPE_INVALID) {
436                 ERROR("Invalid compression type (WIM header flags = %x)",
437                       w->hdr.flags);
438                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
439         }
440
441
442         if (flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
443                 int integrity_status;
444                 ret = check_wim_integrity(w, 
445                                           flags & WIMLIB_OPEN_FLAG_SHOW_PROGRESS, 
446                                           &integrity_status);
447                 if (ret != 0) {
448                         ERROR("Error in check_wim_integrity()");
449                         return ret;
450                 }
451                 if (integrity_status == WIM_INTEGRITY_NONEXISTENT) {
452                         WARNING("No integrity information for `%s'; skipping "
453                                 "integrity check.", w->filename);
454                 } else if (integrity_status == WIM_INTEGRITY_NOT_OK) {
455                         ERROR("WIM is not intact! (Failed integrity check)");
456                         return WIMLIB_ERR_INTEGRITY;
457                 }
458         }
459
460         if (resource_is_compressed(&w->hdr.lookup_table_res_entry)) {
461                 ERROR("Didn't expect a compressed lookup table!");
462                 ERROR("Ask the author to implement support for this.");
463                 return WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE;
464         }
465
466         ret = read_lookup_table(w);
467         if (ret != 0)
468                 return ret;
469
470         w->image_metadata = CALLOC(w->hdr.image_count, 
471                                    sizeof(struct image_metadata));
472
473         if (!w->image_metadata) {
474                 ERROR("Failed to allocate memory for %u metadata structures",
475                       w->hdr.image_count);
476                 return WIMLIB_ERR_NOMEM;
477         }
478         w->current_image = 0;
479
480         DEBUG("Looking for metadata resources in the lookup table.");
481
482         /* Find the images in the WIM by searching the lookup table. */
483         ret = for_lookup_table_entry(w->lookup_table, 
484                                      append_metadata_resource_entry, w);
485
486         if (ret != 0)
487                 return ret;
488
489         /* Make sure all the expected images were found.  (We already have
490          * returned false if *extra* images were found) */
491         if (w->current_image != w->hdr.image_count && w->hdr.part_number == 1) {
492                 ERROR("Only found %u images in WIM, but expected %u",
493                       w->current_image, w->hdr.image_count);
494                 return WIMLIB_ERR_IMAGE_COUNT;
495         }
496
497
498         /* Sort images by the position of their metadata resources.  I'm
499          * assuming that is what determines the other of the images in the WIM
500          * file, rather than their order in the lookup table, which is random
501          * because of hashing. */
502         qsort(w->image_metadata, w->current_image,
503               sizeof(struct image_metadata), sort_image_metadata_by_position);
504
505         w->current_image = WIM_NO_IMAGE;
506
507         /* Read the XML data. */
508         ret = read_xml_data(w->fp, &w->hdr.xml_res_entry, 
509                             &w->xml_data, &w->wim_info);
510
511         if (ret != 0) {
512                 ERROR("Missing or invalid XML data");
513                 return ret;
514         }
515
516         xml_num_images = wim_info_get_num_images(w->wim_info);
517         if (xml_num_images != w->hdr.image_count) {
518                 ERROR("In the file `%s', there are %u <IMAGE> elements "
519                       "in the XML data,", in_wim_path, xml_num_images);
520                 ERROR("but %u images in the WIM!  There must be exactly one "
521                       "<IMAGE> element per image.", w->hdr.image_count);
522                 return WIMLIB_ERR_IMAGE_COUNT;
523         }
524
525         DEBUG("Done beginning read of WIM file `%s'.", in_wim_path);
526         return 0;
527 }
528
529
530 /*
531  * Opens a WIM file and creates a WIMStruct for it.
532  */
533 WIMLIBAPI int wimlib_open_wim(const char *wim_file, int flags, 
534                               WIMStruct **w_ret)
535 {
536         WIMStruct *w;
537         int ret;
538
539         DEBUG("wim_file = `%s', flags = %#x", wim_file, flags);
540         w = new_wim_struct();
541         if (!w) {
542                 ERROR("Failed to allocate memory for WIMStruct");
543                 return WIMLIB_ERR_NOMEM;
544         }
545
546         ret = begin_read(w, wim_file, flags);
547         if (ret != 0) {
548                 DEBUG("Could not begin reading the WIM file `%s'", wim_file);
549                 wimlib_free(w);
550                 return ret;
551         }
552         *w_ret = w;
553         return 0;
554 }
555
556 /* Frees the memory for the WIMStruct, including all internal memory; also
557  * closes all files associated with the WIMStruct.  */
558 WIMLIBAPI void wimlib_free(WIMStruct *w)
559 {
560         DEBUG2("Freeing WIMStruct");
561
562         if (!w)
563                 return;
564         if (w->fp)
565                 fclose(w->fp);
566         if (w->out_fp)
567                 fclose(w->out_fp);
568
569         free_lookup_table(w->lookup_table);
570
571         FREE(w->filename);
572         FREE(w->xml_data);
573         free_wim_info(w->wim_info);
574         if (w->image_metadata) {
575                 for (uint i = 0; i < w->hdr.image_count; i++)
576                         destroy_image_metadata(&w->image_metadata[i], NULL);
577                 FREE(w->image_metadata);
578         }
579 #ifdef WITH_NTFS_3G
580         if (w->ntfs_vol) {
581                 DEBUG("Unmounting NTFS volume");
582                 ntfs_umount(w->ntfs_vol, FALSE);
583         }
584 #endif
585         FREE(w);
586 }
587