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