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