95708866c9197614588f23ecc0caa26ceac71d02
[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         u16 part_number;
359
360         /* Reference count of this stream over all WIM images. */
361         u32 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 /*
369  * Reads the lookup table from a WIM file.
370  *
371  * Saves lookup table entries for non-metadata streams in a hash table, and
372  * saves the metadata entry for each image in a special per-image location (the
373  * image_metadata array).
374  */
375 int
376 read_lookup_table(WIMStruct *w)
377 {
378         int ret;
379         size_t num_entries;
380         struct wim_lookup_table *table;
381         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
382         struct wim_lookup_table_entry_disk
383                         table_buf[BUFFER_SIZE / sizeof(struct wim_lookup_table_entry_disk)]
384                                 _aligned_attribute(8);
385         off_t offset;
386         size_t buf_entries_remaining;
387         const struct wim_lookup_table_entry_disk *disk_entry;
388
389         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
390               w->hdr.lookup_table_res_entry.offset,
391               w->hdr.lookup_table_res_entry.original_size);
392
393         if (resource_is_compressed(&w->hdr.lookup_table_res_entry)) {
394                 ERROR("Didn't expect a compressed lookup table!");
395                 ERROR("Ask the author to implement support for this.");
396                 return WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE;
397         }
398
399         num_entries = w->hdr.lookup_table_res_entry.size /
400                       sizeof(struct wim_lookup_table_entry_disk);
401         table = new_lookup_table(num_entries * 2 + 1);
402         if (!table)
403                 return WIMLIB_ERR_NOMEM;
404
405         w->current_image = 0;
406         offset = w->hdr.lookup_table_res_entry.offset;
407         buf_entries_remaining = 0;
408         for (; num_entries != 0;
409              num_entries--, buf_entries_remaining--, disk_entry++)
410         {
411                 if (buf_entries_remaining == 0) {
412                         size_t entries_to_read, bytes_to_read;
413
414                         entries_to_read = min(ARRAY_LEN(table_buf), num_entries);
415                         bytes_to_read = entries_to_read * sizeof(struct wim_lookup_table_entry_disk);
416                         if (full_pread(w->in_fd, table_buf,
417                                        bytes_to_read, offset) != bytes_to_read)
418                         {
419                                 ERROR_WITH_ERRNO("Error reading lookup table "
420                                                  "(offset=%"PRIu64")", offset);
421                                 ret = WIMLIB_ERR_READ;
422                                 goto out_free_lookup_table;
423                         }
424                         offset += bytes_to_read;
425                         disk_entry = table_buf;
426                         buf_entries_remaining = entries_to_read;
427                 }
428                 cur_entry = new_lookup_table_entry();
429                 if (!cur_entry) {
430                         ret = WIMLIB_ERR_NOMEM;
431                         goto out_free_lookup_table;
432                 }
433
434                 cur_entry->wim = w;
435                 cur_entry->resource_location = RESOURCE_IN_WIM;
436                 get_resource_entry(&disk_entry->resource_entry, &cur_entry->resource_entry);
437                 cur_entry->part_number = le16_to_cpu(disk_entry->part_number);
438                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
439                 copy_hash(cur_entry->hash, disk_entry->hash);
440
441                 if (cur_entry->part_number != w->hdr.part_number) {
442                         ERROR("A lookup table entry in part %hu of the WIM "
443                               "points to part %hu",
444                               w->hdr.part_number, cur_entry->part_number);
445                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
446                         goto out_free_cur_entry;
447                 }
448
449                 if (is_zero_hash(cur_entry->hash)) {
450                         ERROR("The WIM lookup table contains an entry with a "
451                               "SHA1 message digest of all 0's");
452                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
453                         goto out_free_cur_entry;
454                 }
455
456                 if (!(cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
457                     && (cur_entry->resource_entry.size !=
458                         cur_entry->resource_entry.original_size))
459                 {
460                 #ifdef ENABLE_ERROR_MESSAGES
461                         ERROR("Found uncompressed resource with original size "
462                               "not the same as compressed size");
463                         ERROR("The lookup table entry for the resource is as follows:");
464                         print_lookup_table_entry(cur_entry, stderr);
465                 #endif
466                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
467                         goto out_free_cur_entry;
468                 }
469
470                 if (cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
471                         /* Lookup table entry for a metadata resource */
472                         if (cur_entry->refcnt != 1) {
473                         #ifdef ENABLE_ERROR_MESSAGES
474                                 ERROR("Found metadata resource with refcnt != 1:");
475                                 print_lookup_table_entry(cur_entry, stderr);
476                         #endif
477                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
478                                 goto out_free_cur_entry;
479                         }
480
481                         if (w->hdr.part_number != 1) {
482                                 ERROR("Found a metadata resource in a "
483                                       "non-first part of the split WIM!");
484                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
485                                 goto out_free_cur_entry;
486                         }
487                         if (w->current_image == w->hdr.image_count) {
488                                 ERROR("The WIM header says there are %u images "
489                                       "in the WIM, but we found more metadata "
490                                       "resources than this", w->hdr.image_count);
491                                 ret = WIMLIB_ERR_IMAGE_COUNT;
492                                 goto out_free_cur_entry;
493                         }
494
495                         /* Notice very carefully:  We are assigning the metadata
496                          * resources in the exact order mirrored by their lookup
497                          * table entries on disk, which is the behavior of
498                          * Microsoft's software.  In particular, this overrides
499                          * the actual locations of the metadata resources
500                          * themselves in the WIM file as well as any information
501                          * written in the XML data. */
502                         DEBUG("Found metadata resource for image %u at "
503                               "offset %"PRIu64".",
504                               w->current_image + 1,
505                               cur_entry->resource_entry.offset);
506                         w->image_metadata[
507                                 w->current_image++]->metadata_lte = cur_entry;
508                 } else {
509                         /* Lookup table entry for a stream that is not a
510                          * metadata resource */
511                         duplicate_entry = __lookup_resource(table, cur_entry->hash);
512                         if (duplicate_entry) {
513                         #ifdef ENABLE_ERROR_MESSAGES
514                                 ERROR("The WIM lookup table contains two entries with the "
515                                       "same SHA1 message digest!");
516                                 ERROR("The first entry is:");
517                                 print_lookup_table_entry(duplicate_entry, stderr);
518                                 ERROR("The second entry is:");
519                                 print_lookup_table_entry(cur_entry, stderr);
520                         #endif
521                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
522                                 goto out_free_cur_entry;
523                         }
524                         lookup_table_insert(table, cur_entry);
525                 }
526         }
527
528         if (w->hdr.part_number == 1 && w->current_image != w->hdr.image_count)
529         {
530                 ERROR("The WIM header says there are %u images "
531                       "in the WIM, but we only found %d metadata "
532                       "resources!", w->hdr.image_count, w->current_image);
533                 ret = WIMLIB_ERR_IMAGE_COUNT;
534                 goto out_free_lookup_table;
535         }
536         DEBUG("Done reading lookup table.");
537         w->lookup_table = table;
538         ret = 0;
539         goto out;
540 out_free_cur_entry:
541         FREE(cur_entry);
542 out_free_lookup_table:
543         free_lookup_table(table);
544 out:
545         w->current_image = 0;
546         return ret;
547 }
548
549
550 static void
551 write_lookup_table_entry(const struct wim_lookup_table_entry *lte,
552                          struct wim_lookup_table_entry_disk *disk_entry)
553 {
554         put_resource_entry(&lte->output_resource_entry, &disk_entry->resource_entry);
555         disk_entry->part_number = cpu_to_le16(lte->part_number);
556         disk_entry->refcnt = cpu_to_le32(lte->out_refcnt);
557         copy_hash(disk_entry->hash, lte->hash);
558 }
559
560 int
561 write_lookup_table_from_stream_list(struct list_head *stream_list,
562                                     int out_fd,
563                                     struct resource_entry *out_res_entry)
564 {
565         int ret;
566         off_t start_offset;
567         struct wim_lookup_table_entry_disk
568                         table_buf[BUFFER_SIZE / sizeof(struct wim_lookup_table_entry_disk)]
569                                 _aligned_attribute(8);
570         size_t table_size;
571         size_t bytes_to_write;
572         struct wim_lookup_table_entry *lte;
573         size_t cur_idx;
574
575         start_offset = filedes_offset(out_fd);
576         if (start_offset == -1)
577                 goto write_error;
578
579         table_size = 0;
580         cur_idx = 0;
581         list_for_each_entry(lte, stream_list, lookup_table_list) {
582                 if (cur_idx == ARRAY_LEN(table_buf)) {
583                         bytes_to_write = sizeof(table_buf);
584                         if (full_write(out_fd, table_buf,
585                                        bytes_to_write) != bytes_to_write)
586                                 goto write_error;
587                         table_size += bytes_to_write;
588                         cur_idx = 0;
589                 }
590                 write_lookup_table_entry(lte, &table_buf[cur_idx]);
591                 cur_idx++;
592         }
593         if (cur_idx != 0) {
594                 bytes_to_write = cur_idx * sizeof(struct wim_lookup_table_entry_disk);
595                 if (full_write(out_fd, table_buf,
596                                bytes_to_write) != bytes_to_write)
597                         goto write_error;
598                 table_size += bytes_to_write;
599         }
600         out_res_entry->offset        = start_offset;
601         out_res_entry->size          = table_size;
602         out_res_entry->original_size = table_size;
603         out_res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
604         ret = 0;
605 out:
606         return ret;
607 write_error:
608         ERROR_WITH_ERRNO("Failed to write lookup table");
609         ret = WIMLIB_ERR_WRITE;
610         goto out;
611 }
612
613 static int
614 append_lookup_table_entry(struct wim_lookup_table_entry *lte, void *_list)
615 {
616         if (lte->out_refcnt != 0)
617                 list_add_tail(&lte->lookup_table_list, (struct list_head*)_list);
618         return 0;
619 }
620
621 /* Writes the WIM lookup table to the output file. */
622 int
623 write_lookup_table(WIMStruct *w, int image, struct resource_entry *out_res_entry)
624 {
625         LIST_HEAD(stream_list);
626         int start_image;
627         int end_image;
628
629         if (image == WIMLIB_ALL_IMAGES) {
630                 start_image = 1;
631                 end_image = w->hdr.image_count;
632         } else {
633                 start_image = image;
634                 end_image = image;
635         }
636
637         for (int i = start_image; i <= end_image; i++) {
638                 struct wim_lookup_table_entry *metadata_lte;
639
640                 metadata_lte = w->image_metadata[i - 1]->metadata_lte;
641                 metadata_lte->out_refcnt = 1;
642                 metadata_lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
643                 append_lookup_table_entry(metadata_lte, &stream_list);
644         }
645         for_lookup_table_entry(w->lookup_table,
646                                append_lookup_table_entry,
647                                &stream_list);
648         return write_lookup_table_from_stream_list(&stream_list,
649                                                    w->out_fd,
650                                                    out_res_entry);
651 }
652
653 int
654 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
655 {
656         lte->real_refcnt = 0;
657         return 0;
658 }
659
660 int
661 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
662 {
663         lte->out_refcnt = 0;
664         return 0;
665 }
666
667 int
668 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
669 {
670         if (lte->extracted_file != NULL) {
671                 FREE(lte->extracted_file);
672                 lte->extracted_file = NULL;
673         }
674         return 0;
675 }
676
677 void
678 print_lookup_table_entry(const struct wim_lookup_table_entry *lte, FILE *out)
679 {
680         if (!lte) {
681                 tputc(T('\n'), out);
682                 return;
683         }
684         tfprintf(out, T("Offset            = %"PRIu64" bytes\n"),
685                  lte->resource_entry.offset);
686
687         tfprintf(out, T("Size              = %"PRIu64" bytes\n"),
688                  (u64)lte->resource_entry.size);
689
690         tfprintf(out, T("Original size     = %"PRIu64" bytes\n"),
691                  lte->resource_entry.original_size);
692
693         tfprintf(out, T("Part Number       = %hu\n"), lte->part_number);
694         tfprintf(out, T("Reference Count   = %u\n"), lte->refcnt);
695
696         if (lte->unhashed) {
697                 tfprintf(out, T("(Unhashed: inode %p, stream_id = %u)\n"),
698                          lte->back_inode, lte->back_stream_id);
699         } else {
700                 tfprintf(out, T("Hash              = 0x"));
701                 print_hash(lte->hash, out);
702                 tputc(T('\n'), out);
703         }
704
705         tfprintf(out, T("Flags             = "));
706         u8 flags = lte->resource_entry.flags;
707         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
708                 tfputs(T("WIM_RESHDR_FLAG_COMPRESSED, "), out);
709         if (flags & WIM_RESHDR_FLAG_FREE)
710                 tfputs(T("WIM_RESHDR_FLAG_FREE, "), out);
711         if (flags & WIM_RESHDR_FLAG_METADATA)
712                 tfputs(T("WIM_RESHDR_FLAG_METADATA, "), out);
713         if (flags & WIM_RESHDR_FLAG_SPANNED)
714                 tfputs(T("WIM_RESHDR_FLAG_SPANNED, "), out);
715         tputc(T('\n'), out);
716         switch (lte->resource_location) {
717         case RESOURCE_IN_WIM:
718                 if (lte->wim->filename) {
719                         tfprintf(out, T("WIM file          = `%"TS"'\n"),
720                                  lte->wim->filename);
721                 }
722                 break;
723 #ifdef __WIN32__
724         case RESOURCE_WIN32:
725         case RESOURCE_WIN32_ENCRYPTED:
726 #else
727         case RESOURCE_IN_FILE_ON_DISK:
728 #endif
729                 tfprintf(out, T("File on Disk      = `%"TS"'\n"),
730                          lte->file_on_disk);
731                 break;
732 #ifdef WITH_FUSE
733         case RESOURCE_IN_STAGING_FILE:
734                 tfprintf(out, T("Staging File      = `%"TS"'\n"),
735                                 lte->staging_file_name);
736                 break;
737 #endif
738         default:
739                 break;
740         }
741         tputc(T('\n'), out);
742 }
743
744 static int
745 do_print_lookup_table_entry(struct wim_lookup_table_entry *lte, void *fp)
746 {
747         print_lookup_table_entry(lte, (FILE*)fp);
748         return 0;
749 }
750
751 /*
752  * Prints the lookup table of a WIM file.
753  */
754 WIMLIBAPI void
755 wimlib_print_lookup_table(WIMStruct *w)
756 {
757         for_lookup_table_entry(w->lookup_table,
758                                do_print_lookup_table_entry,
759                                stdout);
760 }
761
762 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
763  * lookup table, or NULL if there is none.  */
764 struct wim_lookup_table_entry *
765 __lookup_resource(const struct wim_lookup_table *table, const u8 hash[])
766 {
767         size_t i;
768         struct wim_lookup_table_entry *lte;
769         struct hlist_node *pos;
770
771         wimlib_assert(table != NULL);
772         wimlib_assert(hash != NULL);
773
774         i = *(size_t*)hash % table->capacity;
775         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
776                 if (hashes_equal(hash, lte->hash))
777                         return lte;
778         return NULL;
779 }
780
781 #ifdef WITH_FUSE
782 /*
783  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
784  * given a path name.
785  *
786  * This is only for pre-resolved inodes.
787  */
788 int
789 lookup_resource(WIMStruct *w,
790                 const tchar *path,
791                 int lookup_flags,
792                 struct wim_dentry **dentry_ret,
793                 struct wim_lookup_table_entry **lte_ret,
794                 u16 *stream_idx_ret)
795 {
796         struct wim_dentry *dentry;
797         struct wim_lookup_table_entry *lte;
798         u16 stream_idx;
799         const tchar *stream_name = NULL;
800         struct wim_inode *inode;
801         tchar *p = NULL;
802
803         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
804                 stream_name = path_stream_name(path);
805                 if (stream_name) {
806                         p = (tchar*)stream_name - 1;
807                         *p = T('\0');
808                 }
809         }
810
811         dentry = get_dentry(w, path);
812         if (p)
813                 *p = T(':');
814         if (!dentry)
815                 return -errno;
816
817         inode = dentry->d_inode;
818
819         wimlib_assert(inode->i_resolved);
820
821         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
822               && inode_is_directory(inode))
823                 return -EISDIR;
824
825         if (stream_name) {
826                 struct wim_ads_entry *ads_entry;
827                 u16 ads_idx;
828                 ads_entry = inode_get_ads_entry(inode, stream_name,
829                                                 &ads_idx);
830                 if (ads_entry) {
831                         stream_idx = ads_idx + 1;
832                         lte = ads_entry->lte;
833                         goto out;
834                 } else {
835                         return -ENOENT;
836                 }
837         } else {
838                 lte = inode->i_lte;
839                 stream_idx = 0;
840         }
841 out:
842         if (dentry_ret)
843                 *dentry_ret = dentry;
844         if (lte_ret)
845                 *lte_ret = lte;
846         if (stream_idx_ret)
847                 *stream_idx_ret = stream_idx;
848         return 0;
849 }
850 #endif
851
852 /*
853  * XXX Probably should store the compression type directly in the lookup table
854  * entry
855  */
856 int
857 wim_resource_compression_type(const struct wim_lookup_table_entry *lte)
858 {
859         if (!(lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
860             || lte->resource_location != RESOURCE_IN_WIM)
861                 return WIMLIB_COMPRESSION_TYPE_NONE;
862         return wimlib_get_compression_type(lte->wim);
863 }
864
865 /* Resolve an inode's lookup table entries
866  *
867  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
868  * lookup table) with pointers directly to the lookup table entries.  A circular
869  * linked list of streams sharing the same lookup table entry is created.
870  *
871  * This function always succeeds; unresolved lookup table entries are given a
872  * NULL pointer.
873  */
874 void
875 inode_resolve_ltes(struct wim_inode *inode, struct wim_lookup_table *table)
876 {
877
878         if (!inode->i_resolved) {
879                 struct wim_lookup_table_entry *lte;
880                 /* Resolve the default file stream */
881                 lte = __lookup_resource(table, inode->i_hash);
882                 inode->i_lte = lte;
883                 inode->i_resolved = 1;
884
885                 /* Resolve the alternate data streams */
886                 for (u16 i = 0; i < inode->i_num_ads; i++) {
887                         struct wim_ads_entry *cur_entry = &inode->i_ads_entries[i];
888                         lte = __lookup_resource(table, cur_entry->hash);
889                         cur_entry->lte = lte;
890                 }
891         }
892 }
893
894 void
895 inode_unresolve_ltes(struct wim_inode *inode)
896 {
897         if (inode->i_resolved) {
898                 if (inode->i_lte)
899                         copy_hash(inode->i_hash, inode->i_lte->hash);
900                 else
901                         zero_out_hash(inode->i_hash);
902
903                 for (u16 i = 0; i < inode->i_num_ads; i++) {
904                         if (inode->i_ads_entries[i].lte)
905                                 copy_hash(inode->i_ads_entries[i].hash,
906                                           inode->i_ads_entries[i].lte->hash);
907                         else
908                                 zero_out_hash(inode->i_ads_entries[i].hash);
909                 }
910                 inode->i_resolved = 0;
911         }
912 }
913
914 /*
915  * Returns the lookup table entry for stream @stream_idx of the inode, where
916  * stream_idx = 0 means the default un-named file stream, and stream_idx >= 1
917  * corresponds to an alternate data stream.
918  *
919  * This works for both resolved and un-resolved inodes.
920  */
921 struct wim_lookup_table_entry *
922 inode_stream_lte(const struct wim_inode *inode, unsigned stream_idx,
923                  const struct wim_lookup_table *table)
924 {
925         if (inode->i_resolved)
926                 return inode_stream_lte_resolved(inode, stream_idx);
927         else
928                 return inode_stream_lte_unresolved(inode, stream_idx, table);
929 }
930
931 struct wim_lookup_table_entry *
932 inode_unnamed_lte_resolved(const struct wim_inode *inode)
933 {
934         wimlib_assert(inode->i_resolved);
935         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
936                 if (inode_stream_name_nbytes(inode, i) == 0 &&
937                     !is_zero_hash(inode_stream_hash_resolved(inode, i)))
938                 {
939                         return inode_stream_lte_resolved(inode, i);
940                 }
941         }
942         return NULL;
943 }
944
945 struct wim_lookup_table_entry *
946 inode_unnamed_lte_unresolved(const struct wim_inode *inode,
947                              const struct wim_lookup_table *table)
948 {
949         wimlib_assert(!inode->i_resolved);
950         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
951                 if (inode_stream_name_nbytes(inode, i) == 0 &&
952                     !is_zero_hash(inode_stream_hash_unresolved(inode, i)))
953                 {
954                         return inode_stream_lte_unresolved(inode, i, table);
955                 }
956         }
957         return NULL;
958 }
959
960 /* Return the lookup table entry for the unnamed data stream of an inode, or
961  * NULL if there is none.
962  *
963  * You'd think this would be easier than it actually is, since the unnamed data
964  * stream should be the one referenced from the inode itself.  Alas, if there
965  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
966  * data stream in one of the alternate data streams instead of inside the WIM
967  * dentry itself.  So we need to check the alternate data streams too.
968  *
969  * Also, note that a dentry may appear to have more than one unnamed stream, but
970  * if the SHA1 message digest is all 0's then the corresponding stream does not
971  * really "count" (this is the case for the inode's own file stream when the
972  * file stream that should be there is actually in one of the alternate stream
973  * entries.).  This is despite the fact that we may need to extract such a
974  * missing entry as an empty file or empty named data stream.
975  */
976 struct wim_lookup_table_entry *
977 inode_unnamed_lte(const struct wim_inode *inode,
978                   const struct wim_lookup_table *table)
979 {
980         if (inode->i_resolved)
981                 return inode_unnamed_lte_resolved(inode);
982         else
983                 return inode_unnamed_lte_unresolved(inode, table);
984 }
985
986 static int
987 lte_add_stream_size(struct wim_lookup_table_entry *lte, void *total_bytes_p)
988 {
989         *(u64*)total_bytes_p += lte->resource_entry.size;
990         return 0;
991 }
992
993 u64
994 lookup_table_total_stream_size(struct wim_lookup_table *table)
995 {
996         u64 total_size = 0;
997         for_lookup_table_entry(table, lte_add_stream_size, &total_size);
998         return total_size;
999 }
1000
1001 struct wim_lookup_table_entry **
1002 retrieve_lte_pointer(struct wim_lookup_table_entry *lte)
1003 {
1004         wimlib_assert(lte->unhashed);
1005         struct wim_inode *inode = lte->back_inode;
1006         u32 stream_id = lte->back_stream_id;
1007         if (stream_id == 0)
1008                 return &inode->i_lte;
1009         else
1010                 for (u16 i = 0; i < inode->i_num_ads; i++)
1011                         if (inode->i_ads_entries[i].stream_id == stream_id)
1012                                 return &inode->i_ads_entries[i].lte;
1013         wimlib_assert(0);
1014         return NULL;
1015 }
1016
1017 /* Calculate the SHA1 message digest of a stream and move it from the list of
1018  * unhashed streams to the stream lookup table, possibly joining it with an
1019  * existing lookup table entry for an identical stream.
1020  *
1021  * @lte:  An unhashed lookup table entry.
1022  * @lookup_table:  Lookup table for the WIM.
1023  * @lte_ret:  On success, write a pointer to the resulting lookup table
1024  *            entry to this location.  This will be the same as @lte
1025  *            if it was inserted into the lookup table, or different if
1026  *            a duplicate stream was found.
1027  *
1028  * Returns 0 on success; nonzero if there is an error reading the stream.
1029  */
1030 int
1031 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1032                      struct wim_lookup_table *lookup_table,
1033                      struct wim_lookup_table_entry **lte_ret)
1034 {
1035         int ret;
1036         struct wim_lookup_table_entry *duplicate_lte;
1037         struct wim_lookup_table_entry **back_ptr;
1038
1039         wimlib_assert(lte->unhashed);
1040
1041         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1042          * union with the SHA1 message digest and will no longer be valid once
1043          * the SHA1 has been calculated. */
1044         back_ptr = retrieve_lte_pointer(lte);
1045
1046         ret = sha1_resource(lte);
1047         if (ret)
1048                 return ret;
1049
1050         /* Look for a duplicate stream */
1051         duplicate_lte = __lookup_resource(lookup_table, lte->hash);
1052         list_del(&lte->unhashed_list);
1053         if (duplicate_lte) {
1054                 /* We have a duplicate stream.  Transfer the reference counts
1055                  * from this stream to the duplicate, update the reference to
1056                  * this stream (in an inode or ads_entry) to point to the
1057                  * duplicate, then free this stream. */
1058                 wimlib_assert(!(duplicate_lte->unhashed));
1059                 duplicate_lte->refcnt += lte->refcnt;
1060                 duplicate_lte->out_refcnt += lte->refcnt;
1061                 *back_ptr = duplicate_lte;
1062                 free_lookup_table_entry(lte);
1063                 lte = duplicate_lte;
1064         } else {
1065                 /* No duplicate stream, so we need to insert
1066                  * this stream into the lookup table and treat
1067                  * it as a hashed stream. */
1068                 lookup_table_insert(lookup_table, lte);
1069                 lte->unhashed = 0;
1070         }
1071         if (lte_ret)
1072                 *lte_ret = lte;
1073         return 0;
1074 }
1075