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