36d2d13f69430518dcdafbf59b2649a75af25152
[wimlib] / src / lookup_table.c
1 /*
2  * lookup_table.c
3  *
4  * Lookup table, implemented as a hash table, that maps dentries to file
5  * resources.
6  */
7
8 /*
9  * Copyright (C) 2012 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 "io.h"
30 #include <errno.h>
31
32 #ifdef WITH_FUSE
33 #include <unistd.h>
34 #endif
35
36 struct lookup_table *new_lookup_table(size_t capacity)
37 {
38         struct lookup_table *table;
39         struct hlist_head *array;
40
41         table = MALLOC(sizeof(struct lookup_table));
42         if (!table)
43                 goto err;
44         array = CALLOC(capacity, sizeof(array[0]));
45         if (!array) {
46                 FREE(table);
47                 goto err;
48         }
49         table->num_entries = 0;
50         table->capacity = capacity;
51         table->array = array;
52         return table;
53 err:
54         ERROR("Failed to allocate memory for lookup table with capacity %zu",
55               capacity);
56         return NULL;
57 }
58
59 struct lookup_table_entry *new_lookup_table_entry()
60 {
61         struct lookup_table_entry *lte;
62
63         lte = CALLOC(1, sizeof(struct lookup_table_entry));
64         if (lte) {
65                 lte->part_number  = 1;
66                 lte->refcnt       = 1;
67         } else {
68                 ERROR("Out of memory (tried to allocate %zu bytes for "
69                       "lookup table entry)",
70                       sizeof(struct lookup_table_entry));
71         }
72         return lte;
73 }
74
75 struct lookup_table_entry *
76 clone_lookup_table_entry(const struct lookup_table_entry *old)
77 {
78         struct lookup_table_entry *new;
79
80         new = MALLOC(sizeof(*new));
81         if (!new)
82                 return NULL;
83
84         memcpy(new, old, sizeof(*old));
85         new->extracted_file = NULL;
86         switch (new->resource_location) {
87         case RESOURCE_IN_STAGING_FILE:
88         case RESOURCE_IN_FILE_ON_DISK:
89                 wimlib_assert((void*)&old->file_on_disk ==
90                               (void*)&old->staging_file_name);
91                 new->staging_file_name = STRDUP(old->staging_file_name);
92                 if (!new->staging_file_name)
93                         goto out_free;
94                 break;
95         case RESOURCE_IN_ATTACHED_BUFFER:
96                 new->attached_buffer = MALLOC(wim_resource_size(old));
97                 if (!new->attached_buffer)
98                         goto out_free;
99                 memcpy(new->attached_buffer, old->attached_buffer,
100                        wim_resource_size(old));
101                 break;
102 #ifdef WITH_NTFS_3G
103         case RESOURCE_IN_NTFS_VOLUME:
104                 if (old->ntfs_loc) {
105                         struct ntfs_location *loc;
106                         loc = MALLOC(sizeof(*loc));
107                         if (!loc)
108                                 goto out_free;
109                         memcpy(loc, old->ntfs_loc, sizeof(*loc));
110                         loc->path_utf8 = NULL;
111                         loc->stream_name_utf16 = NULL;
112                         new->ntfs_loc = loc;
113                         loc->path_utf8 = STRDUP(old->ntfs_loc->path_utf8);
114                         if (!loc->path_utf8)
115                                 goto out_free;
116                         loc->stream_name_utf16 = MALLOC(loc->stream_name_utf16_num_chars * 2);
117                         if (!loc->stream_name_utf16)
118                                 goto out_free;
119                         memcpy(loc->stream_name_utf16,
120                                old->ntfs_loc->stream_name_utf16,
121                                loc->stream_name_utf16_num_chars * 2);
122                 }
123                 break;
124 #endif
125         default:
126                 break;
127         }
128         return new;
129 out_free:
130         free_lookup_table_entry(new);
131         return NULL;
132 }
133
134 void free_lookup_table_entry(struct lookup_table_entry *lte)
135 {
136         if (lte) {
137                 switch (lte->resource_location) {
138                 case RESOURCE_IN_STAGING_FILE:
139                 case RESOURCE_IN_ATTACHED_BUFFER:
140                 case RESOURCE_IN_FILE_ON_DISK:
141                         wimlib_assert(((void*)&lte->file_on_disk ==
142                                       (void*)&lte->staging_file_name)
143                                       && ((void*)&lte->file_on_disk ==
144                                       (void*)&lte->attached_buffer));
145                         FREE(lte->file_on_disk);
146                         break;
147 #ifdef WITH_NTFS_3G
148                 case RESOURCE_IN_NTFS_VOLUME:
149                         if (lte->ntfs_loc) {
150                                 FREE(lte->ntfs_loc->path_utf8);
151                                 FREE(lte->ntfs_loc->stream_name_utf16);
152                                 FREE(lte->ntfs_loc);
153                         }
154                         break;
155 #endif
156                 default:
157                         break;
158                 }
159                 FREE(lte->extracted_file);
160                 FREE(lte);
161         }
162 }
163
164 static int do_free_lookup_table_entry(struct lookup_table_entry *entry,
165                                       void *ignore)
166 {
167         free_lookup_table_entry(entry);
168         return 0;
169 }
170
171
172 void free_lookup_table(struct lookup_table *table)
173 {
174         DEBUG2("Freeing lookup table");
175         if (table) {
176                 if (table->array) {
177                         for_lookup_table_entry(table,
178                                                do_free_lookup_table_entry,
179                                                NULL);
180                         FREE(table->array);
181                 }
182                 FREE(table);
183         }
184 }
185
186 /*
187  * Inserts an entry into the lookup table.
188  *
189  * @table:      A pointer to the lookup table.
190  * @entry:      A pointer to the entry to insert.
191  */
192 void lookup_table_insert(struct lookup_table *table,
193                          struct lookup_table_entry *lte)
194 {
195         size_t i = lte->hash_short % table->capacity;
196         hlist_add_head(&lte->hash_list, &table->array[i]);
197
198         /* XXX Make the table grow when too many entries have been inserted. */
199         table->num_entries++;
200 }
201
202 static void finalize_lte(struct lookup_table_entry *lte)
203 {
204         #ifdef WITH_FUSE
205         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
206                 unlink(lte->staging_file_name);
207                 wimlib_assert(lte->staging_list.next);
208                 wimlib_assert(lte->staging_list.prev);
209                 list_del(&lte->staging_list);
210         }
211         #endif
212         free_lookup_table_entry(lte);
213 }
214
215 /* Decrements the reference count for the lookup table entry @lte.  If its
216  * reference count reaches 0, it is unlinked from the lookup table.  If,
217  * furthermore, the entry has no opened file descriptors associated with it, the
218  * entry is freed.  */
219 void lte_decrement_refcnt(struct lookup_table_entry *lte,
220                           struct lookup_table *table)
221 {
222         wimlib_assert(lte != NULL);
223         wimlib_assert(lte->refcnt != 0);
224         if (--lte->refcnt == 0) {
225                 lookup_table_unlink(table, lte);
226         #ifdef WITH_FUSE
227                 if (lte->num_opened_fds == 0)
228         #endif
229                         finalize_lte(lte);
230         }
231 }
232
233 #ifdef WITH_FUSE
234 void lte_decrement_num_opened_fds(struct lookup_table_entry *lte)
235 {
236         wimlib_assert(lte != NULL);
237         wimlib_assert(lte->num_opened_fds != 0);
238         if (atomic_dec(&lte->num_opened_fds) == 0 && lte->refcnt == 0)
239                 finalize_lte(lte);
240 }
241 #endif
242
243 /*
244  * Calls a function on all the entries in the lookup table.  Stop early and
245  * return nonzero if any call to the function returns nonzero.
246  */
247 int for_lookup_table_entry(struct lookup_table *table,
248                            int (*visitor)(struct lookup_table_entry *, void *),
249                            void *arg)
250 {
251         struct lookup_table_entry *lte;
252         struct hlist_node *pos, *tmp;
253         int ret;
254
255         for (size_t i = 0; i < table->capacity; i++) {
256                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
257                                           hash_list)
258                 {
259                         ret = visitor(lte, arg);
260                         if (ret != 0)
261                                 return ret;
262                 }
263         }
264         return 0;
265 }
266
267
268 /*
269  * Reads the lookup table from a WIM file.
270  */
271 int read_lookup_table(WIMStruct *w)
272 {
273         u64    num_entries;
274         u8     buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
275         int    ret;
276         struct lookup_table *table;
277         struct lookup_table_entry *cur_entry = NULL, *duplicate_entry;
278
279         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
280               w->hdr.lookup_table_res_entry.offset,
281               w->hdr.lookup_table_res_entry.original_size);
282
283         if (fseeko(w->fp, w->hdr.lookup_table_res_entry.offset, SEEK_SET) != 0)
284         {
285                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
286                                  "lookup table",
287                                  w->hdr.lookup_table_res_entry.offset);
288                 return WIMLIB_ERR_READ;
289         }
290
291         num_entries = w->hdr.lookup_table_res_entry.original_size /
292                       WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE;
293         table = new_lookup_table(num_entries * 2 + 1);
294         if (!table)
295                 return WIMLIB_ERR_NOMEM;
296
297         while (num_entries--) {
298                 const u8 *p;
299
300                 if (fread(buf, 1, sizeof(buf), w->fp) != sizeof(buf)) {
301                         if (feof(w->fp)) {
302                                 ERROR("Unexpected EOF in WIM lookup table!");
303                         } else {
304                                 ERROR_WITH_ERRNO("Error reading WIM lookup "
305                                                  "table");
306                         }
307                         ret = WIMLIB_ERR_READ;
308                         goto out;
309                 }
310                 cur_entry = new_lookup_table_entry();
311                 if (!cur_entry) {
312                         ret = WIMLIB_ERR_NOMEM;
313                         goto out;
314                 }
315                 cur_entry->wim = w;
316                 cur_entry->resource_location = RESOURCE_IN_WIM;
317
318                 p = get_resource_entry(buf, &cur_entry->resource_entry);
319                 p = get_u16(p, &cur_entry->part_number);
320                 p = get_u32(p, &cur_entry->refcnt);
321                 p = get_bytes(p, SHA1_HASH_SIZE, cur_entry->hash);
322
323                 if (cur_entry->part_number != w->hdr.part_number) {
324                         ERROR("A lookup table entry in part %hu of the WIM "
325                               "points to part %hu",
326                               w->hdr.part_number, cur_entry->part_number);
327                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
328                         goto out_free_cur_entry;
329                 }
330
331                 if (is_zero_hash(cur_entry->hash)) {
332                         ERROR("The WIM lookup table contains an entry with a "
333                               "SHA1 message digest of all 0's");
334                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
335                         goto out_free_cur_entry;
336                 }
337
338                 /* Ordinarily, no two streams should share the same SHA1 message
339                  * digest.  However, this constraint can be broken for metadata
340                  * resources--- two identical images will have the same metadata
341                  * resource, but their lookup table entries are not shared. */
342                 duplicate_entry = __lookup_resource(table, cur_entry->hash);
343                 if (duplicate_entry
344                     && !((duplicate_entry->resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
345                           && cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_METADATA))
346                 {
347                         ERROR("The WIM lookup table contains two entries with the "
348                               "same SHA1 message digest!");
349                         ERROR("The first entry is:");
350                         print_lookup_table_entry(duplicate_entry);
351                         ERROR("The second entry is:");
352                         print_lookup_table_entry(cur_entry);
353                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
354                         goto out_free_cur_entry;
355                 }
356
357                 if (!(cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
358                     && (cur_entry->resource_entry.size !=
359                         cur_entry->resource_entry.original_size))
360                 {
361                         ERROR("Found uncompressed resource with original size "
362                               "not the same as compressed size");
363                         ERROR("The lookup table entry for the resource is as follows:");
364                         print_lookup_table_entry(cur_entry);
365                         ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
366                         goto out_free_cur_entry;
367                 }
368                 lookup_table_insert(table, cur_entry);
369
370         }
371         DEBUG("Done reading lookup table.");
372         w->lookup_table = table;
373         return 0;
374 out_free_cur_entry:
375         FREE(cur_entry);
376 out:
377         free_lookup_table(table);
378         return ret;
379 }
380
381
382 /*
383  * Writes a lookup table entry to the output file.
384  */
385 int write_lookup_table_entry(struct lookup_table_entry *lte, void *__out)
386 {
387         FILE *out;
388         u8 buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
389         u8 *p;
390
391         out = __out;
392
393         /* Don't write entries that have not had file resources or metadata
394          * resources written for them. */
395         if (lte->out_refcnt == 0)
396                 return 0;
397
398         if (lte->output_resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
399                 DEBUG("Writing metadata entry at %lu (orig size = %zu)",
400                       ftello(out), lte->output_resource_entry.original_size);
401
402         p = put_resource_entry(buf, &lte->output_resource_entry);
403         p = put_u16(p, lte->part_number);
404         p = put_u32(p, lte->out_refcnt);
405         p = put_bytes(p, SHA1_HASH_SIZE, lte->hash);
406         if (fwrite(buf, 1, sizeof(buf), out) != sizeof(buf)) {
407                 ERROR_WITH_ERRNO("Failed to write lookup table entry");
408                 return WIMLIB_ERR_WRITE;
409         }
410         return 0;
411 }
412
413
414 int lte_zero_real_refcnt(struct lookup_table_entry *lte, void *ignore)
415 {
416         lte->real_refcnt = 0;
417         return 0;
418 }
419
420 int lte_zero_out_refcnt(struct lookup_table_entry *lte, void *ignore)
421 {
422         lte->out_refcnt = 0;
423         return 0;
424 }
425
426 int lte_free_extracted_file(struct lookup_table_entry *lte, void *ignone)
427 {
428         FREE(lte->extracted_file);
429         lte->extracted_file = NULL;
430         return 0;
431 }
432
433 void print_lookup_table_entry(const struct lookup_table_entry *lte)
434 {
435         if (!lte) {
436                 putchar('\n');
437                 return;
438         }
439         printf("Offset            = %"PRIu64" bytes\n",
440                lte->resource_entry.offset);
441         printf("Size              = %"PRIu64" bytes\n",
442                (u64)lte->resource_entry.size);
443         printf("Original size     = %"PRIu64" bytes\n",
444                lte->resource_entry.original_size);
445         printf("Part Number       = %hu\n", lte->part_number);
446         printf("Reference Count   = %u\n", lte->refcnt);
447         printf("Hash              = 0x");
448         print_hash(lte->hash);
449         putchar('\n');
450         printf("Flags             = ");
451         u8 flags = lte->resource_entry.flags;
452         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
453                 fputs("WIM_RESHDR_FLAG_COMPRESSED, ", stdout);
454         if (flags & WIM_RESHDR_FLAG_FREE)
455                 fputs("WIM_RESHDR_FLAG_FREE, ", stdout);
456         if (flags & WIM_RESHDR_FLAG_METADATA)
457                 fputs("WIM_RESHDR_FLAG_METADATA, ", stdout);
458         if (flags & WIM_RESHDR_FLAG_SPANNED)
459                 fputs("WIM_RESHDR_FLAG_SPANNED, ", stdout);
460         putchar('\n');
461         switch (lte->resource_location) {
462         case RESOURCE_IN_WIM:
463                 if (lte->wim->filename) {
464                         printf("WIM file          = `%s'\n",
465                                lte->wim->filename);
466                 }
467                 break;
468         case RESOURCE_IN_FILE_ON_DISK:
469                 printf("File on Disk      = `%s'\n", lte->file_on_disk);
470                 break;
471         case RESOURCE_IN_STAGING_FILE:
472                 printf("Staging File      = `%s'\n", lte->staging_file_name);
473                 break;
474         default:
475                 break;
476         }
477         putchar('\n');
478 }
479
480 static int do_print_lookup_table_entry(struct lookup_table_entry *lte,
481                                        void *ignore)
482 {
483         print_lookup_table_entry(lte);
484         return 0;
485 }
486
487 /*
488  * Prints the lookup table of a WIM file.
489  */
490 WIMLIBAPI void wimlib_print_lookup_table(WIMStruct *w)
491 {
492         for_lookup_table_entry(w->lookup_table,
493                                do_print_lookup_table_entry,
494                                NULL);
495 }
496
497 /*
498  * Looks up an entry in the lookup table.
499  */
500 struct lookup_table_entry *
501 __lookup_resource(const struct lookup_table *table, const u8 hash[])
502 {
503         size_t i;
504         struct lookup_table_entry *lte;
505         struct hlist_node *pos;
506
507         wimlib_assert(table != NULL);
508         wimlib_assert(hash != NULL);
509
510         i = *(size_t*)hash % table->capacity;
511         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
512                 if (hashes_equal(hash, lte->hash))
513                         return lte;
514         return NULL;
515 }
516
517 #ifdef WITH_FUSE
518 /*
519  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
520  * given a path name.
521  *
522  * This is only for pre-resolved inodes.
523  */
524 int lookup_resource(WIMStruct *w, const char *path,
525                     int lookup_flags,
526                     struct dentry **dentry_ret,
527                     struct lookup_table_entry **lte_ret,
528                     u16 *stream_idx_ret)
529 {
530         struct dentry *dentry;
531         struct lookup_table_entry *lte;
532         u16 stream_idx;
533         const char *stream_name = NULL;
534         struct inode *inode;
535         char *p = NULL;
536
537         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
538                 stream_name = path_stream_name(path);
539                 if (stream_name) {
540                         p = (char*)stream_name - 1;
541                         *p = '\0';
542                 }
543         }
544
545         dentry = get_dentry(w, path);
546         if (p)
547                 *p = ':';
548         if (!dentry)
549                 return -ENOENT;
550
551         inode = dentry->d_inode;
552
553         wimlib_assert(inode->resolved);
554
555         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
556               && inode_is_directory(inode))
557                 return -EISDIR;
558
559         if (stream_name) {
560                 struct ads_entry *ads_entry;
561                 u16 ads_idx;
562                 ads_entry = inode_get_ads_entry(inode, stream_name,
563                                                 &ads_idx);
564                 if (ads_entry) {
565                         stream_idx = ads_idx + 1;
566                         lte = ads_entry->lte;
567                         goto out;
568                 } else {
569                         return -ENOENT;
570                 }
571         } else {
572                 lte = inode->lte;
573                 stream_idx = 0;
574         }
575 out:
576         if (dentry_ret)
577                 *dentry_ret = dentry;
578         if (lte_ret)
579                 *lte_ret = lte;
580         if (stream_idx_ret)
581                 *stream_idx_ret = stream_idx;
582         return 0;
583 }
584 #endif
585
586 static void inode_resolve_ltes(struct inode *inode, struct lookup_table *table)
587 {
588         struct lookup_table_entry *lte;
589
590         wimlib_assert(!inode->resolved);
591
592         /* Resolve the default file stream */
593         lte = __lookup_resource(table, inode->hash);
594         inode->lte = lte;
595         inode->resolved = true;
596
597         /* Resolve the alternate data streams */
598         for (u16 i = 0; i < inode->num_ads; i++) {
599                 struct ads_entry *cur_entry = &inode->ads_entries[i];
600                 lte = __lookup_resource(table, cur_entry->hash);
601                 cur_entry->lte = lte;
602         }
603 }
604
605 static void inode_unresolve_ltes(struct inode *inode)
606 {
607         wimlib_assert(inode->resolved);
608         if (inode->lte)
609                 copy_hash(inode->hash, inode->lte->hash);
610         else
611                 zero_out_hash(inode->hash);
612
613         for (u16 i = 0; i < inode->num_ads; i++) {
614                 if (inode->ads_entries[i].lte)
615                         copy_hash(inode->ads_entries[i].hash,
616                                   inode->ads_entries[i].lte->hash);
617                 else
618                         zero_out_hash(inode->ads_entries[i].hash);
619         }
620         inode->resolved = false;
621 }
622
623 /* Resolve a dentry's lookup table entries
624  *
625  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
626  * lookup table) with pointers directly to the lookup table entries.  A circular
627  * linked list of streams sharing the same lookup table entry is created.
628  *
629  * This function always succeeds; unresolved lookup table entries are given a
630  * NULL pointer.
631  */
632 int dentry_resolve_ltes(struct dentry *dentry, void *table)
633 {
634         if (!dentry->d_inode->resolved)
635                 inode_resolve_ltes(dentry->d_inode, table);
636         return 0;
637 }
638
639 int dentry_unresolve_ltes(struct dentry *dentry, void *ignore)
640 {
641         if (dentry->d_inode->resolved)
642                 inode_unresolve_ltes(dentry->d_inode);
643         return 0;
644 }
645
646 /* Return the lookup table entry for the unnamed data stream of an inode, or
647  * NULL if there is none.
648  *
649  * You'd think this would be easier than it actually is, since the unnamed data
650  * stream should be the one referenced from the inode itself.  Alas, if there
651  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
652  * data stream in one of the alternate data streams instead of inside the WIM
653  * dentry itself.  So we need to check the alternate data streams too.
654  *
655  * Also, note that a dentry may appear to have more than one unnamed stream, but
656  * if the SHA1 message digest is all 0's then the corresponding stream does not
657  * really "count" (this is the case for the inode's own file stream when the
658  * file stream that should be there is actually in one of the alternate stream
659  * entries.).  This is despite the fact that we may need to extract such a
660  * missing entry as an empty file or empty named data stream.
661  */
662 struct lookup_table_entry *
663 inode_unnamed_lte(const struct inode *inode,
664                    const struct lookup_table *table)
665 {
666         if (inode->resolved)
667                 return inode_unnamed_lte_resolved(inode);
668         else
669                 return inode_unnamed_lte_unresolved(inode, table);
670 }
671