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