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