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