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