]> wimlib.net Git - wimlib/blob - src/dentry.c
Fixed bug when capturing NTFS file with multiple named data streams
[wimlib] / src / dentry.c
1 /*
2  * dentry.c
3  *
4  * A dentry (directory entry) contains the metadata for a file.  In the WIM file
5  * format, the dentries are stored in the "metadata resource" section right
6  * after the security data.  Each image in the WIM file has its own metadata
7  * resource with its own security data and dentry tree.  Dentries in different
8  * images may share file resources by referring to the same lookup table
9  * entries.
10  */
11
12 /*
13  * Copyright (C) 2012 Eric Biggers
14  *
15  * This file is part of wimlib, a library for working with WIM files.
16  *
17  * wimlib is free software; you can redistribute it and/or modify it under the
18  * terms of the GNU General Public License as published by the Free Software
19  * Foundation; either version 3 of the License, or (at your option) any later
20  * version.
21  *
22  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
23  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24  * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License along with
27  * wimlib; if not, see http://www.gnu.org/licenses/.
28  */
29
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <unistd.h>
34
35 #include "dentry.h"
36 #include "io.h"
37 #include "lookup_table.h"
38 #include "sha1.h"
39 #include "timestamp.h"
40 #include "wimlib_internal.h"
41
42 /*
43  * Returns true if @dentry has the UTF-8 file name @name that has length
44  * @name_len.
45  */
46 static bool dentry_has_name(const struct dentry *dentry, const char *name, 
47                             size_t name_len)
48 {
49         if (dentry->file_name_utf8_len != name_len)
50                 return false;
51         return memcmp(dentry->file_name_utf8, name, name_len) == 0;
52 }
53
54 static u64 __dentry_correct_length_unaligned(u16 file_name_len,
55                                              u16 short_name_len)
56 {
57         u64 length = WIM_DENTRY_DISK_SIZE;
58         if (file_name_len)
59                 length += file_name_len + 2;
60         if (short_name_len)
61                 length += short_name_len + 2;
62         return length;
63 }
64
65 static u64 dentry_correct_length_unaligned(const struct dentry *dentry)
66 {
67         return __dentry_correct_length_unaligned(dentry->file_name_len,
68                                                  dentry->short_name_len);
69 }
70
71 /* Return the "correct" value to write in the length field of the dentry, based
72  * on the file name length and short name length */
73 static u64 dentry_correct_length(const struct dentry *dentry)
74 {
75         return (dentry_correct_length_unaligned(dentry) + 7) & ~7;
76 }
77
78 static u64 __dentry_total_length(const struct dentry *dentry, u64 length)
79 {
80         for (u16 i = 0; i < dentry->num_ads; i++)
81                 length += ads_entry_total_length(&dentry->ads_entries[i]);
82         return (length + 7) & ~7;
83 }
84
85 u64 dentry_correct_total_length(const struct dentry *dentry)
86 {
87         return __dentry_total_length(dentry,
88                                      dentry_correct_length_unaligned(dentry));
89 }
90
91 /* Real length of a dentry, including the alternate data stream entries, which
92  * are not included in the dentry->length field... */
93 u64 dentry_total_length(const struct dentry *dentry)
94 {
95         return __dentry_total_length(dentry, dentry->length);
96 }
97
98 /* Transfers file attributes from a `stat' buffer to a struct dentry. */
99 void stbuf_to_dentry(const struct stat *stbuf, struct dentry *dentry)
100 {
101         if (S_ISLNK(stbuf->st_mode)) {
102                 dentry->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
103                 dentry->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
104         } else if (S_ISDIR(stbuf->st_mode)) {
105                 dentry->attributes = FILE_ATTRIBUTE_DIRECTORY;
106         } else {
107                 dentry->attributes = FILE_ATTRIBUTE_NORMAL;
108         }
109         if (sizeof(ino_t) >= 8)
110                 dentry->link_group_id = (u64)stbuf->st_ino;
111         else
112                 dentry->link_group_id = (u64)stbuf->st_ino |
113                                    ((u64)stbuf->st_dev << (sizeof(ino_t) * 8));
114         /* Set timestamps */
115         dentry->creation_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
116         dentry->last_write_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
117         dentry->last_access_time = timespec_to_wim_timestamp(&stbuf->st_atim);
118 }
119
120
121 /* Sets all the timestamp fields of the dentry to the current time. */
122 void dentry_update_all_timestamps(struct dentry *dentry)
123 {
124         u64 now = get_wim_timestamp();
125         dentry->creation_time    = now;
126         dentry->last_access_time = now;
127         dentry->last_write_time  = now;
128 }
129
130 /* Returns the alternate data stream entry belonging to @dentry that has the
131  * stream name @stream_name. */
132 struct ads_entry *dentry_get_ads_entry(struct dentry *dentry,
133                                        const char *stream_name)
134 {
135         size_t stream_name_len;
136         if (!stream_name)
137                 return NULL;
138         if (dentry->num_ads) {
139                 u16 i = 0;
140                 stream_name_len = strlen(stream_name);
141                 do {
142                         if (ads_entry_has_name(&dentry->ads_entries[i],
143                                                stream_name, stream_name_len))
144                                 return &dentry->ads_entries[i];
145                 } while (++i != dentry->num_ads);
146         }
147         return NULL;
148 }
149
150 static void ads_entry_init(struct ads_entry *ads_entry)
151 {
152         memset(ads_entry, 0, sizeof(struct ads_entry));
153         INIT_LIST_HEAD(&ads_entry->lte_group_list.list);
154         ads_entry->lte_group_list.type = STREAM_TYPE_ADS;
155 }
156
157 /* 
158  * Add an alternate stream entry to a dentry and return a pointer to it, or NULL
159  * if memory could not be allocated.
160  */
161 struct ads_entry *dentry_add_ads(struct dentry *dentry, const char *stream_name)
162 {
163         u16 num_ads;
164         struct ads_entry *ads_entries;
165         struct ads_entry *new_entry;
166
167         DEBUG("Add alternate data stream %s:%s",
168                dentry->file_name_utf8, stream_name);
169
170         if (dentry->num_ads == 0xffff) {
171                 ERROR("Too many alternate data streams in one dentry!");
172                 return NULL;
173         }
174         num_ads = dentry->num_ads + 1;
175         ads_entries = REALLOC(dentry->ads_entries,
176                               num_ads * sizeof(dentry->ads_entries[0]));
177         if (!ads_entries) {
178                 ERROR("Failed to allocate memory for new alternate data stream");
179                 return NULL;
180         }
181         wimlib_assert(ads_entries == dentry->ads_entries ||
182                         ads_entries < dentry->ads_entries ||
183                         ads_entries > dentry->ads_entries + dentry->num_ads);
184         if (ads_entries != dentry->ads_entries) {
185                 /* We moved the ADS entries.  Adjust the stream lists. */
186                 for (u16 i = 0; i < dentry->num_ads; i++) {
187                         struct list_head *cur = &ads_entries[i].lte_group_list.list;
188                         struct list_head *prev = cur->prev;
189                         struct list_head *next = cur->next;
190                         if ((u8*)prev >= (u8*)dentry->ads_entries
191                             && (u8*)prev < (u8*)(dentry->ads_entries + dentry->num_ads)) {
192                                 /* Previous entry was located in the same ads_entries
193                                  * array!  Adjust our own prev pointer. */
194                                 u16 idx = (struct ads_entry*)prev -
195                                             (struct ads_entry*)&dentry->ads_entries[0].lte_group_list.list;
196                                 cur->prev = &ads_entries[idx].lte_group_list.list;
197                         } else {
198                                 /* Previous entry is located in a different ads_entries
199                                  * array.  Adjust its next pointer. */
200                                 prev->next = cur;
201                         }
202                         next = cur->next;
203                         if ((u8*)next >= (u8*)dentry->ads_entries
204                             && (u8*)next < (u8*)(dentry->ads_entries + dentry->num_ads)) {
205                                 /* Next entry was located in the same ads_entries array!
206                                  * Adjust our own next pointer. */
207                                 u16 idx = (struct ads_entry*)next -
208                                             (struct ads_entry*)&dentry->ads_entries[0].lte_group_list.list;
209                                 cur->next = &ads_entries[idx].lte_group_list.list;
210                         } else {
211                                 /* Next entry is located in a different ads_entries
212                                  * array.  Adjust its prev pointer. */
213                                 next->prev = cur;
214                         }
215                 }
216         }
217
218         new_entry = &ads_entries[num_ads - 1];
219         ads_entry_init(new_entry);
220         if (change_ads_name(new_entry, stream_name) != 0)
221                 return NULL;
222         dentry->ads_entries = ads_entries;
223         dentry->num_ads = num_ads;
224         return new_entry;
225 }
226
227 /* Remove an alternate data stream from a dentry.
228  *
229  * The corresponding lookup table entry for the stream is NOT changed.
230  *
231  * @dentry:     The dentry
232  * @ads_entry:  The alternate data stream entry (it MUST be one of the
233  *                 ads_entry's in the array dentry->ads_entries).
234  */
235 void dentry_remove_ads(struct dentry *dentry, struct ads_entry *ads_entry)
236 {
237         u16 idx;
238         u16 following;
239
240         wimlib_assert(dentry->num_ads);
241         idx = ads_entry - dentry->ads_entries;
242         wimlib_assert(idx < dentry->num_ads);
243         following = dentry->num_ads - idx - 1;
244
245         destroy_ads_entry(ads_entry);
246         memcpy(ads_entry, ads_entry + 1, following * sizeof(struct ads_entry));
247
248         /* We moved the ADS entries.  Adjust the stream lists. */
249         for (u16 i = 0; i < following; i++) {
250                 struct list_head *cur = &ads_entry[i].lte_group_list.list;
251                 cur->prev->next = cur;
252                 cur->next->prev = cur;
253         }
254
255         dentry->num_ads--;
256 }
257
258 /* 
259  * Calls a function on all directory entries in a directory tree.  It is called
260  * on a parent before its children.
261  */
262 int for_dentry_in_tree(struct dentry *root, 
263                        int (*visitor)(struct dentry*, void*), void *arg)
264 {
265         int ret;
266         struct dentry *child;
267
268         ret = visitor(root, arg);
269
270         if (ret != 0)
271                 return ret;
272
273         child = root->children;
274
275         if (!child)
276                 return 0;
277
278         do {
279                 ret = for_dentry_in_tree(child, visitor, arg);
280                 if (ret != 0)
281                         return ret;
282                 child = child->next;
283         } while (child != root->children);
284         return 0;
285 }
286
287 /* 
288  * Like for_dentry_in_tree(), but the visitor function is always called on a
289  * dentry's children before on itself.
290  */
291 int for_dentry_in_tree_depth(struct dentry *root, 
292                              int (*visitor)(struct dentry*, void*), void *arg)
293 {
294         int ret;
295         struct dentry *child;
296         struct dentry *next;
297
298         child = root->children;
299         if (child) {
300                 do {
301                         next = child->next;
302                         ret = for_dentry_in_tree_depth(child, visitor, arg);
303                         if (ret != 0)
304                                 return ret;
305                         child = next;
306                 } while (child != root->children);
307         }
308         return visitor(root, arg);
309 }
310
311 /* 
312  * Calculate the full path of @dentry, based on its parent's full path and on
313  * its UTF-8 file name. 
314  */
315 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
316 {
317         char *full_path;
318         u32 full_path_len;
319         if (dentry_is_root(dentry)) {
320                 full_path = MALLOC(2);
321                 if (!full_path)
322                         goto oom;
323                 full_path[0] = '/';
324                 full_path[1] = '\0';
325                 full_path_len = 1;
326         } else {
327                 char *parent_full_path;
328                 u32 parent_full_path_len;
329                 const struct dentry *parent = dentry->parent;
330
331                 if (dentry_is_root(parent)) {
332                         parent_full_path = "";
333                         parent_full_path_len = 0;
334                 } else {
335                         parent_full_path = parent->full_path_utf8;
336                         parent_full_path_len = parent->full_path_utf8_len;
337                 }
338
339                 full_path_len = parent_full_path_len + 1 +
340                                 dentry->file_name_utf8_len;
341                 full_path = MALLOC(full_path_len + 1);
342                 if (!full_path)
343                         goto oom;
344
345                 memcpy(full_path, parent_full_path, parent_full_path_len);
346                 full_path[parent_full_path_len] = '/';
347                 memcpy(full_path + parent_full_path_len + 1,
348                        dentry->file_name_utf8,
349                        dentry->file_name_utf8_len);
350                 full_path[full_path_len] = '\0';
351         }
352         FREE(dentry->full_path_utf8);
353         dentry->full_path_utf8 = full_path;
354         dentry->full_path_utf8_len = full_path_len;
355         return 0;
356 oom:
357         ERROR("Out of memory while calculating dentry full path");
358         return WIMLIB_ERR_NOMEM;
359 }
360
361 /* 
362  * Recursively calculates the subdir offsets for a directory tree. 
363  *
364  * @dentry:  The root of the directory tree.
365  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
366  *      offset for @dentry. 
367  */
368 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
369 {
370         struct dentry *child;
371
372         child = dentry->children;
373         dentry->subdir_offset = *subdir_offset_p;
374
375         if (child) {
376                 /* Advance the subdir offset by the amount of space the children
377                  * of this dentry take up. */
378                 do {
379                         *subdir_offset_p += dentry_correct_total_length(child);
380                         child = child->next;
381                 } while (child != dentry->children);
382
383                 /* End-of-directory dentry on disk. */
384                 *subdir_offset_p += 8;
385
386                 /* Recursively call calculate_subdir_offsets() on all the
387                  * children. */
388                 do {
389                         calculate_subdir_offsets(child, subdir_offset_p);
390                         child = child->next;
391                 } while (child != dentry->children);
392         } else {
393                 /* On disk, childless directories have a valid subdir_offset
394                  * that points to an 8-byte end-of-directory dentry.  Regular
395                  * files or reparse points have a subdir_offset of 0. */
396                 if (dentry_is_directory(dentry))
397                         *subdir_offset_p += 8;
398                 else
399                         dentry->subdir_offset = 0;
400         }
401 }
402
403
404 /* Returns the child of @dentry that has the file name @name.  
405  * Returns NULL if no child has the name. */
406 struct dentry *get_dentry_child_with_name(const struct dentry *dentry, 
407                                           const char *name)
408 {
409         struct dentry *child;
410         size_t name_len;
411         
412         child = dentry->children;
413         if (child) {
414                 name_len = strlen(name);
415                 do {
416                         if (dentry_has_name(child, name, name_len))
417                                 return child;
418                         child = child->next;
419                 } while (child != dentry->children);
420         }
421         return NULL;
422 }
423
424 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
425  * @cur_dir.  Returns NULL if no dentry having the path is found. */
426 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir,
427                                                const char *path)
428 {
429         struct dentry *child;
430         size_t base_len;
431         const char *new_path;
432
433         if (*path == '\0')
434                 return cur_dir;
435
436         child = cur_dir->children;
437         if (child) {
438                 new_path = path_next_part(path, &base_len);
439                 do {
440                         if (dentry_has_name(child, path, base_len))
441                                 return get_dentry_relative_path(child, new_path);
442                         child = child->next;
443                 } while (child != cur_dir->children);
444         }
445         return NULL;
446 }
447
448 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
449  * such dentry. */
450 struct dentry *get_dentry(WIMStruct *w, const char *path)
451 {
452         struct dentry *root = wim_root_dentry(w);
453         while (*path == '/')
454                 path++;
455         return get_dentry_relative_path(root, path);
456 }
457
458 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
459  * if the dentry is not found. */
460 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
461 {
462         size_t path_len = strlen(path);
463         char buf[path_len + 1];
464
465         memcpy(buf, path, path_len + 1);
466
467         to_parent_name(buf, path_len);
468
469         return get_dentry(w, buf);
470 }
471
472 /* Prints the full path of a dentry. */
473 int print_dentry_full_path(struct dentry *dentry, void *ignore)
474 {
475         if (dentry->full_path_utf8)
476                 puts(dentry->full_path_utf8);
477         return 0;
478 }
479
480 /* We want to be able to show the names of the file attribute flags that are
481  * set. */
482 struct file_attr_flag {
483         u32 flag;
484         const char *name;
485 };
486 struct file_attr_flag file_attr_flags[] = {
487         {FILE_ATTRIBUTE_READONLY,           "READONLY"},
488         {FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
489         {FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
490         {FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
491         {FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
492         {FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
493         {FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
494         {FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
495         {FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
496         {FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
497         {FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
498         {FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
499         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
500         {FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
501         {FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
502 };
503
504 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
505  * available.  If the dentry is unresolved and the lookup table is NULL, the
506  * lookup table entries will not be printed.  Otherwise, they will be. */
507 int print_dentry(struct dentry *dentry, void *lookup_table)
508 {
509         const u8 *hash;
510         struct lookup_table_entry *lte;
511         time_t time;
512         char *p;
513
514         printf("[DENTRY]\n");
515         printf("Length            = %"PRIu64"\n", dentry->length);
516         printf("Attributes        = 0x%x\n", dentry->attributes);
517         for (unsigned i = 0; i < ARRAY_LEN(file_attr_flags); i++)
518                 if (file_attr_flags[i].flag & dentry->attributes)
519                         printf("    FILE_ATTRIBUTE_%s is set\n",
520                                 file_attr_flags[i].name);
521         printf("Security ID       = %d\n", dentry->security_id);
522         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
523 #if 0
524         printf("Unused1           = 0x%"PRIu64"\n", dentry->unused1);
525         printf("Unused2           = %"PRIu64"\n", dentry->unused2);
526 #endif
527 #if 0
528         printf("Creation Time     = 0x%"PRIx64"\n");
529         printf("Last Access Time  = 0x%"PRIx64"\n");
530         printf("Last Write Time   = 0x%"PRIx64"\n");
531 #endif
532
533         /* Translate the timestamps into something readable */
534         time = wim_timestamp_to_unix(dentry->creation_time);
535         p = asctime(gmtime(&time));
536         *(strrchr(p, '\n')) = '\0';
537         printf("Creation Time     = %s UTC\n", p);
538
539         time = wim_timestamp_to_unix(dentry->last_access_time);
540         p = asctime(gmtime(&time));
541         *(strrchr(p, '\n')) = '\0';
542         printf("Last Access Time  = %s UTC\n", p);
543
544         time = wim_timestamp_to_unix(dentry->last_write_time);
545         p = asctime(gmtime(&time));
546         *(strrchr(p, '\n')) = '\0';
547         printf("Last Write Time   = %s UTC\n", p);
548
549         printf("Reparse Tag       = 0x%"PRIx32"\n", dentry->reparse_tag);
550         printf("Hard Link Group   = 0x%"PRIx64"\n", dentry->link_group_id);
551         printf("Number of Alternate Data Streams = %hu\n", dentry->num_ads);
552         printf("Filename          = \"");
553         print_string(dentry->file_name, dentry->file_name_len);
554         puts("\"");
555         printf("Filename Length   = %hu\n", dentry->file_name_len);
556         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
557         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
558         printf("Short Name        = \"");
559         print_string(dentry->short_name, dentry->short_name_len);
560         puts("\"");
561         printf("Short Name Length = %hu\n", dentry->short_name_len);
562         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
563         lte = dentry_stream_lte(dentry, 0, lookup_table);
564         if (lte) {
565                 print_lookup_table_entry(lte);
566         } else {
567                 hash = dentry_stream_hash(dentry, 0);
568                 if (hash) {
569                         printf("Hash              = 0x"); 
570                         print_hash(hash);
571                         putchar('\n');
572                         putchar('\n');
573                 }
574         }
575         for (u16 i = 0; i < dentry->num_ads; i++) {
576                 printf("[Alternate Stream Entry %u]\n", i);
577                 printf("Name = \"%s\"\n", dentry->ads_entries[i].stream_name_utf8);
578                 printf("Name Length (UTF-16) = %u\n",
579                                 dentry->ads_entries[i].stream_name_len);
580                 hash = dentry_stream_hash(dentry, i + 1);
581                 if (hash) {
582                         printf("Hash              = 0x"); 
583                         print_hash(hash);
584                         putchar('\n');
585                 }
586                 print_lookup_table_entry(dentry_stream_lte(dentry, i + 1,
587                                                            lookup_table));
588         }
589         return 0;
590 }
591
592 /* Initializations done on every `struct dentry'. */
593 static void dentry_common_init(struct dentry *dentry)
594 {
595         memset(dentry, 0, sizeof(struct dentry));
596         dentry->refcnt = 1;
597         dentry->security_id = -1;
598         dentry->ads_entries_status = ADS_ENTRIES_DEFAULT;
599         dentry->lte_group_list.type = STREAM_TYPE_NORMAL;
600 }
601
602 /* 
603  * Creates an unlinked directory entry.
604  *
605  * @name:  The UTF-8 filename of the new dentry.
606  *
607  * Returns a pointer to the new dentry, or NULL if out of memory.
608  */
609 struct dentry *new_dentry(const char *name)
610 {
611         struct dentry *dentry;
612         
613         dentry = MALLOC(sizeof(struct dentry));
614         if (!dentry)
615                 goto err;
616
617         dentry_common_init(dentry);
618         if (change_dentry_name(dentry, name) != 0)
619                 goto err;
620
621         dentry_update_all_timestamps(dentry);
622         dentry->next   = dentry;
623         dentry->prev   = dentry;
624         dentry->parent = dentry;
625         INIT_LIST_HEAD(&dentry->link_group_list);
626         INIT_LIST_HEAD(&dentry->lte_group_list.list);
627         return dentry;
628 err:
629         FREE(dentry);
630         ERROR("Failed to allocate new dentry");
631         return NULL;
632 }
633
634 void dentry_free_ads_entries(struct dentry *dentry)
635 {
636         for (u16 i = 0; i < dentry->num_ads; i++)
637                 destroy_ads_entry(&dentry->ads_entries[i]);
638         FREE(dentry->ads_entries);
639         dentry->ads_entries = NULL;
640         dentry->num_ads = 0;
641 }
642
643 static void __destroy_dentry(struct dentry *dentry)
644 {
645         FREE(dentry->file_name);
646         FREE(dentry->file_name_utf8);
647         FREE(dentry->short_name);
648         FREE(dentry->full_path_utf8);
649         if (dentry->extracted_file != dentry->full_path_utf8)
650                 FREE(dentry->extracted_file);
651 }
652
653 /* Frees a WIM dentry. */
654 void free_dentry(struct dentry *dentry)
655 {
656         wimlib_assert(dentry);
657         __destroy_dentry(dentry);
658         /* Don't destroy the ADS entries if they "belong" to a different dentry
659          * */
660         if (dentry->ads_entries_status != ADS_ENTRIES_USER)
661                 dentry_free_ads_entries(dentry);
662         FREE(dentry);
663 }
664
665 /* Like free_dentry(), but assigns a new ADS entries owner if this dentry was
666  * the previous owner, and also deletes the dentry from its link_group_list */
667 void put_dentry(struct dentry *dentry)
668 {
669         if (dentry->ads_entries_status == ADS_ENTRIES_OWNER) {
670                 struct dentry *new_owner;
671                 list_for_each_entry(new_owner, &dentry->link_group_list,
672                                     link_group_list)
673                 {
674                         if (new_owner->ads_entries_status == ADS_ENTRIES_USER) {
675                                 new_owner->ads_entries_status = ADS_ENTRIES_OWNER;
676                                 break;
677                         }
678                 }
679                 dentry->ads_entries_status = ADS_ENTRIES_USER;
680         }
681         list_del(&dentry->link_group_list);
682         free_dentry(dentry);
683 }
684
685
686 /* Partically clones a dentry.
687  *
688  * Beware:
689  *      - memory for file names is not cloned (the pointers are all set to NULL
690  *        and the lengths are set to zero)
691  *      - next, prev, and children pointers and not touched
692  *      - stream entries are not cloned (pointer left untouched).
693  */
694 struct dentry *clone_dentry(struct dentry *old)
695 {
696         struct dentry *new = MALLOC(sizeof(struct dentry));
697         if (!new)
698                 return NULL;
699         memcpy(new, old, sizeof(struct dentry));
700         new->file_name          = NULL;
701         new->file_name_len      = 0;
702         new->file_name_utf8     = NULL;
703         new->file_name_utf8_len = 0;
704         new->short_name         = NULL;
705         new->short_name_len     = 0;
706         return new;
707 }
708
709 /* 
710  * This function is passed as an argument to for_dentry_in_tree_depth() in order
711  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
712  */
713 static int do_free_dentry(struct dentry *dentry, void *__lookup_table)
714 {
715         struct lookup_table *lookup_table = __lookup_table;
716         struct lookup_table_entry *lte;
717         unsigned i;
718
719         if (lookup_table) {
720                 for (i = 0; i <= dentry->num_ads; i++) {
721                         lte = dentry_stream_lte(dentry, i, lookup_table);
722                         lte_decrement_refcnt(lte, lookup_table);
723                 }
724         }
725
726         wimlib_assert(dentry->refcnt != 0);
727         if (--dentry->refcnt == 0)
728                 free_dentry(dentry);
729         return 0;
730 }
731
732 /* 
733  * Unlinks and frees a dentry tree.
734  *
735  * @root:               The root of the tree.
736  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
737  *                      reference counts in the lookup table for the lookup
738  *                      table entries corresponding to the dentries will be
739  *                      decremented.
740  */
741 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table)
742 {
743         if (!root || !root->parent)
744                 return;
745         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
746 }
747
748 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
749 {
750         dentry->refcnt++;
751         return 0;
752 }
753
754 /* 
755  * Links a dentry into the directory tree.
756  *
757  * @dentry: The dentry to link.
758  * @parent: The dentry that will be the parent of @dentry.
759  */
760 void link_dentry(struct dentry *dentry, struct dentry *parent)
761 {
762         wimlib_assert(dentry_is_directory(parent));
763         dentry->parent = parent;
764         if (parent->children) {
765                 /* Not an only child; link to siblings. */
766                 dentry->next = parent->children;
767                 dentry->prev = parent->children->prev;
768                 dentry->next->prev = dentry;
769                 dentry->prev->next = dentry;
770         } else {
771                 /* Only child; link to parent. */
772                 parent->children = dentry;
773                 dentry->next = dentry;
774                 dentry->prev = dentry;
775         }
776 }
777
778
779 /* Unlink a dentry from the directory tree. 
780  *
781  * Note: This merely removes it from the in-memory tree structure.  See
782  * remove_dentry() in mount.c for a function implemented on top of this one that
783  * frees the dentry and implements reference counting for the lookup table
784  * entries. */
785 void unlink_dentry(struct dentry *dentry)
786 {
787         if (dentry_is_root(dentry))
788                 return;
789         if (dentry_is_only_child(dentry)) {
790                 dentry->parent->children = NULL;
791         } else {
792                 if (dentry_is_first_sibling(dentry))
793                         dentry->parent->children = dentry->next;
794                 dentry->next->prev = dentry->prev;
795                 dentry->prev->next = dentry->next;
796         }
797 }
798
799 /* Duplicates a UTF-8 name into UTF-8 and UTF-16 strings and returns the strings
800  * and their lengths in the pointer arguments */
801 int get_names(char **name_utf16_ret, char **name_utf8_ret,
802               u16 *name_utf16_len_ret, u16 *name_utf8_len_ret,
803               const char *name)
804 {
805         size_t utf8_len;
806         size_t utf16_len;
807         char *name_utf16, *name_utf8;
808
809         utf8_len = strlen(name);
810
811         name_utf16 = utf8_to_utf16(name, utf8_len, &utf16_len);
812
813         if (!name_utf16)
814                 return WIMLIB_ERR_NOMEM;
815
816         name_utf8 = MALLOC(utf8_len + 1);
817         if (!name_utf8) {
818                 FREE(name_utf8);
819                 return WIMLIB_ERR_NOMEM;
820         }
821         memcpy(name_utf8, name, utf8_len + 1);
822         FREE(*name_utf8_ret);
823         FREE(*name_utf16_ret);
824         *name_utf8_ret      = name_utf8;
825         *name_utf16_ret     = name_utf16;
826         *name_utf8_len_ret  = utf8_len;
827         *name_utf16_len_ret = utf16_len;
828         return 0;
829 }
830
831 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
832  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
833  * full_path_utf8 fields.  Also recalculates its length. */
834 int change_dentry_name(struct dentry *dentry, const char *new_name)
835 {
836         int ret;
837
838         ret = get_names(&dentry->file_name, &dentry->file_name_utf8,
839                         &dentry->file_name_len, &dentry->file_name_utf8_len,
840                          new_name);
841         FREE(dentry->short_name);
842         dentry->short_name_len = 0;
843         if (ret == 0)
844                 dentry->length = dentry_correct_length(dentry);
845         return ret;
846 }
847
848 /*
849  * Changes the name of an alternate data stream */
850 int change_ads_name(struct ads_entry *entry, const char *new_name)
851 {
852         return get_names(&entry->stream_name, &entry->stream_name_utf8,
853                          &entry->stream_name_len,
854                          &entry->stream_name_utf8_len,
855                          new_name);
856 }
857
858 /* Parameters for calculate_dentry_statistics(). */
859 struct image_statistics {
860         struct lookup_table *lookup_table;
861         u64 *dir_count;
862         u64 *file_count;
863         u64 *total_bytes;
864         u64 *hard_link_bytes;
865 };
866
867 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
868 {
869         struct image_statistics *stats;
870         struct lookup_table_entry *lte; 
871         
872         stats = arg;
873
874         if (dentry_is_directory(dentry) && !dentry_is_root(dentry))
875                 ++*stats->dir_count;
876         else
877                 ++*stats->file_count;
878
879         for (unsigned i = 0; i <= dentry->num_ads; i++) {
880                 lte = dentry_stream_lte(dentry, i, stats->lookup_table);
881                 if (lte) {
882                         *stats->total_bytes += wim_resource_size(lte);
883                         if (++lte->out_refcnt == 1)
884                                 *stats->hard_link_bytes += wim_resource_size(lte);
885                 }
886         }
887         return 0;
888 }
889
890 /* Calculates some statistics about a dentry tree. */
891 void calculate_dir_tree_statistics(struct dentry *root, struct lookup_table *table, 
892                                    u64 *dir_count_ret, u64 *file_count_ret, 
893                                    u64 *total_bytes_ret, 
894                                    u64 *hard_link_bytes_ret)
895 {
896         struct image_statistics stats;
897         *dir_count_ret         = 0;
898         *file_count_ret        = 0;
899         *total_bytes_ret       = 0;
900         *hard_link_bytes_ret   = 0;
901         stats.lookup_table     = table;
902         stats.dir_count       = dir_count_ret;
903         stats.file_count      = file_count_ret;
904         stats.total_bytes     = total_bytes_ret;
905         stats.hard_link_bytes = hard_link_bytes_ret;
906         for_lookup_table_entry(table, zero_out_refcnts, NULL);
907         for_dentry_in_tree(root, calculate_dentry_statistics, &stats);
908 }
909
910
911 /* 
912  * Reads the alternate data stream entries for a dentry.
913  *
914  * @p:  Pointer to buffer that starts with the first alternate stream entry.
915  *
916  * @dentry:     Dentry to load the alternate data streams into.
917  *                      @dentry->num_ads must have been set to the number of
918  *                      alternate data streams that are expected.
919  *
920  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
921  *                              to by @p.
922  *
923  * The format of the on-disk alternate stream entries is as follows:
924  *
925  * struct ads_entry_on_disk {
926  *      u64  length;          // Length of the entry, in bytes.  This includes
927  *                                  all fields (including the stream name and 
928  *                                  null terminator if present, AND the padding!).
929  *      u64  reserved;        // Seems to be unused
930  *      u8   hash[20];        // SHA1 message digest of the uncompressed stream
931  *      u16  stream_name_len; // Length of the stream name, in bytes
932  *      char stream_name[];   // Stream name in UTF-16LE, @stream_name_len bytes long,
933  *                                  not including null terminator
934  *      u16  zero;            // UTF-16 null terminator for the stream name, NOT
935  *                                  included in @stream_name_len.  Based on what
936  *                                  I've observed from filenames in dentries,
937  *                                  this field should not exist when
938  *                                  (@stream_name_len == 0), but you can't
939  *                                  actually tell because of the padding anyway
940  *                                  (provided that the padding is zeroed, which
941  *                                  it always seems to be).
942  *      char padding[];       // Padding to make the size a multiple of 8 bytes.
943  * };
944  *
945  * In addition, the entries are 8-byte aligned.
946  *
947  * Return 0 on success or nonzero on failure.  On success, dentry->ads_entries
948  * is set to an array of `struct ads_entry's of length dentry->num_ads.  On
949  * failure, @dentry is not modified.
950  */
951 static int read_ads_entries(const u8 *p, struct dentry *dentry,
952                             u64 remaining_size)
953 {
954         u16 num_ads;
955         struct ads_entry *ads_entries;
956         int ret;
957
958         num_ads = dentry->num_ads;
959         ads_entries = CALLOC(num_ads, sizeof(struct ads_entry));
960         if (!ads_entries) {
961                 ERROR("Could not allocate memory for %"PRIu16" "
962                       "alternate data stream entries", num_ads);
963                 return WIMLIB_ERR_NOMEM;
964         }
965
966         for (u16 i = 0; i < num_ads; i++) {
967                 struct ads_entry *cur_entry = &ads_entries[i];
968                 u64 length;
969                 u64 length_no_padding;
970                 u64 total_length;
971                 size_t utf8_len;
972                 const u8 *p_save = p;
973
974                 /* Read the base stream entry, excluding the stream name. */
975                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
976                         ERROR("Stream entries go past end of metadata resource");
977                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
978                         ret = WIMLIB_ERR_INVALID_DENTRY;
979                         goto out_free_ads_entries;
980                 }
981
982                 p = get_u64(p, &length);
983                 p += 8; /* Skip the reserved field */
984                 p = get_bytes(p, SHA1_HASH_SIZE, (u8*)cur_entry->hash);
985                 p = get_u16(p, &cur_entry->stream_name_len);
986
987                 cur_entry->stream_name = NULL;
988                 cur_entry->stream_name_utf8 = NULL;
989
990                 /* Length including neither the null terminator nor the padding
991                  * */
992                 length_no_padding = WIM_ADS_ENTRY_DISK_SIZE +
993                                     cur_entry->stream_name_len;
994
995                 /* Length including the null terminator and the padding */
996                 total_length = ((length_no_padding + 2) + 7) & ~7;
997
998                 wimlib_assert(total_length == ads_entry_total_length(cur_entry));
999
1000                 if (remaining_size < length_no_padding) {
1001                         ERROR("Stream entries go past end of metadata resource");
1002                         ERROR("(remaining_size = %"PRIu64" bytes, "
1003                               "length_no_padding = %"PRIu64" bytes)",
1004                               remaining_size, length_no_padding);
1005                         ret = WIMLIB_ERR_INVALID_DENTRY;
1006                         goto out_free_ads_entries;
1007                 }
1008
1009                 /* The @length field in the on-disk ADS entry is expected to be
1010                  * equal to @total_length, which includes all of the entry and
1011                  * the padding that follows it to align the next ADS entry to an
1012                  * 8-byte boundary.  However, to be safe, we'll accept the
1013                  * length field as long as it's not less than the un-padded
1014                  * total length and not more than the padded total length. */
1015                 if (length < length_no_padding || length > total_length) {
1016                         ERROR("Stream entry has unexpected length "
1017                               "field (length field = %"PRIu64", "
1018                               "unpadded total length = %"PRIu64", "
1019                               "padded total length = %"PRIu64")",
1020                               length, length_no_padding, total_length);
1021                         ret = WIMLIB_ERR_INVALID_DENTRY;
1022                         goto out_free_ads_entries;
1023                 }
1024
1025                 if (cur_entry->stream_name_len) {
1026                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
1027                         if (!cur_entry->stream_name) {
1028                                 ret = WIMLIB_ERR_NOMEM;
1029                                 goto out_free_ads_entries;
1030                         }
1031                         get_bytes(p, cur_entry->stream_name_len,
1032                                   (u8*)cur_entry->stream_name);
1033                         cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
1034                                                                     cur_entry->stream_name_len,
1035                                                                     &utf8_len);
1036                         cur_entry->stream_name_utf8_len = utf8_len;
1037
1038                         if (!cur_entry->stream_name_utf8) {
1039                                 ret = WIMLIB_ERR_NOMEM;
1040                                 goto out_free_ads_entries;
1041                         }
1042                 }
1043                 /* It's expected that the size of every ADS entry is a multiple
1044                  * of 8.  However, to be safe, I'm allowing the possibility of
1045                  * an ADS entry at the very end of the metadata resource ending
1046                  * un-aligned.  So although we still need to increment the input
1047                  * pointer by @total_length to reach the next ADS entry, it's
1048                  * possible that less than @total_length is actually remaining
1049                  * in the metadata resource. We should set the remaining size to
1050                  * 0 bytes if this happens. */
1051                 p = p_save + total_length;
1052                 if (remaining_size < total_length)
1053                         remaining_size = 0;
1054                 else
1055                         remaining_size -= total_length;
1056         }
1057         dentry->ads_entries = ads_entries;
1058         return 0;
1059 out_free_ads_entries:
1060         for (u16 i = 0; i < num_ads; i++) {
1061                 FREE(ads_entries[i].stream_name);
1062                 FREE(ads_entries[i].stream_name_utf8);
1063         }
1064         FREE(ads_entries);
1065         return ret;
1066 }
1067
1068 /* 
1069  * Reads a directory entry, including all alternate data stream entries that
1070  * follow it, from the WIM image's metadata resource.
1071  *
1072  * @metadata_resource:  Buffer containing the uncompressed metadata resource.
1073  * @metadata_resource_len:   Length of the metadata resource.
1074  * @offset:     Offset of this directory entry in the metadata resource.
1075  * @dentry:     A `struct dentry' that will be filled in by this function.
1076  *
1077  * Return 0 on success or nonzero on failure.  On failure, @dentry have been
1078  * modified, bu it will be left with no pointers to any allocated buffers.
1079  * On success, the dentry->length field must be examined.  If zero, this was a
1080  * special "end of directory" dentry and not a real dentry.  If nonzero, this
1081  * was a real dentry.
1082  */
1083 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len, 
1084                 u64 offset, struct dentry *dentry)
1085 {
1086         const u8 *p;
1087         u64 calculated_size;
1088         char *file_name = NULL;
1089         char *file_name_utf8 = NULL;
1090         char *short_name = NULL;
1091         u16 short_name_len;
1092         u16 file_name_len;
1093         size_t file_name_utf8_len = 0;
1094         int ret;
1095
1096         dentry_common_init(dentry);
1097
1098         /*Make sure the dentry really fits into the metadata resource.*/
1099         if (offset + 8 > metadata_resource_len || offset + 8 < offset) {
1100                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1101                       "end of the metadata resource (size %"PRIu64")",
1102                       offset, metadata_resource_len);
1103                 return WIMLIB_ERR_INVALID_DENTRY;
1104         }
1105
1106         /* Before reading the whole dentry, we need to read just the length.
1107          * This is because a dentry of length 8 (that is, just the length field)
1108          * terminates the list of sibling directory entries. */
1109
1110         p = get_u64(&metadata_resource[offset], &dentry->length);
1111
1112         /* A zero length field (really a length of 8, since that's how big the
1113          * directory entry is...) indicates that this is the end of directory
1114          * dentry.  We do not read it into memory as an actual dentry, so just
1115          * return successfully in that case. */
1116         if (dentry->length == 0)
1117                 return 0;
1118
1119         /* If the dentry does not overflow the metadata resource buffer and is
1120          * not too short, read the rest of it (excluding the alternate data
1121          * streams, but including the file name and short name variable-length
1122          * fields) into memory. */
1123         if (offset + dentry->length >= metadata_resource_len
1124             || offset + dentry->length < offset)
1125         {
1126                 ERROR("Directory entry at offset %"PRIu64" and with size "
1127                       "%"PRIu64" ends past the end of the metadata resource "
1128                       "(size %"PRIu64")",
1129                       offset, dentry->length, metadata_resource_len);
1130                 return WIMLIB_ERR_INVALID_DENTRY;
1131         }
1132
1133         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
1134                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1135                       dentry->length);
1136                 return WIMLIB_ERR_INVALID_DENTRY;
1137         }
1138
1139         p = get_u32(p, &dentry->attributes);
1140         p = get_u32(p, (u32*)&dentry->security_id);
1141         p = get_u64(p, &dentry->subdir_offset);
1142
1143         /* 2 unused fields */
1144         p += 2 * sizeof(u64);
1145         /*p = get_u64(p, &dentry->unused1);*/
1146         /*p = get_u64(p, &dentry->unused2);*/
1147
1148         p = get_u64(p, &dentry->creation_time);
1149         p = get_u64(p, &dentry->last_access_time);
1150         p = get_u64(p, &dentry->last_write_time);
1151
1152         p = get_bytes(p, SHA1_HASH_SIZE, dentry->hash);
1153         
1154         /*
1155          * I don't know what's going on here.  It seems like M$ screwed up the
1156          * reparse points, then put the fields in the same place and didn't
1157          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1158          * have something to do with this, but it's not documented.
1159          */
1160         if (dentry->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1161                 /* ??? */
1162                 p += 4;
1163                 p = get_u32(p, &dentry->reparse_tag);
1164                 p += 4;
1165         } else {
1166                 p = get_u32(p, &dentry->reparse_tag);
1167                 p = get_u64(p, &dentry->link_group_id);
1168         }
1169
1170         /* By the way, the reparse_reserved field does not actually exist (at
1171          * least when the file is not a reparse point) */
1172         
1173         p = get_u16(p, &dentry->num_ads);
1174
1175         p = get_u16(p, &short_name_len);
1176         p = get_u16(p, &file_name_len);
1177
1178         /* We now know the length of the file name and short name.  Make sure
1179          * the length of the dentry is large enough to actually hold them. 
1180          *
1181          * The calculated length here is unaligned to allow for the possibility
1182          * that the dentry->length names an unaligned length, although this
1183          * would be unexpected. */
1184         calculated_size = __dentry_correct_length_unaligned(file_name_len,
1185                                                             short_name_len);
1186
1187         if (dentry->length < calculated_size) {
1188                 ERROR("Unexpected end of directory entry! (Expected "
1189                       "at least %"PRIu64" bytes, got %"PRIu64" bytes. "
1190                       "short_name_len = %hu, file_name_len = %hu)", 
1191                       calculated_size, dentry->length,
1192                       short_name_len, file_name_len);
1193                 return WIMLIB_ERR_INVALID_DENTRY;
1194         }
1195
1196         /* Read the filename if present.  Note: if the filename is empty, there
1197          * is no null terminator following it. */
1198         if (file_name_len) {
1199                 file_name = MALLOC(file_name_len);
1200                 if (!file_name) {
1201                         ERROR("Failed to allocate %hu bytes for dentry file name",
1202                               file_name_len);
1203                         return WIMLIB_ERR_NOMEM;
1204                 }
1205                 p = get_bytes(p, file_name_len, file_name);
1206
1207                 /* Convert filename to UTF-8. */
1208                 file_name_utf8 = utf16_to_utf8(file_name, file_name_len, 
1209                                                &file_name_utf8_len);
1210
1211                 if (!file_name_utf8) {
1212                         ERROR("Failed to allocate memory to convert UTF-16 "
1213                               "filename (%hu bytes) to UTF-8", file_name_len);
1214                         ret = WIMLIB_ERR_NOMEM;
1215                         goto out_free_file_name;
1216                 }
1217                 if (*(u16*)p)
1218                         WARNING("Expected two zero bytes following the file name "
1219                                 "`%s', but found non-zero bytes", file_name_utf8);
1220                 p += 2;
1221         }
1222
1223         /* Align the calculated size */
1224         calculated_size = (calculated_size + 7) & ~7;
1225
1226         if (dentry->length > calculated_size) {
1227                 /* Weird; the dentry says it's longer than it should be.  Note
1228                  * that the length field does NOT include the size of the
1229                  * alternate stream entries. */
1230
1231                 /* Strangely, some directory entries inexplicably have a little
1232                  * over 70 bytes of extra data.  The exact amount of data seems
1233                  * to be 72 bytes, but it is aligned on the next 8-byte
1234                  * boundary.  It does NOT seem to be alternate data stream
1235                  * entries.  Here's an example of the aligned data:
1236                  *
1237                  * 01000000 40000000 6c786bba c58ede11 b0bb0026 1870892a b6adb76f
1238                  * e63a3e46 8fca8653 0d2effa1 6c786bba c58ede11 b0bb0026 1870892a
1239                  * 00000000 00000000 00000000 00000000
1240                  *
1241                  * Here's one interpretation of how the data is laid out.
1242                  *
1243                  * struct unknown {
1244                  *      u32 field1; (always 0x00000001)
1245                  *      u32 field2; (always 0x40000000)
1246                  *      u8  data[48]; (???)
1247                  *      u64 reserved1; (always 0)
1248                  *      u64 reserved2; (always 0)
1249                  * };*/
1250                 DEBUG("Dentry for file or directory `%s' has %zu extra "
1251                       "bytes of data",
1252                       file_name_utf8, dentry->length - calculated_size);
1253         }
1254
1255         /* Read the short filename if present.  Note: if there is no short
1256          * filename, there is no null terminator following it. */
1257         if (short_name_len) {
1258                 short_name = MALLOC(short_name_len);
1259                 if (!short_name) {
1260                         ERROR("Failed to allocate %hu bytes for short filename",
1261                               short_name_len);
1262                         ret = WIMLIB_ERR_NOMEM;
1263                         goto out_free_file_name_utf8;
1264                 }
1265
1266                 p = get_bytes(p, short_name_len, short_name);
1267                 if (*(u16*)p)
1268                         WARNING("Expected two zero bytes following the file name "
1269                                 "`%s', but found non-zero bytes", file_name_utf8);
1270                 p += 2;
1271         }
1272
1273         /* 
1274          * Read the alternate data streams, if present.  dentry->num_ads tells
1275          * us how many they are, and they will directly follow the dentry
1276          * on-disk.
1277          *
1278          * Note that each alternate data stream entry begins on an 8-byte
1279          * aligned boundary, and the alternate data stream entries are NOT
1280          * included in the dentry->length field for some reason.
1281          */
1282         if (dentry->num_ads != 0) {
1283                 if (calculated_size > metadata_resource_len - offset) {
1284                         ERROR("Not enough space in metadata resource for "
1285                               "alternate stream entries");
1286                         ret = WIMLIB_ERR_INVALID_DENTRY;
1287                         goto out_free_short_name;
1288                 }
1289                 ret = read_ads_entries(&metadata_resource[offset + calculated_size],
1290                                        dentry,
1291                                        metadata_resource_len - offset - calculated_size);
1292                 if (ret != 0)
1293                         goto out_free_short_name;
1294         }
1295
1296         /* We've read all the data for this dentry.  Set the names and their
1297          * lengths, and we've done. */
1298         dentry->file_name          = file_name;
1299         dentry->file_name_utf8     = file_name_utf8;
1300         dentry->short_name         = short_name;
1301         dentry->file_name_len      = file_name_len;
1302         dentry->file_name_utf8_len = file_name_utf8_len;
1303         dentry->short_name_len     = short_name_len;
1304         return 0;
1305 out_free_short_name:
1306         FREE(short_name);
1307 out_free_file_name_utf8:
1308         FREE(file_name_utf8);
1309 out_free_file_name:
1310         FREE(file_name);
1311         return ret;
1312 }
1313
1314 /* Run some miscellaneous verifications on a WIM dentry */
1315 int verify_dentry(struct dentry *dentry, void *wim)
1316 {
1317         const WIMStruct *w = wim;
1318         const struct lookup_table *table = w->lookup_table;
1319         const struct wim_security_data *sd = wim_const_security_data(w);
1320         int ret = WIMLIB_ERR_INVALID_DENTRY;
1321
1322         /* Check the security ID */
1323         if (dentry->security_id < -1) {
1324                 ERROR("Dentry `%s' has an invalid security ID (%d)",
1325                         dentry->full_path_utf8, dentry->security_id);
1326                 goto out;
1327         }
1328         if (dentry->security_id >= sd->num_entries) {
1329                 ERROR("Dentry `%s' has an invalid security ID (%d) "
1330                       "(there are only %u entries in the security table)",
1331                         dentry->full_path_utf8, dentry->security_id,
1332                         sd->num_entries);
1333                 goto out;
1334         }
1335
1336         /* Check that lookup table entries for all the resources exist, except
1337          * if the SHA1 message digest is all 0's, which indicates there is
1338          * intentionally no resource there.  */
1339         if (w->hdr.total_parts == 1) {
1340                 for (unsigned i = 0; i <= dentry->num_ads; i++) {
1341                         struct lookup_table_entry *lte;
1342                         const u8 *hash;
1343                         hash = dentry_stream_hash_unresolved(dentry, i);
1344                         lte = __lookup_resource(table, hash);
1345                         if (!lte && !is_zero_hash(hash)) {
1346                                 ERROR("Could not find lookup table entry for stream "
1347                                       "%u of dentry `%s'", i, dentry->full_path_utf8);
1348                                 goto out;
1349                         }
1350                 }
1351         }
1352
1353         /* Make sure there is only one un-named stream. */
1354         unsigned num_unnamed_streams = 0;
1355         for (unsigned i = 0; i <= dentry->num_ads; i++) {
1356                 const u8 *hash;
1357                 hash = dentry_stream_hash_unresolved(dentry, i);
1358                 if (!dentry_stream_name_len(dentry, i) && !is_zero_hash(hash))
1359                         num_unnamed_streams++;
1360         }
1361         if (num_unnamed_streams > 1) {
1362                 ERROR("Dentry `%s' has multiple (%u) un-named streams", 
1363                       dentry->full_path_utf8, num_unnamed_streams);
1364                 goto out;
1365         }
1366
1367         /* Cannot have a short name but no long name */
1368         if (dentry->short_name_len && !dentry->file_name_len) {
1369                 ERROR("Dentry `%s' has a short name but no long name",
1370                       dentry->full_path_utf8);
1371                 goto out;
1372         }
1373
1374         /* Make sure root dentry is unnamed */
1375         if (dentry_is_root(dentry)) {
1376                 if (dentry->file_name_len) {
1377                         ERROR("The root dentry is named `%s', but it must "
1378                               "be unnamed", dentry->file_name_utf8);
1379                         goto out;
1380                 }
1381         }
1382
1383 #if 0
1384         /* Check timestamps */
1385         if (dentry->last_access_time < dentry->creation_time ||
1386             dentry->last_write_time < dentry->creation_time) {
1387                 WARNING("Dentry `%s' was created after it was last accessed or "
1388                       "written to", dentry->full_path_utf8);
1389         }
1390 #endif
1391
1392         ret = 0;
1393 out:
1394         return ret;
1395 }
1396
1397 /* 
1398  * Writes a WIM dentry to an output buffer.
1399  *
1400  * @dentry:  The dentry structure.
1401  * @p:       The memory location to write the data to.
1402  * @return:  Pointer to the byte after the last byte we wrote as part of the
1403  *              dentry.
1404  */
1405 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
1406 {
1407         u8 *orig_p = p;
1408         const u8 *hash;
1409
1410         /* We calculate the correct length of the dentry ourselves because the
1411          * dentry->length field may been set to an unexpected value from when we
1412          * read the dentry in (for example, there may have been unknown data
1413          * appended to the end of the dentry...) */
1414         u64 length = dentry_correct_length(dentry);
1415
1416         p = put_u64(p, length);
1417         p = put_u32(p, dentry->attributes);
1418         p = put_u32(p, dentry->security_id);
1419         p = put_u64(p, dentry->subdir_offset);
1420         p = put_u64(p, 0); /* unused1 */
1421         p = put_u64(p, 0); /* unused2 */
1422         p = put_u64(p, dentry->creation_time);
1423         p = put_u64(p, dentry->last_access_time);
1424         p = put_u64(p, dentry->last_write_time);
1425         hash = dentry_stream_hash(dentry, 0);
1426         p = put_bytes(p, SHA1_HASH_SIZE, hash);
1427         if (dentry->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1428                 p = put_zeroes(p, 4);
1429                 p = put_u32(p, dentry->reparse_tag);
1430                 p = put_zeroes(p, 4);
1431         } else {
1432                 u64 link_group_id;
1433                 p = put_u32(p, 0);
1434                 if (dentry->link_group_list.next == &dentry->link_group_list)
1435                         link_group_id = 0;
1436                 else
1437                         link_group_id = dentry->link_group_id;
1438                 p = put_u64(p, link_group_id);
1439         }
1440         p = put_u16(p, dentry->num_ads);
1441         p = put_u16(p, dentry->short_name_len);
1442         p = put_u16(p, dentry->file_name_len);
1443         if (dentry->file_name_len) {
1444                 p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
1445                 p = put_u16(p, 0); /* filename padding, 2 bytes. */
1446         }
1447         if (dentry->short_name) {
1448                 p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
1449                 p = put_u16(p, 0); /* short name padding, 2 bytes */
1450         }
1451
1452         /* Align to 8-byte boundary */
1453         wimlib_assert(length >= (p - orig_p)
1454                         && length - (p - orig_p) <= 7);
1455         p = put_zeroes(p, length - (p - orig_p));
1456
1457         /* Write the alternate data streams, if there are any.  Please see
1458          * read_ads_entries() for comments about the format of the on-disk
1459          * alternate data stream entries. */
1460         for (u16 i = 0; i < dentry->num_ads; i++) {
1461                 p = put_u64(p, ads_entry_total_length(&dentry->ads_entries[i]));
1462                 p = put_u64(p, 0); /* Unused */
1463                 hash = dentry_stream_hash(dentry, i + 1);
1464                 p = put_bytes(p, SHA1_HASH_SIZE, hash);
1465                 p = put_u16(p, dentry->ads_entries[i].stream_name_len);
1466                 if (dentry->ads_entries[i].stream_name_len) {
1467                         p = put_bytes(p, dentry->ads_entries[i].stream_name_len,
1468                                          (u8*)dentry->ads_entries[i].stream_name);
1469                         p = put_u16(p, 0);
1470                 }
1471                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1472         }
1473 #ifdef ENABLE_ASSERTIONS
1474         wimlib_assert(p - orig_p == __dentry_total_length(dentry, length));
1475 #endif
1476         return p;
1477 }
1478
1479 /* Recursive function that writes a dentry tree rooted at @parent, not including
1480  * @parent itself, which has already been written. */
1481 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p)
1482 {
1483         const struct dentry *child;
1484
1485         /* Nothing to do if this dentry has no children. */
1486         if (parent->subdir_offset == 0)
1487                 return p;
1488
1489         /* Write child dentries and end-of-directory entry. 
1490          *
1491          * Note: we need to write all of this dentry's children before
1492          * recursively writing the directory trees rooted at each of the child
1493          * dentries, since the on-disk dentries for a dentry's children are
1494          * always located at consecutive positions in the metadata resource! */
1495         child = parent->children;
1496         if (child) {
1497                 do {
1498                         p = write_dentry(child, p);
1499                         child = child->next;
1500                 } while (child != parent->children);
1501         }
1502
1503         /* write end of directory entry */
1504         p = put_u64(p, 0);
1505
1506         /* Recurse on children. */
1507         if (child) {
1508                 do {
1509                         p = write_dentry_tree_recursive(child, p);
1510                         child = child->next;
1511                 } while (child != parent->children);
1512         }
1513         return p;
1514 }
1515
1516 /* Writes a directory tree to the metadata resource.
1517  *
1518  * @root:       Root of the dentry tree.
1519  * @p:          Pointer to a buffer with enough space for the dentry tree.
1520  *
1521  * Returns pointer to the byte after the last byte we wrote.
1522  */
1523 u8 *write_dentry_tree(const struct dentry *root, u8 *p)
1524 {
1525         wimlib_assert(dentry_is_root(root));
1526
1527         /* If we're the root dentry, we have no parent that already
1528          * wrote us, so we need to write ourselves. */
1529         p = write_dentry(root, p);
1530
1531         /* Write end of directory entry after the root dentry just to be safe;
1532          * however the root dentry obviously cannot have any siblings. */
1533         p = put_u64(p, 0);
1534
1535         /* Recursively write the rest of the dentry tree. */
1536         return write_dentry_tree_recursive(root, p);
1537 }
1538
1539 /* Reads the children of a dentry, and all their children, ..., etc. from the
1540  * metadata resource and into the dentry tree.
1541  *
1542  * @metadata_resource:  An array that contains the uncompressed metadata
1543  *                      resource for the WIM file.
1544  *
1545  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1546  *                          bytes.
1547  *
1548  * @dentry:     A pointer to a `struct dentry' that is the root of the directory
1549  *              tree and has already been read from the metadata resource.  It
1550  *              does not need to be the real root because this procedure is
1551  *              called recursively.
1552  *
1553  * @return:     Zero on success, nonzero on failure.
1554  */
1555 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1556                      struct dentry *dentry)
1557 {
1558         u64 cur_offset = dentry->subdir_offset;
1559         struct dentry *prev_child = NULL;
1560         struct dentry *first_child = NULL;
1561         struct dentry *child;
1562         struct dentry cur_child;
1563         int ret;
1564
1565         /* 
1566          * If @dentry has no child dentries, nothing more needs to be done for
1567          * this branch.  This is the case for regular files, symbolic links, and
1568          * *possibly* empty directories (although an empty directory may also
1569          * have one child dentry that is the special end-of-directory dentry)
1570          */
1571         if (cur_offset == 0)
1572                 return 0;
1573
1574         /* Find and read all the children of @dentry. */
1575         while (1) {
1576
1577                 /* Read next child of @dentry into @cur_child. */
1578                 ret = read_dentry(metadata_resource, metadata_resource_len, 
1579                                   cur_offset, &cur_child);
1580                 if (ret != 0)
1581                         break;
1582
1583                 /* Check for end of directory. */
1584                 if (cur_child.length == 0)
1585                         break;
1586
1587                 /* Not end of directory.  Allocate this child permanently and
1588                  * link it to the parent and previous child. */
1589                 child = MALLOC(sizeof(struct dentry));
1590                 if (!child) {
1591                         ERROR("Failed to allocate %zu bytes for new dentry",
1592                               sizeof(struct dentry));
1593                         ret = WIMLIB_ERR_NOMEM;
1594                         break;
1595                 }
1596                 memcpy(child, &cur_child, sizeof(struct dentry));
1597
1598                 if (prev_child) {
1599                         prev_child->next = child;
1600                         child->prev = prev_child;
1601                 } else {
1602                         first_child = child;
1603                 }
1604
1605                 child->parent = dentry;
1606                 prev_child = child;
1607
1608                 /* If there are children of this child, call this procedure
1609                  * recursively. */
1610                 if (child->subdir_offset != 0) {
1611                         ret = read_dentry_tree(metadata_resource, 
1612                                                metadata_resource_len, child);
1613                         if (ret != 0)
1614                                 break;
1615                 }
1616
1617                 /* Advance to the offset of the next child.  Note: We need to
1618                  * advance by the TOTAL length of the dentry, not by the length
1619                  * child->length, which although it does take into account the
1620                  * padding, it DOES NOT take into account alternate stream
1621                  * entries. */
1622                 cur_offset += dentry_total_length(child);
1623         }
1624
1625         /* Link last child to first one, and set parent's children pointer to
1626          * the first child.  */
1627         if (prev_child) {
1628                 prev_child->next = first_child;
1629                 first_child->prev = prev_child;
1630         }
1631         dentry->children = first_child;
1632         return ret;
1633 }