]> wimlib.net Git - wimlib/blob - src/lookup_table.c
6f0786500b817b3bb3568f344778afe1fe623165
[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; plus code to read and write the corresponding on-disk data.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013, 2014 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/assert.h"
32 #include "wimlib/endianness.h"
33 #include "wimlib/error.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/ntfs_3g.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/util.h"
39 #include "wimlib/write.h"
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h> /* for unlink()  */
44
45 /* WIM lookup table:
46  *
47  * This is a logical mapping from SHA1 message digests to the data streams
48  * contained in a WIM.
49  *
50  * Here it is implemented as a hash table.
51  *
52  * Note: Everything will break horribly if there is a SHA1 collision.
53  */
54 struct wim_lookup_table {
55         struct hlist_head *array;
56         size_t num_entries;
57         size_t capacity;
58 };
59
60 struct wim_lookup_table *
61 new_lookup_table(size_t capacity)
62 {
63         struct wim_lookup_table *table;
64         struct hlist_head *array;
65
66         table = MALLOC(sizeof(struct wim_lookup_table));
67         if (table == NULL)
68                 goto oom;
69
70         array = CALLOC(capacity, sizeof(array[0]));
71         if (array == NULL) {
72                 FREE(table);
73                 goto oom;
74         }
75
76         table->num_entries = 0;
77         table->capacity = capacity;
78         table->array = array;
79         return table;
80
81 oom:
82         ERROR("Failed to allocate memory for lookup table "
83               "with capacity %zu", capacity);
84         return NULL;
85 }
86
87 static int
88 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
89 {
90         free_lookup_table_entry(entry);
91         return 0;
92 }
93
94 void
95 free_lookup_table(struct wim_lookup_table *table)
96 {
97         if (table) {
98                 for_lookup_table_entry(table, do_free_lookup_table_entry, NULL);
99                 FREE(table->array);
100                 FREE(table);
101         }
102 }
103
104 struct wim_lookup_table_entry *
105 new_lookup_table_entry(void)
106 {
107         struct wim_lookup_table_entry *lte;
108
109         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
110         if (lte == NULL)
111                 return NULL;
112
113         lte->refcnt = 1;
114
115         /* lte->resource_location = RESOURCE_NONEXISTENT  */
116         BUILD_BUG_ON(RESOURCE_NONEXISTENT != 0);
117
118         return lte;
119 }
120
121 struct wim_lookup_table_entry *
122 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
123 {
124         struct wim_lookup_table_entry *new;
125
126         new = memdup(old, sizeof(struct wim_lookup_table_entry));
127         if (new == NULL)
128                 return NULL;
129
130         new->extracted_file = NULL;
131         switch (new->resource_location) {
132         case RESOURCE_IN_WIM:
133                 list_add(&new->rspec_node, &new->rspec->stream_list);
134                 break;
135
136         case RESOURCE_IN_FILE_ON_DISK:
137 #ifdef __WIN32__
138         case RESOURCE_WIN32_ENCRYPTED:
139 #endif
140 #ifdef WITH_FUSE
141         case RESOURCE_IN_STAGING_FILE:
142                 BUILD_BUG_ON((void*)&old->file_on_disk !=
143                              (void*)&old->staging_file_name);
144 #endif
145                 new->file_on_disk = TSTRDUP(old->file_on_disk);
146                 if (new->file_on_disk == NULL)
147                         goto out_free;
148                 break;
149         case RESOURCE_IN_ATTACHED_BUFFER:
150                 new->attached_buffer = memdup(old->attached_buffer, old->size);
151                 if (new->attached_buffer == NULL)
152                         goto out_free;
153                 break;
154 #ifdef WITH_NTFS_3G
155         case RESOURCE_IN_NTFS_VOLUME:
156                 if (old->ntfs_loc) {
157                         struct ntfs_location *loc;
158                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
159                         if (loc == NULL)
160                                 goto out_free;
161                         loc->path = NULL;
162                         loc->stream_name = NULL;
163                         new->ntfs_loc = loc;
164                         loc->path = STRDUP(old->ntfs_loc->path);
165                         if (loc->path == NULL)
166                                 goto out_free;
167                         if (loc->stream_name_nchars != 0) {
168                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
169                                                           loc->stream_name_nchars * 2);
170                                 if (loc->stream_name == NULL)
171                                         goto out_free;
172                         }
173                 }
174                 break;
175 #endif
176         default:
177                 break;
178         }
179         return new;
180
181 out_free:
182         free_lookup_table_entry(new);
183         return NULL;
184 }
185
186 void
187 lte_put_resource(struct wim_lookup_table_entry *lte)
188 {
189         switch (lte->resource_location) {
190         case RESOURCE_IN_WIM:
191                 list_del(&lte->rspec_node);
192                 if (list_empty(&lte->rspec->stream_list))
193                         FREE(lte->rspec);
194                 break;
195         case RESOURCE_IN_FILE_ON_DISK:
196 #ifdef __WIN32__
197         case RESOURCE_WIN32_ENCRYPTED:
198 #endif
199 #ifdef WITH_FUSE
200         case RESOURCE_IN_STAGING_FILE:
201                 BUILD_BUG_ON((void*)&lte->file_on_disk !=
202                              (void*)&lte->staging_file_name);
203 #endif
204         case RESOURCE_IN_ATTACHED_BUFFER:
205                 BUILD_BUG_ON((void*)&lte->file_on_disk !=
206                              (void*)&lte->attached_buffer);
207                 FREE(lte->file_on_disk);
208                 break;
209 #ifdef WITH_NTFS_3G
210         case RESOURCE_IN_NTFS_VOLUME:
211                 if (lte->ntfs_loc) {
212                         FREE(lte->ntfs_loc->path);
213                         FREE(lte->ntfs_loc->stream_name);
214                         FREE(lte->ntfs_loc);
215                 }
216                 break;
217 #endif
218         default:
219                 break;
220         }
221 }
222
223 void
224 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
225 {
226         if (lte) {
227                 lte_put_resource(lte);
228                 FREE(lte);
229         }
230 }
231
232 /* Should this stream be retained even if it has no references?  */
233 static bool
234 should_retain_lte(const struct wim_lookup_table_entry *lte)
235 {
236         return lte->resource_location == RESOURCE_IN_WIM;
237 }
238
239 static void
240 finalize_lte(struct wim_lookup_table_entry *lte)
241 {
242         if (!should_retain_lte(lte))
243                 free_lookup_table_entry(lte);
244 }
245
246 /*
247  * Decrements the reference count for the lookup table entry @lte, which must be
248  * inserted in the stream lookup table @table.
249  *
250  * If the reference count reaches 0, this may cause @lte to be destroyed.
251  * However, we may retain entries with 0 reference count.  This does not affect
252  * correctness, but it prevents the entries for valid streams in a WIM archive,
253  * which will continue to be present after appending to the file, from being
254  * lost merely because we dropped all references to them.
255  */
256 void
257 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
258                      struct wim_lookup_table *table)
259 {
260         wimlib_assert(lte->refcnt != 0);
261
262         if (--lte->refcnt == 0) {
263                 if (lte->unhashed) {
264                         list_del(&lte->unhashed_list);
265                 #ifdef WITH_FUSE
266                         /* If the stream has been extracted to a staging file
267                          * for a FUSE mount, unlink the staging file.  (Note
268                          * that there still may be open file descriptors to it.)
269                          * */
270                         if (lte->resource_location == RESOURCE_IN_STAGING_FILE)
271                                 unlink(lte->staging_file_name);
272                 #endif
273                 } else {
274                         if (!should_retain_lte(lte))
275                                 lookup_table_unlink(table, lte);
276                 }
277
278                 /* If FUSE mounts are enabled, we don't actually free the entry
279                  * until the last file descriptor has been closed by
280                  * lte_decrement_num_opened_fds().  */
281 #ifdef WITH_FUSE
282                 if (lte->num_opened_fds == 0)
283 #endif
284                         finalize_lte(lte);
285         }
286 }
287
288 #ifdef WITH_FUSE
289 void
290 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
291 {
292         wimlib_assert(lte->num_opened_fds != 0);
293
294         if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
295                 finalize_lte(lte);
296 }
297 #endif
298
299 static void
300 lookup_table_insert_raw(struct wim_lookup_table *table,
301                         struct wim_lookup_table_entry *lte)
302 {
303         size_t i = lte->hash_short % table->capacity;
304
305         hlist_add_head(&lte->hash_list, &table->array[i]);
306 }
307
308 static void
309 enlarge_lookup_table(struct wim_lookup_table *table)
310 {
311         size_t old_capacity, new_capacity;
312         struct hlist_head *old_array, *new_array;
313         struct wim_lookup_table_entry *lte;
314         struct hlist_node *cur, *tmp;
315         size_t i;
316
317         old_capacity = table->capacity;
318         new_capacity = old_capacity * 2;
319         new_array = CALLOC(new_capacity, sizeof(struct hlist_head));
320         if (new_array == NULL)
321                 return;
322         old_array = table->array;
323         table->array = new_array;
324         table->capacity = new_capacity;
325
326         for (i = 0; i < old_capacity; i++) {
327                 hlist_for_each_entry_safe(lte, cur, tmp, &old_array[i], hash_list) {
328                         hlist_del(&lte->hash_list);
329                         lookup_table_insert_raw(table, lte);
330                 }
331         }
332         FREE(old_array);
333 }
334
335 /* Inserts an entry into the lookup table.  */
336 void
337 lookup_table_insert(struct wim_lookup_table *table,
338                     struct wim_lookup_table_entry *lte)
339 {
340         lookup_table_insert_raw(table, lte);
341         if (++table->num_entries > table->capacity)
342                 enlarge_lookup_table(table);
343 }
344
345 /* Unlinks a lookup table entry from the table; does not free it.  */
346 void
347 lookup_table_unlink(struct wim_lookup_table *table,
348                     struct wim_lookup_table_entry *lte)
349 {
350         wimlib_assert(!lte->unhashed);
351         wimlib_assert(table->num_entries != 0);
352
353         hlist_del(&lte->hash_list);
354         table->num_entries--;
355 }
356
357 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
358  * lookup table, or NULL if there is none.  */
359 struct wim_lookup_table_entry *
360 lookup_stream(const struct wim_lookup_table *table, const u8 hash[])
361 {
362         size_t i;
363         struct wim_lookup_table_entry *lte;
364         struct hlist_node *pos;
365
366         i = *(size_t*)hash % table->capacity;
367         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
368                 if (hashes_equal(hash, lte->hash))
369                         return lte;
370         return NULL;
371 }
372
373 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
374  * return nonzero if any call to the function returns nonzero. */
375 int
376 for_lookup_table_entry(struct wim_lookup_table *table,
377                        int (*visitor)(struct wim_lookup_table_entry *, void *),
378                        void *arg)
379 {
380         struct wim_lookup_table_entry *lte;
381         struct hlist_node *pos, *tmp;
382         int ret;
383
384         for (size_t i = 0; i < table->capacity; i++) {
385                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
386                                           hash_list)
387                 {
388                         ret = visitor(lte, arg);
389                         if (ret)
390                                 return ret;
391                 }
392         }
393         return 0;
394 }
395
396 /* qsort() callback that sorts streams (represented by `struct
397  * wim_lookup_table_entry's) into an order optimized for reading.
398  *
399  * Sorting is done primarily by resource location, then secondarily by a
400  * per-resource location order.  For example, resources in WIM files are sorted
401  * primarily by part number, then secondarily by offset, as to implement optimal
402  * reading of either a standalone or split WIM.  */
403 static int
404 cmp_streams_by_sequential_order(const void *p1, const void *p2)
405 {
406         const struct wim_lookup_table_entry *lte1, *lte2;
407         int v;
408         WIMStruct *wim1, *wim2;
409
410         lte1 = *(const struct wim_lookup_table_entry**)p1;
411         lte2 = *(const struct wim_lookup_table_entry**)p2;
412
413         v = (int)lte1->resource_location - (int)lte2->resource_location;
414
415         /* Different resource locations?  */
416         if (v)
417                 return v;
418
419         switch (lte1->resource_location) {
420         case RESOURCE_IN_WIM:
421                 wim1 = lte1->rspec->wim;
422                 wim2 = lte2->rspec->wim;
423
424                 /* Different (possibly split) WIMs?  */
425                 if (wim1 != wim2) {
426                         v = memcmp(wim1->hdr.guid, wim2->hdr.guid, WIM_GUID_LEN);
427                         if (v)
428                                 return v;
429                 }
430
431                 /* Different part numbers in the same WIM?  */
432                 v = (int)wim1->hdr.part_number - (int)wim2->hdr.part_number;
433                 if (v)
434                         return v;
435
436                 if (lte1->rspec->offset_in_wim != lte2->rspec->offset_in_wim)
437                         return cmp_u64(lte1->rspec->offset_in_wim,
438                                        lte2->rspec->offset_in_wim);
439
440                 return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
441
442         case RESOURCE_IN_FILE_ON_DISK:
443 #ifdef WITH_FUSE
444         case RESOURCE_IN_STAGING_FILE:
445 #endif
446 #ifdef __WIN32__
447         case RESOURCE_WIN32_ENCRYPTED:
448 #endif
449                 /* Compare files by path: just a heuristic that will place files
450                  * in the same directory next to each other.  */
451                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
452 #ifdef WITH_NTFS_3G
453         case RESOURCE_IN_NTFS_VOLUME:
454                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
455 #endif
456         default:
457                 /* No additional sorting order defined for this resource
458                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
459                  * everything equal to each other.  */
460                 return 0;
461         }
462 }
463
464 int
465 sort_stream_list(struct list_head *stream_list,
466                  size_t list_head_offset,
467                  int (*compar)(const void *, const void*))
468 {
469         struct list_head *cur;
470         struct wim_lookup_table_entry **array;
471         size_t i;
472         size_t array_size;
473         size_t num_streams = 0;
474
475         list_for_each(cur, stream_list)
476                 num_streams++;
477
478         if (num_streams <= 1)
479                 return 0;
480
481         array_size = num_streams * sizeof(array[0]);
482         array = MALLOC(array_size);
483         if (array == NULL)
484                 return WIMLIB_ERR_NOMEM;
485
486         cur = stream_list->next;
487         for (i = 0; i < num_streams; i++) {
488                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
489                                                             list_head_offset);
490                 cur = cur->next;
491         }
492
493         qsort(array, num_streams, sizeof(array[0]), compar);
494
495         INIT_LIST_HEAD(stream_list);
496         for (i = 0; i < num_streams; i++) {
497                 list_add_tail((struct list_head*)
498                                ((u8*)array[i] + list_head_offset),
499                               stream_list);
500         }
501         FREE(array);
502         return 0;
503 }
504
505 /* Sort the specified list of streams in an order optimized for reading.  */
506 int
507 sort_stream_list_by_sequential_order(struct list_head *stream_list,
508                                      size_t list_head_offset)
509 {
510         return sort_stream_list(stream_list, list_head_offset,
511                                 cmp_streams_by_sequential_order);
512 }
513
514
515 static int
516 add_lte_to_array(struct wim_lookup_table_entry *lte,
517                  void *_pp)
518 {
519         struct wim_lookup_table_entry ***pp = _pp;
520         *(*pp)++ = lte;
521         return 0;
522 }
523
524 /* Iterate through the lookup table entries, but first sort them by stream
525  * offset in the WIM.  Caution: this is intended to be used when the stream
526  * offset field has actually been set. */
527 int
528 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
529                                   int (*visitor)(struct wim_lookup_table_entry *,
530                                                  void *),
531                                   void *arg)
532 {
533         struct wim_lookup_table_entry **lte_array, **p;
534         size_t num_streams = table->num_entries;
535         int ret;
536
537         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
538         if (!lte_array)
539                 return WIMLIB_ERR_NOMEM;
540         p = lte_array;
541         for_lookup_table_entry(table, add_lte_to_array, &p);
542
543         wimlib_assert(p == lte_array + num_streams);
544
545         qsort(lte_array, num_streams, sizeof(lte_array[0]),
546               cmp_streams_by_sequential_order);
547         ret = 0;
548         for (size_t i = 0; i < num_streams; i++) {
549                 ret = visitor(lte_array[i], arg);
550                 if (ret)
551                         break;
552         }
553         FREE(lte_array);
554         return ret;
555 }
556
557 /* On-disk format of a WIM lookup table entry (stream entry). */
558 struct wim_lookup_table_entry_disk {
559         /* Size, offset, and flags of the stream.  */
560         struct wim_reshdr_disk reshdr;
561
562         /* Which part of the split WIM this stream is in; indexed from 1. */
563         le16 part_number;
564
565         /* Reference count of this stream over all WIM images. */
566         le32 refcnt;
567
568         /* SHA1 message digest of the uncompressed data of this stream, or
569          * optionally all zeroes if this stream is of zero length. */
570         u8 hash[SHA1_HASH_SIZE];
571 } _packed_attribute;
572
573 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
574
575 /* Given a nonempty run of consecutive lookup table entries with the
576  * PACKED_STREAMS flag set, count how many specify resources (as opposed to
577  * streams within those resources).
578  *
579  * Returns the resulting count.  */
580 static size_t
581 count_subpacks(const struct wim_lookup_table_entry_disk *entries, size_t max)
582 {
583         size_t count = 0;
584         do {
585                 struct wim_reshdr reshdr;
586
587                 get_wim_reshdr(&(entries++)->reshdr, &reshdr);
588
589                 if (!(reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)) {
590                         /* Run was terminated by a stand-alone stream entry.  */
591                         break;
592                 }
593
594                 if (reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER) {
595                         /* This is a resource entry.  */
596                         count++;
597                 }
598         } while (--max);
599         return count;
600 }
601
602 /* Given a run of consecutive lookup table entries with the PACKED_STREAMS flag
603  * set and having @num_subpacks resource entries, load resource information from
604  * them into the resource specifications in the @subpacks array.
605  *
606  * Returns 0 on success, or a nonzero error code on failure.  */
607 static int
608 do_load_subpack_info(WIMStruct *wim, struct wim_resource_spec **subpacks,
609                      size_t num_subpacks,
610                      const struct wim_lookup_table_entry_disk *entries)
611 {
612         for (size_t i = 0; i < num_subpacks; i++) {
613                 struct wim_reshdr reshdr;
614                 struct alt_chunk_table_header_disk hdr;
615                 struct wim_resource_spec *rspec;
616                 int ret;
617
618                 /* Advance to next resource entry.  */
619
620                 do {
621                         get_wim_reshdr(&(entries++)->reshdr, &reshdr);
622                 } while (reshdr.uncompressed_size != WIM_PACK_MAGIC_NUMBER);
623
624                 rspec = subpacks[i];
625
626                 wim_res_hdr_to_spec(&reshdr, wim, rspec);
627
628                 /* For packed resources, the uncompressed size, compression
629                  * type, and chunk size are stored in the resource itself, not
630                  * in the lookup table.  */
631
632                 ret = full_pread(&wim->in_fd, &hdr,
633                                  sizeof(hdr), reshdr.offset_in_wim);
634                 if (ret) {
635                         ERROR("Failed to read header of packed resource "
636                               "(offset_in_wim=%"PRIu64")",
637                               reshdr.offset_in_wim);
638                         return ret;
639                 }
640
641                 rspec->uncompressed_size = le64_to_cpu(hdr.res_usize);
642
643                 /* Compression format numbers must be the same as in
644                  * WIMGAPI to be compatible here.  */
645                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_NONE != 0);
646                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
647                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
648                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
649                 rspec->compression_type = le32_to_cpu(hdr.compression_format);
650
651                 rspec->chunk_size = le32_to_cpu(hdr.chunk_size);
652
653                 DEBUG("Subpack %zu/%zu: %"PRIu64" => %"PRIu64" "
654                       "(%"TS"/%"PRIu32") @ +%"PRIu64"",
655                       i + 1, num_subpacks,
656                       rspec->uncompressed_size,
657                       rspec->size_in_wim,
658                       wimlib_get_compression_type_string(rspec->compression_type),
659                       rspec->chunk_size,
660                       rspec->offset_in_wim);
661
662         }
663         return 0;
664 }
665
666 /* Given a nonempty run of consecutive lookup table entries with the
667  * PACKED_STREAMS flag set, allocate a 'struct wim_resource_spec' for each
668  * resource within that run.
669  *
670  * Returns 0 on success, or a nonzero error code on failure.
671  * Returns the pointers and count in *subpacks_ret and *num_subpacks_ret.
672  */
673 static int
674 load_subpack_info(WIMStruct *wim,
675                   const struct wim_lookup_table_entry_disk *entries,
676                   size_t num_remaining_entries,
677                   struct wim_resource_spec ***subpacks_ret,
678                   size_t *num_subpacks_ret)
679 {
680         size_t num_subpacks;
681         struct wim_resource_spec **subpacks;
682         size_t i;
683         int ret;
684
685         num_subpacks = count_subpacks(entries, num_remaining_entries);
686         subpacks = CALLOC(num_subpacks, sizeof(subpacks[0]));
687         if (!subpacks)
688                 return WIMLIB_ERR_NOMEM;
689
690         for (i = 0; i < num_subpacks; i++) {
691                 subpacks[i] = MALLOC(sizeof(struct wim_resource_spec));
692                 if (!subpacks[i]) {
693                         ret = WIMLIB_ERR_NOMEM;
694                         goto out_free_subpacks;
695                 }
696         }
697
698         ret = do_load_subpack_info(wim, subpacks, num_subpacks, entries);
699         if (ret)
700                 goto out_free_subpacks;
701
702         *subpacks_ret = subpacks;
703         *num_subpacks_ret = num_subpacks;
704         return 0;
705
706 out_free_subpacks:
707         for (i = 0; i < num_subpacks; i++)
708                 FREE(subpacks[i]);
709         FREE(subpacks);
710         return ret;
711 }
712
713 /* Given a 'struct wim_lookup_table_entry' allocated for a stream entry with
714  * PACKED_STREAMS set, try to bind it to a subpack of the current PACKED_STREAMS
715  * run.  */
716 static int
717 bind_stream_to_subpack(const struct wim_reshdr *reshdr,
718                        struct wim_lookup_table_entry *stream,
719                        struct wim_resource_spec **subpacks,
720                        size_t num_subpacks)
721 {
722         u64 offset = reshdr->offset_in_wim;
723
724         /* XXX: This linear search will be slow in the degenerate case where the
725          * number of subpacks is huge.  */
726         stream->size = reshdr->size_in_wim;
727         stream->flags = reshdr->flags;
728         for (size_t i = 0; i < num_subpacks; i++) {
729                 if (offset + stream->size <= subpacks[i]->uncompressed_size) {
730                         stream->offset_in_res = offset;
731                         lte_bind_wim_resource_spec(stream, subpacks[i]);
732                         return 0;
733                 }
734                 offset -= subpacks[i]->uncompressed_size;
735         }
736         ERROR("Packed stream could not be assigned to any resource");
737         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
738 }
739
740 static void
741 free_subpack_info(struct wim_resource_spec **subpacks, size_t num_subpacks)
742 {
743         if (subpacks) {
744                 for (size_t i = 0; i < num_subpacks; i++)
745                         if (list_empty(&subpacks[i]->stream_list))
746                                 FREE(subpacks[i]);
747                 FREE(subpacks);
748         }
749 }
750
751 static int
752 cmp_streams_by_offset_in_res(const void *p1, const void *p2)
753 {
754         const struct wim_lookup_table_entry *lte1, *lte2;
755
756         lte1 = *(const struct wim_lookup_table_entry**)p1;
757         lte2 = *(const struct wim_lookup_table_entry**)p2;
758
759         return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
760 }
761
762 /* Validate the size and location of a WIM resource.  */
763 static int
764 validate_resource(struct wim_resource_spec *rspec)
765 {
766         struct wim_lookup_table_entry *lte;
767         bool out_of_order;
768         u64 expected_next_offset;
769         int ret;
770
771         /* Verify that the resource itself has a valid offset and size.  */
772         if (rspec->offset_in_wim + rspec->size_in_wim < rspec->size_in_wim)
773                 goto invalid_due_to_overflow;
774
775         /* Verify that each stream in the resource has a valid offset and size.
776          */
777         expected_next_offset = 0;
778         out_of_order = false;
779         list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
780                 if (lte->offset_in_res + lte->size < lte->size ||
781                     lte->offset_in_res + lte->size > rspec->uncompressed_size)
782                         goto invalid_due_to_overflow;
783
784                 if (lte->offset_in_res >= expected_next_offset)
785                         expected_next_offset = lte->offset_in_res + lte->size;
786                 else
787                         out_of_order = true;
788         }
789
790         /* If the streams were not located at strictly increasing positions (not
791          * allowing for overlap), sort them.  Then make sure that none overlap.
792          */
793         if (out_of_order) {
794                 ret = sort_stream_list(&rspec->stream_list,
795                                        offsetof(struct wim_lookup_table_entry,
796                                                 rspec_node),
797                                        cmp_streams_by_offset_in_res);
798                 if (ret)
799                         return ret;
800
801                 expected_next_offset = 0;
802                 list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
803                         if (lte->offset_in_res >= expected_next_offset)
804                                 expected_next_offset = lte->offset_in_res + lte->size;
805                         else
806                                 goto invalid_due_to_overlap;
807                 }
808         }
809
810         return 0;
811
812 invalid_due_to_overflow:
813         ERROR("Invalid resource entry (offset overflow)");
814         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
815
816 invalid_due_to_overlap:
817         ERROR("Invalid resource entry (streams in packed resource overlap)");
818         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
819 }
820
821 static int
822 finish_subpacks(struct wim_resource_spec **subpacks, size_t num_subpacks)
823 {
824         int ret = 0;
825         for (size_t i = 0; i < num_subpacks; i++) {
826                 ret = validate_resource(subpacks[i]);
827                 if (ret)
828                         break;
829         }
830         free_subpack_info(subpacks, num_subpacks);
831         return ret;
832 }
833
834 /*
835  * Reads the lookup table from a WIM file.  Usually, each entry specifies a
836  * stream that the WIM file contains, along with its location and SHA1 message
837  * digest.
838  *
839  * Saves lookup table entries for non-metadata streams in a hash table (set to
840  * wim->lookup_table), and saves the metadata entry for each image in a special
841  * per-image location (the wim->image_metadata array).
842  *
843  * This works for both version WIM_VERSION_DEFAULT (68864) and version
844  * WIM_VERSION_PACKED_STREAMS (3584) WIMs.  In the latter, a consecutive run of
845  * lookup table entries that all have flag WIM_RESHDR_FLAG_PACKED_STREAMS (0x10)
846  * set is a "packed run".  A packed run logically contains zero or more
847  * resources, each of which logically contains zero or more streams.
848  * Physically, in such a run, a "lookup table entry" with uncompressed size
849  * WIM_PACK_MAGIC_NUMBER (0x100000000) specifies a resource, whereas any other
850  * entry specifies a stream.  Within such a run, stream entries and resource
851  * entries need not be in any particular order, except that the order of the
852  * resource entries is important, as it affects how streams are assigned to
853  * resources.  See the code for details.
854  *
855  * Possible return values:
856  *      WIMLIB_ERR_SUCCESS (0)
857  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
858  *      WIMLIB_ERR_NOMEM
859  *
860  *      Or an error code caused by failure to read the lookup table from the WIM
861  *      file.
862  */
863 int
864 read_wim_lookup_table(WIMStruct *wim)
865 {
866         int ret;
867         size_t num_entries;
868         void *buf = NULL;
869         struct wim_lookup_table *table = NULL;
870         struct wim_lookup_table_entry *cur_entry = NULL;
871         size_t num_duplicate_entries = 0;
872         size_t num_wrong_part_entries = 0;
873         u32 image_index = 0;
874         struct wim_resource_spec **cur_subpacks = NULL;
875         size_t cur_num_subpacks = 0;
876
877         DEBUG("Reading lookup table.");
878
879         /* Sanity check: lookup table entries are 50 bytes each.  */
880         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
881                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
882
883         /* Calculate the number of entries in the lookup table.  */
884         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
885                       sizeof(struct wim_lookup_table_entry_disk);
886
887         /* Read the lookup table into a buffer.  */
888         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
889         if (ret)
890                 goto out;
891
892         /* Allocate a hash table to map SHA1 message digests into stream
893          * specifications.  This is the in-memory "lookup table".  */
894         table = new_lookup_table(num_entries * 2 + 1);
895         if (!table)
896                 goto oom;
897
898         /* Allocate and initalize stream entries ('struct
899          * wim_lookup_table_entry's) from the raw lookup table buffer.  Each of
900          * these entries will point to a 'struct wim_resource_spec' that
901          * describes the underlying resource.  In WIMs with version number
902          * WIM_VERSION_PACKED_STREAMS, a resource may contain multiple streams.
903          */
904         for (size_t i = 0; i < num_entries; i++) {
905                 const struct wim_lookup_table_entry_disk *disk_entry =
906                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
907                 struct wim_reshdr reshdr;
908                 u16 part_number;
909
910                 /* Get the resource header  */
911                 get_wim_reshdr(&disk_entry->reshdr, &reshdr);
912
913                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
914                       "uncompressed_size=%"PRIu64", "
915                       "offset_in_wim=%"PRIu64", "
916                       "flags=0x%02x",
917                       reshdr.size_in_wim, reshdr.uncompressed_size,
918                       reshdr.offset_in_wim, reshdr.flags);
919
920                 /* Ignore PACKED_STREAMS flag if it isn't supposed to be used in
921                  * this WIM version.  */
922                 if (wim->hdr.wim_version == WIM_VERSION_DEFAULT)
923                         reshdr.flags &= ~WIM_RESHDR_FLAG_PACKED_STREAMS;
924
925                 /* Allocate a new 'struct wim_lookup_table_entry'.  */
926                 cur_entry = new_lookup_table_entry();
927                 if (!cur_entry)
928                         goto oom;
929
930                 /* Get the part number, reference count, and hash.  */
931                 part_number = le16_to_cpu(disk_entry->part_number);
932                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
933                 copy_hash(cur_entry->hash, disk_entry->hash);
934
935                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
936
937                         /* PACKED_STREAMS entry  */
938
939                         if (!cur_subpacks) {
940                                 /* Starting new run  */
941                                 ret = load_subpack_info(wim, disk_entry,
942                                                         num_entries - i,
943                                                         &cur_subpacks,
944                                                         &cur_num_subpacks);
945                                 if (ret)
946                                         goto out;
947                         }
948
949                         if (reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER) {
950                                 /* Resource entry, not stream entry  */
951                                 goto free_cur_entry_and_continue;
952                         }
953
954                         /* Stream entry  */
955
956                         ret = bind_stream_to_subpack(&reshdr,
957                                                      cur_entry,
958                                                      cur_subpacks,
959                                                      cur_num_subpacks);
960                         if (ret)
961                                 goto out;
962
963                 } else {
964                         /* Normal stream/resource entry; PACKED_STREAMS not set.
965                          */
966
967                         struct wim_resource_spec *rspec;
968
969                         if (unlikely(cur_subpacks)) {
970                                 /* This entry terminated a packed run.  */
971                                 ret = finish_subpacks(cur_subpacks,
972                                                       cur_num_subpacks);
973                                 cur_subpacks = NULL;
974                                 if (ret)
975                                         goto out;
976                         }
977
978                         /* How to handle an uncompressed resource with its
979                          * uncompressed size different from its compressed size?
980                          *
981                          * Based on a simple test, WIMGAPI seems to handle this
982                          * as follows:
983                          *
984                          * if (size_in_wim > uncompressed_size) {
985                          *      Ignore uncompressed_size; use size_in_wim
986                          *      instead.
987                          * } else {
988                          *      Honor uncompressed_size, but treat the part of
989                          *      the file data above size_in_wim as all zeros.
990                          * }
991                          *
992                          * So we will do the same.  */
993                         if (unlikely(!(reshdr.flags &
994                                        WIM_RESHDR_FLAG_COMPRESSED) &&
995                                      (reshdr.size_in_wim >
996                                       reshdr.uncompressed_size)))
997                         {
998                                 reshdr.uncompressed_size = reshdr.size_in_wim;
999                         }
1000
1001                         /* Set up a resource specification for this stream.  */
1002
1003                         rspec = MALLOC(sizeof(struct wim_resource_spec));
1004                         if (!rspec)
1005                                 goto oom;
1006
1007                         wim_res_hdr_to_spec(&reshdr, wim, rspec);
1008
1009                         cur_entry->offset_in_res = 0;
1010                         cur_entry->size = reshdr.uncompressed_size;
1011                         cur_entry->flags = reshdr.flags;
1012
1013                         lte_bind_wim_resource_spec(cur_entry, rspec);
1014                 }
1015
1016                 /* cur_entry is now a stream bound to a resource.  */
1017
1018                 /* Ignore entries with all zeroes in the hash field.  */
1019                 if (is_zero_hash(cur_entry->hash))
1020                         goto free_cur_entry_and_continue;
1021
1022                 /* Verify that the part number matches that of the underlying
1023                  * WIM file.  */
1024                 if (part_number != wim->hdr.part_number) {
1025                         num_wrong_part_entries++;
1026                         goto free_cur_entry_and_continue;
1027                 }
1028
1029                 if (reshdr.flags & WIM_RESHDR_FLAG_METADATA) {
1030
1031                         /* Lookup table entry for a metadata resource.  */
1032
1033                         /* Metadata entries with no references must be ignored.
1034                          * See, for example, the WinPE WIMs from the WAIK v2.1.
1035                          */
1036                         if (cur_entry->refcnt == 0)
1037                                 goto free_cur_entry_and_continue;
1038
1039                         if (cur_entry->refcnt != 1) {
1040                                 /* We don't currently support this case due to
1041                                  * the complications of multiple images sharing
1042                                  * the same metadata resource or a metadata
1043                                  * resource also being referenced by files.  */
1044                                 ERROR("Found metadata resource with refcnt != 1");
1045                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
1046                                 goto out;
1047                         }
1048
1049                         if (wim->hdr.part_number != 1) {
1050                                 WARNING("Ignoring metadata resource found in a "
1051                                         "non-first part of the split WIM");
1052                                 goto free_cur_entry_and_continue;
1053                         }
1054
1055                         /* The number of entries in the lookup table with
1056                          * WIM_RESHDR_FLAG_METADATA set should be the same as
1057                          * the image_count field in the WIM header.  */
1058                         if (image_index == wim->hdr.image_count) {
1059                                 WARNING("Found more metadata resources than images");
1060                                 goto free_cur_entry_and_continue;
1061                         }
1062
1063                         /* Notice very carefully:  We are assigning the metadata
1064                          * resources to images in the same order in which their
1065                          * lookup table entries occur on disk.  (This is also
1066                          * the behavior of Microsoft's software.)  In
1067                          * particular, this overrides the actual locations of
1068                          * the metadata resources themselves in the WIM file as
1069                          * well as any information written in the XML data.  */
1070                         DEBUG("Found metadata resource for image %"PRIu32" at "
1071                               "offset %"PRIu64".",
1072                               image_index + 1,
1073                               reshdr.offset_in_wim);
1074
1075                         wim->image_metadata[image_index++]->metadata_lte = cur_entry;
1076                 } else {
1077                         /* Lookup table entry for a non-metadata stream.  */
1078
1079                         /* Ignore this stream if it's a duplicate.  */
1080                         if (lookup_stream(table, cur_entry->hash)) {
1081                                 num_duplicate_entries++;
1082                                 goto free_cur_entry_and_continue;
1083                         }
1084
1085                         /* Insert the stream into the in-memory lookup table,
1086                          * keyed by its SHA1 message digest.  */
1087                         lookup_table_insert(table, cur_entry);
1088                 }
1089
1090                 continue;
1091
1092         free_cur_entry_and_continue:
1093                 if (cur_subpacks &&
1094                     cur_entry->resource_location == RESOURCE_IN_WIM)
1095                         lte_unbind_wim_resource_spec(cur_entry);
1096                 free_lookup_table_entry(cur_entry);
1097         }
1098         cur_entry = NULL;
1099
1100         if (cur_subpacks) {
1101                 /* End of lookup table terminated a packed run.  */
1102                 ret = finish_subpacks(cur_subpacks, cur_num_subpacks);
1103                 cur_subpacks = NULL;
1104                 if (ret)
1105                         goto out;
1106         }
1107
1108         if (wim->hdr.part_number == 1 && image_index != wim->hdr.image_count) {
1109                 WARNING("Could not find metadata resources for all images");
1110                 for (u32 i = image_index; i < wim->hdr.image_count; i++)
1111                         put_image_metadata(wim->image_metadata[i], NULL);
1112                 wim->hdr.image_count = image_index;
1113         }
1114
1115         if (num_duplicate_entries > 0) {
1116                 WARNING("Ignoring %zu duplicate streams in the WIM lookup table",
1117                         num_duplicate_entries);
1118         }
1119
1120         if (num_wrong_part_entries > 0) {
1121                 WARNING("Ignoring %zu streams with wrong part number",
1122                         num_wrong_part_entries);
1123         }
1124
1125         DEBUG("Done reading lookup table.");
1126         wim->lookup_table = table;
1127         ret = 0;
1128         goto out_free_buf;
1129
1130 oom:
1131         ERROR("Not enough memory to read lookup table!");
1132         ret = WIMLIB_ERR_NOMEM;
1133 out:
1134         free_subpack_info(cur_subpacks, cur_num_subpacks);
1135         free_lookup_table_entry(cur_entry);
1136         free_lookup_table(table);
1137 out_free_buf:
1138         FREE(buf);
1139         return ret;
1140 }
1141
1142 static void
1143 put_wim_lookup_table_entry(struct wim_lookup_table_entry_disk *disk_entry,
1144                            const struct wim_reshdr *out_reshdr,
1145                            u16 part_number, u32 refcnt, const u8 *hash)
1146 {
1147         put_wim_reshdr(out_reshdr, &disk_entry->reshdr);
1148         disk_entry->part_number = cpu_to_le16(part_number);
1149         disk_entry->refcnt = cpu_to_le32(refcnt);
1150         copy_hash(disk_entry->hash, hash);
1151 }
1152
1153 /* Note: the list of stream entries must be sorted so that all entries for the
1154  * same packed resource are consecutive.  In addition, entries with
1155  * WIM_RESHDR_FLAG_METADATA set must be in the same order as the indices of the
1156  * underlying images.  */
1157 int
1158 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
1159                                         struct filedes *out_fd,
1160                                         u16 part_number,
1161                                         struct wim_reshdr *out_reshdr,
1162                                         int write_resource_flags)
1163 {
1164         size_t table_size;
1165         struct wim_lookup_table_entry *lte;
1166         struct wim_lookup_table_entry_disk *table_buf;
1167         struct wim_lookup_table_entry_disk *table_buf_ptr;
1168         int ret;
1169         u64 prev_res_offset_in_wim = ~0ULL;
1170         u64 prev_uncompressed_size;
1171         u64 logical_offset;
1172
1173         table_size = 0;
1174         list_for_each_entry(lte, stream_list, lookup_table_list) {
1175                 table_size += sizeof(struct wim_lookup_table_entry_disk);
1176
1177                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1178                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
1179                 {
1180                         table_size += sizeof(struct wim_lookup_table_entry_disk);
1181                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
1182                 }
1183         }
1184
1185         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
1186               table_size, out_fd->offset);
1187
1188         table_buf = MALLOC(table_size);
1189         if (table_buf == NULL) {
1190                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
1191                       table_size);
1192                 return WIMLIB_ERR_NOMEM;
1193         }
1194         table_buf_ptr = table_buf;
1195
1196         prev_res_offset_in_wim = ~0ULL;
1197         prev_uncompressed_size = 0;
1198         logical_offset = 0;
1199         list_for_each_entry(lte, stream_list, lookup_table_list) {
1200                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1201                         struct wim_reshdr tmp_reshdr;
1202
1203                         /* Eww.  When WIMGAPI sees multiple resource packs, it
1204                          * expects the offsets to be adjusted as if there were
1205                          * really only one pack.  */
1206
1207                         if (lte->out_res_offset_in_wim != prev_res_offset_in_wim) {
1208                                 /* Put the resource entry for pack  */
1209                                 tmp_reshdr.offset_in_wim = lte->out_res_offset_in_wim;
1210                                 tmp_reshdr.size_in_wim = lte->out_res_size_in_wim;
1211                                 tmp_reshdr.uncompressed_size = WIM_PACK_MAGIC_NUMBER;
1212                                 tmp_reshdr.flags = WIM_RESHDR_FLAG_PACKED_STREAMS;
1213
1214                                 put_wim_lookup_table_entry(table_buf_ptr++,
1215                                                            &tmp_reshdr,
1216                                                            part_number,
1217                                                            1, zero_hash);
1218
1219                                 logical_offset += prev_uncompressed_size;
1220
1221                                 prev_res_offset_in_wim = lte->out_res_offset_in_wim;
1222                                 prev_uncompressed_size = lte->out_res_uncompressed_size;
1223                         }
1224                         tmp_reshdr = lte->out_reshdr;
1225                         tmp_reshdr.offset_in_wim += logical_offset;
1226                         put_wim_lookup_table_entry(table_buf_ptr++,
1227                                                    &tmp_reshdr,
1228                                                    part_number,
1229                                                    lte->out_refcnt,
1230                                                    lte->hash);
1231                 } else {
1232                         put_wim_lookup_table_entry(table_buf_ptr++,
1233                                                    &lte->out_reshdr,
1234                                                    part_number,
1235                                                    lte->out_refcnt,
1236                                                    lte->hash);
1237                 }
1238
1239         }
1240         wimlib_assert((u8*)table_buf_ptr - (u8*)table_buf == table_size);
1241
1242         /* Write the lookup table uncompressed.  Although wimlib can handle a
1243          * compressed lookup table, MS software cannot.  */
1244         ret = write_wim_resource_from_buffer(table_buf,
1245                                              table_size,
1246                                              WIM_RESHDR_FLAG_METADATA,
1247                                              out_fd,
1248                                              WIMLIB_COMPRESSION_TYPE_NONE,
1249                                              0,
1250                                              out_reshdr,
1251                                              NULL,
1252                                              write_resource_flags);
1253         FREE(table_buf);
1254         DEBUG("ret=%d", ret);
1255         return ret;
1256 }
1257
1258 int
1259 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1260 {
1261         lte->real_refcnt = 0;
1262         return 0;
1263 }
1264
1265 int
1266 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1267 {
1268         lte->out_refcnt = 0;
1269         return 0;
1270 }
1271
1272 int
1273 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
1274 {
1275         if (lte->extracted_file != NULL) {
1276                 FREE(lte->extracted_file);
1277                 lte->extracted_file = NULL;
1278         }
1279         return 0;
1280 }
1281
1282 /* Allocate a stream entry for the contents of the buffer, or re-use an existing
1283  * entry in @lookup_table for the same stream.  */
1284 struct wim_lookup_table_entry *
1285 new_stream_from_data_buffer(const void *buffer, size_t size,
1286                             struct wim_lookup_table *lookup_table)
1287 {
1288         u8 hash[SHA1_HASH_SIZE];
1289         struct wim_lookup_table_entry *lte, *existing_lte;
1290
1291         sha1_buffer(buffer, size, hash);
1292         existing_lte = lookup_stream(lookup_table, hash);
1293         if (existing_lte) {
1294                 wimlib_assert(existing_lte->size == size);
1295                 lte = existing_lte;
1296                 lte->refcnt++;
1297         } else {
1298                 void *buffer_copy;
1299                 lte = new_lookup_table_entry();
1300                 if (lte == NULL)
1301                         return NULL;
1302                 buffer_copy = memdup(buffer, size);
1303                 if (buffer_copy == NULL) {
1304                         free_lookup_table_entry(lte);
1305                         return NULL;
1306                 }
1307                 lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1308                 lte->attached_buffer    = buffer_copy;
1309                 lte->size               = size;
1310                 copy_hash(lte->hash, hash);
1311                 lookup_table_insert(lookup_table, lte);
1312         }
1313         return lte;
1314 }
1315
1316 /* Calculate the SHA1 message digest of a stream and move it from the list of
1317  * unhashed streams to the stream lookup table, possibly joining it with an
1318  * existing lookup table entry for an identical stream.
1319  *
1320  * @lte:  An unhashed lookup table entry.
1321  * @lookup_table:  Lookup table for the WIM.
1322  * @lte_ret:  On success, write a pointer to the resulting lookup table
1323  *            entry to this location.  This will be the same as @lte
1324  *            if it was inserted into the lookup table, or different if
1325  *            a duplicate stream was found.
1326  *
1327  * Returns 0 on success; nonzero if there is an error reading the stream.
1328  */
1329 int
1330 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1331                      struct wim_lookup_table *lookup_table,
1332                      struct wim_lookup_table_entry **lte_ret)
1333 {
1334         int ret;
1335         struct wim_lookup_table_entry *duplicate_lte;
1336         struct wim_lookup_table_entry **back_ptr;
1337
1338         wimlib_assert(lte->unhashed);
1339
1340         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1341          * union with the SHA1 message digest and will no longer be valid once
1342          * the SHA1 has been calculated. */
1343         back_ptr = retrieve_lte_pointer(lte);
1344
1345         ret = sha1_stream(lte);
1346         if (ret)
1347                 return ret;
1348
1349         /* Look for a duplicate stream */
1350         duplicate_lte = lookup_stream(lookup_table, lte->hash);
1351         list_del(&lte->unhashed_list);
1352         if (duplicate_lte) {
1353                 /* We have a duplicate stream.  Transfer the reference counts
1354                  * from this stream to the duplicate and update the reference to
1355                  * this stream (in an inode or ads_entry) to point to the
1356                  * duplicate.  The caller is responsible for freeing @lte if
1357                  * needed.  */
1358                 wimlib_assert(!(duplicate_lte->unhashed));
1359                 wimlib_assert(duplicate_lte->size == lte->size);
1360                 duplicate_lte->refcnt += lte->refcnt;
1361                 lte->refcnt = 0;
1362                 *back_ptr = duplicate_lte;
1363                 lte = duplicate_lte;
1364         } else {
1365                 /* No duplicate stream, so we need to insert this stream into
1366                  * the lookup table and treat it as a hashed stream. */
1367                 lookup_table_insert(lookup_table, lte);
1368                 lte->unhashed = 0;
1369         }
1370         *lte_ret = lte;
1371         return 0;
1372 }
1373
1374 void
1375 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
1376                              struct wimlib_resource_entry *wentry)
1377 {
1378         memset(wentry, 0, sizeof(*wentry));
1379
1380         wentry->uncompressed_size = lte->size;
1381         if (lte->resource_location == RESOURCE_IN_WIM) {
1382                 wentry->part_number = lte->rspec->wim->hdr.part_number;
1383                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1384                         wentry->compressed_size = 0;
1385                         wentry->offset = lte->offset_in_res;
1386                 } else {
1387                         wentry->compressed_size = lte->rspec->size_in_wim;
1388                         wentry->offset = lte->rspec->offset_in_wim;
1389                 }
1390                 wentry->raw_resource_offset_in_wim = lte->rspec->offset_in_wim;
1391                 /*wentry->raw_resource_uncompressed_size = lte->rspec->uncompressed_size;*/
1392                 wentry->raw_resource_compressed_size = lte->rspec->size_in_wim;
1393         }
1394         copy_hash(wentry->sha1_hash, lte->hash);
1395         wentry->reference_count = lte->refcnt;
1396         wentry->is_compressed = (lte->flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
1397         wentry->is_metadata = (lte->flags & WIM_RESHDR_FLAG_METADATA) != 0;
1398         wentry->is_free = (lte->flags & WIM_RESHDR_FLAG_FREE) != 0;
1399         wentry->is_spanned = (lte->flags & WIM_RESHDR_FLAG_SPANNED) != 0;
1400         wentry->packed = (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) != 0;
1401 }
1402
1403 struct iterate_lte_context {
1404         wimlib_iterate_lookup_table_callback_t cb;
1405         void *user_ctx;
1406 };
1407
1408 static int
1409 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
1410 {
1411         struct iterate_lte_context *ctx = _ctx;
1412         struct wimlib_resource_entry entry;
1413
1414         lte_to_wimlib_resource_entry(lte, &entry);
1415         return (*ctx->cb)(&entry, ctx->user_ctx);
1416 }
1417
1418 /* API function documented in wimlib.h  */
1419 WIMLIBAPI int
1420 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
1421                             wimlib_iterate_lookup_table_callback_t cb,
1422                             void *user_ctx)
1423 {
1424         if (flags != 0)
1425                 return WIMLIB_ERR_INVALID_PARAM;
1426
1427         struct iterate_lte_context ctx = {
1428                 .cb = cb,
1429                 .user_ctx = user_ctx,
1430         };
1431         if (wim_has_metadata(wim)) {
1432                 int ret;
1433                 for (int i = 0; i < wim->hdr.image_count; i++) {
1434                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
1435                                              &ctx);
1436                         if (ret)
1437                                 return ret;
1438                 }
1439         }
1440         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
1441 }