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