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