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