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