Clean up headers
[wimlib] / src / wim.c
1 /*
2  * wim.c - Stuff that doesn't fit into any other file
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * wimlib - Library for working with WIM files
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #include "config.h"
27
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <stdarg.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34
35 #ifdef WITH_NTFS_3G
36 #  include <time.h>
37 #  include <ntfs-3g/volume.h>
38 #endif
39
40 #ifdef __WIN32__
41 #  include "win32.h"
42 #endif
43
44 #include "buffer_io.h"
45 #include "dentry.h"
46 #include "lookup_table.h"
47 #include "wimlib_internal.h"
48 #include "xml.h"
49
50 static int image_print_metadata(WIMStruct *w)
51 {
52         DEBUG("Printing metadata for image %d", w->current_image);
53         print_security_data(wim_security_data(w));
54         return for_dentry_in_tree(wim_root_dentry(w), print_dentry,
55                                   w->lookup_table);
56 }
57
58
59 static int image_print_files(WIMStruct *w)
60 {
61         return for_dentry_in_tree(wim_root_dentry(w), print_dentry_full_path,
62                                   NULL);
63 }
64
65 static WIMStruct *new_wim_struct()
66 {
67         WIMStruct *w = CALLOC(1, sizeof(WIMStruct));
68 #ifdef WITH_FUSE
69         if (pthread_mutex_init(&w->fp_tab_mutex, NULL) != 0) {
70                 ERROR_WITH_ERRNO("Failed to initialize mutex");
71                 FREE(w);
72                 w = NULL;
73         }
74 #endif
75         return w;
76
77 }
78
79 /*
80  * Calls a function on images in the WIM.  If @image is WIMLIB_ALL_IMAGES, @visitor
81  * is called on the WIM once for each image, with each image selected as the
82  * current image in turn.  If @image is a certain image, @visitor is called on
83  * the WIM only once, with that image selected.
84  */
85 int for_image(WIMStruct *w, int image, int (*visitor)(WIMStruct *))
86 {
87         int ret;
88         int start;
89         int end;
90         int i;
91
92         if (image == WIMLIB_ALL_IMAGES) {
93                 start = 1;
94                 end = w->hdr.image_count;
95         } else if (image >= 1 && image <= w->hdr.image_count) {
96                 start = image;
97                 end = image;
98         } else {
99                 return WIMLIB_ERR_INVALID_IMAGE;
100         }
101         for (i = start; i <= end; i++) {
102                 ret = select_wim_image(w, i);
103                 if (ret != 0)
104                         return ret;
105                 ret = visitor(w);
106                 if (ret != 0)
107                         return ret;
108         }
109         return 0;
110 }
111
112 static int sort_image_metadata_by_position(const void *p1, const void *p2)
113 {
114         const struct wim_image_metadata *imd1 = p1;
115         const struct wim_image_metadata *imd2 = p2;
116         u64 offset1 = imd1->metadata_lte->resource_entry.offset;
117         u64 offset2 = imd2->metadata_lte->resource_entry.offset;
118         if (offset1 < offset2)
119                 return -1;
120         else if (offset1 > offset2)
121                 return 1;
122         else
123                 return 0;
124 }
125
126 /*
127  * If @lte points to a metadata resource, append it to the list of metadata
128  * resources in the WIMStruct.  Otherwise, do nothing.
129  */
130 static int append_metadata_resource_entry(struct wim_lookup_table_entry *lte,
131                                           void *wim_p)
132 {
133         WIMStruct *w = wim_p;
134         int ret = 0;
135
136         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
137                 if (w->current_image == w->hdr.image_count) {
138                         ERROR("The WIM header says there are %u images in the WIM,\n"
139                               "        but we found more metadata resources than this",
140                               w->hdr.image_count);
141                         ret = WIMLIB_ERR_IMAGE_COUNT;
142                 } else {
143                         DEBUG("Found metadata resource for image %u at "
144                               "offset %"PRIu64".",
145                               w->current_image + 1,
146                               lte->resource_entry.offset);
147                         w->image_metadata[
148                                 w->current_image++].metadata_lte = lte;
149                 }
150         }
151         return ret;
152 }
153
154 /* Returns the compression type given in the flags of a WIM header. */
155 static int wim_hdr_flags_compression_type(int wim_hdr_flags)
156 {
157         if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESSION) {
158                 if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_LZX)
159                         return WIMLIB_COMPRESSION_TYPE_LZX;
160                 else if (wim_hdr_flags & WIM_HDR_FLAG_COMPRESS_XPRESS)
161                         return WIMLIB_COMPRESSION_TYPE_XPRESS;
162                 else
163                         return WIMLIB_COMPRESSION_TYPE_INVALID;
164         } else {
165                 return WIMLIB_COMPRESSION_TYPE_NONE;
166         }
167 }
168
169 /*
170  * Creates a WIMStruct for a new WIM file.
171  */
172 WIMLIBAPI int wimlib_create_new_wim(int ctype, WIMStruct **w_ret)
173 {
174         WIMStruct *w;
175         struct wim_lookup_table *table;
176         int ret;
177
178         DEBUG("Creating new WIM with %s compression.",
179               wimlib_get_compression_type_string(ctype));
180
181         /* Allocate the WIMStruct. */
182         w = new_wim_struct();
183         if (!w)
184                 return WIMLIB_ERR_NOMEM;
185
186         ret = init_header(&w->hdr, ctype);
187         if (ret != 0)
188                 goto out_free;
189
190         table = new_lookup_table(9001);
191         if (!table) {
192                 ret = WIMLIB_ERR_NOMEM;
193                 goto out_free;
194         }
195         w->lookup_table = table;
196         *w_ret = w;
197         return 0;
198 out_free:
199         FREE(w);
200         return ret;
201 }
202
203 WIMLIBAPI int wimlib_get_num_images(const WIMStruct *w)
204 {
205         return w->hdr.image_count;
206 }
207
208 int select_wim_image(WIMStruct *w, int image)
209 {
210         struct wim_image_metadata *imd;
211         int ret;
212
213         DEBUG("Selecting image %d", image);
214
215         if (image == WIMLIB_NO_IMAGE) {
216                 ERROR("Invalid image: %d", WIMLIB_NO_IMAGE);
217                 return WIMLIB_ERR_INVALID_IMAGE;
218         }
219
220         if (image == w->current_image)
221                 return 0;
222
223         if (image < 1 || image > w->hdr.image_count) {
224                 ERROR("Cannot select image %d: There are only %u images",
225                       image, w->hdr.image_count);
226                 return WIMLIB_ERR_INVALID_IMAGE;
227         }
228
229         /* If a valid image is currently selected, it can be freed if it is not
230          * modified.  */
231         if (w->current_image != WIMLIB_NO_IMAGE) {
232                 imd = wim_get_current_image_metadata(w);
233                 if (!imd->modified) {
234                         DEBUG("Freeing image %u", w->current_image);
235                         destroy_image_metadata(imd, NULL);
236                         imd->root_dentry = NULL;
237                         imd->security_data = NULL;
238                         INIT_HLIST_HEAD(&imd->inode_list);
239                 }
240         }
241         w->current_image = image;
242         imd = &w->image_metadata[image - 1];
243         if (imd->root_dentry) {
244                 ret = 0;
245         } else {
246                 #ifdef ENABLE_DEBUG
247                 DEBUG("Reading metadata resource specified by the following "
248                       "lookup table entry:");
249                 print_lookup_table_entry(imd->metadata_lte, stdout);
250                 #endif
251                 ret = read_metadata_resource(w, imd);
252                 if (ret)
253                         w->current_image = WIMLIB_NO_IMAGE;
254         }
255         return ret;
256 }
257
258
259 /* Returns the compression type of the WIM file. */
260 WIMLIBAPI int wimlib_get_compression_type(const WIMStruct *w)
261 {
262         return wim_hdr_flags_compression_type(w->hdr.flags);
263 }
264
265 WIMLIBAPI const char *wimlib_get_compression_type_string(int ctype)
266 {
267         switch (ctype) {
268                 case WIMLIB_COMPRESSION_TYPE_NONE:
269                         return "None";
270                 case WIMLIB_COMPRESSION_TYPE_LZX:
271                         return "LZX";
272                 case WIMLIB_COMPRESSION_TYPE_XPRESS:
273                         return "XPRESS";
274                 default:
275                         return "Invalid";
276         }
277 }
278
279 /*
280  * Returns the number of an image in the WIM file, given a string that is either
281  * the number of the image, or the name of the image.  The images are numbered
282  * starting at 1.
283  */
284 WIMLIBAPI int wimlib_resolve_image(WIMStruct *w, const char *image_name_or_num)
285 {
286         char *p;
287         int image;
288         int i;
289
290         if (!image_name_or_num || !*image_name_or_num)
291                 return WIMLIB_NO_IMAGE;
292
293         if (strcmp(image_name_or_num, "all") == 0
294             || strcmp(image_name_or_num, "*") == 0)
295                 return WIMLIB_ALL_IMAGES;
296         image = strtol(image_name_or_num, &p, 10);
297         if (p != image_name_or_num && *p == '\0' && image > 0) {
298                 if (image > w->hdr.image_count)
299                         return WIMLIB_NO_IMAGE;
300                 return image;
301         } else {
302                 for (i = 1; i <= w->hdr.image_count; i++) {
303                         if (strcmp(image_name_or_num,
304                                    wimlib_get_image_name(w, i)) == 0)
305                                 return i;
306                 }
307                 return WIMLIB_NO_IMAGE;
308         }
309 }
310
311
312 /* Prints some basic information about a WIM file. */
313 WIMLIBAPI void wimlib_print_wim_information(const WIMStruct *w)
314 {
315         const struct wim_header *hdr;
316
317         hdr = &w->hdr;
318         puts("WIM Information:");
319         puts("----------------");
320         printf("Path:           %s\n", w->filename);
321         fputs ("GUID:           0x", stdout);
322         print_byte_field(hdr->guid, WIM_GID_LEN);
323         putchar('\n');
324         printf("Image Count:    %d\n", hdr->image_count);
325         printf("Compression:    %s\n", wimlib_get_compression_type_string(
326                                                 wimlib_get_compression_type(w)));
327         printf("Part Number:    %d/%d\n", hdr->part_number, hdr->total_parts);
328         printf("Boot Index:     %d\n", hdr->boot_idx);
329         printf("Size:           %"PRIu64" bytes\n",
330                                 wim_info_get_total_bytes(w->wim_info));
331         printf("Integrity Info: %s\n", (w->hdr.integrity.offset != 0) ? "yes" : "no");
332         putchar('\n');
333 }
334
335 WIMLIBAPI bool wimlib_has_integrity_table(const WIMStruct *w)
336 {
337         return w->hdr.integrity.size != 0;
338 }
339
340 WIMLIBAPI void wimlib_print_available_images(const WIMStruct *w, int image)
341 {
342         int first;
343         int last;
344         int i;
345         int n;
346         if (image == WIMLIB_ALL_IMAGES) {
347                 n = printf("Available Images:\n");
348                 first = 1;
349                 last = w->hdr.image_count;
350         } else if (image >= 1 && image <= w->hdr.image_count) {
351                 n = printf("Information for Image %d\n", image);
352                 first = image;
353                 last = image;
354         } else {
355                 printf("wimlib_print_available_images(): Invalid image %d",
356                        image);
357                 return;
358         }
359         for (i = 0; i < n - 1; i++)
360                 putchar('-');
361         putchar('\n');
362         for (i = first; i <= last; i++)
363                 print_image_info(w->wim_info, i);
364 }
365
366
367 /* Prints the metadata for the specified image, which may be WIMLIB_ALL_IMAGES, but
368  * not WIMLIB_NO_IMAGE. */
369 WIMLIBAPI int wimlib_print_metadata(WIMStruct *w, int image)
370 {
371         if (w->hdr.part_number != 1) {
372                 ERROR("Cannot show the metadata from part %hu of a %hu-part split WIM!",
373                        w->hdr.part_number, w->hdr.total_parts);
374                 ERROR("Select the first part of the split WIM to see the metadata.");
375                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
376         }
377         return for_image(w, image, image_print_metadata);
378 }
379
380 WIMLIBAPI int wimlib_print_files(WIMStruct *w, int image)
381 {
382         if (w->hdr.part_number != 1) {
383                 ERROR("Cannot list the files from part %hu of a %hu-part split WIM!",
384                        w->hdr.part_number, w->hdr.total_parts);
385                 ERROR("Select the first part of the split WIM if you'd like to list the files.");
386                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
387         }
388         return for_image(w, image, image_print_files);
389 }
390
391 /* Sets the index of the bootable image. */
392 WIMLIBAPI int wimlib_set_boot_idx(WIMStruct *w, int boot_idx)
393 {
394         if (w->hdr.total_parts != 1) {
395                 ERROR("Cannot modify the boot index of a split WIM!");
396                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
397         }
398         if (boot_idx < 0 || boot_idx > w->hdr.image_count)
399                 return WIMLIB_ERR_INVALID_IMAGE;
400         w->hdr.boot_idx = boot_idx;
401
402         if (boot_idx == 0) {
403                 memset(&w->hdr.boot_metadata_res_entry, 0,
404                        sizeof(struct resource_entry));
405         } else {
406                 memcpy(&w->hdr.boot_metadata_res_entry,
407                        &w->image_metadata[
408                           boot_idx - 1].metadata_lte->resource_entry,
409                        sizeof(struct resource_entry));
410         }
411
412         return 0;
413 }
414
415 WIMLIBAPI int wimlib_get_part_number(const WIMStruct *w, int *total_parts_ret)
416 {
417         if (total_parts_ret)
418                 *total_parts_ret = w->hdr.total_parts;
419         return w->hdr.part_number;
420 }
421
422
423 WIMLIBAPI int wimlib_get_boot_idx(const WIMStruct *w)
424 {
425         return w->hdr.boot_idx;
426 }
427
428 /*
429  * Begins the reading of a WIM file; opens the file and reads its header and
430  * lookup table, and optionally checks the integrity.
431  */
432 static int begin_read(WIMStruct *w, const char *in_wim_path, int open_flags,
433                       wimlib_progress_func_t progress_func)
434 {
435         int ret;
436         int xml_num_images;
437
438         DEBUG("Reading the WIM file `%s'", in_wim_path);
439
440         w->fp = fopen(in_wim_path, "rb");
441         if (!w->fp) {
442                 ERROR_WITH_ERRNO("Failed to open `%s' for reading",
443                                  in_wim_path);
444                 return WIMLIB_ERR_OPEN;
445         }
446
447         /* The absolute path to the WIM is requested so that wimlib_overwrite()
448          * still works even if the process changes its working directory.  This
449          * actually happens if a WIM is mounted read-write, since the FUSE
450          * thread changes directory to "/", and it needs to be able to find the
451          * WIM file again.
452          *
453          * This will break if the full path to the WIM changes in the
454          * intervening time...
455          *
456          * Warning: in Windows native builds, realpath() calls the replacement
457          * function in win32.c.
458          */
459         w->filename = realpath(in_wim_path, NULL);
460         if (!w->filename) {
461                 ERROR_WITH_ERRNO("Failed to resolve WIM filename");
462                 if (errno == ENOMEM)
463                         return WIMLIB_ERR_NOMEM;
464                 else
465                         return WIMLIB_ERR_OPEN;
466         }
467
468         ret = read_header(w->fp, &w->hdr, open_flags);
469         if (ret != 0)
470                 return ret;
471
472         DEBUG("According to header, WIM contains %u images", w->hdr.image_count);
473
474         /* If the boot index is invalid, print a warning and set it to 0 */
475         if (w->hdr.boot_idx > w->hdr.image_count) {
476                 WARNING("In `%s', image %u is marked as bootable, "
477                         "but there are only %u images in the WIM",
478                         in_wim_path, w->hdr.boot_idx, w->hdr.image_count);
479                 w->hdr.boot_idx = 0;
480         }
481
482         if (wimlib_get_compression_type(w) == WIMLIB_COMPRESSION_TYPE_INVALID) {
483                 ERROR("Invalid compression type (WIM header flags = 0x%x)",
484                       w->hdr.flags);
485                 return WIMLIB_ERR_INVALID_COMPRESSION_TYPE;
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.", in_wim_path);
493                 } else if (ret == WIM_INTEGRITY_NOT_OK) {
494                         ERROR("WIM is not intact! (Failed integrity check)");
495                         return WIMLIB_ERR_INTEGRITY;
496                 } else if (ret != WIM_INTEGRITY_OK) {
497                         return ret;
498                 }
499         }
500
501         ret = read_lookup_table(w);
502         if (ret != 0)
503                 return ret;
504
505         if (w->hdr.image_count != 0) {
506                 w->image_metadata = CALLOC(w->hdr.image_count,
507                                            sizeof(struct wim_image_metadata));
508
509                 if (!w->image_metadata) {
510                         ERROR("Failed to allocate memory for %u image metadata structures",
511                               w->hdr.image_count);
512                         return WIMLIB_ERR_NOMEM;
513                 }
514         }
515         w->current_image = 0;
516
517         DEBUG("Looking for metadata resources in the lookup table.");
518
519         /* Find the images in the WIM by searching the lookup table. */
520         ret = for_lookup_table_entry(w->lookup_table,
521                                      append_metadata_resource_entry, w);
522
523         if (ret != 0)
524                 return ret;
525
526         /* Make sure all the expected images were found.  (We already have
527          * returned WIMLIB_ERR_IMAGE_COUNT if *extra* images were found) */
528         if (w->current_image != w->hdr.image_count &&
529             w->hdr.part_number == 1)
530         {
531                 ERROR("Only found %d images in WIM, but expected %u",
532                       w->current_image, w->hdr.image_count);
533                 return WIMLIB_ERR_IMAGE_COUNT;
534         }
535
536         /* Sort images by the position of their metadata resources.  I'm
537          * assuming that is what determines the other of the images in the WIM
538          * file, rather than their order in the lookup table, which is random
539          * because of hashing. */
540         qsort(w->image_metadata, w->current_image,
541               sizeof(struct wim_image_metadata), sort_image_metadata_by_position);
542
543         w->current_image = WIMLIB_NO_IMAGE;
544
545         /* Read the XML data. */
546         ret = read_xml_data(w->fp, &w->hdr.xml_res_entry,
547                             &w->xml_data, &w->wim_info);
548
549         if (ret != 0)
550                 return ret;
551
552         xml_num_images = wim_info_get_num_images(w->wim_info);
553         if (xml_num_images != w->hdr.image_count) {
554                 ERROR("In the file `%s', there are %u <IMAGE> elements "
555                       "in the XML data,", in_wim_path, xml_num_images);
556                 ERROR("but %u images in the WIM!  There must be exactly one "
557                       "<IMAGE> element per image.", w->hdr.image_count);
558                 return WIMLIB_ERR_IMAGE_COUNT;
559         }
560
561         DEBUG("Done beginning read of WIM file `%s'.", in_wim_path);
562         return 0;
563 }
564
565
566 /*
567  * Opens a WIM file and creates a WIMStruct for it.
568  */
569 WIMLIBAPI int wimlib_open_wim(const char *wim_file, int open_flags,
570                               WIMStruct **w_ret,
571                               wimlib_progress_func_t progress_func)
572 {
573         WIMStruct *w;
574         int ret;
575
576         if (!wim_file || !w_ret)
577                 return WIMLIB_ERR_INVALID_PARAM;
578
579         w = new_wim_struct();
580         if (!w)
581                 return WIMLIB_ERR_NOMEM;
582
583         ret = begin_read(w, wim_file, open_flags, progress_func);
584         if (ret == 0)
585                 *w_ret = w;
586         else
587                 wimlib_free(w);
588         return ret;
589 }
590
591 void destroy_image_metadata(struct wim_image_metadata *imd,
592                             struct wim_lookup_table *table)
593 {
594         free_dentry_tree(imd->root_dentry, table);
595         free_security_data(imd->security_data);
596
597         /* Get rid of the lookup table entry for this image's metadata resource
598          * */
599         if (table) {
600                 lookup_table_unlink(table, imd->metadata_lte);
601                 free_lookup_table_entry(imd->metadata_lte);
602         }
603 }
604
605 /* Frees the memory for the WIMStruct, including all internal memory; also
606  * closes all files associated with the WIMStruct.  */
607 WIMLIBAPI void wimlib_free(WIMStruct *w)
608 {
609         DEBUG("Freeing WIMStruct");
610
611         if (!w)
612                 return;
613         if (w->fp)
614                 fclose(w->fp);
615         if (w->out_fp)
616                 fclose(w->out_fp);
617
618 #ifdef WITH_FUSE
619         if (w->fp_tab) {
620                 for (size_t i = 0; i < w->num_allocated_fps; i++)
621                         if (w->fp_tab[i])
622                                 fclose(w->fp_tab[i]);
623                 FREE(w->fp_tab);
624         }
625         pthread_mutex_destroy(&w->fp_tab_mutex);
626 #endif
627
628         free_lookup_table(w->lookup_table);
629
630         FREE(w->filename);
631         FREE(w->xml_data);
632         free_wim_info(w->wim_info);
633         if (w->image_metadata) {
634                 for (unsigned i = 0; i < w->hdr.image_count; i++)
635                         destroy_image_metadata(&w->image_metadata[i], NULL);
636                 FREE(w->image_metadata);
637         }
638 #ifdef WITH_NTFS_3G
639         if (w->ntfs_vol) {
640                 DEBUG("Unmounting NTFS volume");
641                 ntfs_umount(w->ntfs_vol, FALSE);
642         }
643 #endif
644         FREE(w);
645         DEBUG("Freed WIMStruct");
646 }
647
648 /* Get global memory allocations out of the way.  Not strictly necessary in
649  * single-threaded programs like 'imagex'. */
650 WIMLIBAPI int wimlib_global_init()
651 {
652         libxml_global_init();
653         return iconv_global_init();
654 }
655
656 /* Free global memory allocations.  Not strictly necessary if the process using
657  * wimlib is just about to exit (as is the case for 'imagex'). */
658 WIMLIBAPI void wimlib_global_cleanup()
659 {
660         libxml_global_cleanup();
661         iconv_global_cleanup();
662 }