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