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