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