Set FILE_ATTRIBUTE_DIRECTORY for directory symlinks
[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 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
44  * a file name and short name that take the specified numbers of bytes.  This
45  * excludes any alternate data stream entries that may follow the dentry. */
46 static u64 __dentry_correct_length_unaligned(u16 file_name_len,
47                                              u16 short_name_len)
48 {
49         u64 length = WIM_DENTRY_DISK_SIZE;
50         if (file_name_len)
51                 length += file_name_len + 2;
52         if (short_name_len)
53                 length += short_name_len + 2;
54         return length;
55 }
56
57 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
58  * the file name length and short name length.  Note that dentry->length is
59  * ignored; also, this excludes any alternate data stream entries that may
60  * follow the dentry. */
61 static u64 dentry_correct_length_unaligned(const struct dentry *dentry)
62 {
63         return __dentry_correct_length_unaligned(dentry->file_name_len,
64                                                  dentry->short_name_len);
65 }
66
67 /* Return the "correct" value to write in the length field of a WIM dentry,
68  * based on the file name length and short name length. */
69 static u64 dentry_correct_length(const struct dentry *dentry)
70 {
71         return (dentry_correct_length_unaligned(dentry) + 7) & ~7;
72 }
73
74 /* Return %true iff the alternate data stream entry @entry has the UTF-8 stream
75  * name @name that has length @name_len bytes. */
76 static inline bool ads_entry_has_name(const struct ads_entry *entry,
77                                       const char *name, size_t name_len)
78 {
79         if (entry->stream_name_utf8_len != name_len)
80                 return false;
81         return memcmp(entry->stream_name_utf8, name, name_len) == 0;
82 }
83
84 /* Duplicates a UTF-8 name into UTF-8 and UTF-16 strings and returns the strings
85  * and their lengths in the pointer arguments */
86 int get_names(char **name_utf16_ret, char **name_utf8_ret,
87               u16 *name_utf16_len_ret, u16 *name_utf8_len_ret,
88               const char *name)
89 {
90         size_t utf8_len;
91         size_t utf16_len;
92         char *name_utf16, *name_utf8;
93
94         utf8_len = strlen(name);
95
96         name_utf16 = utf8_to_utf16(name, utf8_len, &utf16_len);
97
98         if (!name_utf16)
99                 return WIMLIB_ERR_NOMEM;
100
101         name_utf8 = MALLOC(utf8_len + 1);
102         if (!name_utf8) {
103                 FREE(name_utf8);
104                 return WIMLIB_ERR_NOMEM;
105         }
106         memcpy(name_utf8, name, utf8_len + 1);
107         FREE(*name_utf8_ret);
108         FREE(*name_utf16_ret);
109         *name_utf8_ret      = name_utf8;
110         *name_utf16_ret     = name_utf16;
111         *name_utf8_len_ret  = utf8_len;
112         *name_utf16_len_ret = utf16_len;
113         return 0;
114 }
115
116 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
117  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
118  * full_path_utf8 fields.  Also recalculates its length. */
119 static int change_dentry_name(struct dentry *dentry, const char *new_name)
120 {
121         int ret;
122
123         ret = get_names(&dentry->file_name, &dentry->file_name_utf8,
124                         &dentry->file_name_len, &dentry->file_name_utf8_len,
125                          new_name);
126         FREE(dentry->short_name);
127         dentry->short_name_len = 0;
128         if (ret == 0)
129                 dentry->length = dentry_correct_length(dentry);
130         return ret;
131 }
132
133 /*
134  * Changes the name of an alternate data stream */
135 static int change_ads_name(struct ads_entry *entry, const char *new_name)
136 {
137         return get_names(&entry->stream_name, &entry->stream_name_utf8,
138                          &entry->stream_name_len,
139                          &entry->stream_name_utf8_len,
140                          new_name);
141 }
142
143 /* Returns the total length of a WIM alternate data stream entry on-disk,
144  * including the stream name, the null terminator, AND the padding after the
145  * entry to align the next one (or the next dentry) on an 8-byte boundary. */
146 static u64 ads_entry_total_length(const struct ads_entry *entry)
147 {
148         u64 len = WIM_ADS_ENTRY_DISK_SIZE;
149         if (entry->stream_name_len)
150                 len += entry->stream_name_len + 2;
151         return (len + 7) & ~7;
152 }
153
154
155 static u64 __dentry_total_length(const struct dentry *dentry, u64 length)
156 {
157         const struct inode *inode = dentry->d_inode;
158         for (u16 i = 0; i < inode->num_ads; i++)
159                 length += ads_entry_total_length(&inode->ads_entries[i]);
160         return (length + 7) & ~7;
161 }
162
163 /* Calculate the aligned *total* length of an on-disk WIM dentry.  This includes
164  * all alternate data streams. */
165 u64 dentry_correct_total_length(const struct dentry *dentry)
166 {
167         return __dentry_total_length(dentry,
168                                      dentry_correct_length_unaligned(dentry));
169 }
170
171 /* Like dentry_correct_total_length(), but use the existing dentry->length field
172  * instead of calculating its "correct" value. */
173 static u64 dentry_total_length(const struct dentry *dentry)
174 {
175         return __dentry_total_length(dentry, dentry->length);
176 }
177
178 #ifdef WITH_FUSE
179 /* Transfers file attributes from a struct inode to a `stat' buffer.
180  *
181  * The lookup table entry tells us which stream in the inode we are statting.
182  * For a named data stream, everything returned is the same as the unnamed data
183  * stream except possibly the size and block count. */
184 int inode_to_stbuf(const struct inode *inode, struct lookup_table_entry *lte,
185                    struct stat *stbuf)
186 {
187         if (inode_is_symlink(inode))
188                 stbuf->st_mode = S_IFLNK | 0777;
189         else if (inode_is_directory(inode))
190                 stbuf->st_mode = S_IFDIR | 0755;
191         else
192                 stbuf->st_mode = S_IFREG | 0755;
193
194         stbuf->st_ino   = (ino_t)inode->ino;
195         stbuf->st_nlink = inode->link_count;
196         stbuf->st_uid   = getuid();
197         stbuf->st_gid   = getgid();
198
199         if (lte) {
200                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
201                         wimlib_assert(lte->staging_file_name);
202                         struct stat native_stat;
203                         if (stat(lte->staging_file_name, &native_stat) != 0) {
204                                 DEBUG("Failed to stat `%s': %m",
205                                       lte->staging_file_name);
206                                 return -errno;
207                         }
208                         stbuf->st_size = native_stat.st_size;
209                 } else {
210                         stbuf->st_size = wim_resource_size(lte);
211                 }
212         } else {
213                 stbuf->st_size = 0;
214         }
215
216         stbuf->st_atime   = wim_timestamp_to_unix(inode->last_access_time);
217         stbuf->st_mtime   = wim_timestamp_to_unix(inode->last_write_time);
218         stbuf->st_ctime   = wim_timestamp_to_unix(inode->creation_time);
219         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
220         return 0;
221 }
222 #endif
223
224 int for_dentry_in_rbtree(struct rb_node *root,
225                          int (*visitor)(struct dentry *, void *),
226                          void *arg)
227 {
228         int ret;
229         struct rb_node *node = root;
230         LIST_HEAD(stack);
231         while (true) {
232                 if (node) {
233                         list_add(&rbnode_dentry(node)->tmp_list, &stack);
234                         node = node->rb_left;
235                 } else {
236                         struct list_head *next;
237                         struct dentry *dentry;
238
239                         next = stack.next;
240                         if (next == &stack)
241                                 return 0;
242                         dentry = container_of(next, struct dentry, tmp_list);
243                         list_del(next);
244                         ret = visitor(dentry, arg);
245                         if (ret != 0)
246                                 return ret;
247                         node = dentry->rb_node.rb_right;
248                 }
249         }
250 }
251
252 static int for_dentry_tree_in_rbtree_depth(struct rb_node *node,
253                                            int (*visitor)(struct dentry*, void*),
254                                            void *arg)
255 {
256         int ret;
257         if (node) {
258                 ret = for_dentry_tree_in_rbtree_depth(node->rb_left,
259                                                       visitor, arg);
260                 if (ret != 0)
261                         return ret;
262                 ret = for_dentry_tree_in_rbtree_depth(node->rb_right,
263                                                       visitor, arg);
264                 if (ret != 0)
265                         return ret;
266                 ret = for_dentry_in_tree_depth(rbnode_dentry(node), visitor, arg);
267                 if (ret != 0)
268                         return ret;
269         }
270         return 0;
271 }
272
273 /*#define RECURSIVE_FOR_DENTRY_IN_TREE*/
274
275 #ifdef RECURSIVE_FOR_DENTRY_IN_TREE
276 static int for_dentry_tree_in_rbtree(struct rb_node *node,
277                                      int (*visitor)(struct dentry*, void*),
278                                      void *arg)
279 {
280         int ret;
281         if (node) {
282                 ret = for_dentry_tree_in_rbtree(node->rb_left, visitor, arg);
283                 if (ret != 0)
284                         return ret;
285                 ret = for_dentry_in_tree(rbnode_dentry(node), visitor, arg);
286                 if (ret != 0)
287                         return ret;
288                 ret = for_dentry_tree_in_rbtree(node->rb_right, visitor, arg);
289                 if (ret != 0)
290                         return ret;
291         }
292         return 0;
293 }
294 #endif
295
296 /*
297  * Calls a function on all directory entries in a WIM dentry tree.  Logically,
298  * this is a pre-order traversal (the function is called on a parent dentry
299  * before its children), but sibling dentries will be visited in order as well.
300  *
301  * In reality, the data structures are more complicated than the above might
302  * suggest because there is a separate red-black tree for each dentry that
303  * contains its direct children.
304  */
305 int for_dentry_in_tree(struct dentry *root,
306                        int (*visitor)(struct dentry*, void*), void *arg)
307 {
308 #ifdef RECURSIVE_FOR_DENTRY_IN_TREE
309         int ret = visitor(root, arg);
310         if (ret != 0)
311                 return ret;
312         return for_dentry_tree_in_rbtree(root->d_inode->children.rb_node, visitor, arg);
313 #else
314         int ret;
315         struct list_head main_stack;
316         struct list_head sibling_stack;
317         struct list_head *sibling_stack_bottom;
318         struct dentry *main_dentry;
319         struct rb_node *node;
320         struct list_head *next_sibling;
321         struct dentry *dentry;
322
323         ret = visitor(root, arg);
324         if (ret != 0)
325                 return ret;
326
327         main_dentry = root;
328         sibling_stack_bottom = &sibling_stack;
329         INIT_LIST_HEAD(&main_stack);
330         INIT_LIST_HEAD(&sibling_stack);
331
332         list_add(&root->tmp_list, &main_stack);
333         node = root->d_inode->children.rb_node;
334
335         while (1) {
336                 // Prepare for non-recursive in-order traversal of the red-black
337                 // tree of this dentry's children
338
339                 while (node) {
340                         // Push this node to the sibling stack and examine the
341                         // left neighbor, if any
342                         list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
343                         node = node->rb_left;
344                 }
345
346                 next_sibling = sibling_stack.next;
347                 if (next_sibling == sibling_stack_bottom) {
348                         // Done with all siblings.  Pop the main dentry to move
349                         // back up one level.
350                         main_dentry = container_of(main_stack.next,
351                                                    struct dentry,
352                                                    tmp_list);
353                         list_del(&main_dentry->tmp_list);
354
355                         if (main_dentry == root)
356                                 goto out;
357
358                         // Restore sibling stack bottom from the previous level
359                         sibling_stack_bottom = (void*)main_dentry->parent;
360
361                         // Restore the just-popped main dentry's parent
362                         main_dentry->parent = container_of(main_stack.next,
363                                                            struct dentry,
364                                                            tmp_list);
365
366                         // The next sibling to traverse in the previous level,
367                         // in the in-order traversal of the red-black tree, is
368                         // the one to the right.
369                         node = main_dentry->rb_node.rb_right;
370                 } else {
371                         // The sibling stack is not empty, so there are more to
372                         // go!
373
374                         // Pop a sibling from the stack.
375                         list_del(next_sibling);
376                         dentry = container_of(next_sibling, struct dentry, tmp_list);
377
378                         // Visit the sibling.
379                         ret = visitor(dentry, arg);
380                         if (ret != 0) {
381                                 // Failed.  Restore parent pointers for the
382                                 // dentries in the main stack
383                                 list_for_each_entry(dentry, &main_stack, tmp_list) {
384                                         dentry->parent = container_of(dentry->tmp_list.next,
385                                                                       struct dentry,
386                                                                       tmp_list);
387                                 }
388                                 goto out;
389                         }
390
391                         // We'd like to recursively visit the dentry tree rooted
392                         // at this sibling.  To do this, add it to the main
393                         // stack, save the bottom of this level's sibling stack
394                         // in the dentry->parent field, re-set the bottom of the
395                         // sibling stack to be its current height, and set
396                         // main_dentry to the sibling so it becomes the parent
397                         // dentry in the next iteration through the outer loop.
398                         if (inode_has_children(dentry->d_inode)) {
399                                 list_add(&dentry->tmp_list, &main_stack);
400                                 dentry->parent = (void*)sibling_stack_bottom;
401                                 sibling_stack_bottom = sibling_stack.next;
402
403                                 main_dentry = dentry;
404                                 node = main_dentry->d_inode->children.rb_node;
405                         } else {
406                                 node = dentry->rb_node.rb_right;
407                         }
408                 }
409         }
410 out:
411         root->parent = root;
412         return ret;
413 #endif
414 }
415
416 /*
417  * Like for_dentry_in_tree(), but the visitor function is always called on a
418  * dentry's children before on itself.
419  */
420 int for_dentry_in_tree_depth(struct dentry *root,
421                              int (*visitor)(struct dentry*, void*), void *arg)
422 {
423 #if 1
424         int ret;
425         ret = for_dentry_tree_in_rbtree_depth(root->d_inode->children.rb_node,
426                                               visitor, arg);
427         if (ret != 0)
428                 return ret;
429         return visitor(root, arg);
430
431 #else
432         int ret;
433         struct list_head main_stack;
434         struct list_head sibling_stack;
435         struct list_head *sibling_stack_bottom;
436         struct dentry *main_dentry;
437         struct rb_node *node;
438         struct list_head *next_sibling;
439         struct dentry *dentry;
440
441         main_dentry = root;
442         sibling_stack_bottom = &sibling_stack;
443         INIT_LIST_HEAD(&main_stack);
444         INIT_LIST_HEAD(&sibling_stack);
445
446         list_add(&main_dentry->tmp_list, &main_stack);
447
448         while (1) {
449                 node = main_dentry->d_inode->children.rb_node;
450
451                 while (1) {
452                         if (node->rb_left) {
453                                 list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
454                                 node = node->rb_left;
455                                 continue;
456                         }
457                         if (node->rb_right) {
458                                 list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
459                                 node = node->rb_right;
460                                 continue;
461                         }
462                         list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
463                 }
464
465         pop_sibling:
466                 next_sibling = sibling_stack.next;
467                 if (next_sibling == sibling_stack_bottom) {
468                         main_dentry = container_of(main_stack.next,
469                                                    struct dentry,
470                                                    tmp_list);
471                         list_del(&main_dentry->tmp_list);
472
473
474                         sibling_stack_bottom = (void*)main_dentry->parent;
475
476                         if (main_dentry == root) {
477                                 main_dentry->parent = main_dentry;
478                                 ret = visitor(dentry, arg);
479                                 return ret;
480                         } else {
481                                 main_dentry->parent = container_of(main_stack.next,
482                                                                    struct dentry,
483                                                                    tmp_list);
484                         }
485
486                         ret = visitor(main_dentry, arg);
487
488                         if (ret != 0) {
489                                 list_del(&root->tmp_list);
490                                 list_for_each_entry(dentry, &main_stack, tmp_list) {
491                                         dentry->parent = container_of(dentry->tmp_list.next,
492                                                                       struct dentry,
493                                                                       tmp_list);
494                                 }
495                                 root->parent = root;
496                                 return ret;
497                         }
498                         goto pop_sibling;
499                 } else {
500
501                         list_del(next_sibling);
502                         dentry = container_of(next_sibling, struct dentry, tmp_list);
503
504
505                         list_add(&dentry->tmp_list, &main_stack);
506                         dentry->parent = (void*)sibling_stack_bottom;
507                         sibling_stack_bottom = sibling_stack.next;
508
509                         main_dentry = dentry;
510                 }
511         }
512 #endif
513 }
514
515 /*
516  * Calculate the full path of @dentry, based on its parent's full path and on
517  * its UTF-8 file name.
518  */
519 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
520 {
521         char *full_path;
522         u32 full_path_len;
523         if (dentry_is_root(dentry)) {
524                 full_path = MALLOC(2);
525                 if (!full_path)
526                         goto oom;
527                 full_path[0] = '/';
528                 full_path[1] = '\0';
529                 full_path_len = 1;
530         } else {
531                 char *parent_full_path;
532                 u32 parent_full_path_len;
533                 const struct dentry *parent = dentry->parent;
534
535                 if (dentry_is_root(parent)) {
536                         parent_full_path = "";
537                         parent_full_path_len = 0;
538                 } else {
539                         parent_full_path = parent->full_path_utf8;
540                         parent_full_path_len = parent->full_path_utf8_len;
541                 }
542
543                 full_path_len = parent_full_path_len + 1 +
544                                 dentry->file_name_utf8_len;
545                 full_path = MALLOC(full_path_len + 1);
546                 if (!full_path)
547                         goto oom;
548
549                 memcpy(full_path, parent_full_path, parent_full_path_len);
550                 full_path[parent_full_path_len] = '/';
551                 memcpy(full_path + parent_full_path_len + 1,
552                        dentry->file_name_utf8,
553                        dentry->file_name_utf8_len);
554                 full_path[full_path_len] = '\0';
555         }
556         FREE(dentry->full_path_utf8);
557         dentry->full_path_utf8 = full_path;
558         dentry->full_path_utf8_len = full_path_len;
559         return 0;
560 oom:
561         ERROR("Out of memory while calculating dentry full path");
562         return WIMLIB_ERR_NOMEM;
563 }
564
565 static int increment_subdir_offset(struct dentry *dentry, void *subdir_offset_p)
566 {
567         *(u64*)subdir_offset_p += dentry_correct_total_length(dentry);
568         return 0;
569 }
570
571 static int call_calculate_subdir_offsets(struct dentry *dentry,
572                                          void *subdir_offset_p)
573 {
574         calculate_subdir_offsets(dentry, subdir_offset_p);
575         return 0;
576 }
577
578 /*
579  * Recursively calculates the subdir offsets for a directory tree.
580  *
581  * @dentry:  The root of the directory tree.
582  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
583  *                    offset for @dentry.
584  */
585 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
586 {
587         struct rb_node *node;
588
589         dentry->subdir_offset = *subdir_offset_p;
590         node = dentry->d_inode->children.rb_node;
591         if (node) {
592                 /* Advance the subdir offset by the amount of space the children
593                  * of this dentry take up. */
594                 for_dentry_in_rbtree(node, increment_subdir_offset, subdir_offset_p);
595
596                 /* End-of-directory dentry on disk. */
597                 *subdir_offset_p += 8;
598
599                 /* Recursively call calculate_subdir_offsets() on all the
600                  * children. */
601                 for_dentry_in_rbtree(node, call_calculate_subdir_offsets, subdir_offset_p);
602         } else {
603                 /* On disk, childless directories have a valid subdir_offset
604                  * that points to an 8-byte end-of-directory dentry.  Regular
605                  * files or reparse points have a subdir_offset of 0. */
606                 if (dentry_is_directory(dentry))
607                         *subdir_offset_p += 8;
608                 else
609                         dentry->subdir_offset = 0;
610         }
611 }
612
613 static int compare_names(const char *name_1, u16 len_1,
614                          const char *name_2, u16 len_2)
615 {
616         int result = strncasecmp(name_1, name_2, min(len_1, len_2));
617         if (result) {
618                 return result;
619         } else {
620                 return (int)len_1 - (int)len_2;
621         }
622 }
623
624 static int dentry_compare_names(const struct dentry *d1, const struct dentry *d2)
625 {
626         return compare_names(d1->file_name_utf8, d1->file_name_utf8_len,
627                              d2->file_name_utf8, d2->file_name_utf8_len);
628 }
629
630
631 static struct dentry *
632 get_rbtree_child_with_name(const struct rb_node *node,
633                            const char *name, size_t name_len)
634 {
635         do {
636                 struct dentry *child = rbnode_dentry(node);
637                 int result = compare_names(name, name_len,
638                                            child->file_name_utf8,
639                                            child->file_name_utf8_len);
640                 if (result < 0)
641                         node = node->rb_left;
642                 else if (result > 0)
643                         node = node->rb_right;
644                 else
645                         return child;
646         } while (node);
647         return NULL;
648 }
649
650 /* Returns the child of @dentry that has the file name @name.
651  * Returns NULL if no child has the name. */
652 struct dentry *get_dentry_child_with_name(const struct dentry *dentry,
653                                           const char *name)
654 {
655         struct rb_node *node = dentry->d_inode->children.rb_node;
656         if (node)
657                 return get_rbtree_child_with_name(node, name, strlen(name));
658         else
659                 return NULL;
660 }
661
662 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
663  * @cur_dentry.  Returns NULL if no dentry having the path is found. */
664 static struct dentry *get_dentry_relative_path(struct dentry *cur_dentry,
665                                                const char *path)
666 {
667         if (*path == '\0')
668                 return cur_dentry;
669
670         struct rb_node *node = cur_dentry->d_inode->children.rb_node;
671         if (node) {
672                 struct dentry *child;
673                 size_t base_len;
674                 const char *new_path;
675
676                 new_path = path_next_part(path, &base_len);
677
678                 child = get_rbtree_child_with_name(node, path, base_len);
679                 if (child)
680                         return get_dentry_relative_path(child, new_path);
681         }
682         return NULL;
683 }
684
685 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
686  * such dentry. */
687 struct dentry *get_dentry(WIMStruct *w, const char *path)
688 {
689         struct dentry *root = wim_root_dentry(w);
690         while (*path == '/')
691                 path++;
692         return get_dentry_relative_path(root, path);
693 }
694
695 struct inode *wim_pathname_to_inode(WIMStruct *w, const char *path)
696 {
697         struct dentry *dentry;
698         dentry = get_dentry(w, path);
699         if (dentry)
700                 return dentry->d_inode;
701         else
702                 return NULL;
703 }
704
705 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
706  * if the dentry is not found. */
707 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
708 {
709         size_t path_len = strlen(path);
710         char buf[path_len + 1];
711
712         memcpy(buf, path, path_len + 1);
713
714         to_parent_name(buf, path_len);
715
716         return get_dentry(w, buf);
717 }
718
719 /* Prints the full path of a dentry. */
720 int print_dentry_full_path(struct dentry *dentry, void *ignore)
721 {
722         if (dentry->full_path_utf8)
723                 puts(dentry->full_path_utf8);
724         return 0;
725 }
726
727 /* We want to be able to show the names of the file attribute flags that are
728  * set. */
729 struct file_attr_flag {
730         u32 flag;
731         const char *name;
732 };
733 struct file_attr_flag file_attr_flags[] = {
734         {FILE_ATTRIBUTE_READONLY,           "READONLY"},
735         {FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
736         {FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
737         {FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
738         {FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
739         {FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
740         {FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
741         {FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
742         {FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
743         {FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
744         {FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
745         {FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
746         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
747         {FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
748         {FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
749 };
750
751 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
752  * available.  If the dentry is unresolved and the lookup table is NULL, the
753  * lookup table entries will not be printed.  Otherwise, they will be. */
754 int print_dentry(struct dentry *dentry, void *lookup_table)
755 {
756         const u8 *hash;
757         struct lookup_table_entry *lte;
758         const struct inode *inode = dentry->d_inode;
759         time_t time;
760         char *p;
761
762         printf("[DENTRY]\n");
763         printf("Length            = %"PRIu64"\n", dentry->length);
764         printf("Attributes        = 0x%x\n", inode->attributes);
765         for (unsigned i = 0; i < ARRAY_LEN(file_attr_flags); i++)
766                 if (file_attr_flags[i].flag & inode->attributes)
767                         printf("    FILE_ATTRIBUTE_%s is set\n",
768                                 file_attr_flags[i].name);
769         printf("Security ID       = %d\n", inode->security_id);
770         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
771
772         /* Translate the timestamps into something readable */
773         time = wim_timestamp_to_unix(inode->creation_time);
774         p = asctime(gmtime(&time));
775         *(strrchr(p, '\n')) = '\0';
776         printf("Creation Time     = %s UTC\n", p);
777
778         time = wim_timestamp_to_unix(inode->last_access_time);
779         p = asctime(gmtime(&time));
780         *(strrchr(p, '\n')) = '\0';
781         printf("Last Access Time  = %s UTC\n", p);
782
783         time = wim_timestamp_to_unix(inode->last_write_time);
784         p = asctime(gmtime(&time));
785         *(strrchr(p, '\n')) = '\0';
786         printf("Last Write Time   = %s UTC\n", p);
787
788         printf("Reparse Tag       = 0x%"PRIx32"\n", inode->reparse_tag);
789         printf("Hard Link Group   = 0x%"PRIx64"\n", inode->ino);
790         printf("Hard Link Group Size = %"PRIu32"\n", inode->link_count);
791         printf("Number of Alternate Data Streams = %hu\n", inode->num_ads);
792         printf("Filename          = \"");
793         print_string(dentry->file_name, dentry->file_name_len);
794         puts("\"");
795         printf("Filename Length   = %hu\n", dentry->file_name_len);
796         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
797         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
798         printf("Short Name        = \"");
799         print_string(dentry->short_name, dentry->short_name_len);
800         puts("\"");
801         printf("Short Name Length = %hu\n", dentry->short_name_len);
802         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
803         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
804         if (lte) {
805                 print_lookup_table_entry(lte);
806         } else {
807                 hash = inode_stream_hash(inode, 0);
808                 if (hash) {
809                         printf("Hash              = 0x");
810                         print_hash(hash);
811                         putchar('\n');
812                         putchar('\n');
813                 }
814         }
815         for (u16 i = 0; i < inode->num_ads; i++) {
816                 printf("[Alternate Stream Entry %u]\n", i);
817                 printf("Name = \"%s\"\n", inode->ads_entries[i].stream_name_utf8);
818                 printf("Name Length (UTF-16) = %u\n",
819                         inode->ads_entries[i].stream_name_len);
820                 hash = inode_stream_hash(inode, i + 1);
821                 if (hash) {
822                         printf("Hash              = 0x");
823                         print_hash(hash);
824                         putchar('\n');
825                 }
826                 print_lookup_table_entry(inode_stream_lte(inode, i + 1,
827                                                           lookup_table));
828         }
829         return 0;
830 }
831
832 /* Initializations done on every `struct dentry'. */
833 static void dentry_common_init(struct dentry *dentry)
834 {
835         memset(dentry, 0, sizeof(struct dentry));
836         dentry->refcnt = 1;
837 }
838
839 static struct inode *new_timeless_inode()
840 {
841         struct inode *inode = CALLOC(1, sizeof(struct inode));
842         if (inode) {
843                 inode->security_id = -1;
844                 inode->link_count = 1;
845         #ifdef WITH_FUSE
846                 inode->next_stream_id = 1;
847                 if (pthread_mutex_init(&inode->i_mutex, NULL) != 0) {
848                         ERROR_WITH_ERRNO("Error initializing mutex");
849                         FREE(inode);
850                         return NULL;
851                 }
852         #endif
853                 INIT_LIST_HEAD(&inode->dentry_list);
854         }
855         return inode;
856 }
857
858 static struct inode *new_inode()
859 {
860         struct inode *inode = new_timeless_inode();
861         if (inode) {
862                 u64 now = get_wim_timestamp();
863                 inode->creation_time = now;
864                 inode->last_access_time = now;
865                 inode->last_write_time = now;
866         }
867         return inode;
868 }
869
870 /*
871  * Creates an unlinked directory entry.
872  *
873  * @name:  The UTF-8 filename of the new dentry.
874  *
875  * Returns a pointer to the new dentry, or NULL if out of memory.
876  */
877 struct dentry *new_dentry(const char *name)
878 {
879         struct dentry *dentry;
880
881         dentry = MALLOC(sizeof(struct dentry));
882         if (!dentry)
883                 goto err;
884
885         dentry_common_init(dentry);
886         if (change_dentry_name(dentry, name) != 0)
887                 goto err;
888
889         dentry->parent = dentry;
890
891         return dentry;
892 err:
893         FREE(dentry);
894         ERROR("Failed to allocate new dentry");
895         return NULL;
896 }
897
898
899 static struct dentry *__new_dentry_with_inode(const char *name, bool timeless)
900 {
901         struct dentry *dentry;
902         dentry = new_dentry(name);
903         if (dentry) {
904                 if (timeless)
905                         dentry->d_inode = new_timeless_inode();
906                 else
907                         dentry->d_inode = new_inode();
908                 if (dentry->d_inode) {
909                         inode_add_dentry(dentry, dentry->d_inode);
910                 } else {
911                         free_dentry(dentry);
912                         dentry = NULL;
913                 }
914         }
915         return dentry;
916 }
917
918 struct dentry *new_dentry_with_timeless_inode(const char *name)
919 {
920         return __new_dentry_with_inode(name, true);
921 }
922
923 struct dentry *new_dentry_with_inode(const char *name)
924 {
925         return __new_dentry_with_inode(name, false);
926 }
927
928
929 static int init_ads_entry(struct ads_entry *ads_entry, const char *name)
930 {
931         int ret = 0;
932         memset(ads_entry, 0, sizeof(*ads_entry));
933         if (name && *name)
934                 ret = change_ads_name(ads_entry, name);
935         return ret;
936 }
937
938 static void destroy_ads_entry(struct ads_entry *ads_entry)
939 {
940         FREE(ads_entry->stream_name);
941         FREE(ads_entry->stream_name_utf8);
942 }
943
944
945 /* Frees an inode. */
946 void free_inode(struct inode *inode)
947 {
948         if (inode) {
949                 if (inode->ads_entries) {
950                         for (u16 i = 0; i < inode->num_ads; i++)
951                                 destroy_ads_entry(&inode->ads_entries[i]);
952                         FREE(inode->ads_entries);
953                 }
954         #ifdef WITH_FUSE
955                 wimlib_assert(inode->num_opened_fds == 0);
956                 FREE(inode->fds);
957                 pthread_mutex_destroy(&inode->i_mutex);
958         #endif
959                 FREE(inode->extracted_file);
960                 FREE(inode);
961         }
962 }
963
964 /* Decrements link count on an inode and frees it if the link count reaches 0.
965  * */
966 static void put_inode(struct inode *inode)
967 {
968         wimlib_assert(inode);
969         wimlib_assert(inode->link_count);
970         if (--inode->link_count == 0) {
971         #ifdef WITH_FUSE
972                 if (inode->num_opened_fds == 0)
973         #endif
974                 {
975                         free_inode(inode);
976                 }
977         }
978 }
979
980 /* Frees a WIM dentry.
981  *
982  * The inode is freed only if its link count is decremented to 0.
983  */
984 void free_dentry(struct dentry *dentry)
985 {
986         wimlib_assert(dentry != NULL);
987         FREE(dentry->file_name);
988         FREE(dentry->file_name_utf8);
989         FREE(dentry->short_name);
990         FREE(dentry->full_path_utf8);
991         if (dentry->d_inode)
992                 put_inode(dentry->d_inode);
993         FREE(dentry);
994 }
995
996 void put_dentry(struct dentry *dentry)
997 {
998         wimlib_assert(dentry != NULL);
999         wimlib_assert(dentry->refcnt != 0);
1000
1001         if (--dentry->refcnt == 0)
1002                 free_dentry(dentry);
1003 }
1004
1005 /*
1006  * This function is passed as an argument to for_dentry_in_tree_depth() in order
1007  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
1008  */
1009 static int do_free_dentry(struct dentry *dentry, void *__lookup_table)
1010 {
1011         struct lookup_table *lookup_table = __lookup_table;
1012         unsigned i;
1013
1014         if (lookup_table) {
1015                 struct lookup_table_entry *lte;
1016                 struct inode *inode = dentry->d_inode;
1017                 wimlib_assert(inode->link_count);
1018                 for (i = 0; i <= inode->num_ads; i++) {
1019                         lte = inode_stream_lte(inode, i, lookup_table);
1020                         if (lte)
1021                                 lte_decrement_refcnt(lte, lookup_table);
1022                 }
1023         }
1024
1025         put_dentry(dentry);
1026         return 0;
1027 }
1028
1029 /*
1030  * Unlinks and frees a dentry tree.
1031  *
1032  * @root:               The root of the tree.
1033  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
1034  *                      reference counts in the lookup table for the lookup
1035  *                      table entries corresponding to the dentries will be
1036  *                      decremented.
1037  */
1038 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table)
1039 {
1040         if (!root || !root->parent)
1041                 return;
1042         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1043 }
1044
1045 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
1046 {
1047         dentry->refcnt++;
1048         return 0;
1049 }
1050
1051 /*
1052  * Links a dentry into the directory tree.
1053  *
1054  * @dentry: The dentry to link.
1055  * @parent: The dentry that will be the parent of @dentry.
1056  */
1057 bool dentry_add_child(struct dentry * restrict parent,
1058                       struct dentry * restrict child)
1059 {
1060         wimlib_assert(dentry_is_directory(parent));
1061
1062         struct rb_root *root = &parent->d_inode->children;
1063         struct rb_node **new = &(root->rb_node);
1064         struct rb_node *rb_parent = NULL;
1065
1066         while (*new) {
1067                 struct dentry *this = rbnode_dentry(*new);
1068                 int result = dentry_compare_names(child, this);
1069
1070                 rb_parent = *new;
1071
1072                 if (result < 0)
1073                         new = &((*new)->rb_left);
1074                 else if (result > 0)
1075                         new = &((*new)->rb_right);
1076                 else
1077                         return false;
1078         }
1079         child->parent = parent;
1080         rb_link_node(&child->rb_node, rb_parent, new);
1081         rb_insert_color(&child->rb_node, root);
1082         return true;
1083 }
1084
1085 #ifdef WITH_FUSE
1086 /*
1087  * Unlink a dentry from the directory tree.
1088  *
1089  * Note: This merely removes it from the in-memory tree structure.
1090  */
1091 void unlink_dentry(struct dentry *dentry)
1092 {
1093         struct dentry *parent = dentry->parent;
1094         if (parent == dentry)
1095                 return;
1096         rb_erase(&dentry->rb_node, &parent->d_inode->children);
1097 }
1098 #endif
1099
1100 static inline struct dentry *inode_first_dentry(struct inode *inode)
1101 {
1102         wimlib_assert(inode->dentry_list.next != &inode->dentry_list);
1103         return container_of(inode->dentry_list.next, struct dentry,
1104                             inode_dentry_list);
1105 }
1106
1107 static int verify_inode(struct inode *inode, const WIMStruct *w)
1108 {
1109         const struct lookup_table *table = w->lookup_table;
1110         const struct wim_security_data *sd = wim_const_security_data(w);
1111         const struct dentry *first_dentry = inode_first_dentry(inode);
1112         int ret = WIMLIB_ERR_INVALID_DENTRY;
1113
1114         /* Check the security ID */
1115         if (inode->security_id < -1) {
1116                 ERROR("Dentry `%s' has an invalid security ID (%d)",
1117                         first_dentry->full_path_utf8, inode->security_id);
1118                 goto out;
1119         }
1120         if (inode->security_id >= sd->num_entries) {
1121                 ERROR("Dentry `%s' has an invalid security ID (%d) "
1122                       "(there are only %u entries in the security table)",
1123                         first_dentry->full_path_utf8, inode->security_id,
1124                         sd->num_entries);
1125                 goto out;
1126         }
1127
1128         /* Check that lookup table entries for all the resources exist, except
1129          * if the SHA1 message digest is all 0's, which indicates there is
1130          * intentionally no resource there.  */
1131         if (w->hdr.total_parts == 1) {
1132                 for (unsigned i = 0; i <= inode->num_ads; i++) {
1133                         struct lookup_table_entry *lte;
1134                         const u8 *hash;
1135                         hash = inode_stream_hash_unresolved(inode, i);
1136                         lte = __lookup_resource(table, hash);
1137                         if (!lte && !is_zero_hash(hash)) {
1138                                 ERROR("Could not find lookup table entry for stream "
1139                                       "%u of dentry `%s'", i, first_dentry->full_path_utf8);
1140                                 goto out;
1141                         }
1142                         if (lte && (lte->real_refcnt += inode->link_count) > lte->refcnt)
1143                         {
1144                         #ifdef ENABLE_ERROR_MESSAGES
1145                                 WARNING("The following lookup table entry "
1146                                         "has a reference count of %u, but",
1147                                         lte->refcnt);
1148                                 WARNING("We found %u references to it",
1149                                         lte->real_refcnt);
1150                                 WARNING("(One dentry referencing it is at `%s')",
1151                                          first_dentry->full_path_utf8);
1152
1153                                 print_lookup_table_entry(lte);
1154                         #endif
1155                                 /* Guess what!  install.wim for Windows 8
1156                                  * contains a stream with 2 dentries referencing
1157                                  * it, but the lookup table entry has reference
1158                                  * count of 1.  So we will need to handle this
1159                                  * case and not just make it be an error...  I'm
1160                                  * just setting the reference count to the
1161                                  * number of references we found.
1162                                  * (Unfortunately, even after doing this, the
1163                                  * reference count could be too low if it's also
1164                                  * referenced in other WIM images) */
1165
1166                         #if 1
1167                                 lte->refcnt = lte->real_refcnt;
1168                                 WARNING("Fixing reference count");
1169                         #else
1170                                 goto out;
1171                         #endif
1172                         }
1173                 }
1174         }
1175
1176         /* Make sure there is only one un-named stream. */
1177         unsigned num_unnamed_streams = 0;
1178         for (unsigned i = 0; i <= inode->num_ads; i++) {
1179                 const u8 *hash;
1180                 hash = inode_stream_hash_unresolved(inode, i);
1181                 if (!inode_stream_name_len(inode, i) && !is_zero_hash(hash))
1182                         num_unnamed_streams++;
1183         }
1184         if (num_unnamed_streams > 1) {
1185                 ERROR("Dentry `%s' has multiple (%u) un-named streams",
1186                       first_dentry->full_path_utf8, num_unnamed_streams);
1187                 goto out;
1188         }
1189         inode->verified = true;
1190         ret = 0;
1191 out:
1192         return ret;
1193 }
1194
1195 /* Run some miscellaneous verifications on a WIM dentry */
1196 int verify_dentry(struct dentry *dentry, void *wim)
1197 {
1198         int ret;
1199
1200         if (!dentry->d_inode->verified) {
1201                 ret = verify_inode(dentry->d_inode, wim);
1202                 if (ret != 0)
1203                         return ret;
1204         }
1205
1206         /* Cannot have a short name but no long name */
1207         if (dentry->short_name_len && !dentry->file_name_len) {
1208                 ERROR("Dentry `%s' has a short name but no long name",
1209                       dentry->full_path_utf8);
1210                 return WIMLIB_ERR_INVALID_DENTRY;
1211         }
1212
1213         /* Make sure root dentry is unnamed */
1214         if (dentry_is_root(dentry)) {
1215                 if (dentry->file_name_len) {
1216                         ERROR("The root dentry is named `%s', but it must "
1217                               "be unnamed", dentry->file_name_utf8);
1218                         return WIMLIB_ERR_INVALID_DENTRY;
1219                 }
1220         }
1221
1222 #if 0
1223         /* Check timestamps */
1224         if (inode->last_access_time < inode->creation_time ||
1225             inode->last_write_time < inode->creation_time) {
1226                 WARNING("Dentry `%s' was created after it was last accessed or "
1227                       "written to", dentry->full_path_utf8);
1228         }
1229 #endif
1230
1231         return 0;
1232 }
1233
1234
1235 #ifdef WITH_FUSE
1236 /* Returns the alternate data stream entry belonging to @inode that has the
1237  * stream name @stream_name. */
1238 struct ads_entry *inode_get_ads_entry(struct inode *inode,
1239                                       const char *stream_name,
1240                                       u16 *idx_ret)
1241 {
1242         size_t stream_name_len;
1243         if (!stream_name)
1244                 return NULL;
1245         if (inode->num_ads) {
1246                 u16 i = 0;
1247                 stream_name_len = strlen(stream_name);
1248                 do {
1249                         if (ads_entry_has_name(&inode->ads_entries[i],
1250                                                stream_name, stream_name_len))
1251                         {
1252                                 if (idx_ret)
1253                                         *idx_ret = i;
1254                                 return &inode->ads_entries[i];
1255                         }
1256                 } while (++i != inode->num_ads);
1257         }
1258         return NULL;
1259 }
1260 #endif
1261
1262 #if defined(WITH_FUSE) || defined(WITH_NTFS_3G)
1263 /*
1264  * Add an alternate stream entry to an inode and return a pointer to it, or NULL
1265  * if memory could not be allocated.
1266  */
1267 struct ads_entry *inode_add_ads(struct inode *inode, const char *stream_name)
1268 {
1269         u16 num_ads;
1270         struct ads_entry *ads_entries;
1271         struct ads_entry *new_entry;
1272
1273         DEBUG("Add alternate data stream \"%s\"", stream_name);
1274
1275         if (inode->num_ads >= 0xfffe) {
1276                 ERROR("Too many alternate data streams in one inode!");
1277                 return NULL;
1278         }
1279         num_ads = inode->num_ads + 1;
1280         ads_entries = REALLOC(inode->ads_entries,
1281                               num_ads * sizeof(inode->ads_entries[0]));
1282         if (!ads_entries) {
1283                 ERROR("Failed to allocate memory for new alternate data stream");
1284                 return NULL;
1285         }
1286         inode->ads_entries = ads_entries;
1287
1288         new_entry = &inode->ads_entries[num_ads - 1];
1289         if (init_ads_entry(new_entry, stream_name) != 0)
1290                 return NULL;
1291 #ifdef WITH_FUSE
1292         new_entry->stream_id = inode->next_stream_id++;
1293 #endif
1294         inode->num_ads = num_ads;
1295         return new_entry;
1296 }
1297 #endif
1298
1299 #ifdef WITH_FUSE
1300 /* Remove an alternate data stream from the inode  */
1301 void inode_remove_ads(struct inode *inode, u16 idx,
1302                       struct lookup_table *lookup_table)
1303 {
1304         struct ads_entry *ads_entry;
1305         struct lookup_table_entry *lte;
1306
1307         wimlib_assert(idx < inode->num_ads);
1308         wimlib_assert(inode->resolved);
1309
1310         ads_entry = &inode->ads_entries[idx];
1311
1312         DEBUG("Remove alternate data stream \"%s\"", ads_entry->stream_name_utf8);
1313
1314         lte = ads_entry->lte;
1315         if (lte)
1316                 lte_decrement_refcnt(lte, lookup_table);
1317
1318         destroy_ads_entry(ads_entry);
1319
1320         memcpy(&inode->ads_entries[idx],
1321                &inode->ads_entries[idx + 1],
1322                (inode->num_ads - idx - 1) * sizeof(inode->ads_entries[0]));
1323         inode->num_ads--;
1324 }
1325 #endif
1326
1327
1328
1329 /*
1330  * Reads the alternate data stream entries for a dentry.
1331  *
1332  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1333  *
1334  * @inode:      Inode to load the alternate data streams into.
1335  *                      @inode->num_ads must have been set to the number of
1336  *                      alternate data streams that are expected.
1337  *
1338  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1339  *                              to by @p.
1340  *
1341  * The format of the on-disk alternate stream entries is as follows:
1342  *
1343  * struct ads_entry_on_disk {
1344  *      u64  length;          // Length of the entry, in bytes.  This includes
1345  *                                  all fields (including the stream name and
1346  *                                  null terminator if present, AND the padding!).
1347  *      u64  reserved;        // Seems to be unused
1348  *      u8   hash[20];        // SHA1 message digest of the uncompressed stream
1349  *      u16  stream_name_len; // Length of the stream name, in bytes
1350  *      char stream_name[];   // Stream name in UTF-16LE, @stream_name_len bytes long,
1351  *                                  not including null terminator
1352  *      u16  zero;            // UTF-16 null terminator for the stream name, NOT
1353  *                                  included in @stream_name_len.  Based on what
1354  *                                  I've observed from filenames in dentries,
1355  *                                  this field should not exist when
1356  *                                  (@stream_name_len == 0), but you can't
1357  *                                  actually tell because of the padding anyway
1358  *                                  (provided that the padding is zeroed, which
1359  *                                  it always seems to be).
1360  *      char padding[];       // Padding to make the size a multiple of 8 bytes.
1361  * };
1362  *
1363  * In addition, the entries are 8-byte aligned.
1364  *
1365  * Return 0 on success or nonzero on failure.  On success, inode->ads_entries
1366  * is set to an array of `struct ads_entry's of length inode->num_ads.  On
1367  * failure, @inode is not modified.
1368  */
1369 static int read_ads_entries(const u8 *p, struct inode *inode,
1370                             u64 remaining_size)
1371 {
1372         u16 num_ads;
1373         struct ads_entry *ads_entries;
1374         int ret;
1375
1376         num_ads = inode->num_ads;
1377         ads_entries = CALLOC(num_ads, sizeof(inode->ads_entries[0]));
1378         if (!ads_entries) {
1379                 ERROR("Could not allocate memory for %"PRIu16" "
1380                       "alternate data stream entries", num_ads);
1381                 return WIMLIB_ERR_NOMEM;
1382         }
1383
1384         for (u16 i = 0; i < num_ads; i++) {
1385                 struct ads_entry *cur_entry;
1386                 u64 length;
1387                 u64 length_no_padding;
1388                 u64 total_length;
1389                 size_t utf8_len;
1390                 const u8 *p_save = p;
1391
1392                 cur_entry = &ads_entries[i];
1393
1394         #ifdef WITH_FUSE
1395                 ads_entries[i].stream_id = i + 1;
1396         #endif
1397
1398                 /* Read the base stream entry, excluding the stream name. */
1399                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
1400                         ERROR("Stream entries go past end of metadata resource");
1401                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
1402                         ret = WIMLIB_ERR_INVALID_DENTRY;
1403                         goto out_free_ads_entries;
1404                 }
1405
1406                 p = get_u64(p, &length);
1407                 p += 8; /* Skip the reserved field */
1408                 p = get_bytes(p, SHA1_HASH_SIZE, (u8*)cur_entry->hash);
1409                 p = get_u16(p, &cur_entry->stream_name_len);
1410
1411                 cur_entry->stream_name = NULL;
1412                 cur_entry->stream_name_utf8 = NULL;
1413
1414                 /* Length including neither the null terminator nor the padding
1415                  * */
1416                 length_no_padding = WIM_ADS_ENTRY_DISK_SIZE +
1417                                     cur_entry->stream_name_len;
1418
1419                 /* Length including the null terminator and the padding */
1420                 total_length = ((length_no_padding + 2) + 7) & ~7;
1421
1422                 wimlib_assert(total_length == ads_entry_total_length(cur_entry));
1423
1424                 if (remaining_size < length_no_padding) {
1425                         ERROR("Stream entries go past end of metadata resource");
1426                         ERROR("(remaining_size = %"PRIu64" bytes, "
1427                               "length_no_padding = %"PRIu64" bytes)",
1428                               remaining_size, length_no_padding);
1429                         ret = WIMLIB_ERR_INVALID_DENTRY;
1430                         goto out_free_ads_entries;
1431                 }
1432
1433                 /* The @length field in the on-disk ADS entry is expected to be
1434                  * equal to @total_length, which includes all of the entry and
1435                  * the padding that follows it to align the next ADS entry to an
1436                  * 8-byte boundary.  However, to be safe, we'll accept the
1437                  * length field as long as it's not less than the un-padded
1438                  * total length and not more than the padded total length. */
1439                 if (length < length_no_padding || length > total_length) {
1440                         ERROR("Stream entry has unexpected length "
1441                               "field (length field = %"PRIu64", "
1442                               "unpadded total length = %"PRIu64", "
1443                               "padded total length = %"PRIu64")",
1444                               length, length_no_padding, total_length);
1445                         ret = WIMLIB_ERR_INVALID_DENTRY;
1446                         goto out_free_ads_entries;
1447                 }
1448
1449                 if (cur_entry->stream_name_len) {
1450                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
1451                         if (!cur_entry->stream_name) {
1452                                 ret = WIMLIB_ERR_NOMEM;
1453                                 goto out_free_ads_entries;
1454                         }
1455                         get_bytes(p, cur_entry->stream_name_len,
1456                                   (u8*)cur_entry->stream_name);
1457                         cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
1458                                                                     cur_entry->stream_name_len,
1459                                                                     &utf8_len);
1460                         cur_entry->stream_name_utf8_len = utf8_len;
1461
1462                         if (!cur_entry->stream_name_utf8) {
1463                                 ret = WIMLIB_ERR_NOMEM;
1464                                 goto out_free_ads_entries;
1465                         }
1466                 }
1467                 /* It's expected that the size of every ADS entry is a multiple
1468                  * of 8.  However, to be safe, I'm allowing the possibility of
1469                  * an ADS entry at the very end of the metadata resource ending
1470                  * un-aligned.  So although we still need to increment the input
1471                  * pointer by @total_length to reach the next ADS entry, it's
1472                  * possible that less than @total_length is actually remaining
1473                  * in the metadata resource. We should set the remaining size to
1474                  * 0 bytes if this happens. */
1475                 p = p_save + total_length;
1476                 if (remaining_size < total_length)
1477                         remaining_size = 0;
1478                 else
1479                         remaining_size -= total_length;
1480         }
1481         inode->ads_entries = ads_entries;
1482 #ifdef WITH_FUSE
1483         inode->next_stream_id = inode->num_ads + 1;
1484 #endif
1485         return 0;
1486 out_free_ads_entries:
1487         for (u16 i = 0; i < num_ads; i++)
1488                 destroy_ads_entry(&ads_entries[i]);
1489         FREE(ads_entries);
1490         return ret;
1491 }
1492
1493 /*
1494  * Reads a directory entry, including all alternate data stream entries that
1495  * follow it, from the WIM image's metadata resource.
1496  *
1497  * @metadata_resource:  Buffer containing the uncompressed metadata resource.
1498  * @metadata_resource_len:   Length of the metadata resource.
1499  * @offset:     Offset of this directory entry in the metadata resource.
1500  * @dentry:     A `struct dentry' that will be filled in by this function.
1501  *
1502  * Return 0 on success or nonzero on failure.  On failure, @dentry have been
1503  * modified, bu it will be left with no pointers to any allocated buffers.
1504  * On success, the dentry->length field must be examined.  If zero, this was a
1505  * special "end of directory" dentry and not a real dentry.  If nonzero, this
1506  * was a real dentry.
1507  */
1508 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len,
1509                 u64 offset, struct dentry *dentry)
1510 {
1511         const u8 *p;
1512         u64 calculated_size;
1513         char *file_name = NULL;
1514         char *file_name_utf8 = NULL;
1515         char *short_name = NULL;
1516         u16 short_name_len;
1517         u16 file_name_len;
1518         size_t file_name_utf8_len = 0;
1519         int ret;
1520         struct inode *inode = NULL;
1521
1522         dentry_common_init(dentry);
1523
1524         /*Make sure the dentry really fits into the metadata resource.*/
1525         if (offset + 8 > metadata_resource_len || offset + 8 < offset) {
1526                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1527                       "end of the metadata resource (size %"PRIu64")",
1528                       offset, metadata_resource_len);
1529                 return WIMLIB_ERR_INVALID_DENTRY;
1530         }
1531
1532         /* Before reading the whole dentry, we need to read just the length.
1533          * This is because a dentry of length 8 (that is, just the length field)
1534          * terminates the list of sibling directory entries. */
1535
1536         p = get_u64(&metadata_resource[offset], &dentry->length);
1537
1538         /* A zero length field (really a length of 8, since that's how big the
1539          * directory entry is...) indicates that this is the end of directory
1540          * dentry.  We do not read it into memory as an actual dentry, so just
1541          * return successfully in that case. */
1542         if (dentry->length == 0)
1543                 return 0;
1544
1545         /* If the dentry does not overflow the metadata resource buffer and is
1546          * not too short, read the rest of it (excluding the alternate data
1547          * streams, but including the file name and short name variable-length
1548          * fields) into memory. */
1549         if (offset + dentry->length >= metadata_resource_len
1550             || offset + dentry->length < offset)
1551         {
1552                 ERROR("Directory entry at offset %"PRIu64" and with size "
1553                       "%"PRIu64" ends past the end of the metadata resource "
1554                       "(size %"PRIu64")",
1555                       offset, dentry->length, metadata_resource_len);
1556                 return WIMLIB_ERR_INVALID_DENTRY;
1557         }
1558
1559         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
1560                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1561                       dentry->length);
1562                 return WIMLIB_ERR_INVALID_DENTRY;
1563         }
1564
1565         inode = new_timeless_inode();
1566         if (!inode)
1567                 return WIMLIB_ERR_NOMEM;
1568
1569         p = get_u32(p, &inode->attributes);
1570         p = get_u32(p, (u32*)&inode->security_id);
1571         p = get_u64(p, &dentry->subdir_offset);
1572
1573         /* 2 unused fields */
1574         p += 2 * sizeof(u64);
1575         /*p = get_u64(p, &dentry->unused1);*/
1576         /*p = get_u64(p, &dentry->unused2);*/
1577
1578         p = get_u64(p, &inode->creation_time);
1579         p = get_u64(p, &inode->last_access_time);
1580         p = get_u64(p, &inode->last_write_time);
1581
1582         p = get_bytes(p, SHA1_HASH_SIZE, inode->hash);
1583
1584         /*
1585          * I don't know what's going on here.  It seems like M$ screwed up the
1586          * reparse points, then put the fields in the same place and didn't
1587          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1588          * have something to do with this, but it's not documented.
1589          */
1590         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1591                 /* ??? */
1592                 p += 4;
1593                 p = get_u32(p, &inode->reparse_tag);
1594                 p += 4;
1595         } else {
1596                 p = get_u32(p, &inode->reparse_tag);
1597                 p = get_u64(p, &inode->ino);
1598         }
1599
1600         /* By the way, the reparse_reserved field does not actually exist (at
1601          * least when the file is not a reparse point) */
1602
1603         p = get_u16(p, &inode->num_ads);
1604
1605         p = get_u16(p, &short_name_len);
1606         p = get_u16(p, &file_name_len);
1607
1608         /* We now know the length of the file name and short name.  Make sure
1609          * the length of the dentry is large enough to actually hold them.
1610          *
1611          * The calculated length here is unaligned to allow for the possibility
1612          * that the dentry->length names an unaligned length, although this
1613          * would be unexpected. */
1614         calculated_size = __dentry_correct_length_unaligned(file_name_len,
1615                                                             short_name_len);
1616
1617         if (dentry->length < calculated_size) {
1618                 ERROR("Unexpected end of directory entry! (Expected "
1619                       "at least %"PRIu64" bytes, got %"PRIu64" bytes. "
1620                       "short_name_len = %hu, file_name_len = %hu)",
1621                       calculated_size, dentry->length,
1622                       short_name_len, file_name_len);
1623                 ret = WIMLIB_ERR_INVALID_DENTRY;
1624                 goto out_free_inode;
1625         }
1626
1627         /* Read the filename if present.  Note: if the filename is empty, there
1628          * is no null terminator following it. */
1629         if (file_name_len) {
1630                 file_name = MALLOC(file_name_len);
1631                 if (!file_name) {
1632                         ERROR("Failed to allocate %hu bytes for dentry file name",
1633                               file_name_len);
1634                         ret = WIMLIB_ERR_NOMEM;
1635                         goto out_free_inode;
1636                 }
1637                 p = get_bytes(p, file_name_len, file_name);
1638
1639                 /* Convert filename to UTF-8. */
1640                 file_name_utf8 = utf16_to_utf8(file_name, file_name_len,
1641                                                &file_name_utf8_len);
1642
1643                 if (!file_name_utf8) {
1644                         ERROR("Failed to allocate memory to convert UTF-16 "
1645                               "filename (%hu bytes) to UTF-8", file_name_len);
1646                         ret = WIMLIB_ERR_NOMEM;
1647                         goto out_free_file_name;
1648                 }
1649                 if (*(u16*)p)
1650                         WARNING("Expected two zero bytes following the file name "
1651                                 "`%s', but found non-zero bytes", file_name_utf8);
1652                 p += 2;
1653         }
1654
1655         /* Align the calculated size */
1656         calculated_size = (calculated_size + 7) & ~7;
1657
1658         if (dentry->length > calculated_size) {
1659                 /* Weird; the dentry says it's longer than it should be.  Note
1660                  * that the length field does NOT include the size of the
1661                  * alternate stream entries. */
1662
1663                 /* Strangely, some directory entries inexplicably have a little
1664                  * over 70 bytes of extra data.  The exact amount of data seems
1665                  * to be 72 bytes, but it is aligned on the next 8-byte
1666                  * boundary.  It does NOT seem to be alternate data stream
1667                  * entries.  Here's an example of the aligned data:
1668                  *
1669                  * 01000000 40000000 6c786bba c58ede11 b0bb0026 1870892a b6adb76f
1670                  * e63a3e46 8fca8653 0d2effa1 6c786bba c58ede11 b0bb0026 1870892a
1671                  * 00000000 00000000 00000000 00000000
1672                  *
1673                  * Here's one interpretation of how the data is laid out.
1674                  *
1675                  * struct unknown {
1676                  *      u32 field1; (always 0x00000001)
1677                  *      u32 field2; (always 0x40000000)
1678                  *      u8  data[48]; (???)
1679                  *      u64 reserved1; (always 0)
1680                  *      u64 reserved2; (always 0)
1681                  * };*/
1682                 DEBUG("Dentry for file or directory `%s' has %zu extra "
1683                       "bytes of data",
1684                       file_name_utf8, dentry->length - calculated_size);
1685         }
1686
1687         /* Read the short filename if present.  Note: if there is no short
1688          * filename, there is no null terminator following it. */
1689         if (short_name_len) {
1690                 short_name = MALLOC(short_name_len);
1691                 if (!short_name) {
1692                         ERROR("Failed to allocate %hu bytes for short filename",
1693                               short_name_len);
1694                         ret = WIMLIB_ERR_NOMEM;
1695                         goto out_free_file_name_utf8;
1696                 }
1697
1698                 p = get_bytes(p, short_name_len, short_name);
1699                 if (*(u16*)p)
1700                         WARNING("Expected two zero bytes following the short name of "
1701                                 "`%s', but found non-zero bytes", file_name_utf8);
1702                 p += 2;
1703         }
1704
1705         /*
1706          * Read the alternate data streams, if present.  dentry->num_ads tells
1707          * us how many they are, and they will directly follow the dentry
1708          * on-disk.
1709          *
1710          * Note that each alternate data stream entry begins on an 8-byte
1711          * aligned boundary, and the alternate data stream entries are NOT
1712          * included in the dentry->length field for some reason.
1713          */
1714         if (inode->num_ads != 0) {
1715
1716                 /* Trying different lengths is just a hack to make sure we have
1717                  * a chance of reading the ADS entries correctly despite the
1718                  * poor documentation. */
1719
1720                 if (calculated_size != dentry->length) {
1721                         WARNING("Trying calculated dentry length (%"PRIu64") "
1722                                 "instead of dentry->length field (%"PRIu64") "
1723                                 "to read ADS entries",
1724                                 calculated_size, dentry->length);
1725                 }
1726                 u64 lengths_to_try[3] = {calculated_size,
1727                                          (dentry->length + 7) & ~7,
1728                                          dentry->length};
1729                 ret = WIMLIB_ERR_INVALID_DENTRY;
1730                 for (size_t i = 0; i < ARRAY_LEN(lengths_to_try); i++) {
1731                         if (lengths_to_try[i] > metadata_resource_len - offset)
1732                                 continue;
1733                         ret = read_ads_entries(&metadata_resource[offset + lengths_to_try[i]],
1734                                                inode,
1735                                                metadata_resource_len - offset - lengths_to_try[i]);
1736                         if (ret == 0)
1737                                 goto out;
1738                 }
1739                 ERROR("Failed to read alternate data stream "
1740                       "entries of `%s'", dentry->file_name_utf8);
1741                 goto out_free_short_name;
1742         }
1743 out:
1744
1745         /* We've read all the data for this dentry.  Set the names and their
1746          * lengths, and we've done. */
1747         dentry->d_inode            = inode;
1748         dentry->file_name          = file_name;
1749         dentry->file_name_utf8     = file_name_utf8;
1750         dentry->short_name         = short_name;
1751         dentry->file_name_len      = file_name_len;
1752         dentry->file_name_utf8_len = file_name_utf8_len;
1753         dentry->short_name_len     = short_name_len;
1754         return 0;
1755 out_free_short_name:
1756         FREE(short_name);
1757 out_free_file_name_utf8:
1758         FREE(file_name_utf8);
1759 out_free_file_name:
1760         FREE(file_name);
1761 out_free_inode:
1762         free_inode(inode);
1763         return ret;
1764 }
1765
1766 /* Reads the children of a dentry, and all their children, ..., etc. from the
1767  * metadata resource and into the dentry tree.
1768  *
1769  * @metadata_resource:  An array that contains the uncompressed metadata
1770  *                      resource for the WIM file.
1771  *
1772  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1773  *                          bytes.
1774  *
1775  * @dentry:     A pointer to a `struct dentry' that is the root of the directory
1776  *              tree and has already been read from the metadata resource.  It
1777  *              does not need to be the real root because this procedure is
1778  *              called recursively.
1779  *
1780  * @return:     Zero on success, nonzero on failure.
1781  */
1782 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1783                      struct dentry *dentry)
1784 {
1785         u64 cur_offset = dentry->subdir_offset;
1786         struct dentry *child;
1787         struct dentry cur_child;
1788         int ret;
1789
1790         /*
1791          * If @dentry has no child dentries, nothing more needs to be done for
1792          * this branch.  This is the case for regular files, symbolic links, and
1793          * *possibly* empty directories (although an empty directory may also
1794          * have one child dentry that is the special end-of-directory dentry)
1795          */
1796         if (cur_offset == 0)
1797                 return 0;
1798
1799         /* Find and read all the children of @dentry. */
1800         while (1) {
1801
1802                 /* Read next child of @dentry into @cur_child. */
1803                 ret = read_dentry(metadata_resource, metadata_resource_len,
1804                                   cur_offset, &cur_child);
1805                 if (ret != 0)
1806                         break;
1807
1808                 /* Check for end of directory. */
1809                 if (cur_child.length == 0)
1810                         break;
1811
1812                 /* Not end of directory.  Allocate this child permanently and
1813                  * link it to the parent and previous child. */
1814                 child = MALLOC(sizeof(struct dentry));
1815                 if (!child) {
1816                         ERROR("Failed to allocate %zu bytes for new dentry",
1817                               sizeof(struct dentry));
1818                         ret = WIMLIB_ERR_NOMEM;
1819                         break;
1820                 }
1821                 memcpy(child, &cur_child, sizeof(struct dentry));
1822
1823                 dentry_add_child(dentry, child);
1824
1825                 inode_add_dentry(child, child->d_inode);
1826
1827                 /* If there are children of this child, call this procedure
1828                  * recursively. */
1829                 if (child->subdir_offset != 0) {
1830                         ret = read_dentry_tree(metadata_resource,
1831                                                metadata_resource_len, child);
1832                         if (ret != 0)
1833                                 break;
1834                 }
1835
1836                 /* Advance to the offset of the next child.  Note: We need to
1837                  * advance by the TOTAL length of the dentry, not by the length
1838                  * child->length, which although it does take into account the
1839                  * padding, it DOES NOT take into account alternate stream
1840                  * entries. */
1841                 cur_offset += dentry_total_length(child);
1842         }
1843         return ret;
1844 }
1845
1846 /*
1847  * Writes a WIM dentry to an output buffer.
1848  *
1849  * @dentry:  The dentry structure.
1850  * @p:       The memory location to write the data to.
1851  * @return:  Pointer to the byte after the last byte we wrote as part of the
1852  *              dentry.
1853  */
1854 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
1855 {
1856         u8 *orig_p = p;
1857         const u8 *hash;
1858         const struct inode *inode = dentry->d_inode;
1859
1860         /* We calculate the correct length of the dentry ourselves because the
1861          * dentry->length field may been set to an unexpected value from when we
1862          * read the dentry in (for example, there may have been unknown data
1863          * appended to the end of the dentry...) */
1864         u64 length = dentry_correct_length(dentry);
1865
1866         p = put_u64(p, length);
1867         p = put_u32(p, inode->attributes);
1868         p = put_u32(p, inode->security_id);
1869         p = put_u64(p, dentry->subdir_offset);
1870         p = put_u64(p, 0); /* unused1 */
1871         p = put_u64(p, 0); /* unused2 */
1872         p = put_u64(p, inode->creation_time);
1873         p = put_u64(p, inode->last_access_time);
1874         p = put_u64(p, inode->last_write_time);
1875         hash = inode_stream_hash(inode, 0);
1876         p = put_bytes(p, SHA1_HASH_SIZE, hash);
1877         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1878                 p = put_zeroes(p, 4);
1879                 p = put_u32(p, inode->reparse_tag);
1880                 p = put_zeroes(p, 4);
1881         } else {
1882                 u64 link_group_id;
1883                 p = put_u32(p, 0);
1884                 if (inode->link_count == 1)
1885                         link_group_id = 0;
1886                 else
1887                         link_group_id = inode->ino;
1888                 p = put_u64(p, link_group_id);
1889         }
1890         p = put_u16(p, inode->num_ads);
1891         p = put_u16(p, dentry->short_name_len);
1892         p = put_u16(p, dentry->file_name_len);
1893         if (dentry->file_name_len) {
1894                 p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
1895                 p = put_u16(p, 0); /* filename padding, 2 bytes. */
1896         }
1897         if (dentry->short_name) {
1898                 p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
1899                 p = put_u16(p, 0); /* short name padding, 2 bytes */
1900         }
1901
1902         /* Align to 8-byte boundary */
1903         wimlib_assert(length >= (p - orig_p) && length - (p - orig_p) <= 7);
1904         p = put_zeroes(p, length - (p - orig_p));
1905
1906         /* Write the alternate data streams, if there are any.  Please see
1907          * read_ads_entries() for comments about the format of the on-disk
1908          * alternate data stream entries. */
1909         for (u16 i = 0; i < inode->num_ads; i++) {
1910                 p = put_u64(p, ads_entry_total_length(&inode->ads_entries[i]));
1911                 p = put_u64(p, 0); /* Unused */
1912                 hash = inode_stream_hash(inode, i + 1);
1913                 p = put_bytes(p, SHA1_HASH_SIZE, hash);
1914                 p = put_u16(p, inode->ads_entries[i].stream_name_len);
1915                 if (inode->ads_entries[i].stream_name_len) {
1916                         p = put_bytes(p, inode->ads_entries[i].stream_name_len,
1917                                          (u8*)inode->ads_entries[i].stream_name);
1918                         p = put_u16(p, 0);
1919                 }
1920                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1921         }
1922         wimlib_assert(p - orig_p == __dentry_total_length(dentry, length));
1923         return p;
1924 }
1925
1926 static int write_dentry_cb(struct dentry *dentry, void *_p)
1927 {
1928         u8 **p = _p;
1929         *p = write_dentry(dentry, *p);
1930         return 0;
1931 }
1932
1933 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p);
1934
1935 static int write_dentry_tree_recursive_cb(struct dentry *dentry, void *_p)
1936 {
1937         u8 **p = _p;
1938         *p = write_dentry_tree_recursive(dentry, *p);
1939         return 0;
1940 }
1941
1942 /* Recursive function that writes a dentry tree rooted at @parent, not including
1943  * @parent itself, which has already been written. */
1944 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p)
1945 {
1946         /* Nothing to do if this dentry has no children. */
1947         if (parent->subdir_offset == 0)
1948                 return p;
1949
1950         /* Write child dentries and end-of-directory entry.
1951          *
1952          * Note: we need to write all of this dentry's children before
1953          * recursively writing the directory trees rooted at each of the child
1954          * dentries, since the on-disk dentries for a dentry's children are
1955          * always located at consecutive positions in the metadata resource! */
1956         for_dentry_in_rbtree(parent->d_inode->children.rb_node, write_dentry_cb, &p);
1957
1958         /* write end of directory entry */
1959         p = put_u64(p, 0);
1960
1961         /* Recurse on children. */
1962         for_dentry_in_rbtree(parent->d_inode->children.rb_node,
1963                              write_dentry_tree_recursive_cb, &p);
1964         return p;
1965 }
1966
1967 /* Writes a directory tree to the metadata resource.
1968  *
1969  * @root:       Root of the dentry tree.
1970  * @p:          Pointer to a buffer with enough space for the dentry tree.
1971  *
1972  * Returns pointer to the byte after the last byte we wrote.
1973  */
1974 u8 *write_dentry_tree(const struct dentry *root, u8 *p)
1975 {
1976         DEBUG("Writing dentry tree.");
1977         wimlib_assert(dentry_is_root(root));
1978
1979         /* If we're the root dentry, we have no parent that already
1980          * wrote us, so we need to write ourselves. */
1981         p = write_dentry(root, p);
1982
1983         /* Write end of directory entry after the root dentry just to be safe;
1984          * however the root dentry obviously cannot have any siblings. */
1985         p = put_u64(p, 0);
1986
1987         /* Recursively write the rest of the dentry tree. */
1988         return write_dentry_tree_recursive(root, p);
1989 }
1990