]> wimlib.net Git - wimlib/blob - src/lookup_table.c
read_wim_lookup_table(): Fix error paths
[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 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/glob.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/paths.h"
38 #include "wimlib/resource.h"
39 #include "wimlib/util.h"
40 #include "wimlib/write.h"
41
42 #include <errno.h>
43 #include <stdlib.h>
44 #ifdef WITH_FUSE
45 #  include <unistd.h> /* for unlink() */
46 #endif
47
48 struct wim_lookup_table *
49 new_lookup_table(size_t capacity)
50 {
51         struct wim_lookup_table *table;
52         struct hlist_head *array;
53
54         table = CALLOC(1, sizeof(struct wim_lookup_table));
55         if (table) {
56                 array = CALLOC(capacity, sizeof(array[0]));
57                 if (array) {
58                         table->num_entries = 0;
59                         table->capacity = capacity;
60                         table->array = array;
61                 } else {
62                         FREE(table);
63                         table = NULL;
64                         ERROR("Failed to allocate memory for lookup table "
65                               "with capacity %zu", capacity);
66                 }
67         }
68         return table;
69 }
70
71 struct wim_lookup_table_entry *
72 new_lookup_table_entry(void)
73 {
74         struct wim_lookup_table_entry *lte;
75
76         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
77         if (lte == NULL) {
78                 ERROR("Out of memory (tried to allocate %zu bytes for "
79                       "lookup table entry)",
80                       sizeof(struct wim_lookup_table_entry));
81                 return NULL;
82         }
83         lte->refcnt = 1;
84         BUILD_BUG_ON(RESOURCE_NONEXISTENT != 0);
85         return lte;
86 }
87
88 struct wim_lookup_table_entry *
89 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
90 {
91         struct wim_lookup_table_entry *new;
92
93         new = memdup(old, sizeof(struct wim_lookup_table_entry));
94         if (new == NULL)
95                 return NULL;
96
97         new->extracted_file = NULL;
98         switch (new->resource_location) {
99         case RESOURCE_IN_WIM:
100                 list_add(&new->rspec_node, &new->rspec->stream_list);
101                 break;
102
103         case RESOURCE_IN_FILE_ON_DISK:
104 #ifdef __WIN32__
105         case RESOURCE_WIN32_ENCRYPTED:
106 #endif
107 #ifdef WITH_FUSE
108         case RESOURCE_IN_STAGING_FILE:
109                 BUILD_BUG_ON((void*)&old->file_on_disk !=
110                              (void*)&old->staging_file_name);
111 #endif
112                 new->file_on_disk = TSTRDUP(old->file_on_disk);
113                 if (new->file_on_disk == NULL)
114                         goto out_free;
115                 break;
116         case RESOURCE_IN_ATTACHED_BUFFER:
117                 new->attached_buffer = memdup(old->attached_buffer, old->size);
118                 if (new->attached_buffer == NULL)
119                         goto out_free;
120                 break;
121 #ifdef WITH_NTFS_3G
122         case RESOURCE_IN_NTFS_VOLUME:
123                 if (old->ntfs_loc) {
124                         struct ntfs_location *loc;
125                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
126                         if (loc == NULL)
127                                 goto out_free;
128                         loc->path = NULL;
129                         loc->stream_name = NULL;
130                         new->ntfs_loc = loc;
131                         loc->path = STRDUP(old->ntfs_loc->path);
132                         if (loc->path == NULL)
133                                 goto out_free;
134                         if (loc->stream_name_nchars != 0) {
135                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
136                                                           loc->stream_name_nchars * 2);
137                                 if (loc->stream_name == NULL)
138                                         goto out_free;
139                         }
140                 }
141                 break;
142 #endif
143         default:
144                 break;
145         }
146         return new;
147 out_free:
148         free_lookup_table_entry(new);
149         return NULL;
150 }
151
152 void
153 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
154 {
155         if (lte) {
156                 switch (lte->resource_location) {
157                 case RESOURCE_IN_WIM:
158                         list_del(&lte->rspec_node);
159                         if (list_empty(&lte->rspec->stream_list))
160                                 FREE(lte->rspec);
161                         break;
162                 case RESOURCE_IN_FILE_ON_DISK:
163         #ifdef __WIN32__
164                 case RESOURCE_WIN32_ENCRYPTED:
165         #endif
166         #ifdef WITH_FUSE
167                 case RESOURCE_IN_STAGING_FILE:
168                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
169                                      (void*)&lte->staging_file_name);
170         #endif
171                 case RESOURCE_IN_ATTACHED_BUFFER:
172                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
173                                      (void*)&lte->attached_buffer);
174                         FREE(lte->file_on_disk);
175                         break;
176 #ifdef WITH_NTFS_3G
177                 case RESOURCE_IN_NTFS_VOLUME:
178                         if (lte->ntfs_loc) {
179                                 FREE(lte->ntfs_loc->path);
180                                 FREE(lte->ntfs_loc->stream_name);
181                                 FREE(lte->ntfs_loc);
182                         }
183                         break;
184 #endif
185                 default:
186                         break;
187                 }
188                 FREE(lte);
189         }
190 }
191
192 static int
193 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
194 {
195         free_lookup_table_entry(entry);
196         return 0;
197 }
198
199
200 void
201 free_lookup_table(struct wim_lookup_table *table)
202 {
203         DEBUG("Freeing lookup table.");
204         if (table) {
205                 if (table->array) {
206                         for_lookup_table_entry(table,
207                                                do_free_lookup_table_entry,
208                                                NULL);
209                         FREE(table->array);
210                 }
211                 FREE(table);
212         }
213 }
214
215 static void
216 lookup_table_insert_raw(struct wim_lookup_table *table,
217                         struct wim_lookup_table_entry *lte)
218 {
219         size_t i = lte->hash_short % table->capacity;
220
221         hlist_add_head(&lte->hash_list, &table->array[i]);
222 }
223
224 static void
225 enlarge_lookup_table(struct wim_lookup_table *table)
226 {
227         size_t old_capacity, new_capacity;
228         struct hlist_head *old_array, *new_array;
229         struct wim_lookup_table_entry *lte;
230         struct hlist_node *cur, *tmp;
231         size_t i;
232
233         old_capacity = table->capacity;
234         new_capacity = old_capacity * 2;
235         new_array = CALLOC(new_capacity, sizeof(struct hlist_head));
236         if (new_array == NULL)
237                 return;
238         old_array = table->array;
239         table->array = new_array;
240         table->capacity = new_capacity;
241
242         for (i = 0; i < old_capacity; i++) {
243                 hlist_for_each_entry_safe(lte, cur, tmp, &old_array[i], hash_list) {
244                         hlist_del(&lte->hash_list);
245                         lookup_table_insert_raw(table, lte);
246                 }
247         }
248         FREE(old_array);
249 }
250
251
252 /*
253  * Inserts an entry into the lookup table.
254  *
255  * @table:      A pointer to the lookup table.
256  * @lte:        A pointer to the entry to insert.
257  */
258 void
259 lookup_table_insert(struct wim_lookup_table *table,
260                     struct wim_lookup_table_entry *lte)
261 {
262         lookup_table_insert_raw(table, lte);
263         if (++table->num_entries > table->capacity)
264                 enlarge_lookup_table(table);
265 }
266
267 static void
268 finalize_lte(struct wim_lookup_table_entry *lte)
269 {
270         #ifdef WITH_FUSE
271         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
272                 unlink(lte->staging_file_name);
273                 list_del(&lte->unhashed_list);
274         }
275         #endif
276         free_lookup_table_entry(lte);
277 }
278
279 /* Decrements the reference count for the lookup table entry @lte.  If its
280  * reference count reaches 0, it is unlinked from the lookup table.  If,
281  * furthermore, the entry has no opened file descriptors associated with it, the
282  * entry is freed.  */
283 void
284 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
285                      struct wim_lookup_table *table)
286 {
287         wimlib_assert(lte != NULL);
288         wimlib_assert(lte->refcnt != 0);
289         if (--lte->refcnt == 0) {
290                 if (lte->unhashed)
291                         list_del(&lte->unhashed_list);
292                 else
293                         lookup_table_unlink(table, lte);
294         #ifdef WITH_FUSE
295                 if (lte->num_opened_fds == 0)
296         #endif
297                         finalize_lte(lte);
298         }
299 }
300
301 #ifdef WITH_FUSE
302 void
303 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
304 {
305         if (lte->num_opened_fds != 0)
306                 if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
307                         finalize_lte(lte);
308 }
309 #endif
310
311 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
312  * return nonzero if any call to the function returns nonzero. */
313 int
314 for_lookup_table_entry(struct wim_lookup_table *table,
315                        int (*visitor)(struct wim_lookup_table_entry *, void *),
316                        void *arg)
317 {
318         struct wim_lookup_table_entry *lte;
319         struct hlist_node *pos, *tmp;
320         int ret;
321
322         for (size_t i = 0; i < table->capacity; i++) {
323                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
324                                           hash_list)
325                 {
326                         ret = visitor(lte, arg);
327                         if (ret)
328                                 return ret;
329                 }
330         }
331         return 0;
332 }
333
334 /* qsort() callback that sorts streams (represented by `struct
335  * wim_lookup_table_entry's) into an order optimized for reading.
336  *
337  * Sorting is done primarily by resource location, then secondarily by a
338  * per-resource location order.  For example, resources in WIM files are sorted
339  * primarily by part number, then secondarily by offset, as to implement optimal
340  * reading of either a standalone or split WIM.  */
341 static int
342 cmp_streams_by_sequential_order(const void *p1, const void *p2)
343 {
344         const struct wim_lookup_table_entry *lte1, *lte2;
345         int v;
346         WIMStruct *wim1, *wim2;
347
348         lte1 = *(const struct wim_lookup_table_entry**)p1;
349         lte2 = *(const struct wim_lookup_table_entry**)p2;
350
351         v = (int)lte1->resource_location - (int)lte2->resource_location;
352
353         /* Different resource locations?  */
354         if (v)
355                 return v;
356
357         switch (lte1->resource_location) {
358         case RESOURCE_IN_WIM:
359                 wim1 = lte1->rspec->wim;
360                 wim2 = lte2->rspec->wim;
361
362                 /* Different (possibly split) WIMs?  */
363                 if (wim1 != wim2) {
364                         v = memcmp(wim1->hdr.guid, wim2->hdr.guid, WIM_GID_LEN);
365                         if (v)
366                                 return v;
367                 }
368
369                 /* Different part numbers in the same WIM?  */
370                 v = (int)wim1->hdr.part_number - (int)wim2->hdr.part_number;
371                 if (v)
372                         return v;
373
374                 if (lte1->rspec->offset_in_wim != lte2->rspec->offset_in_wim)
375                         return cmp_u64(lte1->rspec->offset_in_wim,
376                                        lte2->rspec->offset_in_wim);
377
378                 return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
379
380         case RESOURCE_IN_FILE_ON_DISK:
381 #ifdef WITH_FUSE
382         case RESOURCE_IN_STAGING_FILE:
383 #endif
384 #ifdef __WIN32__
385         case RESOURCE_WIN32_ENCRYPTED:
386 #endif
387                 /* Compare files by path: just a heuristic that will place files
388                  * in the same directory next to each other.  */
389                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
390 #ifdef WITH_NTFS_3G
391         case RESOURCE_IN_NTFS_VOLUME:
392                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
393 #endif
394         default:
395                 /* No additional sorting order defined for this resource
396                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
397                  * everything equal to each other.  */
398                 return 0;
399         }
400 }
401
402 int
403 sort_stream_list(struct list_head *stream_list,
404                  size_t list_head_offset,
405                  int (*compar)(const void *, const void*))
406 {
407         struct list_head *cur;
408         struct wim_lookup_table_entry **array;
409         size_t i;
410         size_t array_size;
411         size_t num_streams = 0;
412
413         list_for_each(cur, stream_list)
414                 num_streams++;
415
416         if (num_streams <= 1)
417                 return 0;
418
419         array_size = num_streams * sizeof(array[0]);
420         array = MALLOC(array_size);
421         if (array == NULL)
422                 return WIMLIB_ERR_NOMEM;
423
424         cur = stream_list->next;
425         for (i = 0; i < num_streams; i++) {
426                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
427                                                             list_head_offset);
428                 cur = cur->next;
429         }
430
431         qsort(array, num_streams, sizeof(array[0]), compar);
432
433         INIT_LIST_HEAD(stream_list);
434         for (i = 0; i < num_streams; i++) {
435                 list_add_tail((struct list_head*)
436                                ((u8*)array[i] + list_head_offset),
437                               stream_list);
438         }
439         FREE(array);
440         return 0;
441 }
442
443 /* Sort the specified list of streams in an order optimized for reading.  */
444 int
445 sort_stream_list_by_sequential_order(struct list_head *stream_list,
446                                      size_t list_head_offset)
447 {
448         return sort_stream_list(stream_list, list_head_offset,
449                                 cmp_streams_by_sequential_order);
450 }
451
452
453 static int
454 add_lte_to_array(struct wim_lookup_table_entry *lte,
455                  void *_pp)
456 {
457         struct wim_lookup_table_entry ***pp = _pp;
458         *(*pp)++ = lte;
459         return 0;
460 }
461
462 /* Iterate through the lookup table entries, but first sort them by stream
463  * offset in the WIM.  Caution: this is intended to be used when the stream
464  * offset field has actually been set. */
465 int
466 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
467                                   int (*visitor)(struct wim_lookup_table_entry *,
468                                                  void *),
469                                   void *arg)
470 {
471         struct wim_lookup_table_entry **lte_array, **p;
472         size_t num_streams = table->num_entries;
473         int ret;
474
475         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
476         if (!lte_array)
477                 return WIMLIB_ERR_NOMEM;
478         p = lte_array;
479         for_lookup_table_entry(table, add_lte_to_array, &p);
480
481         wimlib_assert(p == lte_array + num_streams);
482
483         qsort(lte_array, num_streams, sizeof(lte_array[0]),
484               cmp_streams_by_sequential_order);
485         ret = 0;
486         for (size_t i = 0; i < num_streams; i++) {
487                 ret = visitor(lte_array[i], arg);
488                 if (ret)
489                         break;
490         }
491         FREE(lte_array);
492         return ret;
493 }
494
495 /* On-disk format of a WIM lookup table entry (stream entry). */
496 struct wim_lookup_table_entry_disk {
497         /* Size, offset, and flags of the stream.  */
498         struct wim_reshdr_disk reshdr;
499
500         /* Which part of the split WIM this stream is in; indexed from 1. */
501         le16 part_number;
502
503         /* Reference count of this stream over all WIM images. */
504         le32 refcnt;
505
506         /* SHA1 message digest of the uncompressed data of this stream, or
507          * optionally all zeroes if this stream is of zero length. */
508         u8 hash[SHA1_HASH_SIZE];
509 } _packed_attribute;
510
511 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
512
513 /* Validate the size and location of a WIM resource.  */
514 static int
515 validate_resource(const struct wim_resource_spec *rspec)
516 {
517         struct wim_lookup_table_entry *lte;
518         u64 cur_offset;
519
520         /* Verify that calculating the offset of the end of the resource doesn't
521          * overflow.  */
522         if (rspec->offset_in_wim + rspec->size_in_wim < rspec->size_in_wim)
523                 goto invalid;
524
525         /* Verify that each stream in the resource has a valid offset and size,
526          * and that no streams overlap, and that the streams were added in order
527          * of increasing offset.  */
528         cur_offset = 0;
529         list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
530                 if (lte->offset_in_res + lte->size < lte->size ||
531                     lte->offset_in_res + lte->size > rspec->uncompressed_size ||
532                     lte->offset_in_res < cur_offset)
533                         goto invalid;
534
535                 cur_offset = lte->offset_in_res + lte->size;
536         }
537         return 0;
538
539 invalid:
540
541         ERROR("Invalid resource entry!");
542         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
543 }
544
545 /*
546  * Reads the lookup table from a WIM file.  Each entry specifies a stream that
547  * the WIM file contains, along with its location and SHA1 message digest.
548  *
549  * Saves lookup table entries for non-metadata streams in a hash table, and
550  * saves the metadata entry for each image in a special per-image location (the
551  * image_metadata array).
552  *
553  * Return values:
554  *      WIMLIB_ERR_SUCCESS (0)
555  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
556  *      WIMLIB_ERR_RESOURCE_NOT_FOUND
557  *
558  *      Or an error code caused by failure to read the lookup table into memory.
559  */
560 int
561 read_wim_lookup_table(WIMStruct *wim)
562 {
563         int ret;
564         size_t i;
565         size_t num_entries;
566         struct wim_lookup_table *table;
567         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
568         struct wim_resource_spec *cur_rspec;
569         void *buf;
570         bool back_to_back_pack;
571
572         DEBUG("Reading lookup table.");
573
574         /* Sanity check: lookup table entries are 50 bytes each.  */
575         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
576                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
577
578         /* Calculate number of entries in the lookup table.  */
579         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
580                       sizeof(struct wim_lookup_table_entry_disk);
581
582         /* Read the lookup table into a buffer.  */
583         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
584         if (ret)
585                 goto out;
586
587         /* Allocate a hash table to map SHA1 message digests into stream
588          * specifications.  This is the in-memory "lookup table".  */
589         table = new_lookup_table(num_entries * 2 + 1);
590         if (table == NULL) {
591                 ERROR("Not enough memory to read lookup table.");
592                 ret = WIMLIB_ERR_NOMEM;
593                 goto out_free_buf;
594         }
595
596         /* Allocate and initalize stream entries from the raw lookup table
597          * buffer.  */
598         wim->current_image = 0;
599         cur_rspec = NULL;
600         for (i = 0; i < num_entries; i++) {
601                 const struct wim_lookup_table_entry_disk *disk_entry =
602                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
603                 u16 part_number;
604                 struct wim_reshdr reshdr;
605
606                 get_wim_reshdr(&disk_entry->reshdr, &reshdr);
607
608                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
609                       "uncompressed_size=%"PRIu64", "
610                       "offset_in_wim=%"PRIu64", "
611                       "flags=0x%02x",
612                       reshdr.size_in_wim, reshdr.uncompressed_size,
613                       reshdr.offset_in_wim, reshdr.flags);
614
615                 if (wim->hdr.wim_version == WIM_VERSION_DEFAULT)
616                         reshdr.flags &= ~WIM_RESHDR_FLAG_PACKED_STREAMS;
617
618                 cur_entry = new_lookup_table_entry();
619                 if (cur_entry == NULL) {
620                         ERROR("Not enough memory to read lookup table!");
621                         ret = WIMLIB_ERR_NOMEM;
622                         goto out_free_lookup_table;
623                 }
624
625                 part_number = le16_to_cpu(disk_entry->part_number);
626                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
627                 copy_hash(cur_entry->hash, disk_entry->hash);
628
629                 if (part_number != wim->hdr.part_number) {
630                         WARNING("A lookup table entry in part %hu of the WIM "
631                                 "points to part %hu (ignoring it)",
632                                 wim->hdr.part_number, part_number);
633                         free_lookup_table_entry(cur_entry);
634                         continue;
635                 }
636
637                 if (!(reshdr.flags & (WIM_RESHDR_FLAG_PACKED_STREAMS |
638                                       WIM_RESHDR_FLAG_COMPRESSED))) {
639                         if (reshdr.uncompressed_size != reshdr.size_in_wim) {
640                                 ERROR("Invalid resource entry!");
641                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
642                                 goto out_free_cur_entry;
643                         }
644                 }
645
646                 back_to_back_pack = false;
647                 if (!(reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) ||
648                     cur_rspec == NULL ||
649                     (back_to_back_pack =
650                      ((reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
651                       reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER &&
652                       cur_rspec != NULL &&
653                       cur_rspec->size_in_wim != 0)))
654                 {
655                         /* Starting new run of streams that share the same WIM
656                          * resource.  */
657                         struct wim_lookup_table_entry *prev_entry = NULL;
658
659                         if (back_to_back_pack &&
660                             !list_empty(&cur_rspec->stream_list))
661                         {
662                                 prev_entry = list_entry(cur_rspec->stream_list.prev,
663                                                         struct wim_lookup_table_entry,
664                                                         rspec_node);
665                                 lte_unbind_wim_resource_spec(prev_entry);
666                                 cur_rspec->uncompressed_size -= prev_entry->size;
667                         }
668                         if (cur_rspec != NULL) {
669                                 ret = validate_resource(cur_rspec);
670                                 if (ret)
671                                         goto out_free_cur_entry;
672                         }
673
674                         /* Allocate the resource specification and initialize it
675                          * with values from the current stream entry.  */
676                         cur_rspec = MALLOC(sizeof(*cur_rspec));
677                         if (cur_rspec == NULL) {
678                                 ERROR("Not enough memory to read lookup table!");
679                                 ret = WIMLIB_ERR_NOMEM;
680                                 goto out_free_cur_entry;
681                         }
682                         wim_res_hdr_to_spec(&reshdr, wim, cur_rspec);
683
684                         /* If this is a packed run, the current stream entry may
685                          * specify a stream within the resource, and not the
686                          * resource itself.  Zero possibly irrelevant data until
687                          * it is read for certain.  */
688                         if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
689                                 cur_rspec->size_in_wim = 0;
690                                 cur_rspec->uncompressed_size = 0;
691                                 cur_rspec->offset_in_wim = 0;
692                         }
693
694                         if (prev_entry) {
695                                 lte_bind_wim_resource_spec(prev_entry, cur_rspec);
696                                 cur_rspec->uncompressed_size = prev_entry->size;
697                         }
698                 }
699
700                 if ((reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
701                     reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER)
702                 {
703                         /* Found the specification for the packed resource.
704                          * Transfer the values to the `struct
705                          * wim_resource_spec', and discard the current stream
706                          * since this lookup table entry did not, in fact,
707                          * correspond to a "stream".  */
708
709                         cur_rspec->offset_in_wim = reshdr.offset_in_wim;
710                         cur_rspec->size_in_wim = reshdr.size_in_wim;
711                         cur_rspec->flags = reshdr.flags;
712                         DEBUG("Full pack is %"PRIu64" compressed bytes "
713                               "at file offset %"PRIu64" (flags 0x%02x)",
714                               cur_rspec->size_in_wim,
715                               cur_rspec->offset_in_wim,
716                               cur_rspec->flags);
717                         free_lookup_table_entry(cur_entry);
718                         continue;
719                 }
720
721                 if (is_zero_hash(cur_entry->hash)) {
722                         free_lookup_table_entry(cur_entry);
723                         continue;
724                 }
725
726                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
727                         /* Continuing the pack with another stream.  */
728                         DEBUG("Continuing packed run with stream: "
729                               "%"PRIu64" uncompressed bytes @ resource offset %"PRIu64")",
730                               reshdr.size_in_wim, reshdr.offset_in_wim);
731                         cur_rspec->uncompressed_size += reshdr.size_in_wim;
732                 }
733
734                 lte_bind_wim_resource_spec(cur_entry, cur_rspec);
735                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
736                         /* In packed runs, the offset field is used for
737                          * in-resource offset, not the in-WIM offset, and the
738                          * size field is used for the uncompressed size, not the
739                          * compressed size.  */
740                         cur_entry->offset_in_res = reshdr.offset_in_wim;
741                         cur_entry->size = reshdr.size_in_wim;
742                         cur_entry->flags = reshdr.flags;
743                 } else {
744                         /* Normal case: The stream corresponds one-to-one with
745                          * the resource entry.  */
746                         cur_entry->offset_in_res = 0;
747                         cur_entry->size = reshdr.uncompressed_size;
748                         cur_entry->flags = reshdr.flags;
749                         cur_rspec = NULL;
750                 }
751
752                 if (cur_entry->flags & WIM_RESHDR_FLAG_METADATA) {
753                         /* Lookup table entry for a metadata resource */
754
755                         /* Metadata entries with no references must be ignored;
756                          * see for example the WinPE WIMs from the WAIK v2.1.
757                          * */
758                         if (cur_entry->refcnt == 0) {
759                                 free_lookup_table_entry(cur_entry);
760                                 continue;
761                         }
762
763                         if (cur_entry->refcnt != 1) {
764                                 if (wimlib_print_errors) {
765                                         ERROR("Found metadata resource with refcnt != 1:");
766                                         print_lookup_table_entry(cur_entry, stderr);
767                                 }
768                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
769                                 goto out_free_cur_entry;
770                         }
771
772                         if (wim->hdr.part_number != 1) {
773                                 WARNING("Ignoring metadata resource found in a "
774                                         "non-first part of the split WIM");
775                                 free_lookup_table_entry(cur_entry);
776                                 continue;
777                         }
778                         if (wim->current_image == wim->hdr.image_count) {
779                                 WARNING("The WIM header says there are %u images "
780                                         "in the WIM, but we found more metadata "
781                                         "resources than this (ignoring the extra)",
782                                         wim->hdr.image_count);
783                                 free_lookup_table_entry(cur_entry);
784                                 continue;
785                         }
786
787                         /* Notice very carefully:  We are assigning the metadata
788                          * resources in the exact order mirrored by their lookup
789                          * table entries on disk, which is the behavior of
790                          * Microsoft's software.  In particular, this overrides
791                          * the actual locations of the metadata resources
792                          * themselves in the WIM file as well as any information
793                          * written in the XML data. */
794                         DEBUG("Found metadata resource for image %u at "
795                               "offset %"PRIu64".",
796                               wim->current_image + 1,
797                               cur_entry->rspec->offset_in_wim);
798                         wim->image_metadata[
799                                 wim->current_image++]->metadata_lte = cur_entry;
800                         continue;
801                 }
802
803                 /* Lookup table entry for a stream that is not a metadata
804                  * resource.  */
805                 duplicate_entry = lookup_resource(table, cur_entry->hash);
806                 if (duplicate_entry) {
807                         if (wimlib_print_errors) {
808                                 WARNING("The WIM lookup table contains two entries with the "
809                                       "same SHA1 message digest!");
810                                 WARNING("The first entry is:");
811                                 print_lookup_table_entry(duplicate_entry, stderr);
812                                 WARNING("The second entry is:");
813                                 print_lookup_table_entry(cur_entry, stderr);
814                         }
815                         free_lookup_table_entry(cur_entry);
816                         continue;
817                 }
818
819                 /* Finally, insert the stream into the lookup table, keyed by
820                  * its SHA1 message digest.  */
821                 lookup_table_insert(table, cur_entry);
822         }
823
824         /* Validate the last resource.  */
825         if (cur_rspec != NULL) {
826                 ret = validate_resource(cur_rspec);
827                 if (ret)
828                         goto out_free_lookup_table;
829         }
830
831         if (wim->hdr.part_number == 1 && wim->current_image != wim->hdr.image_count) {
832                 WARNING("The header of \"%"TS"\" says there are %u images in\n"
833                         "          the WIM, but we only found %d metadata resources!  Acting as if\n"
834                         "          the header specified only %d images instead.",
835                         wim->filename, wim->hdr.image_count,
836                         wim->current_image, wim->current_image);
837                 for (int i = wim->current_image; i < wim->hdr.image_count; i++)
838                         put_image_metadata(wim->image_metadata[i], NULL);
839                 wim->hdr.image_count = wim->current_image;
840         }
841         DEBUG("Done reading lookup table.");
842         wim->lookup_table = table;
843         ret = 0;
844         goto out_free_buf;
845
846 out_free_cur_entry:
847         free_lookup_table_entry(cur_entry);
848 out_free_lookup_table:
849         free_lookup_table(table);
850 out_free_buf:
851         FREE(buf);
852 out:
853         wim->current_image = 0;
854         return ret;
855 }
856
857 static void
858 put_wim_lookup_table_entry(struct wim_lookup_table_entry_disk *disk_entry,
859                            const struct wim_reshdr *out_reshdr,
860                            u16 part_number, u32 refcnt, const u8 *hash)
861 {
862         put_wim_reshdr(out_reshdr, &disk_entry->reshdr);
863         disk_entry->part_number = cpu_to_le16(part_number);
864         disk_entry->refcnt = cpu_to_le32(refcnt);
865         copy_hash(disk_entry->hash, hash);
866 }
867
868 int
869 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
870                                         struct filedes *out_fd,
871                                         u16 part_number,
872                                         struct wim_reshdr *out_reshdr,
873                                         int write_resource_flags)
874 {
875         size_t table_size;
876         struct wim_lookup_table_entry *lte;
877         struct wim_lookup_table_entry_disk *table_buf;
878         struct wim_lookup_table_entry_disk *table_buf_ptr;
879         int ret;
880         u64 prev_res_offset_in_wim = ~0ULL;
881
882         table_size = 0;
883         list_for_each_entry(lte, stream_list, lookup_table_list) {
884                 table_size += sizeof(struct wim_lookup_table_entry_disk);
885
886                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
887                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
888                 {
889                         table_size += sizeof(struct wim_lookup_table_entry_disk);
890                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
891                 }
892         }
893
894         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
895               table_size, out_fd->offset);
896
897         table_buf = MALLOC(table_size);
898         if (table_buf == NULL) {
899                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
900                       table_size);
901                 return WIMLIB_ERR_NOMEM;
902         }
903         table_buf_ptr = table_buf;
904
905         prev_res_offset_in_wim = ~0ULL;
906         list_for_each_entry(lte, stream_list, lookup_table_list) {
907
908                 put_wim_lookup_table_entry(table_buf_ptr++,
909                                            &lte->out_reshdr,
910                                            part_number,
911                                            lte->out_refcnt,
912                                            lte->hash);
913                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
914                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
915                 {
916                         /* Put the main resource entry for the pack.  */
917
918                         struct wim_reshdr reshdr;
919
920                         reshdr.offset_in_wim = lte->out_res_offset_in_wim;
921                         reshdr.size_in_wim = lte->out_res_size_in_wim;
922                         reshdr.uncompressed_size = WIM_PACK_MAGIC_NUMBER;
923                         reshdr.flags = WIM_RESHDR_FLAG_PACKED_STREAMS;
924
925                         DEBUG("Putting main entry for pack: "
926                               "size_in_wim=%"PRIu64", "
927                               "offset_in_wim=%"PRIu64", "
928                               "uncompressed_size=%"PRIu64,
929                               reshdr.size_in_wim,
930                               reshdr.offset_in_wim,
931                               reshdr.uncompressed_size);
932
933                         put_wim_lookup_table_entry(table_buf_ptr++,
934                                                    &reshdr,
935                                                    part_number,
936                                                    1, zero_hash);
937                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
938                 }
939
940         }
941         wimlib_assert((u8*)table_buf_ptr - (u8*)table_buf == table_size);
942
943         /* Write the lookup table uncompressed.  Although wimlib can handle a
944          * compressed lookup table, MS software cannot.  */
945         ret = write_wim_resource_from_buffer(table_buf,
946                                              table_size,
947                                              WIM_RESHDR_FLAG_METADATA,
948                                              out_fd,
949                                              WIMLIB_COMPRESSION_TYPE_NONE,
950                                              0,
951                                              out_reshdr,
952                                              NULL,
953                                              write_resource_flags);
954         FREE(table_buf);
955         DEBUG("ret=%d", ret);
956         return ret;
957 }
958
959 int
960 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
961 {
962         lte->real_refcnt = 0;
963         return 0;
964 }
965
966 int
967 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
968 {
969         lte->out_refcnt = 0;
970         return 0;
971 }
972
973 int
974 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
975 {
976         if (lte->extracted_file != NULL) {
977                 FREE(lte->extracted_file);
978                 lte->extracted_file = NULL;
979         }
980         return 0;
981 }
982
983 void
984 print_lookup_table_entry(const struct wim_lookup_table_entry *lte, FILE *out)
985 {
986         if (lte == NULL) {
987                 tputc(T('\n'), out);
988                 return;
989         }
990
991
992         tprintf(T("Uncompressed size     = %"PRIu64" bytes\n"),
993                 lte->size);
994         if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
995                 tprintf(T("Offset                = %"PRIu64" bytes\n"),
996                         lte->offset_in_res);
997
998                 tprintf(T("Raw uncompressed size = %"PRIu64" bytes\n"),
999                         lte->rspec->uncompressed_size);
1000
1001                 tprintf(T("Raw compressed size   = %"PRIu64" bytes\n"),
1002                         lte->rspec->size_in_wim);
1003
1004                 tprintf(T("Raw offset            = %"PRIu64" bytes\n"),
1005                         lte->rspec->offset_in_wim);
1006         } else if (lte->resource_location == RESOURCE_IN_WIM) {
1007                 tprintf(T("Compressed size       = %"PRIu64" bytes\n"),
1008                         lte->rspec->size_in_wim);
1009
1010                 tprintf(T("Offset                = %"PRIu64" bytes\n"),
1011                         lte->rspec->offset_in_wim);
1012         }
1013
1014         tfprintf(out, T("Reference Count       = %u\n"), lte->refcnt);
1015
1016         if (lte->unhashed) {
1017                 tfprintf(out, T("(Unhashed: inode %p, stream_id = %u)\n"),
1018                          lte->back_inode, lte->back_stream_id);
1019         } else {
1020                 tfprintf(out, T("Hash                  = 0x"));
1021                 print_hash(lte->hash, out);
1022                 tputc(T('\n'), out);
1023         }
1024
1025         tfprintf(out, T("Flags                 = "));
1026         u8 flags = lte->flags;
1027         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
1028                 tfputs(T("WIM_RESHDR_FLAG_COMPRESSED, "), out);
1029         if (flags & WIM_RESHDR_FLAG_FREE)
1030                 tfputs(T("WIM_RESHDR_FLAG_FREE, "), out);
1031         if (flags & WIM_RESHDR_FLAG_METADATA)
1032                 tfputs(T("WIM_RESHDR_FLAG_METADATA, "), out);
1033         if (flags & WIM_RESHDR_FLAG_SPANNED)
1034                 tfputs(T("WIM_RESHDR_FLAG_SPANNED, "), out);
1035         if (flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1036                 tfputs(T("WIM_RESHDR_FLAG_PACKED_STREAMS, "), out);
1037         tputc(T('\n'), out);
1038         switch (lte->resource_location) {
1039         case RESOURCE_IN_WIM:
1040                 if (lte->rspec->wim->filename) {
1041                         tfprintf(out, T("WIM file              = `%"TS"'\n"),
1042                                  lte->rspec->wim->filename);
1043                 }
1044                 break;
1045 #ifdef __WIN32__
1046         case RESOURCE_WIN32_ENCRYPTED:
1047 #endif
1048         case RESOURCE_IN_FILE_ON_DISK:
1049                 tfprintf(out, T("File on Disk          = `%"TS"'\n"),
1050                          lte->file_on_disk);
1051                 break;
1052 #ifdef WITH_FUSE
1053         case RESOURCE_IN_STAGING_FILE:
1054                 tfprintf(out, T("Staging File          = `%"TS"'\n"),
1055                                 lte->staging_file_name);
1056                 break;
1057 #endif
1058         default:
1059                 break;
1060         }
1061         tputc(T('\n'), out);
1062 }
1063
1064 void
1065 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
1066                              struct wimlib_resource_entry *wentry)
1067 {
1068         memset(wentry, 0, sizeof(*wentry));
1069
1070         wentry->uncompressed_size = lte->size;
1071         if (lte->resource_location == RESOURCE_IN_WIM) {
1072                 wentry->part_number = lte->rspec->wim->hdr.part_number;
1073                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1074                         wentry->compressed_size = 0;
1075                         wentry->offset = lte->offset_in_res;
1076                 } else {
1077                         wentry->compressed_size = lte->rspec->size_in_wim;
1078                         wentry->offset = lte->rspec->offset_in_wim;
1079                 }
1080                 wentry->raw_resource_offset_in_wim = lte->rspec->offset_in_wim;
1081                 /*wentry->raw_resource_uncompressed_size = lte->rspec->uncompressed_size;*/
1082                 wentry->raw_resource_compressed_size = lte->rspec->size_in_wim;
1083         }
1084         copy_hash(wentry->sha1_hash, lte->hash);
1085         wentry->reference_count = lte->refcnt;
1086         wentry->is_compressed = (lte->flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
1087         wentry->is_metadata = (lte->flags & WIM_RESHDR_FLAG_METADATA) != 0;
1088         wentry->is_free = (lte->flags & WIM_RESHDR_FLAG_FREE) != 0;
1089         wentry->is_spanned = (lte->flags & WIM_RESHDR_FLAG_SPANNED) != 0;
1090         wentry->packed = (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) != 0;
1091 }
1092
1093 struct iterate_lte_context {
1094         wimlib_iterate_lookup_table_callback_t cb;
1095         void *user_ctx;
1096 };
1097
1098 static int
1099 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
1100 {
1101         struct iterate_lte_context *ctx = _ctx;
1102         struct wimlib_resource_entry entry;
1103
1104         lte_to_wimlib_resource_entry(lte, &entry);
1105         return (*ctx->cb)(&entry, ctx->user_ctx);
1106 }
1107
1108 /* API function documented in wimlib.h  */
1109 WIMLIBAPI int
1110 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
1111                             wimlib_iterate_lookup_table_callback_t cb,
1112                             void *user_ctx)
1113 {
1114         struct iterate_lte_context ctx = {
1115                 .cb = cb,
1116                 .user_ctx = user_ctx,
1117         };
1118         if (wim->hdr.part_number == 1) {
1119                 int ret;
1120                 for (int i = 0; i < wim->hdr.image_count; i++) {
1121                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
1122                                              &ctx);
1123                         if (ret)
1124                                 return ret;
1125                 }
1126         }
1127         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
1128 }
1129
1130 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
1131  * lookup table, or NULL if there is none.  */
1132 struct wim_lookup_table_entry *
1133 lookup_resource(const struct wim_lookup_table *table, const u8 hash[])
1134 {
1135         size_t i;
1136         struct wim_lookup_table_entry *lte;
1137         struct hlist_node *pos;
1138
1139         wimlib_assert(table != NULL);
1140         wimlib_assert(hash != NULL);
1141
1142         i = *(size_t*)hash % table->capacity;
1143         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
1144                 if (hashes_equal(hash, lte->hash))
1145                         return lte;
1146         return NULL;
1147 }
1148
1149 #ifdef WITH_FUSE
1150 /*
1151  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
1152  * given a path name.
1153  *
1154  * This is only for pre-resolved inodes.
1155  */
1156 int
1157 wim_pathname_to_stream(WIMStruct *wim,
1158                        const tchar *path,
1159                        int lookup_flags,
1160                        struct wim_dentry **dentry_ret,
1161                        struct wim_lookup_table_entry **lte_ret,
1162                        u16 *stream_idx_ret)
1163 {
1164         struct wim_dentry *dentry;
1165         struct wim_lookup_table_entry *lte;
1166         u16 stream_idx;
1167         const tchar *stream_name = NULL;
1168         struct wim_inode *inode;
1169         tchar *p = NULL;
1170
1171         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
1172                 stream_name = path_stream_name(path);
1173                 if (stream_name) {
1174                         p = (tchar*)stream_name - 1;
1175                         *p = T('\0');
1176                 }
1177         }
1178
1179         dentry = get_dentry(wim, path, WIMLIB_CASE_SENSITIVE);
1180         if (p)
1181                 *p = T(':');
1182         if (!dentry)
1183                 return -errno;
1184
1185         inode = dentry->d_inode;
1186
1187         if (!inode->i_resolved)
1188                 if (inode_resolve_ltes(inode, wim->lookup_table, false))
1189                         return -EIO;
1190
1191         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
1192               && inode_is_directory(inode))
1193                 return -EISDIR;
1194
1195         if (stream_name) {
1196                 struct wim_ads_entry *ads_entry;
1197                 u16 ads_idx;
1198                 ads_entry = inode_get_ads_entry(inode, stream_name,
1199                                                 &ads_idx);
1200                 if (ads_entry) {
1201                         stream_idx = ads_idx + 1;
1202                         lte = ads_entry->lte;
1203                         goto out;
1204                 } else {
1205                         return -ENOENT;
1206                 }
1207         } else {
1208                 lte = inode_unnamed_stream_resolved(inode, &stream_idx);
1209         }
1210 out:
1211         if (dentry_ret)
1212                 *dentry_ret = dentry;
1213         if (lte_ret)
1214                 *lte_ret = lte;
1215         if (stream_idx_ret)
1216                 *stream_idx_ret = stream_idx;
1217         return 0;
1218 }
1219 #endif
1220
1221 int
1222 resource_not_found_error(const struct wim_inode *inode, const u8 *hash)
1223 {
1224         if (wimlib_print_errors) {
1225                 ERROR("\"%"TS"\": resource not found", inode_first_full_path(inode));
1226                 tfprintf(stderr, T("        SHA-1 message digest of missing resource:\n        "));
1227                 print_hash(hash, stderr);
1228                 tputc(T('\n'), stderr);
1229         }
1230         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1231 }
1232
1233 /*
1234  * Resolve an inode's lookup table entries.
1235  *
1236  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
1237  * lookup table) with pointers directly to the lookup table entries.
1238  *
1239  * If @force is %false:
1240  *      If any needed SHA1 message digests are not found in the lookup table,
1241  *      WIMLIB_ERR_RESOURCE_NOT_FOUND is returned and the inode is left
1242  *      unmodified.
1243  * If @force is %true:
1244  *      If any needed SHA1 message digests are not found in the lookup table,
1245  *      new entries are allocated and inserted into the lookup table.
1246  */
1247 int
1248 inode_resolve_ltes(struct wim_inode *inode, struct wim_lookup_table *table,
1249                    bool force)
1250 {
1251         const u8 *hash;
1252
1253         if (!inode->i_resolved) {
1254                 struct wim_lookup_table_entry *lte, *ads_lte;
1255
1256                 /* Resolve the default file stream */
1257                 lte = NULL;
1258                 hash = inode->i_hash;
1259                 if (!is_zero_hash(hash)) {
1260                         lte = lookup_resource(table, hash);
1261                         if (!lte) {
1262                                 if (force) {
1263                                         lte = new_lookup_table_entry();
1264                                         if (!lte)
1265                                                 return WIMLIB_ERR_NOMEM;
1266                                         copy_hash(lte->hash, hash);
1267                                         lookup_table_insert(table, lte);
1268                                 } else {
1269                                         goto resource_not_found;
1270                                 }
1271                         }
1272                 }
1273
1274                 /* Resolve the alternate data streams */
1275                 struct wim_lookup_table_entry *ads_ltes[inode->i_num_ads];
1276                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1277                         struct wim_ads_entry *cur_entry;
1278
1279                         ads_lte = NULL;
1280                         cur_entry = &inode->i_ads_entries[i];
1281                         hash = cur_entry->hash;
1282                         if (!is_zero_hash(hash)) {
1283                                 ads_lte = lookup_resource(table, hash);
1284                                 if (!ads_lte) {
1285                                         if (force) {
1286                                                 ads_lte = new_lookup_table_entry();
1287                                                 if (!ads_lte)
1288                                                         return WIMLIB_ERR_NOMEM;
1289                                                 copy_hash(ads_lte->hash, hash);
1290                                                 lookup_table_insert(table, ads_lte);
1291                                         } else {
1292                                                 goto resource_not_found;
1293                                         }
1294                                 }
1295                         }
1296                         ads_ltes[i] = ads_lte;
1297                 }
1298                 inode->i_lte = lte;
1299                 for (u16 i = 0; i < inode->i_num_ads; i++)
1300                         inode->i_ads_entries[i].lte = ads_ltes[i];
1301                 inode->i_resolved = 1;
1302         }
1303         return 0;
1304
1305 resource_not_found:
1306         return resource_not_found_error(inode, hash);
1307 }
1308
1309 void
1310 inode_unresolve_ltes(struct wim_inode *inode)
1311 {
1312         if (inode->i_resolved) {
1313                 if (inode->i_lte)
1314                         copy_hash(inode->i_hash, inode->i_lte->hash);
1315                 else
1316                         zero_out_hash(inode->i_hash);
1317
1318                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1319                         if (inode->i_ads_entries[i].lte)
1320                                 copy_hash(inode->i_ads_entries[i].hash,
1321                                           inode->i_ads_entries[i].lte->hash);
1322                         else
1323                                 zero_out_hash(inode->i_ads_entries[i].hash);
1324                 }
1325                 inode->i_resolved = 0;
1326         }
1327 }
1328
1329 /*
1330  * Returns the lookup table entry for stream @stream_idx of the inode, where
1331  * stream_idx = 0 means the default un-named file stream, and stream_idx >= 1
1332  * corresponds to an alternate data stream.
1333  *
1334  * This works for both resolved and un-resolved inodes.
1335  */
1336 struct wim_lookup_table_entry *
1337 inode_stream_lte(const struct wim_inode *inode, unsigned stream_idx,
1338                  const struct wim_lookup_table *table)
1339 {
1340         if (inode->i_resolved)
1341                 return inode_stream_lte_resolved(inode, stream_idx);
1342         else
1343                 return inode_stream_lte_unresolved(inode, stream_idx, table);
1344 }
1345
1346 struct wim_lookup_table_entry *
1347 inode_unnamed_stream_resolved(const struct wim_inode *inode, u16 *stream_idx_ret)
1348 {
1349         wimlib_assert(inode->i_resolved);
1350         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1351                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1352                     !is_zero_hash(inode_stream_hash_resolved(inode, i)))
1353                 {
1354                         *stream_idx_ret = i;
1355                         return inode_stream_lte_resolved(inode, i);
1356                 }
1357         }
1358         *stream_idx_ret = 0;
1359         return NULL;
1360 }
1361
1362 struct wim_lookup_table_entry *
1363 inode_unnamed_lte_resolved(const struct wim_inode *inode)
1364 {
1365         u16 stream_idx;
1366         return inode_unnamed_stream_resolved(inode, &stream_idx);
1367 }
1368
1369 struct wim_lookup_table_entry *
1370 inode_unnamed_lte_unresolved(const struct wim_inode *inode,
1371                              const struct wim_lookup_table *table)
1372 {
1373         wimlib_assert(!inode->i_resolved);
1374         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1375                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1376                     !is_zero_hash(inode_stream_hash_unresolved(inode, i)))
1377                 {
1378                         return inode_stream_lte_unresolved(inode, i, table);
1379                 }
1380         }
1381         return NULL;
1382 }
1383
1384 /* Return the lookup table entry for the unnamed data stream of an inode, or
1385  * NULL if there is none.
1386  *
1387  * You'd think this would be easier than it actually is, since the unnamed data
1388  * stream should be the one referenced from the inode itself.  Alas, if there
1389  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
1390  * data stream in one of the alternate data streams instead of inside the WIM
1391  * dentry itself.  So we need to check the alternate data streams too.
1392  *
1393  * Also, note that a dentry may appear to have more than one unnamed stream, but
1394  * if the SHA1 message digest is all 0's then the corresponding stream does not
1395  * really "count" (this is the case for the inode's own file stream when the
1396  * file stream that should be there is actually in one of the alternate stream
1397  * entries.).  This is despite the fact that we may need to extract such a
1398  * missing entry as an empty file or empty named data stream.
1399  */
1400 struct wim_lookup_table_entry *
1401 inode_unnamed_lte(const struct wim_inode *inode,
1402                   const struct wim_lookup_table *table)
1403 {
1404         if (inode->i_resolved)
1405                 return inode_unnamed_lte_resolved(inode);
1406         else
1407                 return inode_unnamed_lte_unresolved(inode, table);
1408 }
1409
1410 /* Returns the SHA1 message digest of the unnamed data stream of a WIM inode, or
1411  * 'zero_hash' if the unnamed data stream is missing has all zeroes in its SHA1
1412  * message digest field.  */
1413 const u8 *
1414 inode_unnamed_stream_hash(const struct wim_inode *inode)
1415 {
1416         const u8 *hash;
1417
1418         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1419                 if (inode_stream_name_nbytes(inode, i) == 0) {
1420                         hash = inode_stream_hash(inode, i);
1421                         if (!is_zero_hash(hash))
1422                                 return hash;
1423                 }
1424         }
1425         return zero_hash;
1426 }
1427
1428 struct wim_lookup_table_entry **
1429 retrieve_lte_pointer(struct wim_lookup_table_entry *lte)
1430 {
1431         wimlib_assert(lte->unhashed);
1432         struct wim_inode *inode = lte->back_inode;
1433         u32 stream_id = lte->back_stream_id;
1434         if (stream_id == 0)
1435                 return &inode->i_lte;
1436         else
1437                 for (u16 i = 0; i < inode->i_num_ads; i++)
1438                         if (inode->i_ads_entries[i].stream_id == stream_id)
1439                                 return &inode->i_ads_entries[i].lte;
1440         wimlib_assert(0);
1441         return NULL;
1442 }
1443
1444 /* Calculate the SHA1 message digest of a stream and move it from the list of
1445  * unhashed streams to the stream lookup table, possibly joining it with an
1446  * existing lookup table entry for an identical stream.
1447  *
1448  * @lte:  An unhashed lookup table entry.
1449  * @lookup_table:  Lookup table for the WIM.
1450  * @lte_ret:  On success, write a pointer to the resulting lookup table
1451  *            entry to this location.  This will be the same as @lte
1452  *            if it was inserted into the lookup table, or different if
1453  *            a duplicate stream was found.
1454  *
1455  * Returns 0 on success; nonzero if there is an error reading the stream.
1456  */
1457 int
1458 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1459                      struct wim_lookup_table *lookup_table,
1460                      struct wim_lookup_table_entry **lte_ret)
1461 {
1462         int ret;
1463         struct wim_lookup_table_entry *duplicate_lte;
1464         struct wim_lookup_table_entry **back_ptr;
1465
1466         wimlib_assert(lte->unhashed);
1467
1468         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1469          * union with the SHA1 message digest and will no longer be valid once
1470          * the SHA1 has been calculated. */
1471         back_ptr = retrieve_lte_pointer(lte);
1472
1473         ret = sha1_stream(lte);
1474         if (ret)
1475                 return ret;
1476
1477         /* Look for a duplicate stream */
1478         duplicate_lte = lookup_resource(lookup_table, lte->hash);
1479         list_del(&lte->unhashed_list);
1480         if (duplicate_lte) {
1481                 /* We have a duplicate stream.  Transfer the reference counts
1482                  * from this stream to the duplicate and update the reference to
1483                  * this stream (in an inode or ads_entry) to point to the
1484                  * duplicate.  The caller is responsible for freeing @lte if
1485                  * needed.  */
1486                 wimlib_assert(!(duplicate_lte->unhashed));
1487                 wimlib_assert(duplicate_lte->size == lte->size);
1488                 duplicate_lte->refcnt += lte->refcnt;
1489                 lte->refcnt = 0;
1490                 *back_ptr = duplicate_lte;
1491                 lte = duplicate_lte;
1492         } else {
1493                 /* No duplicate stream, so we need to insert this stream into
1494                  * the lookup table and treat it as a hashed stream. */
1495                 lookup_table_insert(lookup_table, lte);
1496                 lte->unhashed = 0;
1497         }
1498         *lte_ret = lte;
1499         return 0;
1500 }
1501
1502 static int
1503 lte_clone_if_new(struct wim_lookup_table_entry *lte, void *_lookup_table)
1504 {
1505         struct wim_lookup_table *lookup_table = _lookup_table;
1506
1507         if (lookup_resource(lookup_table, lte->hash))
1508                 return 0;  /*  Resource already present.  */
1509
1510         lte = clone_lookup_table_entry(lte);
1511         if (lte == NULL)
1512                 return WIMLIB_ERR_NOMEM;
1513         lte->out_refcnt = 1;
1514         lookup_table_insert(lookup_table, lte);
1515         return 0;
1516 }
1517
1518 static int
1519 lte_delete_if_new(struct wim_lookup_table_entry *lte, void *_lookup_table)
1520 {
1521         struct wim_lookup_table *lookup_table = _lookup_table;
1522
1523         if (lte->out_refcnt) {
1524                 lookup_table_unlink(lookup_table, lte);
1525                 free_lookup_table_entry(lte);
1526         }
1527         return 0;
1528 }
1529
1530 /* API function documented in wimlib.h  */
1531 WIMLIBAPI int
1532 wimlib_reference_resources(WIMStruct *wim,
1533                            WIMStruct **resource_wims, unsigned num_resource_wims,
1534                            int ref_flags)
1535 {
1536         int ret;
1537         unsigned i;
1538
1539         if (wim == NULL)
1540                 return WIMLIB_ERR_INVALID_PARAM;
1541
1542         if (num_resource_wims != 0 && resource_wims == NULL)
1543                 return WIMLIB_ERR_INVALID_PARAM;
1544
1545         for (i = 0; i < num_resource_wims; i++)
1546                 if (resource_wims[i] == NULL)
1547                         return WIMLIB_ERR_INVALID_PARAM;
1548
1549         for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1550
1551         for (i = 0; i < num_resource_wims; i++) {
1552                 ret = for_lookup_table_entry(resource_wims[i]->lookup_table,
1553                                              lte_clone_if_new,
1554                                              wim->lookup_table);
1555                 if (ret)
1556                         goto out_rollback;
1557         }
1558         return 0;
1559
1560 out_rollback:
1561         for_lookup_table_entry(wim->lookup_table, lte_delete_if_new,
1562                                wim->lookup_table);
1563         return ret;
1564 }
1565
1566 static int
1567 reference_resource_paths(WIMStruct *wim,
1568                          const tchar * const *resource_wimfiles,
1569                          unsigned num_resource_wimfiles,
1570                          int ref_flags,
1571                          int open_flags,
1572                          wimlib_progress_func_t progress_func)
1573 {
1574         WIMStruct **resource_wims;
1575         unsigned i;
1576         int ret;
1577
1578         resource_wims = CALLOC(num_resource_wimfiles, sizeof(resource_wims[0]));
1579         if (!resource_wims)
1580                 return WIMLIB_ERR_NOMEM;
1581
1582         for (i = 0; i < num_resource_wimfiles; i++) {
1583                 DEBUG("Referencing resources from path \"%"TS"\"",
1584                       resource_wimfiles[i]);
1585                 ret = wimlib_open_wim(resource_wimfiles[i], open_flags,
1586                                       &resource_wims[i], progress_func);
1587                 if (ret)
1588                         goto out_free_resource_wims;
1589         }
1590
1591         ret = wimlib_reference_resources(wim, resource_wims,
1592                                          num_resource_wimfiles, ref_flags);
1593         if (ret)
1594                 goto out_free_resource_wims;
1595
1596         for (i = 0; i < num_resource_wimfiles; i++)
1597                 list_add_tail(&resource_wims[i]->subwim_node, &wim->subwims);
1598
1599         ret = 0;
1600         goto out_free_array;
1601
1602 out_free_resource_wims:
1603         for (i = 0; i < num_resource_wimfiles; i++)
1604                 wimlib_free(resource_wims[i]);
1605 out_free_array:
1606         FREE(resource_wims);
1607         return ret;
1608 }
1609
1610 static int
1611 reference_resource_glob(WIMStruct *wim, const tchar *refglob,
1612                         int ref_flags, int open_flags,
1613                         wimlib_progress_func_t progress_func)
1614 {
1615         glob_t globbuf;
1616         int ret;
1617
1618         /* Note: glob() is replaced in Windows native builds.  */
1619         ret = tglob(refglob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1620         if (ret) {
1621                 if (ret == GLOB_NOMATCH) {
1622                         if (ref_flags & WIMLIB_REF_FLAG_GLOB_ERR_ON_NOMATCH) {
1623                                 ERROR("Found no files for glob \"%"TS"\"", refglob);
1624                                 return WIMLIB_ERR_GLOB_HAD_NO_MATCHES;
1625                         } else {
1626                                 return reference_resource_paths(wim,
1627                                                                 &refglob,
1628                                                                 1,
1629                                                                 ref_flags,
1630                                                                 open_flags,
1631                                                                 progress_func);
1632                         }
1633                 } else {
1634                         ERROR_WITH_ERRNO("Failed to process glob \"%"TS"\"", refglob);
1635                         if (ret == GLOB_NOSPACE)
1636                                 return WIMLIB_ERR_NOMEM;
1637                         else
1638                                 return WIMLIB_ERR_READ;
1639                 }
1640         }
1641
1642         ret = reference_resource_paths(wim,
1643                                        (const tchar * const *)globbuf.gl_pathv,
1644                                        globbuf.gl_pathc,
1645                                        ref_flags,
1646                                        open_flags,
1647                                        progress_func);
1648         globfree(&globbuf);
1649         return ret;
1650 }
1651
1652 /* API function documented in wimlib.h  */
1653 WIMLIBAPI int
1654 wimlib_reference_resource_files(WIMStruct *wim,
1655                                 const tchar * const * resource_wimfiles_or_globs,
1656                                 unsigned count,
1657                                 int ref_flags,
1658                                 int open_flags,
1659                                 wimlib_progress_func_t progress_func)
1660 {
1661         unsigned i;
1662         int ret;
1663
1664         if (ref_flags & WIMLIB_REF_FLAG_GLOB_ENABLE) {
1665                 for (i = 0; i < count; i++) {
1666                         ret = reference_resource_glob(wim,
1667                                                       resource_wimfiles_or_globs[i],
1668                                                       ref_flags,
1669                                                       open_flags,
1670                                                       progress_func);
1671                         if (ret)
1672                                 return ret;
1673                 }
1674                 return 0;
1675         } else {
1676                 return reference_resource_paths(wim, resource_wimfiles_or_globs,
1677                                                 count, ref_flags,
1678                                                 open_flags, progress_func);
1679         }
1680 }