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