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