955aac35661faf7dfcf6cc37669a32fb36de5858
[wimlib] / src / lookup_table.c
1 /*
2  * lookup_table.c
3  *
4  * Lookup table, implemented as a hash table, that maps SHA1 message digests to
5  * data streams.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/util.h"
39
40 #include <errno.h>
41 #include <stdlib.h>
42 #ifdef WITH_FUSE
43 #  include <unistd.h> /* for unlink() */
44 #endif
45
46 struct wim_lookup_table *
47 new_lookup_table(size_t capacity)
48 {
49         struct wim_lookup_table *table;
50         struct hlist_head *array;
51
52         table = CALLOC(1, sizeof(struct wim_lookup_table));
53         if (table) {
54                 array = CALLOC(capacity, sizeof(array[0]));
55                 if (array) {
56                         table->num_entries = 0;
57                         table->capacity = capacity;
58                         table->array = array;
59                 } else {
60                         FREE(table);
61                         table = NULL;
62                         ERROR("Failed to allocate memory for lookup table "
63                               "with capacity %zu", capacity);
64                 }
65         }
66         return table;
67 }
68
69 struct wim_lookup_table_entry *
70 new_lookup_table_entry(void)
71 {
72         struct wim_lookup_table_entry *lte;
73
74         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
75         if (lte) {
76                 lte->part_number  = 1;
77                 lte->refcnt       = 1;
78         } else {
79                 ERROR("Out of memory (tried to allocate %zu bytes for "
80                       "lookup table entry)",
81                       sizeof(struct wim_lookup_table_entry));
82         }
83         return lte;
84 }
85
86 struct wim_lookup_table_entry *
87 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
88 {
89         struct wim_lookup_table_entry *new;
90
91         new = memdup(old, sizeof(struct wim_lookup_table_entry));
92         if (!new)
93                 return NULL;
94
95         new->extracted_file = NULL;
96         switch (new->resource_location) {
97 #ifdef __WIN32__
98         case RESOURCE_WIN32:
99         case RESOURCE_WIN32_ENCRYPTED:
100 #else
101         case RESOURCE_IN_FILE_ON_DISK:
102 #endif
103 #ifdef WITH_FUSE
104         case RESOURCE_IN_STAGING_FILE:
105                 BUILD_BUG_ON((void*)&old->file_on_disk !=
106                              (void*)&old->staging_file_name);
107 #endif
108                 new->file_on_disk = TSTRDUP(old->file_on_disk);
109                 if (!new->file_on_disk)
110                         goto out_free;
111                 break;
112         case RESOURCE_IN_ATTACHED_BUFFER:
113                 new->attached_buffer = memdup(old->attached_buffer,
114                                               wim_resource_size(old));
115                 if (!new->attached_buffer)
116                         goto out_free;
117                 break;
118 #ifdef WITH_NTFS_3G
119         case RESOURCE_IN_NTFS_VOLUME:
120                 if (old->ntfs_loc) {
121                         struct ntfs_location *loc;
122                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
123                         if (!loc)
124                                 goto out_free;
125                         loc->path = NULL;
126                         loc->stream_name = NULL;
127                         new->ntfs_loc = loc;
128                         loc->path = STRDUP(old->ntfs_loc->path);
129                         if (!loc->path)
130                                 goto out_free;
131                         if (loc->stream_name_nchars) {
132                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
133                                                           loc->stream_name_nchars * 2);
134                                 if (!loc->stream_name)
135                                         goto out_free;
136                         }
137                 }
138                 break;
139 #endif
140         default:
141                 break;
142         }
143         return new;
144 out_free:
145         free_lookup_table_entry(new);
146         return NULL;
147 }
148
149 void
150 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
151 {
152         if (lte) {
153                 switch (lte->resource_location) {
154         #ifdef __WIN32__
155                 case RESOURCE_WIN32:
156                 case RESOURCE_WIN32_ENCRYPTED:
157         #else
158                 case RESOURCE_IN_FILE_ON_DISK:
159         #endif
160         #ifdef WITH_FUSE
161                 case RESOURCE_IN_STAGING_FILE:
162                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
163                                      (void*)&lte->staging_file_name);
164         #endif
165                 case RESOURCE_IN_ATTACHED_BUFFER:
166                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
167                                      (void*)&lte->attached_buffer);
168                         FREE(lte->file_on_disk);
169                         break;
170 #ifdef WITH_NTFS_3G
171                 case RESOURCE_IN_NTFS_VOLUME:
172                         if (lte->ntfs_loc) {
173                                 FREE(lte->ntfs_loc->path);
174                                 FREE(lte->ntfs_loc->stream_name);
175                                 FREE(lte->ntfs_loc);
176                         }
177                         break;
178 #endif
179                 default:
180                         break;
181                 }
182                 FREE(lte);
183         }
184 }
185
186 static int
187 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
188 {
189         free_lookup_table_entry(entry);
190         return 0;
191 }
192
193
194 void
195 free_lookup_table(struct wim_lookup_table *table)
196 {
197         DEBUG2("Freeing lookup table");
198         if (table) {
199                 if (table->array) {
200                         for_lookup_table_entry(table,
201                                                do_free_lookup_table_entry,
202                                                NULL);
203                         FREE(table->array);
204                 }
205                 FREE(table);
206         }
207 }
208
209 /*
210  * Inserts an entry into the lookup table.
211  *
212  * @table:      A pointer to the lookup table.
213  * @lte:        A pointer to the entry to insert.
214  */
215 void
216 lookup_table_insert(struct wim_lookup_table *table,
217                     struct wim_lookup_table_entry *lte)
218 {
219         size_t i = lte->hash_short % table->capacity;
220         hlist_add_head(&lte->hash_list, &table->array[i]);
221
222         /* XXX Make the table grow when too many entries have been inserted. */
223         table->num_entries++;
224 }
225
226 static void
227 finalize_lte(struct wim_lookup_table_entry *lte)
228 {
229         #ifdef WITH_FUSE
230         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
231                 unlink(lte->staging_file_name);
232                 list_del(&lte->unhashed_list);
233         }
234         #endif
235         free_lookup_table_entry(lte);
236 }
237
238 /* Decrements the reference count for the lookup table entry @lte.  If its
239  * reference count reaches 0, it is unlinked from the lookup table.  If,
240  * furthermore, the entry has no opened file descriptors associated with it, the
241  * entry is freed.  */
242 void
243 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
244                      struct wim_lookup_table *table)
245 {
246         wimlib_assert(lte != NULL);
247         wimlib_assert(lte->refcnt != 0);
248         if (--lte->refcnt == 0) {
249                 if (lte->unhashed)
250                         list_del(&lte->unhashed_list);
251                 else
252                         lookup_table_unlink(table, lte);
253         #ifdef WITH_FUSE
254                 if (lte->num_opened_fds == 0)
255         #endif
256                         finalize_lte(lte);
257         }
258 }
259
260 #ifdef WITH_FUSE
261 void
262 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
263 {
264         if (lte->num_opened_fds != 0)
265                 if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
266                         finalize_lte(lte);
267 }
268 #endif
269
270 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
271  * return nonzero if any call to the function returns nonzero. */
272 int
273 for_lookup_table_entry(struct wim_lookup_table *table,
274                        int (*visitor)(struct wim_lookup_table_entry *, void *),
275                        void *arg)
276 {
277         struct wim_lookup_table_entry *lte;
278         struct hlist_node *pos, *tmp;
279         int ret;
280
281         for (size_t i = 0; i < table->capacity; i++) {
282                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
283                                           hash_list)
284                 {
285                         wimlib_assert2(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
286                         ret = visitor(lte, arg);
287                         if (ret)
288                                 return ret;
289                 }
290         }
291         return 0;
292 }
293
294 int
295 cmp_streams_by_wim_position(const void *p1, const void *p2)
296 {
297         const struct wim_lookup_table_entry *lte1, *lte2;
298         lte1 = *(const struct wim_lookup_table_entry**)p1;
299         lte2 = *(const struct wim_lookup_table_entry**)p2;
300         if (lte1->resource_entry.offset < lte2->resource_entry.offset)
301                 return -1;
302         else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
303                 return 1;
304         else
305                 return 0;
306 }
307
308
309 static int
310 add_lte_to_array(struct wim_lookup_table_entry *lte,
311                  void *_pp)
312 {
313         struct wim_lookup_table_entry ***pp = _pp;
314         *(*pp)++ = lte;
315         return 0;
316 }
317
318 /* Iterate through the lookup table entries, but first sort them by stream
319  * offset in the WIM.  Caution: this is intended to be used when the stream
320  * offset field has actually been set. */
321 int
322 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
323                                   int (*visitor)(struct wim_lookup_table_entry *,
324                                                  void *),
325                                   void *arg)
326 {
327         struct wim_lookup_table_entry **lte_array, **p;
328         size_t num_streams = table->num_entries;
329         int ret;
330
331         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
332         if (!lte_array)
333                 return WIMLIB_ERR_NOMEM;
334         p = lte_array;
335         for_lookup_table_entry(table, add_lte_to_array, &p);
336
337         wimlib_assert(p == lte_array + num_streams);
338
339         qsort(lte_array, num_streams, sizeof(lte_array[0]),
340               cmp_streams_by_wim_position);
341         ret = 0;
342         for (size_t i = 0; i < num_streams; i++) {
343                 ret = visitor(lte_array[i], arg);
344                 if (ret)
345                         break;
346         }
347         FREE(lte_array);
348         return ret;
349 }
350
351 /* On-disk format of a WIM lookup table entry (stream entry). */
352 struct wim_lookup_table_entry_disk {
353         /* Location, offset, compression status, and metadata status of the
354          * stream. */
355         struct resource_entry_disk resource_entry;
356
357         /* Which part of the split WIM this stream is in; indexed from 1. */
358         le16 part_number;
359
360         /* Reference count of this stream over all WIM images. */
361         le32 refcnt;
362
363         /* SHA1 message digest of the uncompressed data of this stream, or
364          * optionally all zeroes if this stream is of zero length. */
365         u8 hash[SHA1_HASH_SIZE];
366 } _packed_attribute;
367
368 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
369
370 /*
371  * Reads the lookup table from a WIM file.
372  *
373  * Saves lookup table entries for non-metadata streams in a hash table, and
374  * saves the metadata entry for each image in a special per-image location (the
375  * image_metadata array).
376  */
377 int
378 read_lookup_table(WIMStruct *w)
379 {
380         int ret;
381         size_t num_entries;
382         struct wim_lookup_table *table;
383         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
384         struct wim_lookup_table_entry_disk
385                         table_buf[BUFFER_SIZE / sizeof(struct wim_lookup_table_entry_disk)]
386                                 _aligned_attribute(8);
387
388         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
389                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
390
391         off_t offset;
392         size_t buf_entries_remaining;
393         const struct wim_lookup_table_entry_disk *disk_entry;
394
395         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
396               w->hdr.lookup_table_res_entry.offset,
397               w->hdr.lookup_table_res_entry.original_size);
398
399         if (resource_is_compressed(&w->hdr.lookup_table_res_entry)) {
400                 ERROR("Didn't expect a compressed lookup table!");
401                 ERROR("Ask the author to implement support for this.");
402                 return WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE;
403         }
404
405         num_entries = w->hdr.lookup_table_res_entry.size /
406                       sizeof(struct wim_lookup_table_entry_disk);
407         table = new_lookup_table(num_entries * 2 + 1);
408         if (!table)
409                 return WIMLIB_ERR_NOMEM;
410
411         w->current_image = 0;
412         offset = w->hdr.lookup_table_res_entry.offset;
413         buf_entries_remaining = 0;
414         for (; num_entries != 0;
415              num_entries--, buf_entries_remaining--, disk_entry++)
416         {
417                 if (buf_entries_remaining == 0) {
418                         size_t entries_to_read, bytes_to_read;
419
420                         entries_to_read = min(ARRAY_LEN(table_buf), num_entries);
421                         bytes_to_read = entries_to_read * sizeof(struct wim_lookup_table_entry_disk);
422                         if (full_pread(w->in_fd, table_buf,
423                                        bytes_to_read, offset) != bytes_to_read)
424                         {
425                                 ERROR_WITH_ERRNO("Error reading lookup table "
426                                                  "(offset=%"PRIu64")", offset);
427                                 ret = WIMLIB_ERR_READ;
428                                 goto out_free_lookup_table;
429                         }
430                         offset += bytes_to_read;
431                         disk_entry = table_buf;
432                         buf_entries_remaining = entries_to_read;
433                 }
434                 cur_entry = new_lookup_table_entry();
435                 if (!cur_entry) {
436                         ret = WIMLIB_ERR_NOMEM;
437                         goto out_free_lookup_table;
438                 }
439
440                 cur_entry->wim = w;
441                 cur_entry->resource_location = RESOURCE_IN_WIM;
442                 get_resource_entry(&disk_entry->resource_entry, &cur_entry->resource_entry);
443                 cur_entry->part_number = le16_to_cpu(disk_entry->part_number);
444                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
445                 copy_hash(cur_entry->hash, disk_entry->hash);
446
447                 if (cur_entry->part_number != w->hdr.part_number) {
448                         ERROR("A lookup table entry in part %hu of the WIM "
449                               "points to part %hu",
450                               w->hdr.part_number, cur_entry->part_number);
451                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
452                         goto out_free_cur_entry;
453                 }
454
455                 if (is_zero_hash(cur_entry->hash)) {
456                         ERROR("The WIM lookup table contains an entry with a "
457                               "SHA1 message digest of all 0's");
458                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
459                         goto out_free_cur_entry;
460                 }
461
462                 if (!(cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
463                     && (cur_entry->resource_entry.size !=
464                         cur_entry->resource_entry.original_size))
465                 {
466                         if (wimlib_print_errors) {
467                                 ERROR("Found uncompressed resource with original size "
468                                       "not the same as compressed size");
469                                 ERROR("The lookup table entry for the resource is as follows:");
470                                 print_lookup_table_entry(cur_entry, stderr);
471                         }
472                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
473                         goto out_free_cur_entry;
474                 }
475
476                 if (cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
477                         /* Lookup table entry for a metadata resource */
478                         if (cur_entry->refcnt != 1) {
479                                 if (wimlib_print_errors) {
480                                         ERROR("Found metadata resource with refcnt != 1:");
481                                         print_lookup_table_entry(cur_entry, stderr);
482                                 }
483                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
484                                 goto out_free_cur_entry;
485                         }
486
487                         if (w->hdr.part_number != 1) {
488                                 ERROR("Found a metadata resource in a "
489                                       "non-first part of the split WIM!");
490                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
491                                 goto out_free_cur_entry;
492                         }
493                         if (w->current_image == w->hdr.image_count) {
494                                 ERROR("The WIM header says there are %u images "
495                                       "in the WIM, but we found more metadata "
496                                       "resources than this", w->hdr.image_count);
497                                 ret = WIMLIB_ERR_IMAGE_COUNT;
498                                 goto out_free_cur_entry;
499                         }
500
501                         /* Notice very carefully:  We are assigning the metadata
502                          * resources in the exact order mirrored by their lookup
503                          * table entries on disk, which is the behavior of
504                          * Microsoft's software.  In particular, this overrides
505                          * the actual locations of the metadata resources
506                          * themselves in the WIM file as well as any information
507                          * written in the XML data. */
508                         DEBUG("Found metadata resource for image %u at "
509                               "offset %"PRIu64".",
510                               w->current_image + 1,
511                               cur_entry->resource_entry.offset);
512                         w->image_metadata[
513                                 w->current_image++]->metadata_lte = cur_entry;
514                 } else {
515                         /* Lookup table entry for a stream that is not a
516                          * metadata resource */
517                         duplicate_entry = __lookup_resource(table, cur_entry->hash);
518                         if (duplicate_entry) {
519                                 if (wimlib_print_errors) {
520                                         ERROR("The WIM lookup table contains two entries with the "
521                                               "same SHA1 message digest!");
522                                         ERROR("The first entry is:");
523                                         print_lookup_table_entry(duplicate_entry, stderr);
524                                         ERROR("The second entry is:");
525                                         print_lookup_table_entry(cur_entry, stderr);
526                                 }
527                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
528                                 goto out_free_cur_entry;
529                         }
530                         lookup_table_insert(table, cur_entry);
531                 }
532         }
533
534         if (w->hdr.part_number == 1 && w->current_image != w->hdr.image_count)
535         {
536                 ERROR("The WIM header says there are %u images "
537                       "in the WIM, but we only found %d metadata "
538                       "resources!", w->hdr.image_count, w->current_image);
539                 ret = WIMLIB_ERR_IMAGE_COUNT;
540                 goto out_free_lookup_table;
541         }
542         DEBUG("Done reading lookup table.");
543         w->lookup_table = table;
544         ret = 0;
545         goto out;
546 out_free_cur_entry:
547         FREE(cur_entry);
548 out_free_lookup_table:
549         free_lookup_table(table);
550 out:
551         w->current_image = 0;
552         return ret;
553 }
554
555
556 static void
557 write_lookup_table_entry(const struct wim_lookup_table_entry *lte,
558                          struct wim_lookup_table_entry_disk *disk_entry)
559 {
560         put_resource_entry(&lte->output_resource_entry, &disk_entry->resource_entry);
561         disk_entry->part_number = cpu_to_le16(lte->part_number);
562         disk_entry->refcnt = cpu_to_le32(lte->out_refcnt);
563         copy_hash(disk_entry->hash, lte->hash);
564 }
565
566 int
567 write_lookup_table_from_stream_list(struct list_head *stream_list,
568                                     int out_fd,
569                                     struct resource_entry *out_res_entry)
570 {
571         int ret;
572         off_t start_offset;
573         struct wim_lookup_table_entry_disk
574                         table_buf[BUFFER_SIZE / sizeof(struct wim_lookup_table_entry_disk)]
575                                 _aligned_attribute(8);
576         size_t table_size;
577         size_t bytes_to_write;
578         struct wim_lookup_table_entry *lte;
579         size_t cur_idx;
580
581         start_offset = filedes_offset(out_fd);
582         if (start_offset == -1)
583                 goto write_error;
584
585         table_size = 0;
586         cur_idx = 0;
587         list_for_each_entry(lte, stream_list, lookup_table_list) {
588                 if (cur_idx == ARRAY_LEN(table_buf)) {
589                         bytes_to_write = sizeof(table_buf);
590                         if (full_write(out_fd, table_buf,
591                                        bytes_to_write) != bytes_to_write)
592                                 goto write_error;
593                         table_size += bytes_to_write;
594                         cur_idx = 0;
595                 }
596                 write_lookup_table_entry(lte, &table_buf[cur_idx]);
597                 cur_idx++;
598         }
599         if (cur_idx != 0) {
600                 bytes_to_write = cur_idx * sizeof(struct wim_lookup_table_entry_disk);
601                 if (full_write(out_fd, table_buf,
602                                bytes_to_write) != bytes_to_write)
603                         goto write_error;
604                 table_size += bytes_to_write;
605         }
606         out_res_entry->offset        = start_offset;
607         out_res_entry->size          = table_size;
608         out_res_entry->original_size = table_size;
609         out_res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
610         ret = 0;
611 out:
612         return ret;
613 write_error:
614         ERROR_WITH_ERRNO("Failed to write lookup table");
615         ret = WIMLIB_ERR_WRITE;
616         goto out;
617 }
618
619 static int
620 append_lookup_table_entry(struct wim_lookup_table_entry *lte, void *_list)
621 {
622         if (lte->out_refcnt != 0)
623                 list_add_tail(&lte->lookup_table_list, (struct list_head*)_list);
624         return 0;
625 }
626
627 /* Writes the WIM lookup table to the output file. */
628 int
629 write_lookup_table(WIMStruct *w, int image, struct resource_entry *out_res_entry)
630 {
631         LIST_HEAD(stream_list);
632         int start_image;
633         int end_image;
634
635         if (image == WIMLIB_ALL_IMAGES) {
636                 start_image = 1;
637                 end_image = w->hdr.image_count;
638         } else {
639                 start_image = image;
640                 end_image = image;
641         }
642
643         for (int i = start_image; i <= end_image; i++) {
644                 struct wim_lookup_table_entry *metadata_lte;
645
646                 metadata_lte = w->image_metadata[i - 1]->metadata_lte;
647                 metadata_lte->out_refcnt = 1;
648                 metadata_lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
649                 append_lookup_table_entry(metadata_lte, &stream_list);
650         }
651         for_lookup_table_entry(w->lookup_table,
652                                append_lookup_table_entry,
653                                &stream_list);
654         return write_lookup_table_from_stream_list(&stream_list,
655                                                    w->out_fd,
656                                                    out_res_entry);
657 }
658
659 int
660 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
661 {
662         lte->real_refcnt = 0;
663         return 0;
664 }
665
666 int
667 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
668 {
669         lte->out_refcnt = 0;
670         return 0;
671 }
672
673 int
674 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
675 {
676         if (lte->extracted_file != NULL) {
677                 FREE(lte->extracted_file);
678                 lte->extracted_file = NULL;
679         }
680         return 0;
681 }
682
683 void
684 print_lookup_table_entry(const struct wim_lookup_table_entry *lte, FILE *out)
685 {
686         if (!lte) {
687                 tputc(T('\n'), out);
688                 return;
689         }
690         tfprintf(out, T("Offset            = %"PRIu64" bytes\n"),
691                  lte->resource_entry.offset);
692
693         tfprintf(out, T("Size              = %"PRIu64" bytes\n"),
694                  (u64)lte->resource_entry.size);
695
696         tfprintf(out, T("Original size     = %"PRIu64" bytes\n"),
697                  lte->resource_entry.original_size);
698
699         tfprintf(out, T("Part Number       = %hu\n"), lte->part_number);
700         tfprintf(out, T("Reference Count   = %u\n"), lte->refcnt);
701
702         if (lte->unhashed) {
703                 tfprintf(out, T("(Unhashed: inode %p, stream_id = %u)\n"),
704                          lte->back_inode, lte->back_stream_id);
705         } else {
706                 tfprintf(out, T("Hash              = 0x"));
707                 print_hash(lte->hash, out);
708                 tputc(T('\n'), out);
709         }
710
711         tfprintf(out, T("Flags             = "));
712         u8 flags = lte->resource_entry.flags;
713         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
714                 tfputs(T("WIM_RESHDR_FLAG_COMPRESSED, "), out);
715         if (flags & WIM_RESHDR_FLAG_FREE)
716                 tfputs(T("WIM_RESHDR_FLAG_FREE, "), out);
717         if (flags & WIM_RESHDR_FLAG_METADATA)
718                 tfputs(T("WIM_RESHDR_FLAG_METADATA, "), out);
719         if (flags & WIM_RESHDR_FLAG_SPANNED)
720                 tfputs(T("WIM_RESHDR_FLAG_SPANNED, "), out);
721         tputc(T('\n'), out);
722         switch (lte->resource_location) {
723         case RESOURCE_IN_WIM:
724                 if (lte->wim->filename) {
725                         tfprintf(out, T("WIM file          = `%"TS"'\n"),
726                                  lte->wim->filename);
727                 }
728                 break;
729 #ifdef __WIN32__
730         case RESOURCE_WIN32:
731         case RESOURCE_WIN32_ENCRYPTED:
732 #else
733         case RESOURCE_IN_FILE_ON_DISK:
734 #endif
735                 tfprintf(out, T("File on Disk      = `%"TS"'\n"),
736                          lte->file_on_disk);
737                 break;
738 #ifdef WITH_FUSE
739         case RESOURCE_IN_STAGING_FILE:
740                 tfprintf(out, T("Staging File      = `%"TS"'\n"),
741                                 lte->staging_file_name);
742                 break;
743 #endif
744         default:
745                 break;
746         }
747         tputc(T('\n'), out);
748 }
749
750 static int
751 do_print_lookup_table_entry(struct wim_lookup_table_entry *lte, void *fp)
752 {
753         print_lookup_table_entry(lte, (FILE*)fp);
754         return 0;
755 }
756
757 /*
758  * Prints the lookup table of a WIM file.
759  */
760 WIMLIBAPI void
761 wimlib_print_lookup_table(WIMStruct *wim)
762 {
763         for (int i = 0; i < wim->hdr.image_count; i++)
764                 print_lookup_table_entry(wim->image_metadata[i]->metadata_lte, stdout);
765         for_lookup_table_entry(wim->lookup_table,
766                                do_print_lookup_table_entry,
767                                stdout);
768 }
769
770 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
771  * lookup table, or NULL if there is none.  */
772 struct wim_lookup_table_entry *
773 __lookup_resource(const struct wim_lookup_table *table, const u8 hash[])
774 {
775         size_t i;
776         struct wim_lookup_table_entry *lte;
777         struct hlist_node *pos;
778
779         wimlib_assert(table != NULL);
780         wimlib_assert(hash != NULL);
781
782         i = *(size_t*)hash % table->capacity;
783         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
784                 if (hashes_equal(hash, lte->hash))
785                         return lte;
786         return NULL;
787 }
788
789 #ifdef WITH_FUSE
790 /*
791  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
792  * given a path name.
793  *
794  * This is only for pre-resolved inodes.
795  */
796 int
797 lookup_resource(WIMStruct *w,
798                 const tchar *path,
799                 int lookup_flags,
800                 struct wim_dentry **dentry_ret,
801                 struct wim_lookup_table_entry **lte_ret,
802                 u16 *stream_idx_ret)
803 {
804         struct wim_dentry *dentry;
805         struct wim_lookup_table_entry *lte;
806         u16 stream_idx;
807         const tchar *stream_name = NULL;
808         struct wim_inode *inode;
809         tchar *p = NULL;
810
811         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
812                 stream_name = path_stream_name(path);
813                 if (stream_name) {
814                         p = (tchar*)stream_name - 1;
815                         *p = T('\0');
816                 }
817         }
818
819         dentry = get_dentry(w, path);
820         if (p)
821                 *p = T(':');
822         if (!dentry)
823                 return -errno;
824
825         inode = dentry->d_inode;
826
827         wimlib_assert(inode->i_resolved);
828
829         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
830               && inode_is_directory(inode))
831                 return -EISDIR;
832
833         if (stream_name) {
834                 struct wim_ads_entry *ads_entry;
835                 u16 ads_idx;
836                 ads_entry = inode_get_ads_entry(inode, stream_name,
837                                                 &ads_idx);
838                 if (ads_entry) {
839                         stream_idx = ads_idx + 1;
840                         lte = ads_entry->lte;
841                         goto out;
842                 } else {
843                         return -ENOENT;
844                 }
845         } else {
846                 lte = inode->i_lte;
847                 stream_idx = 0;
848         }
849 out:
850         if (dentry_ret)
851                 *dentry_ret = dentry;
852         if (lte_ret)
853                 *lte_ret = lte;
854         if (stream_idx_ret)
855                 *stream_idx_ret = stream_idx;
856         return 0;
857 }
858 #endif
859
860 /*
861  * XXX Probably should store the compression type directly in the lookup table
862  * entry
863  */
864 int
865 wim_resource_compression_type(const struct wim_lookup_table_entry *lte)
866 {
867         if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
868             || lte->resource_location != RESOURCE_IN_WIM)
869                 return WIMLIB_COMPRESSION_TYPE_NONE;
870         return wimlib_get_compression_type(lte->wim);
871 }
872
873 /* Resolve an inode's lookup table entries
874  *
875  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
876  * lookup table) with pointers directly to the lookup table entries.  A circular
877  * linked list of streams sharing the same lookup table entry is created.
878  *
879  * This function always succeeds; unresolved lookup table entries are given a
880  * NULL pointer.
881  */
882 void
883 inode_resolve_ltes(struct wim_inode *inode, struct wim_lookup_table *table)
884 {
885
886         if (!inode->i_resolved) {
887                 struct wim_lookup_table_entry *lte;
888                 /* Resolve the default file stream */
889                 lte = __lookup_resource(table, inode->i_hash);
890                 inode->i_lte = lte;
891                 inode->i_resolved = 1;
892
893                 /* Resolve the alternate data streams */
894                 for (u16 i = 0; i < inode->i_num_ads; i++) {
895                         struct wim_ads_entry *cur_entry = &inode->i_ads_entries[i];
896                         lte = __lookup_resource(table, cur_entry->hash);
897                         cur_entry->lte = lte;
898                 }
899         }
900 }
901
902 void
903 inode_unresolve_ltes(struct wim_inode *inode)
904 {
905         if (inode->i_resolved) {
906                 if (inode->i_lte)
907                         copy_hash(inode->i_hash, inode->i_lte->hash);
908                 else
909                         zero_out_hash(inode->i_hash);
910
911                 for (u16 i = 0; i < inode->i_num_ads; i++) {
912                         if (inode->i_ads_entries[i].lte)
913                                 copy_hash(inode->i_ads_entries[i].hash,
914                                           inode->i_ads_entries[i].lte->hash);
915                         else
916                                 zero_out_hash(inode->i_ads_entries[i].hash);
917                 }
918                 inode->i_resolved = 0;
919         }
920 }
921
922 /*
923  * Returns the lookup table entry for stream @stream_idx of the inode, where
924  * stream_idx = 0 means the default un-named file stream, and stream_idx >= 1
925  * corresponds to an alternate data stream.
926  *
927  * This works for both resolved and un-resolved inodes.
928  */
929 struct wim_lookup_table_entry *
930 inode_stream_lte(const struct wim_inode *inode, unsigned stream_idx,
931                  const struct wim_lookup_table *table)
932 {
933         if (inode->i_resolved)
934                 return inode_stream_lte_resolved(inode, stream_idx);
935         else
936                 return inode_stream_lte_unresolved(inode, stream_idx, table);
937 }
938
939 struct wim_lookup_table_entry *
940 inode_unnamed_lte_resolved(const struct wim_inode *inode)
941 {
942         wimlib_assert(inode->i_resolved);
943         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
944                 if (inode_stream_name_nbytes(inode, i) == 0 &&
945                     !is_zero_hash(inode_stream_hash_resolved(inode, i)))
946                 {
947                         return inode_stream_lte_resolved(inode, i);
948                 }
949         }
950         return NULL;
951 }
952
953 struct wim_lookup_table_entry *
954 inode_unnamed_lte_unresolved(const struct wim_inode *inode,
955                              const struct wim_lookup_table *table)
956 {
957         wimlib_assert(!inode->i_resolved);
958         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
959                 if (inode_stream_name_nbytes(inode, i) == 0 &&
960                     !is_zero_hash(inode_stream_hash_unresolved(inode, i)))
961                 {
962                         return inode_stream_lte_unresolved(inode, i, table);
963                 }
964         }
965         return NULL;
966 }
967
968 /* Return the lookup table entry for the unnamed data stream of an inode, or
969  * NULL if there is none.
970  *
971  * You'd think this would be easier than it actually is, since the unnamed data
972  * stream should be the one referenced from the inode itself.  Alas, if there
973  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
974  * data stream in one of the alternate data streams instead of inside the WIM
975  * dentry itself.  So we need to check the alternate data streams too.
976  *
977  * Also, note that a dentry may appear to have more than one unnamed stream, but
978  * if the SHA1 message digest is all 0's then the corresponding stream does not
979  * really "count" (this is the case for the inode's own file stream when the
980  * file stream that should be there is actually in one of the alternate stream
981  * entries.).  This is despite the fact that we may need to extract such a
982  * missing entry as an empty file or empty named data stream.
983  */
984 struct wim_lookup_table_entry *
985 inode_unnamed_lte(const struct wim_inode *inode,
986                   const struct wim_lookup_table *table)
987 {
988         if (inode->i_resolved)
989                 return inode_unnamed_lte_resolved(inode);
990         else
991                 return inode_unnamed_lte_unresolved(inode, table);
992 }
993
994 static int
995 lte_add_stream_size(struct wim_lookup_table_entry *lte, void *total_bytes_p)
996 {
997         *(u64*)total_bytes_p += lte->resource_entry.size;
998         return 0;
999 }
1000
1001 u64
1002 lookup_table_total_stream_size(struct wim_lookup_table *table)
1003 {
1004         u64 total_size = 0;
1005         for_lookup_table_entry(table, lte_add_stream_size, &total_size);
1006         return total_size;
1007 }
1008
1009 struct wim_lookup_table_entry **
1010 retrieve_lte_pointer(struct wim_lookup_table_entry *lte)
1011 {
1012         wimlib_assert(lte->unhashed);
1013         struct wim_inode *inode = lte->back_inode;
1014         u32 stream_id = lte->back_stream_id;
1015         if (stream_id == 0)
1016                 return &inode->i_lte;
1017         else
1018                 for (u16 i = 0; i < inode->i_num_ads; i++)
1019                         if (inode->i_ads_entries[i].stream_id == stream_id)
1020                                 return &inode->i_ads_entries[i].lte;
1021         wimlib_assert(0);
1022         return NULL;
1023 }
1024
1025 /* Calculate the SHA1 message digest of a stream and move it from the list of
1026  * unhashed streams to the stream lookup table, possibly joining it with an
1027  * existing lookup table entry for an identical stream.
1028  *
1029  * @lte:  An unhashed lookup table entry.
1030  * @lookup_table:  Lookup table for the WIM.
1031  * @lte_ret:  On success, write a pointer to the resulting lookup table
1032  *            entry to this location.  This will be the same as @lte
1033  *            if it was inserted into the lookup table, or different if
1034  *            a duplicate stream was found.
1035  *
1036  * Returns 0 on success; nonzero if there is an error reading the stream.
1037  */
1038 int
1039 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1040                      struct wim_lookup_table *lookup_table,
1041                      struct wim_lookup_table_entry **lte_ret)
1042 {
1043         int ret;
1044         struct wim_lookup_table_entry *duplicate_lte;
1045         struct wim_lookup_table_entry **back_ptr;
1046
1047         wimlib_assert(lte->unhashed);
1048
1049         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1050          * union with the SHA1 message digest and will no longer be valid once
1051          * the SHA1 has been calculated. */
1052         back_ptr = retrieve_lte_pointer(lte);
1053
1054         ret = sha1_resource(lte);
1055         if (ret)
1056                 return ret;
1057
1058         /* Look for a duplicate stream */
1059         duplicate_lte = __lookup_resource(lookup_table, lte->hash);
1060         list_del(&lte->unhashed_list);
1061         if (duplicate_lte) {
1062                 /* We have a duplicate stream.  Transfer the reference counts
1063                  * from this stream to the duplicate, update the reference to
1064                  * this stream (in an inode or ads_entry) to point to the
1065                  * duplicate, then free this stream. */
1066                 wimlib_assert(!(duplicate_lte->unhashed));
1067                 duplicate_lte->refcnt += lte->refcnt;
1068                 duplicate_lte->out_refcnt += lte->refcnt;
1069                 *back_ptr = duplicate_lte;
1070                 free_lookup_table_entry(lte);
1071                 lte = duplicate_lte;
1072         } else {
1073                 /* No duplicate stream, so we need to insert
1074                  * this stream into the lookup table and treat
1075                  * it as a hashed stream. */
1076                 lookup_table_insert(lookup_table, lte);
1077                 lte->unhashed = 0;
1078         }
1079         if (lte_ret)
1080                 *lte_ret = lte;
1081         return 0;
1082 }
1083