]> wimlib.net Git - wimlib/blob - src/lookup_table.c
wimlib: strict checks for unassigned flags
[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/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         DEBUG("Freeing lookup table.");
98         if (table == NULL)
99                 return;
100
101         if (table->array) {
102                 for_lookup_table_entry(table,
103                                        do_free_lookup_table_entry,
104                                        NULL);
105                 FREE(table->array);
106         }
107         FREE(table);
108 }
109
110 struct wim_lookup_table_entry *
111 new_lookup_table_entry(void)
112 {
113         struct wim_lookup_table_entry *lte;
114
115         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
116         if (lte == NULL)
117                 return NULL;
118
119         lte->refcnt = 1;
120
121         /* lte->resource_location = RESOURCE_NONEXISTENT  */
122         BUILD_BUG_ON(RESOURCE_NONEXISTENT != 0);
123
124         return lte;
125 }
126
127 struct wim_lookup_table_entry *
128 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
129 {
130         struct wim_lookup_table_entry *new;
131
132         new = memdup(old, sizeof(struct wim_lookup_table_entry));
133         if (new == NULL)
134                 return NULL;
135
136         new->extracted_file = NULL;
137         switch (new->resource_location) {
138         case RESOURCE_IN_WIM:
139                 list_add(&new->rspec_node, &new->rspec->stream_list);
140                 break;
141
142         case RESOURCE_IN_FILE_ON_DISK:
143 #ifdef __WIN32__
144         case RESOURCE_WIN32_ENCRYPTED:
145 #endif
146 #ifdef WITH_FUSE
147         case RESOURCE_IN_STAGING_FILE:
148                 BUILD_BUG_ON((void*)&old->file_on_disk !=
149                              (void*)&old->staging_file_name);
150 #endif
151                 new->file_on_disk = TSTRDUP(old->file_on_disk);
152                 if (new->file_on_disk == NULL)
153                         goto out_free;
154                 break;
155         case RESOURCE_IN_ATTACHED_BUFFER:
156                 new->attached_buffer = memdup(old->attached_buffer, old->size);
157                 if (new->attached_buffer == NULL)
158                         goto out_free;
159                 break;
160 #ifdef WITH_NTFS_3G
161         case RESOURCE_IN_NTFS_VOLUME:
162                 if (old->ntfs_loc) {
163                         struct ntfs_location *loc;
164                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
165                         if (loc == NULL)
166                                 goto out_free;
167                         loc->path = NULL;
168                         loc->stream_name = NULL;
169                         new->ntfs_loc = loc;
170                         loc->path = STRDUP(old->ntfs_loc->path);
171                         if (loc->path == NULL)
172                                 goto out_free;
173                         if (loc->stream_name_nchars != 0) {
174                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
175                                                           loc->stream_name_nchars * 2);
176                                 if (loc->stream_name == NULL)
177                                         goto out_free;
178                         }
179                 }
180                 break;
181 #endif
182         default:
183                 break;
184         }
185         return new;
186
187 out_free:
188         free_lookup_table_entry(new);
189         return NULL;
190 }
191
192 void
193 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
194 {
195         if (lte) {
196                 switch (lte->resource_location) {
197                 case RESOURCE_IN_WIM:
198                         list_del(&lte->rspec_node);
199                         if (list_empty(&lte->rspec->stream_list))
200                                 FREE(lte->rspec);
201                         break;
202                 case RESOURCE_IN_FILE_ON_DISK:
203         #ifdef __WIN32__
204                 case RESOURCE_WIN32_ENCRYPTED:
205         #endif
206         #ifdef WITH_FUSE
207                 case RESOURCE_IN_STAGING_FILE:
208                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
209                                      (void*)&lte->staging_file_name);
210         #endif
211                 case RESOURCE_IN_ATTACHED_BUFFER:
212                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
213                                      (void*)&lte->attached_buffer);
214                         FREE(lte->file_on_disk);
215                         break;
216 #ifdef WITH_NTFS_3G
217                 case RESOURCE_IN_NTFS_VOLUME:
218                         if (lte->ntfs_loc) {
219                                 FREE(lte->ntfs_loc->path);
220                                 FREE(lte->ntfs_loc->stream_name);
221                                 FREE(lte->ntfs_loc);
222                         }
223                         break;
224 #endif
225                 default:
226                         break;
227                 }
228                 FREE(lte);
229         }
230 }
231
232 /* Decrements the reference count for the lookup table entry @lte.  If its
233  * reference count reaches 0, it is unlinked from the lookup table.  If,
234  * furthermore, the entry has no opened file descriptors associated with it, the
235  * entry is freed.  */
236 void
237 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
238                      struct wim_lookup_table *table)
239 {
240         wimlib_assert(lte->refcnt != 0);
241
242         if (--lte->refcnt == 0) {
243                 if (lte->unhashed) {
244                         list_del(&lte->unhashed_list);
245                 #ifdef WITH_FUSE
246                         /* If the stream has been extracted to a staging file
247                          * for a FUSE mount, unlink the staging file.  (Note
248                          * that there still may be open file descriptors to it.)
249                          * */
250                         if (lte->resource_location == RESOURCE_IN_STAGING_FILE)
251                                 unlink(lte->staging_file_name);
252                 #endif
253                 } else {
254                         lookup_table_unlink(table, lte);
255                 }
256
257                 /* If FUSE mounts are enabled, we don't actually free the entry
258                  * until the last file descriptor has been closed by
259                  * lte_decrement_num_opened_fds().  */
260 #ifdef WITH_FUSE
261                 if (lte->num_opened_fds == 0)
262 #endif
263                         free_lookup_table_entry(lte);
264         }
265 }
266
267 #ifdef WITH_FUSE
268 void
269 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
270 {
271         wimlib_assert(lte->num_opened_fds != 0);
272
273         if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
274                 free_lookup_table_entry(lte);
275 }
276 #endif
277
278 static void
279 lookup_table_insert_raw(struct wim_lookup_table *table,
280                         struct wim_lookup_table_entry *lte)
281 {
282         size_t i = lte->hash_short % table->capacity;
283
284         hlist_add_head(&lte->hash_list, &table->array[i]);
285 }
286
287 static void
288 enlarge_lookup_table(struct wim_lookup_table *table)
289 {
290         size_t old_capacity, new_capacity;
291         struct hlist_head *old_array, *new_array;
292         struct wim_lookup_table_entry *lte;
293         struct hlist_node *cur, *tmp;
294         size_t i;
295
296         old_capacity = table->capacity;
297         new_capacity = old_capacity * 2;
298         new_array = CALLOC(new_capacity, sizeof(struct hlist_head));
299         if (new_array == NULL)
300                 return;
301         old_array = table->array;
302         table->array = new_array;
303         table->capacity = new_capacity;
304
305         for (i = 0; i < old_capacity; i++) {
306                 hlist_for_each_entry_safe(lte, cur, tmp, &old_array[i], hash_list) {
307                         hlist_del(&lte->hash_list);
308                         lookup_table_insert_raw(table, lte);
309                 }
310         }
311         FREE(old_array);
312 }
313
314 /* Inserts an entry into the lookup table.  */
315 void
316 lookup_table_insert(struct wim_lookup_table *table,
317                     struct wim_lookup_table_entry *lte)
318 {
319         lookup_table_insert_raw(table, lte);
320         if (++table->num_entries > table->capacity)
321                 enlarge_lookup_table(table);
322 }
323
324 /* Unlinks a lookup table entry from the table; does not free it.  */
325 void
326 lookup_table_unlink(struct wim_lookup_table *table,
327                     struct wim_lookup_table_entry *lte)
328 {
329         wimlib_assert(!lte->unhashed);
330         wimlib_assert(table->num_entries != 0);
331
332         hlist_del(&lte->hash_list);
333         table->num_entries--;
334 }
335
336 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
337  * lookup table, or NULL if there is none.  */
338 struct wim_lookup_table_entry *
339 lookup_stream(const struct wim_lookup_table *table, const u8 hash[])
340 {
341         size_t i;
342         struct wim_lookup_table_entry *lte;
343         struct hlist_node *pos;
344
345         i = *(size_t*)hash % table->capacity;
346         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
347                 if (hashes_equal(hash, lte->hash))
348                         return lte;
349         return NULL;
350 }
351
352 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
353  * return nonzero if any call to the function returns nonzero. */
354 int
355 for_lookup_table_entry(struct wim_lookup_table *table,
356                        int (*visitor)(struct wim_lookup_table_entry *, void *),
357                        void *arg)
358 {
359         struct wim_lookup_table_entry *lte;
360         struct hlist_node *pos, *tmp;
361         int ret;
362
363         for (size_t i = 0; i < table->capacity; i++) {
364                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
365                                           hash_list)
366                 {
367                         ret = visitor(lte, arg);
368                         if (ret)
369                                 return ret;
370                 }
371         }
372         return 0;
373 }
374
375 /* qsort() callback that sorts streams (represented by `struct
376  * wim_lookup_table_entry's) into an order optimized for reading.
377  *
378  * Sorting is done primarily by resource location, then secondarily by a
379  * per-resource location order.  For example, resources in WIM files are sorted
380  * primarily by part number, then secondarily by offset, as to implement optimal
381  * reading of either a standalone or split WIM.  */
382 static int
383 cmp_streams_by_sequential_order(const void *p1, const void *p2)
384 {
385         const struct wim_lookup_table_entry *lte1, *lte2;
386         int v;
387         WIMStruct *wim1, *wim2;
388
389         lte1 = *(const struct wim_lookup_table_entry**)p1;
390         lte2 = *(const struct wim_lookup_table_entry**)p2;
391
392         v = (int)lte1->resource_location - (int)lte2->resource_location;
393
394         /* Different resource locations?  */
395         if (v)
396                 return v;
397
398         switch (lte1->resource_location) {
399         case RESOURCE_IN_WIM:
400                 wim1 = lte1->rspec->wim;
401                 wim2 = lte2->rspec->wim;
402
403                 /* Different (possibly split) WIMs?  */
404                 if (wim1 != wim2) {
405                         v = memcmp(wim1->hdr.guid, wim2->hdr.guid, WIM_GID_LEN);
406                         if (v)
407                                 return v;
408                 }
409
410                 /* Different part numbers in the same WIM?  */
411                 v = (int)wim1->hdr.part_number - (int)wim2->hdr.part_number;
412                 if (v)
413                         return v;
414
415                 if (lte1->rspec->offset_in_wim != lte2->rspec->offset_in_wim)
416                         return cmp_u64(lte1->rspec->offset_in_wim,
417                                        lte2->rspec->offset_in_wim);
418
419                 return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
420
421         case RESOURCE_IN_FILE_ON_DISK:
422 #ifdef WITH_FUSE
423         case RESOURCE_IN_STAGING_FILE:
424 #endif
425 #ifdef __WIN32__
426         case RESOURCE_WIN32_ENCRYPTED:
427 #endif
428                 /* Compare files by path: just a heuristic that will place files
429                  * in the same directory next to each other.  */
430                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
431 #ifdef WITH_NTFS_3G
432         case RESOURCE_IN_NTFS_VOLUME:
433                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
434 #endif
435         default:
436                 /* No additional sorting order defined for this resource
437                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
438                  * everything equal to each other.  */
439                 return 0;
440         }
441 }
442
443 int
444 sort_stream_list(struct list_head *stream_list,
445                  size_t list_head_offset,
446                  int (*compar)(const void *, const void*))
447 {
448         struct list_head *cur;
449         struct wim_lookup_table_entry **array;
450         size_t i;
451         size_t array_size;
452         size_t num_streams = 0;
453
454         list_for_each(cur, stream_list)
455                 num_streams++;
456
457         if (num_streams <= 1)
458                 return 0;
459
460         array_size = num_streams * sizeof(array[0]);
461         array = MALLOC(array_size);
462         if (array == NULL)
463                 return WIMLIB_ERR_NOMEM;
464
465         cur = stream_list->next;
466         for (i = 0; i < num_streams; i++) {
467                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
468                                                             list_head_offset);
469                 cur = cur->next;
470         }
471
472         qsort(array, num_streams, sizeof(array[0]), compar);
473
474         INIT_LIST_HEAD(stream_list);
475         for (i = 0; i < num_streams; i++) {
476                 list_add_tail((struct list_head*)
477                                ((u8*)array[i] + list_head_offset),
478                               stream_list);
479         }
480         FREE(array);
481         return 0;
482 }
483
484 /* Sort the specified list of streams in an order optimized for reading.  */
485 int
486 sort_stream_list_by_sequential_order(struct list_head *stream_list,
487                                      size_t list_head_offset)
488 {
489         return sort_stream_list(stream_list, list_head_offset,
490                                 cmp_streams_by_sequential_order);
491 }
492
493
494 static int
495 add_lte_to_array(struct wim_lookup_table_entry *lte,
496                  void *_pp)
497 {
498         struct wim_lookup_table_entry ***pp = _pp;
499         *(*pp)++ = lte;
500         return 0;
501 }
502
503 /* Iterate through the lookup table entries, but first sort them by stream
504  * offset in the WIM.  Caution: this is intended to be used when the stream
505  * offset field has actually been set. */
506 int
507 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
508                                   int (*visitor)(struct wim_lookup_table_entry *,
509                                                  void *),
510                                   void *arg)
511 {
512         struct wim_lookup_table_entry **lte_array, **p;
513         size_t num_streams = table->num_entries;
514         int ret;
515
516         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
517         if (!lte_array)
518                 return WIMLIB_ERR_NOMEM;
519         p = lte_array;
520         for_lookup_table_entry(table, add_lte_to_array, &p);
521
522         wimlib_assert(p == lte_array + num_streams);
523
524         qsort(lte_array, num_streams, sizeof(lte_array[0]),
525               cmp_streams_by_sequential_order);
526         ret = 0;
527         for (size_t i = 0; i < num_streams; i++) {
528                 ret = visitor(lte_array[i], arg);
529                 if (ret)
530                         break;
531         }
532         FREE(lte_array);
533         return ret;
534 }
535
536 /* On-disk format of a WIM lookup table entry (stream entry). */
537 struct wim_lookup_table_entry_disk {
538         /* Size, offset, and flags of the stream.  */
539         struct wim_reshdr_disk reshdr;
540
541         /* Which part of the split WIM this stream is in; indexed from 1. */
542         le16 part_number;
543
544         /* Reference count of this stream over all WIM images. */
545         le32 refcnt;
546
547         /* SHA1 message digest of the uncompressed data of this stream, or
548          * optionally all zeroes if this stream is of zero length. */
549         u8 hash[SHA1_HASH_SIZE];
550 } _packed_attribute;
551
552 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
553
554 /* Validate the size and location of a WIM resource.  */
555 static int
556 validate_resource(const struct wim_resource_spec *rspec)
557 {
558         struct wim_lookup_table_entry *lte;
559         u64 cur_offset;
560
561         /* Verify that calculating the offset of the end of the resource doesn't
562          * overflow.  */
563         if (rspec->offset_in_wim + rspec->size_in_wim < rspec->size_in_wim)
564                 goto invalid;
565
566         /* Verify that each stream in the resource has a valid offset and size,
567          * and that no streams overlap, and that the streams were added in order
568          * of increasing offset.  */
569         cur_offset = 0;
570         list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
571                 if (lte->offset_in_res + lte->size < lte->size ||
572                     lte->offset_in_res + lte->size > rspec->uncompressed_size ||
573                     lte->offset_in_res < cur_offset)
574                         goto invalid;
575
576                 cur_offset = lte->offset_in_res + lte->size;
577         }
578         return 0;
579
580 invalid:
581
582         ERROR("Invalid resource entry!");
583         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
584 }
585
586 /*
587  * Reads the lookup table from a WIM file.  Each entry specifies a stream that
588  * the WIM file contains, along with its location and SHA1 message digest.
589  *
590  * Saves lookup table entries for non-metadata streams in a hash table, and
591  * saves the metadata entry for each image in a special per-image location (the
592  * image_metadata array).
593  *
594  * Return values:
595  *      WIMLIB_ERR_SUCCESS (0)
596  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
597  *      WIMLIB_ERR_RESOURCE_NOT_FOUND
598  *
599  *      Or an error code caused by failure to read the lookup table into memory.
600  */
601 int
602 read_wim_lookup_table(WIMStruct *wim)
603 {
604         int ret;
605         size_t i;
606         size_t num_entries;
607         struct wim_lookup_table *table;
608         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
609         struct wim_resource_spec *cur_rspec;
610         void *buf;
611         bool back_to_back_pack;
612
613         DEBUG("Reading lookup table.");
614
615         /* Sanity check: lookup table entries are 50 bytes each.  */
616         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
617                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
618
619         /* Calculate number of entries in the lookup table.  */
620         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
621                       sizeof(struct wim_lookup_table_entry_disk);
622
623         /* Read the lookup table into a buffer.  */
624         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
625         if (ret)
626                 goto out;
627
628         /* Allocate a hash table to map SHA1 message digests into stream
629          * specifications.  This is the in-memory "lookup table".  */
630         table = new_lookup_table(num_entries * 2 + 1);
631         if (table == NULL) {
632                 ERROR("Not enough memory to read lookup table.");
633                 ret = WIMLIB_ERR_NOMEM;
634                 goto out_free_buf;
635         }
636
637         /* Allocate and initalize stream entries from the raw lookup table
638          * buffer.  */
639         wim->current_image = 0;
640         cur_rspec = NULL;
641         for (i = 0; i < num_entries; i++) {
642                 const struct wim_lookup_table_entry_disk *disk_entry =
643                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
644                 u16 part_number;
645                 struct wim_reshdr reshdr;
646
647                 get_wim_reshdr(&disk_entry->reshdr, &reshdr);
648
649                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
650                       "uncompressed_size=%"PRIu64", "
651                       "offset_in_wim=%"PRIu64", "
652                       "flags=0x%02x",
653                       reshdr.size_in_wim, reshdr.uncompressed_size,
654                       reshdr.offset_in_wim, reshdr.flags);
655
656                 if (wim->hdr.wim_version == WIM_VERSION_DEFAULT)
657                         reshdr.flags &= ~WIM_RESHDR_FLAG_PACKED_STREAMS;
658
659                 cur_entry = new_lookup_table_entry();
660                 if (cur_entry == NULL) {
661                         ERROR("Not enough memory to read lookup table!");
662                         ret = WIMLIB_ERR_NOMEM;
663                         goto err;
664                 }
665
666                 part_number = le16_to_cpu(disk_entry->part_number);
667                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
668                 copy_hash(cur_entry->hash, disk_entry->hash);
669
670                 if (part_number != wim->hdr.part_number) {
671                         WARNING("A lookup table entry in part %hu of the WIM "
672                                 "points to part %hu (ignoring it)",
673                                 wim->hdr.part_number, part_number);
674                         free_lookup_table_entry(cur_entry);
675                         continue;
676                 }
677
678                 if (!(reshdr.flags & (WIM_RESHDR_FLAG_PACKED_STREAMS |
679                                       WIM_RESHDR_FLAG_COMPRESSED))) {
680                         if (reshdr.uncompressed_size != reshdr.size_in_wim) {
681                                 ERROR("Invalid resource entry!");
682                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
683                                 goto err;
684                         }
685                 }
686
687                 back_to_back_pack = false;
688                 if (!(reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) ||
689                     cur_rspec == NULL ||
690                     (back_to_back_pack =
691                      ((reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
692                       reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER &&
693                       cur_rspec != NULL &&
694                       cur_rspec->size_in_wim != 0)))
695                 {
696                         /* Starting new run of streams that share the same WIM
697                          * resource.  */
698                         struct wim_lookup_table_entry *prev_entry = NULL;
699
700                         if (back_to_back_pack &&
701                             !list_empty(&cur_rspec->stream_list))
702                         {
703                                 prev_entry = list_entry(cur_rspec->stream_list.prev,
704                                                         struct wim_lookup_table_entry,
705                                                         rspec_node);
706                                 lte_unbind_wim_resource_spec(prev_entry);
707                         }
708                         if (cur_rspec != NULL) {
709                                 ret = validate_resource(cur_rspec);
710                                 if (ret)
711                                         goto err;
712                         }
713
714                         /* Allocate the resource specification and initialize it
715                          * with values from the current stream entry.  */
716                         cur_rspec = MALLOC(sizeof(*cur_rspec));
717                         if (cur_rspec == NULL) {
718                                 ERROR("Not enough memory to read lookup table!");
719                                 ret = WIMLIB_ERR_NOMEM;
720                                 goto err;
721                         }
722                         wim_res_hdr_to_spec(&reshdr, wim, cur_rspec);
723
724                         /* If this is a packed run, the current stream entry may
725                          * specify a stream within the resource, and not the
726                          * resource itself.  Zero possibly irrelevant data until
727                          * it is read for certain.  (Note that the computation
728                          * of 'back_to_back_pack' tests if 'size_in_wim' is
729                          * nonzero to see if the resource info has been read;
730                          * hence we need to set it to 0 here.)  */
731                         if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
732                                 cur_rspec->size_in_wim = 0;
733                                 cur_rspec->uncompressed_size = 0;
734                                 cur_rspec->offset_in_wim = 0;
735                         }
736
737                         if (prev_entry)
738                                 lte_bind_wim_resource_spec(prev_entry, cur_rspec);
739                 }
740
741                 if ((reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
742                     reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER)
743                 {
744                         /* Found the specification for the packed resource.
745                          * Transfer the values to the `struct
746                          * wim_resource_spec', and discard the current stream
747                          * since this lookup table entry did not, in fact,
748                          * correspond to a "stream".
749                          */
750
751                         /* Uncompressed size of the resource pack is actually
752                          * stored in the header of the resource itself.  Read
753                          * it, and also grab the chunk size and compression type
754                          * (which are not necessarily the defaults from the WIM
755                          * header).  */
756                         struct alt_chunk_table_header_disk hdr;
757
758                         ret = full_pread(&wim->in_fd, &hdr,
759                                          sizeof(hdr), reshdr.offset_in_wim);
760                         if (ret)
761                                 goto err;
762
763                         cur_rspec->uncompressed_size = le64_to_cpu(hdr.res_usize);
764                         cur_rspec->offset_in_wim = reshdr.offset_in_wim;
765                         cur_rspec->size_in_wim = reshdr.size_in_wim;
766                         cur_rspec->flags = reshdr.flags;
767
768                         /* Compression format numbers must be the same as in
769                          * WIMGAPI to be compatible here.  */
770                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_NONE != 0);
771                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
772                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
773                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
774                         cur_rspec->compression_type = le32_to_cpu(hdr.compression_format);
775
776                         cur_rspec->chunk_size = le32_to_cpu(hdr.chunk_size);
777
778                         DEBUG("Full pack is %"PRIu64" compressed bytes "
779                               "at file offset %"PRIu64" (flags 0x%02x)",
780                               cur_rspec->size_in_wim,
781                               cur_rspec->offset_in_wim,
782                               cur_rspec->flags);
783                         free_lookup_table_entry(cur_entry);
784                         continue;
785                 }
786
787                 if (is_zero_hash(cur_entry->hash)) {
788                         free_lookup_table_entry(cur_entry);
789                         continue;
790                 }
791
792                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
793                         /* Continuing the pack with another stream.  */
794                         DEBUG("Continuing pack with stream: "
795                               "%"PRIu64" uncompressed bytes @ "
796                               "resource offset %"PRIu64")",
797                               reshdr.size_in_wim, reshdr.offset_in_wim);
798                 }
799
800                 lte_bind_wim_resource_spec(cur_entry, cur_rspec);
801                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
802                         /* In packed runs, the offset field is used for
803                          * in-resource offset, not the in-WIM offset, and the
804                          * size field is used for the uncompressed size, not the
805                          * compressed size.  */
806                         cur_entry->offset_in_res = reshdr.offset_in_wim;
807                         cur_entry->size = reshdr.size_in_wim;
808                         cur_entry->flags = reshdr.flags;
809                 } else {
810                         /* Normal case: The stream corresponds one-to-one with
811                          * the resource entry.  */
812                         cur_entry->offset_in_res = 0;
813                         cur_entry->size = reshdr.uncompressed_size;
814                         cur_entry->flags = reshdr.flags;
815                         cur_rspec = NULL;
816                 }
817
818                 if (cur_entry->flags & WIM_RESHDR_FLAG_METADATA) {
819                         /* Lookup table entry for a metadata resource */
820
821                         /* Metadata entries with no references must be ignored;
822                          * see for example the WinPE WIMs from the WAIK v2.1.
823                          * */
824                         if (cur_entry->refcnt == 0) {
825                                 free_lookup_table_entry(cur_entry);
826                                 continue;
827                         }
828
829                         if (cur_entry->refcnt != 1) {
830                                 ERROR("Found metadata resource with refcnt != 1");
831                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
832                                 goto err;
833                         }
834
835                         if (wim->hdr.part_number != 1) {
836                                 WARNING("Ignoring metadata resource found in a "
837                                         "non-first part of the split WIM");
838                                 free_lookup_table_entry(cur_entry);
839                                 continue;
840                         }
841                         if (wim->current_image == wim->hdr.image_count) {
842                                 WARNING("The WIM header says there are %u images "
843                                         "in the WIM, but we found more metadata "
844                                         "resources than this (ignoring the extra)",
845                                         wim->hdr.image_count);
846                                 free_lookup_table_entry(cur_entry);
847                                 continue;
848                         }
849
850                         /* Notice very carefully:  We are assigning the metadata
851                          * resources in the exact order mirrored by their lookup
852                          * table entries on disk, which is the behavior of
853                          * Microsoft's software.  In particular, this overrides
854                          * the actual locations of the metadata resources
855                          * themselves in the WIM file as well as any information
856                          * written in the XML data. */
857                         DEBUG("Found metadata resource for image %u at "
858                               "offset %"PRIu64".",
859                               wim->current_image + 1,
860                               cur_entry->rspec->offset_in_wim);
861                         wim->image_metadata[
862                                 wim->current_image++]->metadata_lte = cur_entry;
863                         continue;
864                 }
865
866                 /* Lookup table entry for a stream that is not a metadata
867                  * resource.  */
868                 duplicate_entry = lookup_stream(table, cur_entry->hash);
869                 if (duplicate_entry) {
870                         WARNING("The WIM lookup table contains two entries "
871                                 "with the same SHA1 message digest!");
872                         free_lookup_table_entry(cur_entry);
873                         continue;
874                 }
875
876                 /* Finally, insert the stream into the lookup table, keyed by
877                  * its SHA1 message digest.  */
878                 lookup_table_insert(table, cur_entry);
879         }
880         cur_entry = NULL;
881
882         /* Validate the last resource.  */
883         if (cur_rspec != NULL) {
884                 ret = validate_resource(cur_rspec);
885                 if (ret)
886                         goto err;
887         }
888
889         if (wim->hdr.part_number == 1 && wim->current_image != wim->hdr.image_count) {
890                 WARNING("The header of \"%"TS"\" says there are %u images in\n"
891                         "          the WIM, but we only found %d metadata resources!  Acting as if\n"
892                         "          the header specified only %d images instead.",
893                         wim->filename, wim->hdr.image_count,
894                         wim->current_image, wim->current_image);
895                 for (int i = wim->current_image; i < wim->hdr.image_count; i++)
896                         put_image_metadata(wim->image_metadata[i], NULL);
897                 wim->hdr.image_count = wim->current_image;
898         }
899         DEBUG("Done reading lookup table.");
900         wim->lookup_table = table;
901         ret = 0;
902         goto out_free_buf;
903
904 err:
905         if (cur_rspec && list_empty(&cur_rspec->stream_list))
906                 FREE(cur_rspec);
907         free_lookup_table_entry(cur_entry);
908         free_lookup_table(table);
909 out_free_buf:
910         FREE(buf);
911 out:
912         wim->current_image = 0;
913         return ret;
914 }
915
916 static void
917 put_wim_lookup_table_entry(struct wim_lookup_table_entry_disk *disk_entry,
918                            const struct wim_reshdr *out_reshdr,
919                            u16 part_number, u32 refcnt, const u8 *hash)
920 {
921         put_wim_reshdr(out_reshdr, &disk_entry->reshdr);
922         disk_entry->part_number = cpu_to_le16(part_number);
923         disk_entry->refcnt = cpu_to_le32(refcnt);
924         copy_hash(disk_entry->hash, hash);
925 }
926
927 int
928 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
929                                         struct filedes *out_fd,
930                                         u16 part_number,
931                                         struct wim_reshdr *out_reshdr,
932                                         int write_resource_flags)
933 {
934         size_t table_size;
935         struct wim_lookup_table_entry *lte;
936         struct wim_lookup_table_entry_disk *table_buf;
937         struct wim_lookup_table_entry_disk *table_buf_ptr;
938         int ret;
939         u64 prev_res_offset_in_wim = ~0ULL;
940
941         table_size = 0;
942         list_for_each_entry(lte, stream_list, lookup_table_list) {
943                 table_size += sizeof(struct wim_lookup_table_entry_disk);
944
945                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
946                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
947                 {
948                         table_size += sizeof(struct wim_lookup_table_entry_disk);
949                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
950                 }
951         }
952
953         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
954               table_size, out_fd->offset);
955
956         table_buf = MALLOC(table_size);
957         if (table_buf == NULL) {
958                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
959                       table_size);
960                 return WIMLIB_ERR_NOMEM;
961         }
962         table_buf_ptr = table_buf;
963
964         prev_res_offset_in_wim = ~0ULL;
965         list_for_each_entry(lte, stream_list, lookup_table_list) {
966
967                 put_wim_lookup_table_entry(table_buf_ptr++,
968                                            &lte->out_reshdr,
969                                            part_number,
970                                            lte->out_refcnt,
971                                            lte->hash);
972                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
973                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
974                 {
975                         /* Put the main resource entry for the pack.  */
976
977                         struct wim_reshdr reshdr;
978
979                         reshdr.offset_in_wim = lte->out_res_offset_in_wim;
980                         reshdr.size_in_wim = lte->out_res_size_in_wim;
981                         reshdr.uncompressed_size = WIM_PACK_MAGIC_NUMBER;
982                         reshdr.flags = WIM_RESHDR_FLAG_PACKED_STREAMS;
983
984                         DEBUG("Putting main entry for pack: "
985                               "size_in_wim=%"PRIu64", "
986                               "offset_in_wim=%"PRIu64", "
987                               "uncompressed_size=%"PRIu64,
988                               reshdr.size_in_wim,
989                               reshdr.offset_in_wim,
990                               reshdr.uncompressed_size);
991
992                         put_wim_lookup_table_entry(table_buf_ptr++,
993                                                    &reshdr,
994                                                    part_number,
995                                                    1, zero_hash);
996                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
997                 }
998
999         }
1000         wimlib_assert((u8*)table_buf_ptr - (u8*)table_buf == table_size);
1001
1002         /* Write the lookup table uncompressed.  Although wimlib can handle a
1003          * compressed lookup table, MS software cannot.  */
1004         ret = write_wim_resource_from_buffer(table_buf,
1005                                              table_size,
1006                                              WIM_RESHDR_FLAG_METADATA,
1007                                              out_fd,
1008                                              WIMLIB_COMPRESSION_TYPE_NONE,
1009                                              0,
1010                                              out_reshdr,
1011                                              NULL,
1012                                              write_resource_flags);
1013         FREE(table_buf);
1014         DEBUG("ret=%d", ret);
1015         return ret;
1016 }
1017
1018 int
1019 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1020 {
1021         lte->real_refcnt = 0;
1022         return 0;
1023 }
1024
1025 int
1026 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1027 {
1028         lte->out_refcnt = 0;
1029         return 0;
1030 }
1031
1032 int
1033 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
1034 {
1035         if (lte->extracted_file != NULL) {
1036                 FREE(lte->extracted_file);
1037                 lte->extracted_file = NULL;
1038         }
1039         return 0;
1040 }
1041
1042 /* Allocate a stream entry for the contents of the buffer, or re-use an existing
1043  * entry in @lookup_table for the same stream.  */
1044 struct wim_lookup_table_entry *
1045 new_stream_from_data_buffer(const void *buffer, size_t size,
1046                             struct wim_lookup_table *lookup_table)
1047 {
1048         u8 hash[SHA1_HASH_SIZE];
1049         struct wim_lookup_table_entry *lte, *existing_lte;
1050
1051         sha1_buffer(buffer, size, hash);
1052         existing_lte = lookup_stream(lookup_table, hash);
1053         if (existing_lte) {
1054                 wimlib_assert(existing_lte->size == size);
1055                 lte = existing_lte;
1056                 lte->refcnt++;
1057         } else {
1058                 void *buffer_copy;
1059                 lte = new_lookup_table_entry();
1060                 if (lte == NULL)
1061                         return NULL;
1062                 buffer_copy = memdup(buffer, size);
1063                 if (buffer_copy == NULL) {
1064                         free_lookup_table_entry(lte);
1065                         return NULL;
1066                 }
1067                 lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1068                 lte->attached_buffer    = buffer_copy;
1069                 lte->size               = size;
1070                 copy_hash(lte->hash, hash);
1071                 lookup_table_insert(lookup_table, lte);
1072         }
1073         return lte;
1074 }
1075
1076 /* Calculate the SHA1 message digest of a stream and move it from the list of
1077  * unhashed streams to the stream lookup table, possibly joining it with an
1078  * existing lookup table entry for an identical stream.
1079  *
1080  * @lte:  An unhashed lookup table entry.
1081  * @lookup_table:  Lookup table for the WIM.
1082  * @lte_ret:  On success, write a pointer to the resulting lookup table
1083  *            entry to this location.  This will be the same as @lte
1084  *            if it was inserted into the lookup table, or different if
1085  *            a duplicate stream was found.
1086  *
1087  * Returns 0 on success; nonzero if there is an error reading the stream.
1088  */
1089 int
1090 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1091                      struct wim_lookup_table *lookup_table,
1092                      struct wim_lookup_table_entry **lte_ret)
1093 {
1094         int ret;
1095         struct wim_lookup_table_entry *duplicate_lte;
1096         struct wim_lookup_table_entry **back_ptr;
1097
1098         wimlib_assert(lte->unhashed);
1099
1100         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1101          * union with the SHA1 message digest and will no longer be valid once
1102          * the SHA1 has been calculated. */
1103         back_ptr = retrieve_lte_pointer(lte);
1104
1105         ret = sha1_stream(lte);
1106         if (ret)
1107                 return ret;
1108
1109         /* Look for a duplicate stream */
1110         duplicate_lte = lookup_stream(lookup_table, lte->hash);
1111         list_del(&lte->unhashed_list);
1112         if (duplicate_lte) {
1113                 /* We have a duplicate stream.  Transfer the reference counts
1114                  * from this stream to the duplicate and update the reference to
1115                  * this stream (in an inode or ads_entry) to point to the
1116                  * duplicate.  The caller is responsible for freeing @lte if
1117                  * needed.  */
1118                 wimlib_assert(!(duplicate_lte->unhashed));
1119                 wimlib_assert(duplicate_lte->size == lte->size);
1120                 duplicate_lte->refcnt += lte->refcnt;
1121                 lte->refcnt = 0;
1122                 *back_ptr = duplicate_lte;
1123                 lte = duplicate_lte;
1124         } else {
1125                 /* No duplicate stream, so we need to insert this stream into
1126                  * the lookup table and treat it as a hashed stream. */
1127                 lookup_table_insert(lookup_table, lte);
1128                 lte->unhashed = 0;
1129         }
1130         *lte_ret = lte;
1131         return 0;
1132 }
1133
1134 void
1135 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
1136                              struct wimlib_resource_entry *wentry)
1137 {
1138         memset(wentry, 0, sizeof(*wentry));
1139
1140         wentry->uncompressed_size = lte->size;
1141         if (lte->resource_location == RESOURCE_IN_WIM) {
1142                 wentry->part_number = lte->rspec->wim->hdr.part_number;
1143                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1144                         wentry->compressed_size = 0;
1145                         wentry->offset = lte->offset_in_res;
1146                 } else {
1147                         wentry->compressed_size = lte->rspec->size_in_wim;
1148                         wentry->offset = lte->rspec->offset_in_wim;
1149                 }
1150                 wentry->raw_resource_offset_in_wim = lte->rspec->offset_in_wim;
1151                 /*wentry->raw_resource_uncompressed_size = lte->rspec->uncompressed_size;*/
1152                 wentry->raw_resource_compressed_size = lte->rspec->size_in_wim;
1153         }
1154         copy_hash(wentry->sha1_hash, lte->hash);
1155         wentry->reference_count = lte->refcnt;
1156         wentry->is_compressed = (lte->flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
1157         wentry->is_metadata = (lte->flags & WIM_RESHDR_FLAG_METADATA) != 0;
1158         wentry->is_free = (lte->flags & WIM_RESHDR_FLAG_FREE) != 0;
1159         wentry->is_spanned = (lte->flags & WIM_RESHDR_FLAG_SPANNED) != 0;
1160         wentry->packed = (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) != 0;
1161 }
1162
1163 struct iterate_lte_context {
1164         wimlib_iterate_lookup_table_callback_t cb;
1165         void *user_ctx;
1166 };
1167
1168 static int
1169 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
1170 {
1171         struct iterate_lte_context *ctx = _ctx;
1172         struct wimlib_resource_entry entry;
1173
1174         lte_to_wimlib_resource_entry(lte, &entry);
1175         return (*ctx->cb)(&entry, ctx->user_ctx);
1176 }
1177
1178 /* API function documented in wimlib.h  */
1179 WIMLIBAPI int
1180 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
1181                             wimlib_iterate_lookup_table_callback_t cb,
1182                             void *user_ctx)
1183 {
1184         if (flags != 0)
1185                 return WIMLIB_ERR_INVALID_PARAM;
1186
1187         struct iterate_lte_context ctx = {
1188                 .cb = cb,
1189                 .user_ctx = user_ctx,
1190         };
1191         if (wim->hdr.part_number == 1) {
1192                 int ret;
1193                 for (int i = 0; i < wim->hdr.image_count; i++) {
1194                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
1195                                              &ctx);
1196                         if (ret)
1197                                 return ret;
1198                 }
1199         }
1200         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
1201 }