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