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