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