]> wimlib.net Git - wimlib/blob - src/wim.c
Various cleanups
[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 #include <errno.h>
32
33 #include "dentry.h"
34 #include <unistd.h>
35 #include <fcntl.h>
36
37 #ifdef WITH_NTFS_3G
38 #include <time.h>
39 #include <ntfs-3g/volume.h>
40 #endif
41
42 #include "wimlib_internal.h"
43 #include "io.h"
44 #include "lookup_table.h"
45 #include "xml.h"
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 == WIMLIB_NO_IMAGE) {
212                 ERROR("Invalid image: %d", WIMLIB_NO_IMAGE);
213                 return WIMLIB_ERR_INVALID_IMAGE;
214         }
215
216         if (image == w->current_image)
217                 return 0;
218
219         if (image < 1 || image > w->hdr.image_count) {
220                 ERROR("Cannot select image %d: There are only %u images",
221                       image, w->hdr.image_count);
222                 return WIMLIB_ERR_INVALID_IMAGE;
223         }
224
225         /* If a valid image is currently selected, it can be freed if it is not
226          * modified.  */
227         if (w->current_image != WIMLIB_NO_IMAGE) {
228                 imd = wim_get_current_image_metadata(w);
229                 if (!imd->modified) {
230                         DEBUG("Freeing image %u", w->current_image);
231                         destroy_image_metadata(imd, NULL);
232                         imd->root_dentry = NULL;
233                         imd->security_data = NULL;
234                         INIT_HLIST_HEAD(&imd->inode_list);
235                 }
236         }
237
238         w->current_image = image;
239         imd = wim_get_current_image_metadata(w);
240
241         if (imd->root_dentry) {
242                 return 0;
243         } else {
244                 #ifdef ENABLE_DEBUG
245                 DEBUG("Reading metadata resource specified by the following "
246                       "lookup table entry:");
247                 print_lookup_table_entry(imd->metadata_lte);
248                 #endif
249                 return read_metadata_resource(w, imd);
250         }
251 }
252
253
254 /* Returns the compression type of the WIM file. */
255 WIMLIBAPI int wimlib_get_compression_type(const WIMStruct *w)
256 {
257         return wim_hdr_flags_compression_type(w->hdr.flags);
258 }
259
260 WIMLIBAPI const char *wimlib_get_compression_type_string(int ctype)
261 {
262         switch (ctype) {
263                 case WIMLIB_COMPRESSION_TYPE_NONE:
264                         return "None";
265                 case WIMLIB_COMPRESSION_TYPE_LZX:
266                         return "LZX";
267                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
268                         return "XPRESS";
269                 default:
270                         return "Invalid";
271         }
272 }
273
274 /*
275  * Returns the number of an image in the WIM file, given a string that is either
276  * the number of the image, or the name of the image.  The images are numbered
277  * starting at 1.
278  */
279 WIMLIBAPI int wimlib_resolve_image(WIMStruct *w, const char *image_name_or_num)
280 {
281         char *p;
282         int image;
283         int i;
284
285         if (!image_name_or_num || !*image_name_or_num)
286                 return WIMLIB_NO_IMAGE;
287
288         if (strcmp(image_name_or_num, "all") == 0
289             || strcmp(image_name_or_num, "*") == 0)
290                 return WIMLIB_ALL_IMAGES;
291         image = strtol(image_name_or_num, &p, 10);
292         if (p != image_name_or_num && *p == '\0' && image > 0) {
293                 if (image > w->hdr.image_count)
294                         return WIMLIB_NO_IMAGE;
295                 return image;
296         } else {
297                 for (i = 1; i <= w->hdr.image_count; i++) {
298                         if (strcmp(image_name_or_num,
299                                    wimlib_get_image_name(w, i)) == 0)
300                                 return i;
301                 }
302                 return WIMLIB_NO_IMAGE;
303         }
304 }
305
306
307 /* Prints some basic information about a WIM file. */
308 WIMLIBAPI void wimlib_print_wim_information(const WIMStruct *w)
309 {
310         const struct wim_header *hdr;
311
312         hdr = &w->hdr;
313         puts("WIM Information:");
314         puts("----------------");
315         printf("Path:           %s\n", w->filename);
316         fputs ("GUID:           0x", stdout);
317         print_byte_field(hdr->guid, WIM_GID_LEN);
318         putchar('\n');
319         printf("Image Count:    %d\n", hdr->image_count);
320         printf("Compression:    %s\n", wimlib_get_compression_type_string(
321                                                 wimlib_get_compression_type(w)));
322         printf("Part Number:    %d/%d\n", hdr->part_number, hdr->total_parts);
323         printf("Boot Index:     %d\n", hdr->boot_idx);
324         printf("Size:           %"PRIu64" bytes\n",
325                                 wim_info_get_total_bytes(w->wim_info));
326         printf("Integrity Info: %s\n", (w->hdr.integrity.size != 0) ? "yes" : "no");
327         putchar('\n');
328 }
329
330 WIMLIBAPI bool wimlib_has_integrity_table(const WIMStruct *w)
331 {
332         return w->hdr.integrity.size != 0;
333 }
334
335 WIMLIBAPI void wimlib_print_available_images(const WIMStruct *w, int image)
336 {
337         int first;
338         int last;
339         int i;
340         int n;
341         if (image == WIMLIB_ALL_IMAGES) {
342                 n = printf("Available Images:\n");
343                 first = 1;
344                 last = w->hdr.image_count;
345         } else if (image >= 1 && image <= w->hdr.image_count) {
346                 n = printf("Information for Image %d\n", image);
347                 first = image;
348                 last = image;
349         } else {
350                 printf("wimlib_print_available_images(): Invalid image %d",
351                        image);
352                 return;
353         }
354         for (i = 0; i < n - 1; i++)
355                 putchar('-');
356         putchar('\n');
357         for (i = first; i <= last; i++)
358                 print_image_info(w->wim_info, i);
359 }
360
361
362 /* Prints the metadata for the specified image, which may be WIMLIB_ALL_IMAGES, but
363  * not WIMLIB_NO_IMAGE. */
364 WIMLIBAPI int wimlib_print_metadata(WIMStruct *w, int image)
365 {
366         if (!w)
367                 return WIMLIB_ERR_INVALID_PARAM;
368         if (w->hdr.part_number != 1) {
369                 ERROR("Cannot show the metadata from part %hu of a %hu-part split WIM!",
370                        w->hdr.part_number, w->hdr.total_parts);
371                 ERROR("Select the first part of the split WIM to see the metadata.");
372                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
373         }
374         return for_image(w, image, print_metadata);
375 }
376
377 WIMLIBAPI int wimlib_print_files(WIMStruct *w, int image)
378 {
379         if (!w)
380                 return WIMLIB_ERR_INVALID_PARAM;
381         if (w->hdr.part_number != 1) {
382                 ERROR("Cannot list the files from part %hu of a %hu-part split WIM!",
383                        w->hdr.part_number, w->hdr.total_parts);
384                 ERROR("Select the first part of the split WIM if you'd like to list the files.");
385                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
386         }
387         return for_image(w, image, print_files);
388 }
389
390 /* Sets the index of the bootable image. */
391 WIMLIBAPI int wimlib_set_boot_idx(WIMStruct *w, int boot_idx)
392 {
393         if (!w)
394                 return WIMLIB_ERR_INVALID_PARAM;
395         if (w->hdr.total_parts != 1) {
396                 ERROR("Cannot modify the boot index of a split WIM!");
397                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
398         }
399         if (boot_idx < 0 || boot_idx > w->hdr.image_count)
400                 return WIMLIB_ERR_INVALID_IMAGE;
401         w->hdr.boot_idx = boot_idx;
402
403         if (boot_idx == 0) {
404                 memset(&w->hdr.boot_metadata_res_entry, 0,
405                        sizeof(struct resource_entry));
406         } else {
407                 memcpy(&w->hdr.boot_metadata_res_entry,
408                        &w->image_metadata[
409                           boot_idx - 1].metadata_lte->resource_entry,
410                        sizeof(struct resource_entry));
411         }
412
413         return 0;
414 }
415
416 WIMLIBAPI int wimlib_get_part_number(const WIMStruct *w, int *total_parts_ret)
417 {
418         if (total_parts_ret)
419                 *total_parts_ret = w->hdr.total_parts;
420         return w->hdr.part_number;
421 }
422
423
424 WIMLIBAPI int wimlib_get_boot_idx(const WIMStruct *w)
425 {
426         return w->hdr.boot_idx;
427 }
428
429 /*
430  * Begins the reading of a WIM file; opens the file and reads its header and
431  * lookup table, and optionally checks the integrity.
432  */
433 static int begin_read(WIMStruct *w, const char *in_wim_path, int open_flags,
434                       wimlib_progress_func_t progress_func)
435 {
436         int ret;
437         int xml_num_images;
438
439         DEBUG("Reading the WIM file `%s'", in_wim_path);
440
441         w->fp = fopen(in_wim_path, "rb");
442         if (!w->fp) {
443                 ERROR_WITH_ERRNO("Failed to open `%s' for reading",
444                                  in_wim_path);
445                 return WIMLIB_ERR_OPEN;
446         }
447
448         /* The absolute path to the WIM is requested so that wimlib_overwrite()
449          * still works even if the process changes its working directory.  This
450          * actually happens if a WIM is mounted read-write, since the FUSE
451          * thread changes directory to "/", and it needs to be able to find the
452          * WIM file again.
453          *
454          * This will break if the full path to the WIM changes in the
455          * intervening time...
456          */
457         w->filename = realpath(in_wim_path, NULL);
458         if (!w->filename) {
459                 ERROR_WITH_ERRNO("Failed to resolve WIM filename");
460                 if (errno == ENOMEM)
461                         ret = WIMLIB_ERR_NOMEM;
462                 else
463                         ret = WIMLIB_ERR_OPEN;
464                 goto out_close;
465         }
466
467         ret = read_header(w->fp, &w->hdr, open_flags);
468         if (ret != 0)
469                 goto out_close;
470
471         DEBUG("According to header, WIM contains %u images", w->hdr.image_count);
472
473         /* If the boot index is invalid, print a warning and set it to 0 */
474         if (w->hdr.boot_idx > w->hdr.image_count) {
475                 WARNING("In `%s', image %u is marked as bootable, "
476                         "but there are only %u images in the WIM",
477                         in_wim_path, w->hdr.boot_idx, w->hdr.image_count);
478                 w->hdr.boot_idx = 0;
479         }
480
481         if (wimlib_get_compression_type(w) == WIMLIB_COMPRESSION_TYPE_INVALID) {
482                 ERROR("Invalid compression type (WIM header flags = %x)",
483                       w->hdr.flags);
484                 ret = WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
485                 goto out_close;
486         }
487
488         if (open_flags & WIMLIB_OPEN_FLAG_CHECK_INTEGRITY) {
489                 ret = check_wim_integrity(w, progress_func);
490                 if (ret == WIM_INTEGRITY_NONEXISTENT) {
491                         WARNING("No integrity information for `%s'; skipping "
492                                 "integrity check.", w->filename);
493                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
494                         ERROR("WIM is not intact! (Failed integrity check)");
495                         ret = WIMLIB_ERR_INTEGRITY;
496                         goto out_close;
497                 } else if (ret != 0) {
498                         goto out_close;
499                 }
500         }
501
502         if (resource_is_compressed(&w->hdr.lookup_table_res_entry)) {
503                 ERROR("Didn't expect a compressed lookup table!");
504                 ERROR("Ask the author to implement support for this.");
505                 ret = WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE;
506                 goto out_close;
507         }
508
509         ret = read_lookup_table(w);
510         if (ret != 0)
511                 goto out_close;
512
513         w->image_metadata = CALLOC(w->hdr.image_count,
514                                    sizeof(struct image_metadata));
515
516         if (!w->image_metadata) {
517                 ERROR("Failed to allocate memory for %u metadata structures",
518                       w->hdr.image_count);
519                 ret = WIMLIB_ERR_NOMEM;
520                 goto out_free_lookup_table;
521         }
522         w->current_image = 0;
523
524         DEBUG("Looking for metadata resources in the lookup table.");
525
526         /* Find the images in the WIM by searching the lookup table. */
527         ret = for_lookup_table_entry(w->lookup_table,
528                                      append_metadata_resource_entry, w);
529
530         if (ret != 0)
531                 goto out_free_image_metadata;
532
533         /* Make sure all the expected images were found.  (We already have
534          * returned false if *extra* images were found) */
535         if (w->current_image != w->hdr.image_count &&
536             w->hdr.part_number == 1)
537         {
538                 ERROR("Only found %u images in WIM, but expected %u",
539                       w->current_image, w->hdr.image_count);
540                 ret = WIMLIB_ERR_IMAGE_COUNT;
541                 goto out_free_image_metadata;
542         }
543
544         /* Sort images by the position of their metadata resources.  I'm
545          * assuming that is what determines the other of the images in the WIM
546          * file, rather than their order in the lookup table, which is random
547          * because of hashing. */
548         qsort(w->image_metadata, w->current_image,
549               sizeof(struct image_metadata), sort_image_metadata_by_position);
550
551         w->current_image = WIMLIB_NO_IMAGE;
552
553         /* Read the XML data. */
554         ret = read_xml_data(w->fp, &w->hdr.xml_res_entry,
555                             &w->xml_data, &w->wim_info);
556
557         if (ret != 0)
558                 goto out_free_image_metadata;
559
560         xml_num_images = wim_info_get_num_images(w->wim_info);
561         if (xml_num_images != w->hdr.image_count) {
562                 ERROR("In the file `%s', there are %u <IMAGE> elements "
563                       "in the XML data,", in_wim_path, xml_num_images);
564                 ERROR("but %u images in the WIM!  There must be exactly one "
565                       "<IMAGE> element per image.", w->hdr.image_count);
566                 ret = WIMLIB_ERR_IMAGE_COUNT;
567                 goto out_free_xml_data;
568         }
569
570         DEBUG("Done beginning read of WIM file `%s'.", in_wim_path);
571         /*return 0;*/
572
573         //
574         // Everything is freed in wimlib_free() anyway, so no need to roll back
575         // changes here.
576         //
577 out_free_xml_data:
578         /*FREE(w->xml_data);*/
579         /*w->xml_data = NULL;*/
580         /*free_wim_info(w->wim_info);*/
581         /*w->wim_info = NULL;*/
582 out_free_image_metadata:
583         /*FREE(w->image_metadata);*/
584         /*w->image_metadata = NULL;*/
585         /*w->current_image = WIMLIB_NO_IMAGE;*/
586 out_free_lookup_table:
587         /*free_lookup_table(w->lookup_table);*/
588         /*w->lookup_table = NULL;*/
589 out_close:
590         /*fclose(w->fp);*/
591         /*w->fp = NULL;*/
592         return ret;
593 }
594
595
596 /*
597  * Opens a WIM file and creates a WIMStruct for it.
598  */
599 WIMLIBAPI int wimlib_open_wim(const char *wim_file, int open_flags,
600                               WIMStruct **w_ret,
601                               wimlib_progress_func_t progress_func)
602 {
603         WIMStruct *w;
604         int ret;
605
606         if (!wim_file || !w_ret)
607                 return WIMLIB_ERR_INVALID_PARAM;
608         w = new_wim_struct();
609         if (!w) {
610                 ERROR("Failed to allocate memory for WIMStruct");
611                 return WIMLIB_ERR_NOMEM;
612         }
613
614         ret = begin_read(w, wim_file, open_flags, progress_func);
615         if (ret == 0) {
616                 *w_ret = w;
617         } else {
618                 DEBUG("Could not begin reading the WIM file `%s'", wim_file);
619                 wimlib_free(w);
620         }
621         return ret;
622 }
623
624 /* Frees the memory for the WIMStruct, including all internal memory; also
625  * closes all files associated with the WIMStruct.  */
626 WIMLIBAPI void wimlib_free(WIMStruct *w)
627 {
628         DEBUG2("Freeing WIMStruct");
629
630         if (!w)
631                 return;
632         if (w->fp)
633                 fclose(w->fp);
634         if (w->out_fp)
635                 fclose(w->out_fp);
636
637 #ifdef WITH_FUSE
638         if (w->fp_tab) {
639                 for (size_t i = 0; i < w->num_allocated_fps; i++)
640                         if (w->fp_tab[i])
641                                 fclose(w->fp_tab[i]);
642                 FREE(w->fp_tab);
643         }
644         pthread_mutex_destroy(&w->fp_tab_mutex);
645 #endif
646
647         free_lookup_table(w->lookup_table);
648
649         FREE(w->filename);
650         FREE(w->xml_data);
651         free_wim_info(w->wim_info);
652         if (w->image_metadata) {
653                 for (uint i = 0; i < w->hdr.image_count; i++)
654                         destroy_image_metadata(&w->image_metadata[i], NULL);
655                 FREE(w->image_metadata);
656         }
657 #ifdef WITH_NTFS_3G
658         if (w->ntfs_vol) {
659                 DEBUG("Unmounting NTFS volume");
660                 ntfs_umount(w->ntfs_vol, FALSE);
661         }
662 #endif
663         FREE(w);
664 }