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