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