]> wimlib.net Git - wimlib/blob - src/dentry.c
55da50cff6834063df67cae38477f8db0b6215d2
[wimlib] / src / dentry.c
1 /*
2  * dentry.c - see description below
3  */
4
5 /*
6  * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 /*
23  * This file contains logic to deal with WIM directory entries, or "dentries":
24  *
25  *  - Reading a dentry tree from a metadata resource in a WIM file
26  *  - Writing a dentry tree to a metadata resource in a WIM file
27  *  - Iterating through a tree of WIM dentries
28  *  - Path lookup: translating a path into a WIM dentry or inode
29  *  - Creating, modifying, and deleting WIM dentries
30  *
31  * Notes:
32  *
33  *  - A WIM file can contain multiple images, each of which has an independent
34  *    tree of dentries.  "On disk", the dentry tree for an image is stored in
35  *    the "metadata resource" for that image.
36  *
37  *  - Multiple dentries in an image may correspond to the same inode, or "file".
38  *    When this occurs, it means that the file has multiple names, or "hard
39  *    links".  A dentry is not a file, but rather the name of a file!
40  *
41  *  - Inodes are not represented explicitly in the WIM file format.  Instead,
42  *    the metadata resource provides a "hard link group ID" for each dentry.
43  *    wimlib handles pulling out actual inodes from this information, but this
44  *    occurs in inode_fixup.c and not in this file.
45  *
46  *  - wimlib does not allow *directory* hard links, so a WIM image really does
47  *    have a *tree* of dentries (and not an arbitrary graph of dentries).
48  *
49  *  - wimlib indexes dentries both case-insensitively and case-sensitively,
50  *    allowing either behavior to be used for path lookup.
51  *
52  *  - Multiple dentries in a directory might have the same case-insensitive
53  *    name.  But wimlib enforces that at most one dentry in a directory can have
54  *    a given case-sensitive name.
55  */
56
57 #ifdef HAVE_CONFIG_H
58 #  include "config.h"
59 #endif
60
61 #include <errno.h>
62
63 #include "wimlib/assert.h"
64 #include "wimlib/dentry.h"
65 #include "wimlib/inode.h"
66 #include "wimlib/encoding.h"
67 #include "wimlib/endianness.h"
68 #include "wimlib/metadata.h"
69 #include "wimlib/paths.h"
70
71 /* On-disk format of a WIM dentry (directory entry), located in the metadata
72  * resource for a WIM image.  */
73 struct wim_dentry_on_disk {
74
75         /* Length of this directory entry in bytes, not including any extra
76          * stream entries.  Should be a multiple of 8 so that the following
77          * dentry or extra stream entry is aligned on an 8-byte boundary.  (If
78          * not, wimlib will round it up.)  It must be at least as long as the
79          * fixed-length fields of the dentry (WIM_DENTRY_DISK_SIZE), plus the
80          * lengths of the file name and/or short name if present, plus the size
81          * of any "extra" data.
82          *
83          * It is also possible for this field to be 0.  This case indicates the
84          * end of a list of sibling entries in a directory.  It also means the
85          * real length is 8, because the dentry included only the length field,
86          * but that takes up 8 bytes.  */
87         le64 length;
88
89         /* File attributes for the file or directory.  This is a bitwise OR of
90          * the FILE_ATTRIBUTE_* constants and should correspond to the value
91          * retrieved by GetFileAttributes() on Windows. */
92         le32 attributes;
93
94         /* A value that specifies the security descriptor for this file or
95          * directory.  If -1, the file or directory has no security descriptor.
96          * Otherwise, it is a 0-based index into the WIM image's table of
97          * security descriptors (see: `struct wim_security_data') */
98         sle32 security_id;
99
100         /* Offset, in bytes, from the start of the uncompressed metadata
101          * resource of this directory's child directory entries, or 0 if this
102          * directory entry does not correspond to a directory or otherwise does
103          * not have any children. */
104         le64 subdir_offset;
105
106         /* Reserved fields */
107         le64 unused_1;
108         le64 unused_2;
109
110         /* Creation time, last access time, and last write time, in
111          * 100-nanosecond intervals since 12:00 a.m UTC January 1, 1601.  They
112          * should correspond to the times gotten by calling GetFileTime() on
113          * Windows. */
114         le64 creation_time;
115         le64 last_access_time;
116         le64 last_write_time;
117
118         /*
119          * Usually this is the SHA-1 message digest of the file's "contents"
120          * (the unnamed data stream).
121          *
122          * If the file has FILE_ATTRIBUTE_REPARSE_POINT set, then this is
123          * instead usually the SHA-1 message digest of the uncompressed reparse
124          * point data.
125          *
126          * However, there are some special rules that need to be applied to
127          * interpret this field correctly when extra stream entries are present.
128          * See the code for details.
129          */
130         u8 default_hash[SHA1_HASH_SIZE];
131
132         /* The format of the following data is not yet completely known and they
133          * do not correspond to Microsoft's documentation.
134          *
135          * If this directory entry is for a reparse point (has
136          * FILE_ATTRIBUTE_REPARSE_POINT set in the 'attributes' field), then the
137          * version of the following fields containing the reparse tag is valid.
138          * Furthermore, the field notated as not_rpfixed, as far as I can tell,
139          * is supposed to be set to 1 if reparse point fixups (a.k.a. fixing the
140          * targets of absolute symbolic links) were *not* done, and otherwise 0.
141          *
142          * If this directory entry is not for a reparse point, then the version
143          * of the following fields containing the hard_link_group_id is valid.
144          * All MS says about this field is that "If this file is part of a hard
145          * link set, all the directory entries in the set will share the same
146          * value in this field.".  However, more specifically I have observed
147          * the following:
148          *    - If the file is part of a hard link set of size 1, then the
149          *    hard_link_group_id should be set to either 0, which is treated
150          *    specially as indicating "not hardlinked", or any unique value.
151          *    - The specific nonzero values used to identity hard link sets do
152          *    not matter, as long as they are unique.
153          *    - However, due to bugs in Microsoft's software, it is actually NOT
154          *    guaranteed that directory entries that share the same hard link
155          *    group ID are actually hard linked to each either.  See
156          *    inode_fixup.c for the code that handles this.
157          */
158         union {
159                 struct {
160                         le32 rp_unknown_1;
161                         le32 reparse_tag;
162                         le16 rp_unknown_2;
163                         le16 not_rpfixed;
164                 } _packed_attribute reparse;
165                 struct {
166                         le32 rp_unknown_1;
167                         le64 hard_link_group_id;
168                 } _packed_attribute nonreparse;
169         };
170
171         /* Number of extra stream entries that directly follow this dentry
172          * on-disk.  */
173         le16 num_extra_streams;
174
175         /* If nonzero, this is the length, in bytes, of this dentry's UTF-16LE
176          * encoded short name (8.3 DOS-compatible name), excluding the null
177          * terminator.  If zero, then the long name of this dentry does not have
178          * a corresponding short name (but this does not exclude the possibility
179          * that another dentry for the same file has a short name).  */
180         le16 short_name_nbytes;
181
182         /* If nonzero, this is the length, in bytes, of this dentry's UTF-16LE
183          * encoded "long" name, excluding the null terminator.  If zero, then
184          * this file has no long name.  The root dentry should not have a long
185          * name, but all other dentries in the image should have long names.  */
186         le16 file_name_nbytes;
187
188         /* Beginning of optional, variable-length fields  */
189
190         /* If file_name_nbytes != 0, the next field will be the UTF-16LE encoded
191          * long file name.  This will be null-terminated, so the size of this
192          * field will really be file_name_nbytes + 2.  */
193         /*utf16lechar file_name[];*/
194
195         /* If short_name_nbytes != 0, the next field will be the UTF-16LE
196          * encoded short name.  This will be null-terminated, so the size of
197          * this field will really be short_name_nbytes + 2.  */
198         /*utf16lechar short_name[];*/
199
200         /* If there is still space in the dentry (according to the 'length'
201          * field) after 8-byte alignment, then the remaining space will be a
202          * variable-length list of tagged metadata items.  See tagged_items.c
203          * for more information.  */
204         /* u8 tagged_items[] _aligned_attribute(8); */
205
206 } _packed_attribute;
207         /* If num_extra_streams != 0, then there are that many extra stream
208          * entries following the dentry, starting on the next 8-byte aligned
209          * boundary.  They are not counted in the 'length' field of the dentry.
210          */
211
212 /* On-disk format of an extra stream entry.  This represents an extra NTFS-style
213  * "stream" associated with the file, such as a named data stream.  */
214 struct wim_extra_stream_entry_on_disk {
215
216         /* Length of this extra stream entry, in bytes.  This includes all
217          * fixed-length fields, plus the name and null terminator if present,
218          * and any needed padding such that the length is a multiple of 8.  */
219         le64 length;
220
221         /* Reserved field  */
222         le64 reserved;
223
224         /* SHA-1 message digest of this stream's uncompressed data, or all
225          * zeroes if this stream's data is of zero length.  */
226         u8 hash[SHA1_HASH_SIZE];
227
228         /* Length of this stream's name, in bytes and excluding the null
229          * terminator; or 0 if this stream is unnamed.  */
230         le16 name_nbytes;
231
232         /* Stream name in UTF-16LE.  It is @name_nbytes bytes long, excluding
233          * the null terminator.  There is a null terminator character if
234          * @name_nbytes != 0; i.e., if this stream is named.  */
235         utf16lechar name[];
236 } _packed_attribute;
237
238 static void
239 do_dentry_set_name(struct wim_dentry *dentry, utf16lechar *file_name,
240                    size_t file_name_nbytes)
241 {
242         FREE(dentry->file_name);
243         dentry->file_name = file_name;
244         dentry->file_name_nbytes = file_name_nbytes;
245
246         if (dentry_has_short_name(dentry)) {
247                 FREE(dentry->short_name);
248                 dentry->short_name = NULL;
249                 dentry->short_name_nbytes = 0;
250         }
251 }
252
253 /*
254  * Set the name of a WIM dentry from a UTF-16LE string.
255  *
256  * This sets the long name of the dentry.  The short name will automatically be
257  * removed, since it may not be appropriate for the new long name.
258  *
259  * The @name string need not be null-terminated, since its length is specified
260  * in @name_nbytes.
261  *
262  * If @name_nbytes is 0, both the long and short names of the dentry will be
263  * removed.
264  *
265  * Only use this function on unlinked dentries, since it doesn't update the name
266  * indices.  For dentries that are currently linked into the tree, use
267  * rename_wim_path().
268  *
269  * Returns 0 or WIMLIB_ERR_NOMEM.
270  */
271 int
272 dentry_set_name_utf16le(struct wim_dentry *dentry, const utf16lechar *name,
273                         size_t name_nbytes)
274 {
275         utf16lechar *dup = NULL;
276
277         if (name_nbytes) {
278                 dup = utf16le_dupz(name, name_nbytes);
279                 if (!dup)
280                         return WIMLIB_ERR_NOMEM;
281         }
282         do_dentry_set_name(dentry, dup, name_nbytes);
283         return 0;
284 }
285
286
287 /*
288  * Set the name of a WIM dentry from a 'tchar' string.
289  *
290  * This sets the long name of the dentry.  The short name will automatically be
291  * removed, since it may not be appropriate for the new long name.
292  *
293  * If @name is NULL or empty, both the long and short names of the dentry will
294  * be removed.
295  *
296  * Only use this function on unlinked dentries, since it doesn't update the name
297  * indices.  For dentries that are currently linked into the tree, use
298  * rename_wim_path().
299  *
300  * Returns 0 or an error code resulting from a failed string conversion.
301  */
302 int
303 dentry_set_name(struct wim_dentry *dentry, const tchar *name)
304 {
305         utf16lechar *name_utf16le = NULL;
306         size_t name_utf16le_nbytes = 0;
307         int ret;
308
309         if (name && *name) {
310                 ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
311                                       &name_utf16le, &name_utf16le_nbytes);
312                 if (ret)
313                         return ret;
314         }
315
316         do_dentry_set_name(dentry, name_utf16le, name_utf16le_nbytes);
317         return 0;
318 }
319
320 /* Calculate the minimum unaligned length, in bytes, of an on-disk WIM dentry
321  * that has names of the specified lengths.  (Zero length means the
322  * corresponding name actually does not exist.)  The returned value excludes
323  * tagged metadata items as well as any extra stream entries that may need to
324  * follow the dentry.  */
325 static size_t
326 dentry_min_len_with_names(u16 file_name_nbytes, u16 short_name_nbytes)
327 {
328         size_t length = sizeof(struct wim_dentry_on_disk);
329         if (file_name_nbytes)
330                 length += (u32)file_name_nbytes + 2;
331         if (short_name_nbytes)
332                 length += (u32)short_name_nbytes + 2;
333         return length;
334 }
335
336
337 /* Return the length, in bytes, required for the specified stream on-disk, when
338  * represented as an extra stream entry.  */
339 static size_t
340 stream_out_total_length(const struct wim_inode_stream *strm)
341 {
342         /* Account for the fixed length portion  */
343         size_t len = sizeof(struct wim_extra_stream_entry_on_disk);
344
345         /* For named streams, account for the variable-length name.  */
346         if (stream_is_named(strm))
347                 len += utf16le_len_bytes(strm->stream_name) + 2;
348
349         /* Account for any necessary padding to the next 8-byte boundary.  */
350         return (len + 7) & ~7;
351 }
352
353 /*
354  * Calculate the total number of bytes that will be consumed when a dentry is
355  * written.  This includes the fixed-length portion of the dentry, the name
356  * fields, any tagged metadata items, and any extra stream entries.  This also
357  * includes all alignment bytes.
358  */
359 size_t
360 dentry_out_total_length(const struct wim_dentry *dentry)
361 {
362         const struct wim_inode *inode = dentry->d_inode;
363         size_t len;
364
365         len = dentry_min_len_with_names(dentry->file_name_nbytes,
366                                         dentry->short_name_nbytes);
367         len = (len + 7) & ~7;
368
369         if (inode->i_extra_size) {
370                 len += inode->i_extra_size;
371                 len = (len + 7) & ~7;
372         }
373
374         if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
375                 /*
376                  * Extra stream entries:
377                  *
378                  * - Use one extra stream entry for each named data stream
379                  * - Use one extra stream entry for the unnamed data stream when there is either:
380                  *      - a reparse point stream
381                  *      - at least one named data stream (for Windows PE bug workaround)
382                  * - Use one extra stream entry for the reparse point stream if there is one
383                  */
384                 bool have_named_data_stream = false;
385                 bool have_reparse_point_stream = false;
386                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
387                         const struct wim_inode_stream *strm = &inode->i_streams[i];
388                         if (stream_is_named_data_stream(strm)) {
389                                 len += stream_out_total_length(strm);
390                                 have_named_data_stream = true;
391                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
392                                 wimlib_assert(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT);
393                                 have_reparse_point_stream = true;
394                         }
395                 }
396
397                 if (have_named_data_stream || have_reparse_point_stream) {
398                         if (have_reparse_point_stream)
399                                 len += (sizeof(struct wim_extra_stream_entry_on_disk) + 7) & ~7;
400                         len += (sizeof(struct wim_extra_stream_entry_on_disk) + 7) & ~7;
401                 }
402         }
403
404         return len;
405 }
406
407 /* Internal version of for_dentry_in_tree() that omits the NULL check  */
408 static int
409 do_for_dentry_in_tree(struct wim_dentry *dentry,
410                       int (*visitor)(struct wim_dentry *, void *), void *arg)
411 {
412         int ret;
413         struct wim_dentry *child;
414
415         ret = (*visitor)(dentry, arg);
416         if (unlikely(ret))
417                 return ret;
418
419         for_dentry_child(child, dentry) {
420                 ret = do_for_dentry_in_tree(child, visitor, arg);
421                 if (unlikely(ret))
422                         return ret;
423         }
424         return 0;
425 }
426
427 /* Internal version of for_dentry_in_tree_depth() that omits the NULL check  */
428 static int
429 do_for_dentry_in_tree_depth(struct wim_dentry *dentry,
430                             int (*visitor)(struct wim_dentry *, void *), void *arg)
431 {
432         int ret;
433         struct wim_dentry *child;
434
435         for_dentry_child_postorder(child, dentry) {
436                 ret = do_for_dentry_in_tree_depth(child, visitor, arg);
437                 if (unlikely(ret))
438                         return ret;
439         }
440         return unlikely((*visitor)(dentry, arg));
441 }
442
443 /*
444  * Call a function on all dentries in a tree.
445  *
446  * @arg will be passed as the second argument to each invocation of @visitor.
447  *
448  * This function does a pre-order traversal --- that is, a parent will be
449  * visited before its children.  It also will visit siblings in order of
450  * case-sensitive filename.  Equivalently, this function visits the entire tree
451  * in the case-sensitive lexicographic order of the full paths.
452  *
453  * It is safe to pass NULL for @root, which means that the dentry tree is empty.
454  * In this case, this function does nothing.
455  *
456  * @visitor must not modify the structure of the dentry tree during the
457  * traversal.
458  *
459  * The return value will be 0 if all calls to @visitor returned 0.  Otherwise,
460  * the return value will be the first nonzero value returned by @visitor.
461  */
462 int
463 for_dentry_in_tree(struct wim_dentry *root,
464                    int (*visitor)(struct wim_dentry *, void *), void *arg)
465 {
466         if (unlikely(!root))
467                 return 0;
468         return do_for_dentry_in_tree(root, visitor, arg);
469 }
470
471 /* Like for_dentry_in_tree(), but do a depth-first traversal of the dentry tree.
472  * That is, the visitor function will be called on a dentry's children before
473  * itself.  It will be safe to free a dentry when visiting it.  */
474 static int
475 for_dentry_in_tree_depth(struct wim_dentry *root,
476                          int (*visitor)(struct wim_dentry *, void *), void *arg)
477 {
478         if (unlikely(!root))
479                 return 0;
480         return do_for_dentry_in_tree_depth(root, visitor, arg);
481 }
482
483 /*
484  * Calculate the full path to @dentry within the WIM image, if not already done.
485  *
486  * The full name will be saved in the cached value 'dentry->_full_path'.
487  *
488  * Whenever possible, use dentry_full_path() instead of calling this and
489  * accessing _full_path directly.
490  *
491  * Returns 0 or an error code resulting from a failed string conversion.
492  */
493 int
494 calculate_dentry_full_path(struct wim_dentry *dentry)
495 {
496         size_t ulen;
497         size_t dummy;
498         const struct wim_dentry *d;
499
500         if (dentry->_full_path)
501                 return 0;
502
503         ulen = 0;
504         d = dentry;
505         do {
506                 ulen += d->file_name_nbytes / sizeof(utf16lechar);
507                 ulen++;
508                 d = d->d_parent;  /* assumes d == d->d_parent for root  */
509         } while (!dentry_is_root(d));
510
511         utf16lechar ubuf[ulen];
512         utf16lechar *p = &ubuf[ulen];
513
514         d = dentry;
515         do {
516                 p -= d->file_name_nbytes / sizeof(utf16lechar);
517                 memcpy(p, d->file_name, d->file_name_nbytes);
518                 *--p = cpu_to_le16(WIM_PATH_SEPARATOR);
519                 d = d->d_parent;  /* assumes d == d->d_parent for root  */
520         } while (!dentry_is_root(d));
521
522         wimlib_assert(p == ubuf);
523
524         return utf16le_to_tstr(ubuf, ulen * sizeof(utf16lechar),
525                                &dentry->_full_path, &dummy);
526 }
527
528 /*
529  * Return the full path to the @dentry within the WIM image, or NULL if the full
530  * path could not be determined due to a string conversion error.
531  *
532  * The returned memory will be cached in the dentry, so the caller is not
533  * responsible for freeing it.
534  */
535 tchar *
536 dentry_full_path(struct wim_dentry *dentry)
537 {
538         calculate_dentry_full_path(dentry);
539         return dentry->_full_path;
540 }
541
542 static int
543 dentry_calculate_subdir_offset(struct wim_dentry *dentry, void *_subdir_offset_p)
544 {
545         if (dentry_is_directory(dentry)) {
546                 u64 *subdir_offset_p = _subdir_offset_p;
547                 struct wim_dentry *child;
548
549                 /* Set offset of directory's child dentries  */
550                 dentry->subdir_offset = *subdir_offset_p;
551
552                 /* Account for child dentries  */
553                 for_dentry_child(child, dentry)
554                         *subdir_offset_p += dentry_out_total_length(child);
555
556                 /* Account for end-of-directory entry  */
557                 *subdir_offset_p += 8;
558         } else {
559                 /* Not a directory; set subdir_offset to 0  */
560                 dentry->subdir_offset = 0;
561         }
562         return 0;
563 }
564
565 /*
566  * Calculate the subdir offsets for a dentry tree, in preparation of writing
567  * that dentry tree to a metadata resource.
568  *
569  * The subdir offset of each dentry is the offset in the uncompressed metadata
570  * resource at which its child dentries begin, or 0 if that dentry has no
571  * children.
572  *
573  * The caller must initialize *subdir_offset_p to the first subdir offset that
574  * is available to use after the root dentry is written.
575  *
576  * When this function returns, *subdir_offset_p will have been advanced past the
577  * size needed for the dentry tree within the uncompressed metadata resource.
578  */
579 void
580 calculate_subdir_offsets(struct wim_dentry *root, u64 *subdir_offset_p)
581 {
582         for_dentry_in_tree(root, dentry_calculate_subdir_offset, subdir_offset_p);
583 }
584
585 /* Compare the UTF-16LE long filenames of two dentries case insensitively.  */
586 static int
587 dentry_compare_names_case_insensitive(const struct wim_dentry *d1,
588                                       const struct wim_dentry *d2)
589 {
590         return cmp_utf16le_strings(d1->file_name,
591                                    d1->file_name_nbytes / 2,
592                                    d2->file_name,
593                                    d2->file_name_nbytes / 2,
594                                    true);
595 }
596
597 /* Compare the UTF-16LE long filenames of two dentries case sensitively.  */
598 static int
599 dentry_compare_names_case_sensitive(const struct wim_dentry *d1,
600                                     const struct wim_dentry *d2)
601 {
602         return cmp_utf16le_strings(d1->file_name,
603                                    d1->file_name_nbytes / 2,
604                                    d2->file_name,
605                                    d2->file_name_nbytes / 2,
606                                    false);
607 }
608
609 static int
610 _avl_dentry_compare_names_ci(const struct avl_tree_node *n1,
611                              const struct avl_tree_node *n2)
612 {
613         const struct wim_dentry *d1, *d2;
614
615         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node_ci);
616         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node_ci);
617         return dentry_compare_names_case_insensitive(d1, d2);
618 }
619
620 static int
621 _avl_dentry_compare_names(const struct avl_tree_node *n1,
622                           const struct avl_tree_node *n2)
623 {
624         const struct wim_dentry *d1, *d2;
625
626         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node);
627         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node);
628         return dentry_compare_names_case_sensitive(d1, d2);
629 }
630
631 /* Default case sensitivity behavior for searches with
632  * WIMLIB_CASE_PLATFORM_DEFAULT specified.  This can be modified by passing
633  * WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE or
634  * WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE to wimlib_global_init().  */
635 bool default_ignore_case =
636 #ifdef __WIN32__
637         true
638 #else
639         false
640 #endif
641 ;
642
643 /* Case-sensitive dentry lookup.  Only @file_name and @file_name_nbytes of
644  * @dummy must be valid.  */
645 static struct wim_dentry *
646 dir_lookup(const struct wim_inode *dir, const struct wim_dentry *dummy)
647 {
648         struct avl_tree_node *node;
649
650         node = avl_tree_lookup_node(dir->i_children,
651                                     &dummy->d_index_node,
652                                     _avl_dentry_compare_names);
653         if (!node)
654                 return NULL;
655         return avl_tree_entry(node, struct wim_dentry, d_index_node);
656 }
657
658 /* Case-insensitive dentry lookup.  Only @file_name and @file_name_nbytes of
659  * @dummy must be valid.  */
660 static struct wim_dentry *
661 dir_lookup_ci(const struct wim_inode *dir, const struct wim_dentry *dummy)
662 {
663         struct avl_tree_node *node;
664
665         node = avl_tree_lookup_node(dir->i_children_ci,
666                                     &dummy->d_index_node_ci,
667                                     _avl_dentry_compare_names_ci);
668         if (!node)
669                 return NULL;
670         return avl_tree_entry(node, struct wim_dentry, d_index_node_ci);
671 }
672
673 /* Given a UTF-16LE filename and a directory, look up the dentry for the file.
674  * Return it if found, otherwise NULL.  This has configurable case sensitivity,
675  * and @name need not be null-terminated.  */
676 struct wim_dentry *
677 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
678                                    const utf16lechar *name,
679                                    size_t name_nbytes,
680                                    CASE_SENSITIVITY_TYPE case_ctype)
681 {
682         const struct wim_inode *dir = dentry->d_inode;
683         bool ignore_case = will_ignore_case(case_ctype);
684         struct wim_dentry dummy;
685         struct wim_dentry *child;
686
687         dummy.file_name = (utf16lechar*)name;
688         dummy.file_name_nbytes = name_nbytes;
689
690         if (!ignore_case)
691                 /* Case-sensitive lookup.  */
692                 return dir_lookup(dir, &dummy);
693
694         /* Case-insensitive lookup.  */
695
696         child = dir_lookup_ci(dir, &dummy);
697         if (!child)
698                 return NULL;
699
700         if (likely(list_empty(&child->d_ci_conflict_list)))
701                 /* Only one dentry has this case-insensitive name; return it */
702                 return child;
703
704         /* Multiple dentries have the same case-insensitive name.  Choose the
705          * dentry with the same case-sensitive name, if one exists; otherwise
706          * print a warning and choose one of the possible dentries arbitrarily.
707          */
708         struct wim_dentry *alt = child;
709         size_t num_alts = 0;
710
711         do {
712                 num_alts++;
713                 if (!dentry_compare_names_case_sensitive(&dummy, alt))
714                         return alt;
715                 alt = list_entry(alt->d_ci_conflict_list.next,
716                                  struct wim_dentry, d_ci_conflict_list);
717         } while (alt != child);
718
719         WARNING("Result of case-insensitive lookup is ambiguous\n"
720                 "          (returning \"%"TS"\" of %zu "
721                 "possible files, including \"%"TS"\")",
722                 dentry_full_path(child),
723                 num_alts,
724                 dentry_full_path(list_entry(child->d_ci_conflict_list.next,
725                                             struct wim_dentry,
726                                             d_ci_conflict_list)));
727         return child;
728 }
729
730 /* Given a 'tchar' filename and a directory, look up the dentry for the file.
731  * If the filename was successfully converted to UTF-16LE and the dentry was
732  * found, return it; otherwise return NULL.  This has configurable case
733  * sensitivity.  */
734 struct wim_dentry *
735 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name,
736                            CASE_SENSITIVITY_TYPE case_type)
737 {
738         int ret;
739         const utf16lechar *name_utf16le;
740         size_t name_utf16le_nbytes;
741         struct wim_dentry *child;
742
743         ret = tstr_get_utf16le_and_len(name, &name_utf16le,
744                                        &name_utf16le_nbytes);
745         if (ret)
746                 return NULL;
747
748         child = get_dentry_child_with_utf16le_name(dentry,
749                                                    name_utf16le,
750                                                    name_utf16le_nbytes,
751                                                    case_type);
752         tstr_put_utf16le(name_utf16le);
753         return child;
754 }
755
756 /* This is the UTF-16LE version of get_dentry(), currently private to this file
757  * because no one needs it besides get_dentry().  */
758 static struct wim_dentry *
759 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path,
760                    CASE_SENSITIVITY_TYPE case_type)
761 {
762         struct wim_dentry *cur_dentry;
763         const utf16lechar *name_start, *name_end;
764
765         /* Start with the root directory of the image.  Note: this will be NULL
766          * if an image has been added directly with wimlib_add_empty_image() but
767          * no files have been added yet; in that case we fail with ENOENT.  */
768         cur_dentry = wim_get_current_root_dentry(wim);
769
770         name_start = path;
771         for (;;) {
772                 if (cur_dentry == NULL) {
773                         errno = ENOENT;
774                         return NULL;
775                 }
776
777                 if (*name_start && !dentry_is_directory(cur_dentry)) {
778                         errno = ENOTDIR;
779                         return NULL;
780                 }
781
782                 while (*name_start == cpu_to_le16(WIM_PATH_SEPARATOR))
783                         name_start++;
784
785                 if (!*name_start)
786                         return cur_dentry;
787
788                 name_end = name_start;
789                 do {
790                         ++name_end;
791                 } while (*name_end != cpu_to_le16(WIM_PATH_SEPARATOR) && *name_end);
792
793                 cur_dentry = get_dentry_child_with_utf16le_name(cur_dentry,
794                                                                 name_start,
795                                                                 (u8*)name_end - (u8*)name_start,
796                                                                 case_type);
797                 name_start = name_end;
798         }
799 }
800
801 /*
802  * WIM path lookup: translate a path in the currently selected WIM image to the
803  * corresponding dentry, if it exists.
804  *
805  * @wim
806  *      The WIMStruct for the WIM.  The search takes place in the currently
807  *      selected image.
808  *
809  * @path
810  *      The path to look up, given relative to the root of the WIM image.
811  *      Characters with value WIM_PATH_SEPARATOR are taken to be path
812  *      separators.  Leading path separators are ignored, whereas one or more
813  *      trailing path separators cause the path to only match a directory.
814  *
815  * @case_type
816  *      The case-sensitivity behavior of this function, as one of the following
817  *      constants:
818  *
819  *    - WIMLIB_CASE_SENSITIVE:  Perform the search case sensitively.  This means
820  *      that names must match exactly.
821  *
822  *    - WIMLIB_CASE_INSENSITIVE:  Perform the search case insensitively.  This
823  *      means that names are considered to match if they are equal when
824  *      transformed to upper case.  If a path component matches multiple names
825  *      case-insensitively, the name that matches the path component
826  *      case-sensitively is chosen, if existent; otherwise one
827  *      case-insensitively matching name is chosen arbitrarily.
828  *
829  *    - WIMLIB_CASE_PLATFORM_DEFAULT:  Perform either case-sensitive or
830  *      case-insensitive search, depending on the value of the global variable
831  *      default_ignore_case.
832  *
833  *    In any case, no Unicode normalization is done before comparing strings.
834  *
835  * Returns a pointer to the dentry that is the result of the lookup, or NULL if
836  * no such dentry exists.  If NULL is returned, errno is set to one of the
837  * following values:
838  *
839  *      ENOTDIR if one of the path components used as a directory existed but
840  *      was not, in fact, a directory.
841  *
842  *      ENOENT otherwise.
843  *
844  * Additional notes:
845  *
846  *    - This function does not consider a reparse point to be a directory, even
847  *      if it has FILE_ATTRIBUTE_DIRECTORY set.
848  *
849  *    - This function does not dereference symbolic links or junction points
850  *      when performing the search.
851  *
852  *    - Since this function ignores leading slashes, the empty path is valid and
853  *      names the root directory of the WIM image.
854  *
855  *    - An image added with wimlib_add_empty_image() does not have a root
856  *      directory yet, and this function will fail with ENOENT for any path on
857  *      such an image.
858  */
859 struct wim_dentry *
860 get_dentry(WIMStruct *wim, const tchar *path, CASE_SENSITIVITY_TYPE case_type)
861 {
862         int ret;
863         const utf16lechar *path_utf16le;
864         struct wim_dentry *dentry;
865
866         ret = tstr_get_utf16le(path, &path_utf16le);
867         if (ret)
868                 return NULL;
869         dentry = get_dentry_utf16le(wim, path_utf16le, case_type);
870         tstr_put_utf16le(path_utf16le);
871         return dentry;
872 }
873
874 /* Modify @path, which is a null-terminated string @len 'tchars' in length,
875  * in-place to produce the path to its parent directory.  */
876 static void
877 to_parent_name(tchar *path, size_t len)
878 {
879         ssize_t i = (ssize_t)len - 1;
880         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
881                 i--;
882         while (i >= 0 && path[i] != WIM_PATH_SEPARATOR)
883                 i--;
884         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
885                 i--;
886         path[i + 1] = T('\0');
887 }
888
889 /* Similar to get_dentry(), but returns the dentry named by @path with the last
890  * component stripped off.
891  *
892  * Note: The returned dentry is NOT guaranteed to be a directory.  */
893 struct wim_dentry *
894 get_parent_dentry(WIMStruct *wim, const tchar *path,
895                   CASE_SENSITIVITY_TYPE case_type)
896 {
897         size_t path_len = tstrlen(path);
898         tchar buf[path_len + 1];
899
900         tmemcpy(buf, path, path_len + 1);
901         to_parent_name(buf, path_len);
902         return get_dentry(wim, buf, case_type);
903 }
904
905 /*
906  * Create an unlinked dentry.
907  *
908  * @name specifies the long name to give the new dentry.  If NULL or empty, the
909  * new dentry will be given no long name.
910  *
911  * The new dentry will have no short name and no associated inode.
912  *
913  * On success, returns 0 and a pointer to the new, allocated dentry is stored in
914  * *dentry_ret.  On failure, returns WIMLIB_ERR_NOMEM or an error code resulting
915  * from a failed string conversion.
916  */
917 int
918 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
919 {
920         struct wim_dentry *dentry;
921         int ret;
922
923         dentry = CALLOC(1, sizeof(struct wim_dentry));
924         if (!dentry)
925                 return WIMLIB_ERR_NOMEM;
926
927         if (name && *name) {
928                 ret = dentry_set_name(dentry, name);
929                 if (ret) {
930                         FREE(dentry);
931                         return ret;
932                 }
933         }
934         dentry->d_parent = dentry;
935         *dentry_ret = dentry;
936         return 0;
937 }
938
939 static int
940 _new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret,
941                        bool timeless)
942 {
943         struct wim_dentry *dentry;
944         struct wim_inode *inode;
945         int ret;
946
947         ret = new_dentry(name, &dentry);
948         if (ret)
949                 return ret;
950
951         if (timeless)
952                 inode = new_timeless_inode();
953         else
954                 inode = new_inode();
955         if (!inode) {
956                 free_dentry(dentry);
957                 return WIMLIB_ERR_NOMEM;
958         }
959
960         d_associate(dentry, inode);
961
962         *dentry_ret = dentry;
963         return 0;
964 }
965
966 /* Like new_dentry(), but also allocate an inode and associate it with the
967  * dentry.  The timestamps for the inode will be set to the current time.  */
968 int
969 new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret)
970 {
971         return _new_dentry_with_inode(name, dentry_ret, false);
972 }
973
974 /* Like new_dentry_with_inode(), but don't bother setting the timestamps for the
975  * new inode; instead, just leave them as 0, under the presumption that the
976  * caller will set them itself.  */
977 int
978 new_dentry_with_timeless_inode(const tchar *name, struct wim_dentry **dentry_ret)
979 {
980         return _new_dentry_with_inode(name, dentry_ret, true);
981 }
982
983 /* Create an unnamed dentry with a new inode for a directory with the default
984  * metadata.  */
985 int
986 new_filler_directory(struct wim_dentry **dentry_ret)
987 {
988         int ret;
989         struct wim_dentry *dentry;
990
991         ret = new_dentry_with_inode(NULL, &dentry);
992         if (ret)
993                 return ret;
994         /* Leave the inode number as 0; this is allowed for non
995          * hard-linked files. */
996         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
997         *dentry_ret = dentry;
998         return 0;
999 }
1000
1001 static int
1002 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1003 {
1004         dentry->d_inode->i_visited = 0;
1005         return 0;
1006 }
1007
1008 void
1009 dentry_tree_clear_inode_visited(struct wim_dentry *root)
1010 {
1011         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1012 }
1013
1014 /*
1015  * Free a WIM dentry.
1016  *
1017  * In addition to freeing the dentry itself, this disassociates the dentry from
1018  * its inode.  If the inode is no longer in use, it will be freed as well.
1019  */
1020 void
1021 free_dentry(struct wim_dentry *dentry)
1022 {
1023         if (dentry) {
1024                 d_disassociate(dentry);
1025                 FREE(dentry->file_name);
1026                 FREE(dentry->short_name);
1027                 FREE(dentry->_full_path);
1028                 FREE(dentry);
1029         }
1030 }
1031
1032 static int
1033 do_free_dentry(struct wim_dentry *dentry, void *_ignore)
1034 {
1035         free_dentry(dentry);
1036         return 0;
1037 }
1038
1039 static int
1040 do_free_dentry_and_unref_blobs(struct wim_dentry *dentry, void *blob_table)
1041 {
1042         inode_unref_blobs(dentry->d_inode, blob_table);
1043         free_dentry(dentry);
1044         return 0;
1045 }
1046
1047 /*
1048  * Free all dentries in a tree.
1049  *
1050  * @root:
1051  *      The root of the dentry tree to free.  If NULL, this function has no
1052  *      effect.
1053  *
1054  * @blob_table:
1055  *      A pointer to the blob table for the WIM, or NULL if not specified.  If
1056  *      specified, this function will decrement the reference counts of the
1057  *      blobs referenced by the dentries.
1058  *
1059  * This function also releases references to the corresponding inodes.
1060  *
1061  * This function does *not* unlink @root from its parent directory, if it has
1062  * one.  If @root has a parent, the caller must unlink @root before calling this
1063  * function.
1064  */
1065 void
1066 free_dentry_tree(struct wim_dentry *root, struct blob_table *blob_table)
1067 {
1068         int (*f)(struct wim_dentry *, void *);
1069
1070         if (blob_table)
1071                 f = do_free_dentry_and_unref_blobs;
1072         else
1073                 f = do_free_dentry;
1074
1075         for_dentry_in_tree_depth(root, f, blob_table);
1076 }
1077
1078 /* Insert the @child dentry into the case sensitive index of the @dir directory.
1079  * Return NULL if successfully inserted, otherwise a pointer to the
1080  * already-inserted duplicate.  */
1081 static struct wim_dentry *
1082 dir_index_child(struct wim_inode *dir, struct wim_dentry *child)
1083 {
1084         struct avl_tree_node *duplicate;
1085
1086         duplicate = avl_tree_insert(&dir->i_children,
1087                                     &child->d_index_node,
1088                                     _avl_dentry_compare_names);
1089         if (!duplicate)
1090                 return NULL;
1091         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node);
1092 }
1093
1094 /* Insert the @child dentry into the case insensitive index of the @dir
1095  * directory.  Return NULL if successfully inserted, otherwise a pointer to the
1096  * already-inserted duplicate.  */
1097 static struct wim_dentry *
1098 dir_index_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1099 {
1100         struct avl_tree_node *duplicate;
1101
1102         duplicate = avl_tree_insert(&dir->i_children_ci,
1103                                     &child->d_index_node_ci,
1104                                     _avl_dentry_compare_names_ci);
1105         if (!duplicate)
1106                 return NULL;
1107         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node_ci);
1108 }
1109
1110 /* Remove the specified dentry from its directory's case-sensitive index.  */
1111 static void
1112 dir_unindex_child(struct wim_inode *dir, struct wim_dentry *child)
1113 {
1114         avl_tree_remove(&dir->i_children, &child->d_index_node);
1115 }
1116
1117 /* Remove the specified dentry from its directory's case-insensitive index.  */
1118 static void
1119 dir_unindex_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1120 {
1121         avl_tree_remove(&dir->i_children_ci, &child->d_index_node_ci);
1122 }
1123
1124 /* Return true iff the specified dentry is in its parent directory's
1125  * case-insensitive index.  */
1126 static bool
1127 dentry_in_ci_index(const struct wim_dentry *dentry)
1128 {
1129         return !avl_tree_node_is_unlinked(&dentry->d_index_node_ci);
1130 }
1131
1132 /*
1133  * Link a dentry into the tree.
1134  *
1135  * @parent:
1136  *      The dentry that will be the parent of @child.  It must name a directory.
1137  *
1138  * @child:
1139  *      The dentry to link.  It must be currently unlinked.
1140  *
1141  * Returns NULL if successful.  If @parent already contains a dentry with the
1142  * same case-sensitive name as @child, returns a pointer to this duplicate
1143  * dentry.
1144  */
1145 struct wim_dentry *
1146 dentry_add_child(struct wim_dentry *parent, struct wim_dentry *child)
1147 {
1148         struct wim_dentry *duplicate;
1149         struct wim_inode *dir;
1150
1151         wimlib_assert(parent != child);
1152
1153         dir = parent->d_inode;
1154
1155         wimlib_assert(inode_is_directory(dir));
1156
1157         duplicate = dir_index_child(dir, child);
1158         if (duplicate)
1159                 return duplicate;
1160
1161         duplicate = dir_index_child_ci(dir, child);
1162         if (duplicate) {
1163                 list_add(&child->d_ci_conflict_list, &duplicate->d_ci_conflict_list);
1164                 avl_tree_node_set_unlinked(&child->d_index_node_ci);
1165         } else {
1166                 INIT_LIST_HEAD(&child->d_ci_conflict_list);
1167         }
1168         child->d_parent = parent;
1169         return NULL;
1170 }
1171
1172 /* Unlink a dentry from the tree.  */
1173 void
1174 unlink_dentry(struct wim_dentry *dentry)
1175 {
1176         struct wim_inode *dir;
1177
1178         /* Do nothing if the dentry is root or it's already unlinked.  Not
1179          * actually necessary based on the current callers, but we do the check
1180          * here to be safe.  */
1181         if (unlikely(dentry->d_parent == dentry))
1182                 return;
1183
1184         dir = dentry->d_parent->d_inode;
1185
1186         dir_unindex_child(dir, dentry);
1187
1188         if (dentry_in_ci_index(dentry)) {
1189
1190                 dir_unindex_child_ci(dir, dentry);
1191
1192                 if (!list_empty(&dentry->d_ci_conflict_list)) {
1193                         /* Make a different case-insensitively-the-same dentry
1194                          * be the "representative" in the search index.  */
1195                         struct list_head *next;
1196                         struct wim_dentry *other;
1197                         struct wim_dentry *existing;
1198
1199                         next = dentry->d_ci_conflict_list.next;
1200                         other = list_entry(next, struct wim_dentry, d_ci_conflict_list);
1201                         existing = dir_index_child_ci(dir, other);
1202                         wimlib_assert(existing == NULL);
1203                 }
1204         }
1205         list_del(&dentry->d_ci_conflict_list);
1206
1207         /* Not actually necessary, but to be safe don't retain the now-obsolete
1208          * parent pointer.  */
1209         dentry->d_parent = dentry;
1210 }
1211
1212 static int
1213 read_extra_data(const u8 *p, const u8 *end, struct wim_inode *inode)
1214 {
1215         while (((uintptr_t)p & 7) && p < end)
1216                 p++;
1217
1218         if (unlikely(p < end)) {
1219                 inode->i_extra = memdup(p, end - p);
1220                 if (!inode->i_extra)
1221                         return WIMLIB_ERR_NOMEM;
1222                 inode->i_extra_size = end - p;
1223         }
1224         return 0;
1225 }
1226
1227 /*
1228  * Set the type of each stream for an encrypted file.
1229  *
1230  * All data streams of the encrypted file should have been packed into a single
1231  * stream in the format provided by ReadEncryptedFileRaw() on Windows.  We
1232  * assign this stream type STREAM_TYPE_EFSRPC_RAW_DATA.
1233  *
1234  * Encrypted files can't have a reparse point stream.  In the on-disk NTFS
1235  * format they can, but as far as I know the reparse point stream of an
1236  * encrypted file can't be stored in the WIM format in a way that's compatible
1237  * with WIMGAPI, nor is there even any way for it to be read or written on
1238  * Windows when the process does not have access to the file encryption key.
1239  */
1240 static void
1241 assign_stream_types_encrypted(struct wim_inode *inode)
1242 {
1243         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1244                 struct wim_inode_stream *strm = &inode->i_streams[i];
1245                 if (!stream_is_named(strm) && !is_zero_hash(strm->_stream_hash))
1246                 {
1247                         strm->stream_type = STREAM_TYPE_EFSRPC_RAW_DATA;
1248                         return;
1249                 }
1250         }
1251 }
1252
1253 /*
1254  * Set the type of each stream for an unencrypted file.
1255  *
1256  * There will be an unnamed data stream, a reparse point stream, or both an
1257  * unnamed data stream and a reparse point stream.  In addition, there may be
1258  * named data streams.
1259  */
1260 static void
1261 assign_stream_types_unencrypted(struct wim_inode *inode)
1262 {
1263         bool found_reparse_point_stream = false;
1264         bool found_unnamed_data_stream = false;
1265         struct wim_inode_stream *unnamed_stream_with_zero_hash = NULL;
1266
1267         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1268                 struct wim_inode_stream *strm = &inode->i_streams[i];
1269
1270                 if (stream_is_named(strm)) {
1271                         /* Named data stream  */
1272                         strm->stream_type = STREAM_TYPE_DATA;
1273                 } else if (!is_zero_hash(strm->_stream_hash)) {
1274                         if ((inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1275                             !found_reparse_point_stream) {
1276                                 found_reparse_point_stream = true;
1277                                 strm->stream_type = STREAM_TYPE_REPARSE_POINT;
1278                         } else if (!found_unnamed_data_stream) {
1279                                 found_unnamed_data_stream = true;
1280                                 strm->stream_type = STREAM_TYPE_DATA;
1281                         }
1282                 } else {
1283                         /* If no stream name is specified and the hash is zero,
1284                          * then remember this stream for later so that we can
1285                          * assign it to the unnamed data stream if we don't find
1286                          * a better candidate.  */
1287                         unnamed_stream_with_zero_hash = strm;
1288                 }
1289         }
1290
1291         if (!found_unnamed_data_stream && unnamed_stream_with_zero_hash != NULL)
1292                 unnamed_stream_with_zero_hash->stream_type = STREAM_TYPE_DATA;
1293 }
1294
1295 /*
1296  * Read and interpret the collection of streams for the specified inode.
1297  */
1298 static int
1299 setup_inode_streams(const u8 *p, const u8 *end, struct wim_inode *inode,
1300                     unsigned num_extra_streams, const u8 *default_hash,
1301                     u64 *offset_p)
1302 {
1303         const u8 *orig_p = p;
1304
1305         inode->i_num_streams = 1 + num_extra_streams;
1306
1307         if (likely(inode->i_num_streams <= ARRAY_LEN(inode->i_embedded_streams))) {
1308                 inode->i_streams = inode->i_embedded_streams;
1309         } else {
1310                 inode->i_streams = CALLOC(inode->i_num_streams,
1311                                           sizeof(inode->i_streams[0]));
1312                 if (!inode->i_streams)
1313                         return WIMLIB_ERR_NOMEM;
1314         }
1315
1316         /* Use the default hash field for the first stream  */
1317         inode->i_streams[0].stream_name = (utf16lechar *)NO_STREAM_NAME;
1318         copy_hash(inode->i_streams[0]._stream_hash, default_hash);
1319         inode->i_streams[0].stream_type = STREAM_TYPE_UNKNOWN;
1320         inode->i_streams[0].stream_id = 0;
1321
1322         /* Read the extra stream entries  */
1323         for (unsigned i = 1; i < inode->i_num_streams; i++) {
1324                 struct wim_inode_stream *strm;
1325                 const struct wim_extra_stream_entry_on_disk *disk_strm;
1326                 u64 length;
1327                 u16 name_nbytes;
1328
1329                 strm = &inode->i_streams[i];
1330
1331                 strm->stream_id = i;
1332
1333                 /* Do we have at least the size of the fixed-length data we know
1334                  * need?  */
1335                 if ((end - p) < sizeof(struct wim_extra_stream_entry_on_disk))
1336                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1337
1338                 disk_strm = (const struct wim_extra_stream_entry_on_disk *)p;
1339
1340                 /* Read the length field  */
1341                 length = le64_to_cpu(disk_strm->length);
1342
1343                 /* 8-byte align the length  */
1344                 length = (length + 7) & ~7;
1345
1346                 /* Make sure the length field is neither so small it doesn't
1347                  * include all the fixed-length data nor so large it overflows
1348                  * the metadata resource buffer. */
1349                 if (length < sizeof(struct wim_extra_stream_entry_on_disk) ||
1350                     length > (end - p))
1351                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1352
1353                 /* Read the rest of the fixed-length data. */
1354
1355                 copy_hash(strm->_stream_hash, disk_strm->hash);
1356                 name_nbytes = le16_to_cpu(disk_strm->name_nbytes);
1357
1358                 /* If stream_name_nbytes != 0, the stream is named.  */
1359                 if (name_nbytes != 0) {
1360                         /* The name is encoded in UTF16-LE, which uses 2-byte
1361                          * coding units, so the length of the name had better be
1362                          * an even number of bytes.  */
1363                         if (name_nbytes & 1)
1364                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1365
1366                         /* Add the length of the stream name to get the length
1367                          * we actually need to read.  Make sure this isn't more
1368                          * than the specified length of the entry.  */
1369                         if (sizeof(struct wim_extra_stream_entry_on_disk) +
1370                             name_nbytes > length)
1371                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1372
1373                         strm->stream_name = utf16le_dupz(disk_strm->name,
1374                                                          name_nbytes);
1375                         if (!strm->stream_name)
1376                                 return WIMLIB_ERR_NOMEM;
1377                 } else {
1378                         strm->stream_name = (utf16lechar *)NO_STREAM_NAME;
1379                 }
1380
1381                 strm->stream_type = STREAM_TYPE_UNKNOWN;
1382
1383                 p += length;
1384         }
1385
1386         inode->i_next_stream_id = inode->i_num_streams;
1387
1388         /* Now, assign a type to each stream.  Unfortunately this requires
1389          * various hacks because stream types aren't explicitly provided in the
1390          * WIM on-disk format.  */
1391
1392         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
1393                 assign_stream_types_encrypted(inode);
1394         else
1395                 assign_stream_types_unencrypted(inode);
1396
1397         *offset_p += p - orig_p;
1398         return 0;
1399 }
1400
1401 /* Read a dentry, including all extra stream entries that follow it, from an
1402  * uncompressed metadata resource buffer.  */
1403 static int
1404 read_dentry(const u8 * restrict buf, size_t buf_len,
1405             u64 *offset_p, struct wim_dentry **dentry_ret)
1406 {
1407         u64 offset = *offset_p;
1408         u64 length;
1409         const u8 *p;
1410         const struct wim_dentry_on_disk *disk_dentry;
1411         struct wim_dentry *dentry;
1412         struct wim_inode *inode;
1413         u16 short_name_nbytes;
1414         u16 file_name_nbytes;
1415         u64 calculated_size;
1416         int ret;
1417
1418         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1419
1420         /* Before reading the whole dentry, we need to read just the length.
1421          * This is because a dentry of length 8 (that is, just the length field)
1422          * terminates the list of sibling directory entries. */
1423
1424         /* Check for buffer overrun.  */
1425         if (unlikely(offset + sizeof(u64) > buf_len ||
1426                      offset + sizeof(u64) < offset))
1427                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1428
1429         /* Get pointer to the dentry data.  */
1430         p = &buf[offset];
1431         disk_dentry = (const struct wim_dentry_on_disk*)p;
1432
1433         /* Get dentry length.  */
1434         length = (le64_to_cpu(disk_dentry->length) + 7) & ~7;
1435
1436         /* Check for end-of-directory.  */
1437         if (length <= 8) {
1438                 *dentry_ret = NULL;
1439                 return 0;
1440         }
1441
1442         /* Validate dentry length.  */
1443         if (unlikely(length < sizeof(struct wim_dentry_on_disk)))
1444                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1445
1446         /* Check for buffer overrun.  */
1447         if (unlikely(offset + length > buf_len ||
1448                      offset + length < offset))
1449                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1450
1451         /* Allocate new dentry structure, along with a preliminary inode.  */
1452         ret = new_dentry_with_timeless_inode(NULL, &dentry);
1453         if (ret)
1454                 return ret;
1455
1456         inode = dentry->d_inode;
1457
1458         /* Read more fields: some into the dentry, and some into the inode.  */
1459         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1460         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1461         dentry->subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1462         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1463         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1464         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1465
1466         /* I don't know what's going on here.  It seems like M$ screwed up the
1467          * reparse points, then put the fields in the same place and didn't
1468          * document it.  So we have some fields we read for reparse points, and
1469          * some fields in the same place for non-reparse-points.  */
1470         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1471                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->reparse.rp_unknown_1);
1472                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
1473                 inode->i_rp_unknown_2 = le16_to_cpu(disk_dentry->reparse.rp_unknown_2);
1474                 inode->i_not_rpfixed = le16_to_cpu(disk_dentry->reparse.not_rpfixed);
1475                 /* Leave inode->i_ino at 0.  Note: this means that WIM cannot
1476                  * represent multiple hard links to a reparse point file.  */
1477         } else {
1478                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->nonreparse.rp_unknown_1);
1479                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
1480         }
1481
1482         /* Now onto reading the names.  There are two of them: the (long) file
1483          * name, and the short name.  */
1484
1485         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
1486         file_name_nbytes = le16_to_cpu(disk_dentry->file_name_nbytes);
1487
1488         if (unlikely((short_name_nbytes & 1) | (file_name_nbytes & 1))) {
1489                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1490                 goto err_free_dentry;
1491         }
1492
1493         /* We now know the length of the file name and short name.  Make sure
1494          * the length of the dentry is large enough to actually hold them.  */
1495         calculated_size = dentry_min_len_with_names(file_name_nbytes,
1496                                                     short_name_nbytes);
1497
1498         if (unlikely(length < calculated_size)) {
1499                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1500                 goto err_free_dentry;
1501         }
1502
1503         /* Advance p to point past the base dentry, to the first name.  */
1504         p += sizeof(struct wim_dentry_on_disk);
1505
1506         /* Read the filename if present.  Note: if the filename is empty, there
1507          * is no null terminator following it.  */
1508         if (file_name_nbytes) {
1509                 dentry->file_name = utf16le_dupz(p, file_name_nbytes);
1510                 if (dentry->file_name == NULL) {
1511                         ret = WIMLIB_ERR_NOMEM;
1512                         goto err_free_dentry;
1513                 }
1514                 dentry->file_name_nbytes = file_name_nbytes;
1515                 p += (u32)file_name_nbytes + 2;
1516         }
1517
1518         /* Read the short filename if present.  Note: if there is no short
1519          * filename, there is no null terminator following it. */
1520         if (short_name_nbytes) {
1521                 dentry->short_name = utf16le_dupz(p, short_name_nbytes);
1522                 if (dentry->short_name == NULL) {
1523                         ret = WIMLIB_ERR_NOMEM;
1524                         goto err_free_dentry;
1525                 }
1526                 dentry->short_name_nbytes = short_name_nbytes;
1527                 p += (u32)short_name_nbytes + 2;
1528         }
1529
1530         /* Read extra data at end of dentry (but before extra stream entries).
1531          * This may contain tagged metadata items.  */
1532         ret = read_extra_data(p, &buf[offset + length], inode);
1533         if (ret)
1534                 goto err_free_dentry;
1535
1536         offset += length;
1537
1538         /* Set up the inode's collection of streams.  */
1539         ret = setup_inode_streams(&buf[offset],
1540                                   &buf[buf_len],
1541                                   inode,
1542                                   le16_to_cpu(disk_dentry->num_extra_streams),
1543                                   disk_dentry->default_hash,
1544                                   &offset);
1545         if (ret)
1546                 goto err_free_dentry;
1547
1548         *offset_p = offset;  /* Sets offset of next dentry in directory  */
1549         *dentry_ret = dentry;
1550         return 0;
1551
1552 err_free_dentry:
1553         free_dentry(dentry);
1554         return ret;
1555 }
1556
1557 /* Is the dentry named "." or ".." ?  */
1558 static bool
1559 dentry_is_dot_or_dotdot(const struct wim_dentry *dentry)
1560 {
1561         if (dentry->file_name_nbytes <= 4) {
1562                 if (dentry->file_name_nbytes == 4) {
1563                         if (dentry->file_name[0] == cpu_to_le16('.') &&
1564                             dentry->file_name[1] == cpu_to_le16('.'))
1565                                 return true;
1566                 } else if (dentry->file_name_nbytes == 2) {
1567                         if (dentry->file_name[0] == cpu_to_le16('.'))
1568                                 return true;
1569                 }
1570         }
1571         return false;
1572 }
1573
1574 static int
1575 read_dentry_tree_recursive(const u8 * restrict buf, size_t buf_len,
1576                            struct wim_dentry * restrict dir)
1577 {
1578         u64 cur_offset = dir->subdir_offset;
1579
1580         /* Check for cyclic directory structure, which would cause infinite
1581          * recursion if not handled.  */
1582         for (struct wim_dentry *d = dir->d_parent;
1583              !dentry_is_root(d); d = d->d_parent)
1584         {
1585                 if (unlikely(d->subdir_offset == cur_offset)) {
1586                         ERROR("Cyclic directory structure detected: children "
1587                               "of \"%"TS"\" coincide with children of \"%"TS"\"",
1588                               dentry_full_path(dir), dentry_full_path(d));
1589                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1590                 }
1591         }
1592
1593         for (;;) {
1594                 struct wim_dentry *child;
1595                 struct wim_dentry *duplicate;
1596                 int ret;
1597
1598                 /* Read next child of @dir.  */
1599                 ret = read_dentry(buf, buf_len, &cur_offset, &child);
1600                 if (ret)
1601                         return ret;
1602
1603                 /* Check for end of directory.  */
1604                 if (child == NULL)
1605                         return 0;
1606
1607                 /* All dentries except the root should be named.  */
1608                 if (unlikely(!dentry_has_long_name(child))) {
1609                         WARNING("Ignoring unnamed dentry in "
1610                                 "directory \"%"TS"\"", dentry_full_path(dir));
1611                         free_dentry(child);
1612                         continue;
1613                 }
1614
1615                 /* Don't allow files named "." or "..".  */
1616                 if (unlikely(dentry_is_dot_or_dotdot(child))) {
1617                         WARNING("Ignoring file named \".\" or \"..\"; "
1618                                 "potentially malicious archive!!!");
1619                         free_dentry(child);
1620                         continue;
1621                 }
1622
1623                 /* Link the child into the directory.  */
1624                 duplicate = dentry_add_child(dir, child);
1625                 if (unlikely(duplicate)) {
1626                         /* We already found a dentry with this same
1627                          * case-sensitive long name.  Only keep the first one.
1628                          */
1629                         WARNING("Ignoring duplicate file \"%"TS"\" "
1630                                 "(the WIM image already contains a file "
1631                                 "at that path with the exact same name)",
1632                                 dentry_full_path(duplicate));
1633                         free_dentry(child);
1634                         continue;
1635                 }
1636
1637                 /* If this child is a directory that itself has children, call
1638                  * this procedure recursively.  */
1639                 if (child->subdir_offset != 0) {
1640                         if (likely(dentry_is_directory(child))) {
1641                                 ret = read_dentry_tree_recursive(buf,
1642                                                                  buf_len,
1643                                                                  child);
1644                                 if (ret)
1645                                         return ret;
1646                         } else {
1647                                 WARNING("Ignoring children of "
1648                                         "non-directory file \"%"TS"\"",
1649                                         dentry_full_path(child));
1650                         }
1651                 }
1652         }
1653 }
1654
1655 /*
1656  * Read a tree of dentries from a WIM metadata resource.
1657  *
1658  * @buf:
1659  *      Buffer containing an uncompressed WIM metadata resource.
1660  *
1661  * @buf_len:
1662  *      Length of the uncompressed metadata resource, in bytes.
1663  *
1664  * @root_offset
1665  *      Offset in the metadata resource of the root of the dentry tree.
1666  *
1667  * @root_ret:
1668  *      On success, either NULL or a pointer to the root dentry is written to
1669  *      this location.  The former case only occurs in the unexpected case that
1670  *      the tree began with an end-of-directory entry.
1671  *
1672  * Return values:
1673  *      WIMLIB_ERR_SUCCESS (0)
1674  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1675  *      WIMLIB_ERR_NOMEM
1676  */
1677 int
1678 read_dentry_tree(const u8 *buf, size_t buf_len,
1679                  u64 root_offset, struct wim_dentry **root_ret)
1680 {
1681         int ret;
1682         struct wim_dentry *root;
1683
1684         DEBUG("Reading dentry tree (root_offset=%"PRIu64")", root_offset);
1685
1686         ret = read_dentry(buf, buf_len, &root_offset, &root);
1687         if (ret)
1688                 return ret;
1689
1690         if (likely(root != NULL)) {
1691                 if (unlikely(dentry_has_long_name(root) ||
1692                              dentry_has_short_name(root)))
1693                 {
1694                         WARNING("The root directory has a nonempty name; "
1695                                 "removing it.");
1696                         dentry_set_name(root, NULL);
1697                 }
1698
1699                 if (unlikely(!dentry_is_directory(root))) {
1700                         ERROR("The root of the WIM image is not a directory!");
1701                         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1702                         goto err_free_dentry_tree;
1703                 }
1704
1705                 if (likely(root->subdir_offset != 0)) {
1706                         ret = read_dentry_tree_recursive(buf, buf_len, root);
1707                         if (ret)
1708                                 goto err_free_dentry_tree;
1709                 }
1710         } else {
1711                 WARNING("The metadata resource has no directory entries; "
1712                         "treating as an empty image.");
1713         }
1714         *root_ret = root;
1715         return 0;
1716
1717 err_free_dentry_tree:
1718         free_dentry_tree(root, NULL);
1719         return ret;
1720 }
1721
1722 static u8 *
1723 write_extra_stream_entry(u8 * restrict p, const utf16lechar * restrict name,
1724                          const u8 * restrict hash)
1725 {
1726         struct wim_extra_stream_entry_on_disk *disk_strm =
1727                         (struct wim_extra_stream_entry_on_disk *)p;
1728         u8 *orig_p = p;
1729         size_t name_nbytes;
1730
1731         if (name == NO_STREAM_NAME)
1732                 name_nbytes = 0;
1733         else
1734                 name_nbytes = utf16le_len_bytes(name);
1735
1736         disk_strm->reserved = 0;
1737         copy_hash(disk_strm->hash, hash);
1738         disk_strm->name_nbytes = cpu_to_le16(name_nbytes);
1739         p += sizeof(struct wim_extra_stream_entry_on_disk);
1740         if (name_nbytes != 0)
1741                 p = mempcpy(p, name, name_nbytes + 2);
1742         /* Align to 8-byte boundary */
1743         while ((uintptr_t)p & 7)
1744                 *p++ = 0;
1745         disk_strm->length = cpu_to_le64(p - orig_p);
1746         return p;
1747 }
1748
1749 /*
1750  * Write a WIM dentry to an output buffer.
1751  *
1752  * This includes any extra stream entries that may follow the dentry itself.
1753  *
1754  * @dentry:
1755  *      The dentry to write.
1756  *
1757  * @p:
1758  *      The memory location to which to write the data.
1759  *
1760  * Returns a pointer to the byte following the last written.
1761  */
1762 static u8 *
1763 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
1764 {
1765         const struct wim_inode *inode;
1766         struct wim_dentry_on_disk *disk_dentry;
1767         const u8 *orig_p;
1768
1769         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
1770         orig_p = p;
1771
1772         inode = dentry->d_inode;
1773         disk_dentry = (struct wim_dentry_on_disk*)p;
1774
1775         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
1776         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
1777         disk_dentry->subdir_offset = cpu_to_le64(dentry->subdir_offset);
1778
1779         disk_dentry->unused_1 = cpu_to_le64(0);
1780         disk_dentry->unused_2 = cpu_to_le64(0);
1781
1782         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
1783         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
1784         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
1785         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1786                 disk_dentry->reparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1787                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
1788                 disk_dentry->reparse.rp_unknown_2 = cpu_to_le16(inode->i_rp_unknown_2);
1789                 disk_dentry->reparse.not_rpfixed = cpu_to_le16(inode->i_not_rpfixed);
1790         } else {
1791                 disk_dentry->nonreparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1792                 disk_dentry->nonreparse.hard_link_group_id =
1793                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
1794         }
1795
1796         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->short_name_nbytes);
1797         disk_dentry->file_name_nbytes = cpu_to_le16(dentry->file_name_nbytes);
1798         p += sizeof(struct wim_dentry_on_disk);
1799
1800         wimlib_assert(dentry_is_root(dentry) != dentry_has_long_name(dentry));
1801
1802         if (dentry_has_long_name(dentry))
1803                 p = mempcpy(p, dentry->file_name, (u32)dentry->file_name_nbytes + 2);
1804
1805         if (dentry_has_short_name(dentry))
1806                 p = mempcpy(p, dentry->short_name, (u32)dentry->short_name_nbytes + 2);
1807
1808         /* Align to 8-byte boundary */
1809         while ((uintptr_t)p & 7)
1810                 *p++ = 0;
1811
1812         if (inode->i_extra_size) {
1813                 /* Extra tagged items --- not usually present.  */
1814                 p = mempcpy(p, inode->i_extra, inode->i_extra_size);
1815
1816                 /* Align to 8-byte boundary */
1817                 while ((uintptr_t)p & 7)
1818                         *p++ = 0;
1819         }
1820
1821         disk_dentry->length = cpu_to_le64(p - orig_p);
1822
1823         /* Streams  */
1824
1825         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1826                 const struct wim_inode_stream *efs_strm;
1827                 const u8 *efs_hash;
1828
1829                 efs_strm = inode_get_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA,
1830                                             NO_STREAM_NAME);
1831                 efs_hash = efs_strm ? stream_hash(efs_strm) : zero_hash;
1832                 copy_hash(disk_dentry->default_hash, efs_hash);
1833                 disk_dentry->num_extra_streams = cpu_to_le16(0);
1834         } else {
1835                 /*
1836                  * Extra stream entries:
1837                  *
1838                  * - Use one extra stream entry for each named data stream
1839                  * - Use one extra stream entry for the unnamed data stream when there is either:
1840                  *      - a reparse point stream
1841                  *      - at least one named data stream (for Windows PE bug workaround)
1842                  * - Use one extra stream entry for the reparse point stream if there is one
1843                  */
1844                 bool have_named_data_stream = false;
1845                 bool have_reparse_point_stream = false;
1846                 u16 num_extra_streams = 0;
1847                 const u8 *unnamed_data_stream_hash = zero_hash;
1848                 const u8 *reparse_point_hash;
1849                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1850                         const struct wim_inode_stream *strm = &inode->i_streams[i];
1851                         if (strm->stream_type == STREAM_TYPE_DATA) {
1852                                 if (stream_is_named(strm))
1853                                         have_named_data_stream = true;
1854                                 else
1855                                         unnamed_data_stream_hash = stream_hash(strm);
1856                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
1857                                 have_reparse_point_stream = true;
1858                                 reparse_point_hash = stream_hash(strm);
1859                         }
1860                 }
1861
1862                 if (have_reparse_point_stream || have_named_data_stream) {
1863
1864                         copy_hash(disk_dentry->default_hash, zero_hash);
1865
1866                         if (have_reparse_point_stream) {
1867                                 p = write_extra_stream_entry(p, NO_STREAM_NAME,
1868                                                              reparse_point_hash);
1869                                 num_extra_streams++;
1870                         }
1871
1872                         p = write_extra_stream_entry(p, NO_STREAM_NAME,
1873                                                      unnamed_data_stream_hash);
1874                         num_extra_streams++;
1875                 } else {
1876                         copy_hash(disk_dentry->default_hash, unnamed_data_stream_hash);
1877                 }
1878
1879                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1880                         const struct wim_inode_stream *strm = &inode->i_streams[i];
1881                         if (stream_is_named_data_stream(strm)) {
1882                                 p = write_extra_stream_entry(p, strm->stream_name,
1883                                                              stream_hash(strm));
1884                                 num_extra_streams++;
1885                         }
1886                 }
1887                 disk_dentry->num_extra_streams = cpu_to_le16(num_extra_streams);
1888         }
1889
1890         return p;
1891 }
1892
1893 static int
1894 write_dir_dentries(struct wim_dentry *dir, void *_pp)
1895 {
1896         if (dir->subdir_offset != 0) {
1897                 u8 **pp = _pp;
1898                 u8 *p = *pp;
1899                 struct wim_dentry *child;
1900
1901                 /* write child dentries */
1902                 for_dentry_child(child, dir)
1903                         p = write_dentry(child, p);
1904
1905                 /* write end of directory entry */
1906                 *(u64*)p = 0;
1907                 p += 8;
1908                 *pp = p;
1909         }
1910         return 0;
1911 }
1912
1913 /*
1914  * Write a directory tree to the metadata resource.
1915  *
1916  * @root:
1917  *      The root of a dentry tree on which calculate_subdir_offsets() has been
1918  *      called.  This cannot be NULL; if the dentry tree is empty, the caller is
1919  *      expected to first generate a dummy root directory.
1920  *
1921  * @p:
1922  *      Pointer to a buffer with enough space for the dentry tree.  This size
1923  *      must have been obtained by calculate_subdir_offsets().
1924  *
1925  * Returns a pointer to the byte following the last written.
1926  */
1927 u8 *
1928 write_dentry_tree(struct wim_dentry *root, u8 *p)
1929 {
1930         DEBUG("Writing dentry tree.");
1931
1932         wimlib_assert(root != NULL);
1933
1934         /* write root dentry and end-of-directory entry following it */
1935         p = write_dentry(root, p);
1936         *(u64*)p = 0;
1937         p += 8;
1938
1939         /* write the rest of the dentry tree */
1940         for_dentry_in_tree(root, write_dir_dentries, &p);
1941
1942         return p;
1943 }