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