]> wimlib.net Git - wimlib/blob - src/dentry.c
Tweak support for extracting paths
[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/paths.h"
41 #include "wimlib/resource.h"
42 #include "wimlib/security.h"
43 #include "wimlib/sha1.h"
44 #include "wimlib/timestamp.h"
45
46 #include <errno.h>
47
48 /* WIM alternate data stream entry (on-disk format) */
49 struct wim_ads_entry_on_disk {
50         /*  Length of the entry, in bytes.  This apparently includes all
51          *  fixed-length fields, plus the stream name and null terminator if
52          *  present, and the padding up to an 8 byte boundary.  wimlib is a
53          *  little less strict when reading the entries, and only requires that
54          *  the number of bytes from this field is at least as large as the size
55          *  of the fixed length fields and stream name without null terminator.
56          *  */
57         le64  length;
58
59         le64  reserved;
60
61         /* SHA1 message digest of the uncompressed stream; or, alternatively,
62          * can be all zeroes if the stream has zero length. */
63         u8 hash[SHA1_HASH_SIZE];
64
65         /* Length of the stream name, in bytes.  0 if the stream is unnamed.  */
66         le16 stream_name_nbytes;
67
68         /* Stream name in UTF-16LE.  It is @stream_name_nbytes bytes long,
69          * excluding the the null terminator.  There is a null terminator
70          * character if @stream_name_nbytes != 0; i.e., if this stream is named.
71          * */
72         utf16lechar stream_name[];
73 } _packed_attribute;
74
75 #define WIM_ADS_ENTRY_DISK_SIZE 38
76
77 /* On-disk format of a WIM dentry (directory entry), located in the metadata
78  * resource for a WIM image.  */
79 struct wim_dentry_on_disk {
80
81         /* Length of this directory entry in bytes, not including any alternate
82          * data stream entries.  Should be a multiple of 8 so that the following
83          * dentry or alternate data stream entry is aligned on an 8-byte
84          * boundary.  (If not, wimlib will round it up.)  It must be at least as
85          * long as the fixed-length fields of the dentry (WIM_DENTRY_DISK_SIZE),
86          * plus the lengths of the file name and/or short name if present.
87          *
88          * It is also possible for this field to be 0.  This situation, which is
89          * undocumented, indicates the end of a list of sibling nodes in a
90          * directory.  It also means the real length is 8, because the dentry
91          * included only the length field, but that takes up 8 bytes.  */
92         le64 length;
93
94         /* Attributes of the file or directory.  This is a bitwise OR of the
95          * FILE_ATTRIBUTE_* constants and should correspond to the value
96          * retrieved by GetFileAttributes() on Windows. */
97         le32 attributes;
98
99         /* A value that specifies the security descriptor for this file or
100          * directory.  If -1, the file or directory has no security descriptor.
101          * Otherwise, it is a 0-based index into the WIM image's table of
102          * security descriptors (see: `struct wim_security_data') */
103         sle32 security_id;
104
105         /* Offset, in bytes, from the start of the uncompressed metadata
106          * resource of this directory's child directory entries, or 0 if this
107          * directory entry does not correspond to a directory or otherwise does
108          * not have any children. */
109         le64 subdir_offset;
110
111         /* Reserved fields */
112         le64 unused_1;
113         le64 unused_2;
114
115
116         /* Creation time, last access time, and last write time, in
117          * 100-nanosecond intervals since 12:00 a.m UTC January 1, 1601.  They
118          * should correspond to the times gotten by calling GetFileTime() on
119          * Windows. */
120         le64 creation_time;
121         le64 last_access_time;
122         le64 last_write_time;
123
124         /* Vaguely, the SHA-1 message digest ("hash") of the file's contents.
125          * More specifically, this is for the "unnamed data stream" rather than
126          * any "alternate data streams".  This hash value is used to look up the
127          * corresponding entry in the WIM's stream lookup table to actually find
128          * the file contents within the WIM.
129          *
130          * If the file has no unnamed data stream (e.g. is a directory), then
131          * this field will be all zeroes.  If the unnamed data stream is empty
132          * (i.e. an "empty file"), then this field is also expected to be all
133          * zeroes.  (It will be if wimlib created the WIM image, at least;
134          * otherwise it can't be ruled out that the SHA-1 message digest of 0
135          * bytes of data is given explicitly.)
136          *
137          * If the file has reparse data, then this field will instead specify
138          * the SHA-1 message digest of the reparse data.  If it is somehow
139          * possible for a file to have both an unnamed data stream and reparse
140          * data, then this is not handled by wimlib.
141          *
142          * As a further special case, if this field is all zeroes but there is
143          * an alternate data stream entry with no name and a nonzero SHA-1
144          * message digest field, then that hash must be used instead of this
145          * one.  In fact, when named data streams are present, some versions of
146          * Windows PE contain a bug where they only look in the alternate data
147          * stream entries for the unnamed data stream, not here.
148          */
149         u8 unnamed_stream_hash[SHA1_HASH_SIZE];
150
151         /* The format of the following data is not yet completely known and they
152          * do not correspond to Microsoft's documentation.
153          *
154          * If this directory entry is for a reparse point (has
155          * FILE_ATTRIBUTE_REPARSE_POINT set in the attributes field), then the
156          * version of the following fields containing the reparse tag is valid.
157          * Furthermore, the field notated as not_rpfixed, as far as I can tell,
158          * is supposed to be set to 1 if reparse point fixups (a.k.a. fixing the
159          * targets of absolute symbolic links) were *not* done, and otherwise 0.
160          *
161          * If this directory entry is not for a reparse point, then the version
162          * of the following fields containing the hard_link_group_id is valid.
163          * All MS says about this field is that "If this file is part of a hard
164          * link set, all the directory entries in the set will share the same
165          * value in this field.".  However, more specifically I have observed
166          * the following:
167          *    - If the file is part of a hard link set of size 1, then the
168          *    hard_link_group_id should be set to either 0, which is treated
169          *    specially as indicating "not hardlinked", or any unique value.
170          *    - The specific nonzero values used to identity hard link sets do
171          *    not matter, as long as they are unique.
172          *    - However, due to bugs in Microsoft's software, it is actually NOT
173          *    guaranteed that directory entries that share the same hard link
174          *    group ID are actually hard linked to each either.  We have to
175          *    handle this by using special code to use distinguishing features
176          *    (which is possible because some information about the underlying
177          *    inode is repeated in each dentry) to split up these fake hard link
178          *    groups into what they actually are supposed to be.
179          */
180         union {
181                 struct {
182                         le32 rp_unknown_1;
183                         le32 reparse_tag;
184                         le16 rp_unknown_2;
185                         le16 not_rpfixed;
186                 } _packed_attribute reparse;
187                 struct {
188                         le32 rp_unknown_1;
189                         le64 hard_link_group_id;
190                 } _packed_attribute nonreparse;
191         };
192
193         /* Number of alternate data stream entries that directly follow this
194          * dentry on-disk. */
195         le16 num_alternate_data_streams;
196
197         /* Length of this file's UTF-16LE encoded short name (8.3 DOS-compatible
198          * name), if present, in bytes, excluding the null terminator.  If this
199          * file has no short name, then this field should be 0.  */
200         le16 short_name_nbytes;
201
202         /* Length of this file's UTF-16LE encoded "long" name, excluding the
203          * null terminator.  If this file has no short name, then this field
204          * should be 0.  It's expected that only the root dentry has this field
205          * set to 0.  */
206         le16 file_name_nbytes;
207
208         /* Followed by variable length file name, in UTF16-LE, if
209          * file_name_nbytes != 0.  Includes null terminator. */
210         /*utf16lechar file_name[];*/
211
212         /* Followed by variable length short name, in UTF16-LE, if
213          * short_name_nbytes != 0.  Includes null terminator. */
214         /*utf16lechar short_name[];*/
215 } _packed_attribute;
216
217 #define WIM_DENTRY_DISK_SIZE 102
218
219 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
220  * a file name and short name that take the specified numbers of bytes.  This
221  * excludes any alternate data stream entries that may follow the dentry. */
222 static u64
223 dentry_correct_length_unaligned(u16 file_name_nbytes, u16 short_name_nbytes)
224 {
225         u64 length = sizeof(struct wim_dentry_on_disk);
226         if (file_name_nbytes)
227                 length += file_name_nbytes + 2;
228         if (short_name_nbytes)
229                 length += short_name_nbytes + 2;
230         return length;
231 }
232
233 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
234  * the file name length and short name length.  Note that dentry->length is
235  * ignored; also, this excludes any alternate data stream entries that may
236  * follow the dentry. */
237 static u64
238 dentry_correct_length_aligned(const struct wim_dentry *dentry)
239 {
240         u64 len;
241
242         len = dentry_correct_length_unaligned(dentry->file_name_nbytes,
243                                               dentry->short_name_nbytes);
244         return (len + 7) & ~7;
245 }
246
247 /* Duplicates a string of system-dependent encoding into a UTF-16LE string and
248  * returns the string and its length, in bytes, in the pointer arguments.  Frees
249  * any existing string at the return location before overwriting it. */
250 static int
251 get_utf16le_name(const tchar *name, utf16lechar **name_utf16le_ret,
252                  u16 *name_utf16le_nbytes_ret)
253 {
254         utf16lechar *name_utf16le;
255         size_t name_utf16le_nbytes;
256         int ret;
257 #if TCHAR_IS_UTF16LE
258         name_utf16le_nbytes = tstrlen(name) * sizeof(utf16lechar);
259         name_utf16le = MALLOC(name_utf16le_nbytes + sizeof(utf16lechar));
260         if (name_utf16le == NULL)
261                 return WIMLIB_ERR_NOMEM;
262         memcpy(name_utf16le, name, name_utf16le_nbytes + sizeof(utf16lechar));
263         ret = 0;
264 #else
265
266         ret = tstr_to_utf16le(name, tstrlen(name), &name_utf16le,
267                               &name_utf16le_nbytes);
268         if (ret == 0) {
269                 if (name_utf16le_nbytes > 0xffff) {
270                         FREE(name_utf16le);
271                         ERROR("Multibyte string \"%"TS"\" is too long!", name);
272                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
273                 }
274         }
275 #endif
276         if (ret == 0) {
277                 FREE(*name_utf16le_ret);
278                 *name_utf16le_ret = name_utf16le;
279                 *name_utf16le_nbytes_ret = name_utf16le_nbytes;
280         }
281         return ret;
282 }
283
284 /* Sets the name of a WIM dentry from a multibyte string. */
285 int
286 set_dentry_name(struct wim_dentry *dentry, const tchar *new_name)
287 {
288         int ret;
289         ret = get_utf16le_name(new_name, &dentry->file_name,
290                                &dentry->file_name_nbytes);
291         if (ret == 0) {
292                 /* Clear the short name and recalculate the dentry length */
293                 if (dentry_has_short_name(dentry)) {
294                         FREE(dentry->short_name);
295                         dentry->short_name = NULL;
296                         dentry->short_name_nbytes = 0;
297                 }
298         }
299         return ret;
300 }
301
302 /* Returns the total length of a WIM alternate data stream entry on-disk,
303  * including the stream name, the null terminator, AND the padding after the
304  * entry to align the next ADS entry or dentry on an 8-byte boundary. */
305 static u64
306 ads_entry_total_length(const struct wim_ads_entry *entry)
307 {
308         u64 len = sizeof(struct wim_ads_entry_on_disk);
309         if (entry->stream_name_nbytes)
310                 len += entry->stream_name_nbytes + 2;
311         return (len + 7) & ~7;
312 }
313
314 /*
315  * Determine whether to include a "dummy" stream when writing a WIM dentry:
316  *
317  * Some versions of Microsoft's WIM software (the boot driver(s) in WinPE 3.0,
318  * for example) contain a bug where they assume the first alternate data stream
319  * (ADS) entry of a dentry with a nonzero ADS count specifies the unnamed
320  * stream, even if it has a name and the unnamed stream is already specified in
321  * the hash field of the dentry itself.
322  *
323  * wimlib has to work around this behavior by carefully emulating the behavior
324  * of (most versions of) ImageX/WIMGAPI, which move the unnamed stream reference
325  * into the alternate stream entries whenever there are named data streams, even
326  * though there is already a field in the dentry itself for the unnamed stream
327  * reference, which then goes to waste.
328  */
329 static inline bool inode_needs_dummy_stream(const struct wim_inode *inode)
330 {
331         return (inode->i_num_ads > 0 &&
332                 inode->i_num_ads < 0xffff && /* overflow check */
333                 inode->i_canonical_streams); /* assume the dentry is okay if it
334                                                 already had an unnamed ADS entry
335                                                 when it was read in  */
336 }
337
338 /* Calculate the total number of bytes that will be consumed when a WIM dentry
339  * is written.  This includes base dentry and name fields as well as all
340  * alternate data stream entries and alignment bytes.  */
341 u64
342 dentry_out_total_length(const struct wim_dentry *dentry)
343 {
344         u64 length = dentry_correct_length_aligned(dentry);
345         const struct wim_inode *inode = dentry->d_inode;
346
347         if (inode_needs_dummy_stream(inode))
348                 length += ads_entry_total_length(&(struct wim_ads_entry){});
349
350         for (u16 i = 0; i < inode->i_num_ads; i++)
351                 length += ads_entry_total_length(&inode->i_ads_entries[i]);
352
353         return length;
354 }
355
356 /* Calculate the aligned, total length of a dentry, including all alternate data
357  * stream entries.  Uses dentry->length.  */
358 static u64
359 dentry_in_total_length(const struct wim_dentry *dentry)
360 {
361         u64 length = dentry->length;
362         const struct wim_inode *inode = dentry->d_inode;
363         for (u16 i = 0; i < inode->i_num_ads; i++)
364                 length += ads_entry_total_length(&inode->i_ads_entries[i]);
365         return (length + 7) & ~7;
366 }
367
368 int
369 for_dentry_in_rbtree(struct rb_node *root,
370                      int (*visitor)(struct wim_dentry *, void *),
371                      void *arg)
372 {
373         int ret;
374         struct rb_node *node = root;
375         LIST_HEAD(stack);
376         while (1) {
377                 if (node) {
378                         list_add(&rbnode_dentry(node)->tmp_list, &stack);
379                         node = node->rb_left;
380                 } else {
381                         struct list_head *next;
382                         struct wim_dentry *dentry;
383
384                         next = stack.next;
385                         if (next == &stack)
386                                 return 0;
387                         dentry = container_of(next, struct wim_dentry, tmp_list);
388                         list_del(next);
389                         ret = visitor(dentry, arg);
390                         if (ret != 0)
391                                 return ret;
392                         node = dentry->rb_node.rb_right;
393                 }
394         }
395 }
396
397 static int
398 for_dentry_tree_in_rbtree_depth(struct rb_node *node,
399                                 int (*visitor)(struct wim_dentry*, void*),
400                                 void *arg)
401 {
402         int ret;
403         if (node) {
404                 ret = for_dentry_tree_in_rbtree_depth(node->rb_left,
405                                                       visitor, arg);
406                 if (ret != 0)
407                         return ret;
408                 ret = for_dentry_tree_in_rbtree_depth(node->rb_right,
409                                                       visitor, arg);
410                 if (ret != 0)
411                         return ret;
412                 ret = for_dentry_in_tree_depth(rbnode_dentry(node), visitor, arg);
413                 if (ret != 0)
414                         return ret;
415         }
416         return 0;
417 }
418
419 static int
420 for_dentry_tree_in_rbtree(struct rb_node *node,
421                           int (*visitor)(struct wim_dentry*, void*),
422                           void *arg)
423 {
424         int ret;
425         if (node) {
426                 ret = for_dentry_tree_in_rbtree(node->rb_left, visitor, arg);
427                 if (ret)
428                         return ret;
429                 ret = for_dentry_in_tree(rbnode_dentry(node), visitor, arg);
430                 if (ret)
431                         return ret;
432                 ret = for_dentry_tree_in_rbtree(node->rb_right, visitor, arg);
433                 if (ret)
434                         return ret;
435         }
436         return 0;
437 }
438
439 /*
440  * Iterate over all children of @dentry, calling the function @visitor, passing
441  * it a child dentry and the extra argument @arg.
442  *
443  * Note: this function iterates over ALL child dentries, even those with the
444  * same case-insensitive name.
445  *
446  * Note: this function clobbers the tmp_list field of the child dentries.  */
447 int
448 for_dentry_child(const struct wim_dentry *dentry,
449                  int (*visitor)(struct wim_dentry *, void *),
450                  void *arg)
451 {
452         return for_dentry_in_rbtree(dentry->d_inode->i_children.rb_node,
453                                     visitor,
454                                     arg);
455 }
456
457 /* Calls a function on all directory entries in a WIM dentry tree.  Logically,
458  * this is a pre-order traversal (the function is called on a parent dentry
459  * before its children), but sibling dentries will be visited in order as well.
460  * */
461 int
462 for_dentry_in_tree(struct wim_dentry *root,
463                    int (*visitor)(struct wim_dentry*, void*), void *arg)
464 {
465         int ret;
466
467         if (root == NULL)
468                 return 0;
469         ret = (*visitor)(root, arg);
470         if (ret)
471                 return ret;
472         return for_dentry_tree_in_rbtree(root->d_inode->i_children.rb_node,
473                                          visitor,
474                                          arg);
475 }
476
477 /* Like for_dentry_in_tree(), but the visitor function is always called on a
478  * dentry's children before on itself. */
479 int
480 for_dentry_in_tree_depth(struct wim_dentry *root,
481                          int (*visitor)(struct wim_dentry*, void*), void *arg)
482 {
483         int ret;
484
485         if (root == NULL)
486                 return 0;
487         ret = for_dentry_tree_in_rbtree_depth(root->d_inode->i_children.rb_node,
488                                               visitor, arg);
489         if (ret)
490                 return ret;
491         return (*visitor)(root, arg);
492 }
493
494 /* Calculate the full path of @dentry.  The full path of its parent must have
495  * already been calculated, or it must be the root dentry. */
496 int
497 calculate_dentry_full_path(struct wim_dentry *dentry)
498 {
499         tchar *full_path;
500         u32 full_path_nbytes;
501         int ret;
502
503         if (dentry->_full_path)
504                 return 0;
505
506         if (dentry_is_root(dentry)) {
507                 static const tchar _root_path[] = {WIM_PATH_SEPARATOR, T('\0')};
508                 full_path = TSTRDUP(_root_path);
509                 if (full_path == NULL)
510                         return WIMLIB_ERR_NOMEM;
511                 full_path_nbytes = 1 * sizeof(tchar);
512         } else {
513                 struct wim_dentry *parent;
514                 tchar *parent_full_path;
515                 u32 parent_full_path_nbytes;
516                 size_t filename_nbytes;
517
518                 parent = dentry->parent;
519                 if (dentry_is_root(parent)) {
520                         parent_full_path = T("");
521                         parent_full_path_nbytes = 0;
522                 } else {
523                         if (parent->_full_path == NULL) {
524                                 ret = calculate_dentry_full_path(parent);
525                                 if (ret)
526                                         return ret;
527                         }
528                         parent_full_path = parent->_full_path;
529                         parent_full_path_nbytes = parent->full_path_nbytes;
530                 }
531
532                 /* Append this dentry's name as a tchar string to the full path
533                  * of the parent followed by the path separator */
534         #if TCHAR_IS_UTF16LE
535                 filename_nbytes = dentry->file_name_nbytes;
536         #else
537                 {
538                         int ret = utf16le_to_tstr_nbytes(dentry->file_name,
539                                                          dentry->file_name_nbytes,
540                                                          &filename_nbytes);
541                         if (ret)
542                                 return ret;
543                 }
544         #endif
545
546                 full_path_nbytes = parent_full_path_nbytes + sizeof(tchar) +
547                                    filename_nbytes;
548                 full_path = MALLOC(full_path_nbytes + sizeof(tchar));
549                 if (full_path == NULL)
550                         return WIMLIB_ERR_NOMEM;
551                 memcpy(full_path, parent_full_path, parent_full_path_nbytes);
552                 full_path[parent_full_path_nbytes / sizeof(tchar)] = WIM_PATH_SEPARATOR;
553         #if TCHAR_IS_UTF16LE
554                 memcpy(&full_path[parent_full_path_nbytes / sizeof(tchar) + 1],
555                        dentry->file_name,
556                        filename_nbytes + sizeof(tchar));
557         #else
558                 utf16le_to_tstr_buf(dentry->file_name,
559                                     dentry->file_name_nbytes,
560                                     &full_path[parent_full_path_nbytes /
561                                                sizeof(tchar) + 1]);
562         #endif
563         }
564         dentry->_full_path = full_path;
565         dentry->full_path_nbytes= full_path_nbytes;
566         return 0;
567 }
568
569 static int
570 do_calculate_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
571 {
572         return calculate_dentry_full_path(dentry);
573 }
574
575 int
576 calculate_dentry_tree_full_paths(struct wim_dentry *root)
577 {
578         return for_dentry_in_tree(root, do_calculate_dentry_full_path, NULL);
579 }
580
581 tchar *
582 dentry_full_path(struct wim_dentry *dentry)
583 {
584         calculate_dentry_full_path(dentry);
585         return dentry->_full_path;
586 }
587
588 static int
589 increment_subdir_offset(struct wim_dentry *dentry, void *subdir_offset_p)
590 {
591         *(u64*)subdir_offset_p += dentry_out_total_length(dentry);
592         return 0;
593 }
594
595 static int
596 call_calculate_subdir_offsets(struct wim_dentry *dentry, void *subdir_offset_p)
597 {
598         calculate_subdir_offsets(dentry, subdir_offset_p);
599         return 0;
600 }
601
602 /*
603  * Recursively calculates the subdir offsets for a directory tree.
604  *
605  * @dentry:  The root of the directory tree.
606  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
607  *                    offset for @dentry.
608  */
609 void
610 calculate_subdir_offsets(struct wim_dentry *dentry, u64 *subdir_offset_p)
611 {
612         struct rb_node *node;
613
614         dentry->subdir_offset = *subdir_offset_p;
615         node = dentry->d_inode->i_children.rb_node;
616         if (node) {
617                 /* Advance the subdir offset by the amount of space the children
618                  * of this dentry take up. */
619                 for_dentry_in_rbtree(node, increment_subdir_offset, subdir_offset_p);
620
621                 /* End-of-directory dentry on disk. */
622                 *subdir_offset_p += 8;
623
624                 /* Recursively call calculate_subdir_offsets() on all the
625                  * children. */
626                 for_dentry_in_rbtree(node, call_calculate_subdir_offsets, subdir_offset_p);
627         } else {
628                 /* On disk, childless directories have a valid subdir_offset
629                  * that points to an 8-byte end-of-directory dentry.  Regular
630                  * files or reparse points have a subdir_offset of 0. */
631                 if (dentry_is_directory(dentry))
632                         *subdir_offset_p += 8;
633                 else
634                         dentry->subdir_offset = 0;
635         }
636 }
637
638 static int
639 dentry_compare_names_case_insensitive(const struct wim_dentry *d1,
640                                       const struct wim_dentry *d2)
641 {
642         return cmp_utf16le_strings(d1->file_name,
643                                    d1->file_name_nbytes / 2,
644                                    d2->file_name,
645                                    d2->file_name_nbytes / 2,
646                                    true);
647 }
648
649 static int
650 dentry_compare_names_case_sensitive(const struct wim_dentry *d1,
651                                     const struct wim_dentry *d2)
652 {
653         return cmp_utf16le_strings(d1->file_name,
654                                    d1->file_name_nbytes / 2,
655                                    d2->file_name,
656                                    d2->file_name_nbytes / 2,
657                                    false);
658 }
659
660 /* Return %true iff the alternate data stream entry @entry has the UTF-16LE
661  * stream name @name that has length @name_nbytes bytes. */
662 static inline bool
663 ads_entry_has_name(const struct wim_ads_entry *entry,
664                    const utf16lechar *name, size_t name_nbytes,
665                    bool ignore_case)
666 {
667         return 0 == cmp_utf16le_strings(name,
668                                         name_nbytes / 2,
669                                         entry->stream_name,
670                                         entry->stream_name_nbytes / 2,
671                                         ignore_case);
672 }
673
674 /* Default case sensitivity behavior for searches with
675  * WIMLIB_CASE_PLATFORM_DEFAULT specified.  This can be modified by
676  * wimlib_global_init().  */
677 bool default_ignore_case =
678 #ifdef __WIN32__
679         true
680 #else
681         false
682 #endif
683 ;
684
685 static bool
686 will_ignore_case(CASE_SENSITIVITY_TYPE case_type)
687 {
688         if (case_type == WIMLIB_CASE_SENSITIVE)
689                 return false;
690         if (case_type == WIMLIB_CASE_INSENSITIVE)
691                 return true;
692
693         return default_ignore_case;
694 }
695
696
697 /* Given a UTF-16LE filename and a directory, look up the dentry for the file.
698  * Return it if found, otherwise NULL.  This is case-sensitive on UNIX and
699  * case-insensitive on Windows. */
700 struct wim_dentry *
701 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
702                                    const utf16lechar *name,
703                                    size_t name_nbytes,
704                                    CASE_SENSITIVITY_TYPE case_ctype)
705 {
706         struct rb_node *node;
707
708         bool ignore_case = will_ignore_case(case_ctype);
709
710         if (ignore_case)
711                 node = dentry->d_inode->i_children_case_insensitive.rb_node;
712         else
713                 node = dentry->d_inode->i_children.rb_node;
714
715         struct wim_dentry *child;
716         while (node) {
717                 if (ignore_case)
718                         child = rb_entry(node, struct wim_dentry, rb_node_case_insensitive);
719                 else
720                         child = rb_entry(node, struct wim_dentry, rb_node);
721
722                 int result = cmp_utf16le_strings(name,
723                                                  name_nbytes / 2,
724                                                  child->file_name,
725                                                  child->file_name_nbytes / 2,
726                                                  ignore_case);
727                 if (result < 0) {
728                         node = node->rb_left;
729                 } else if (result > 0) {
730                         node = node->rb_right;
731                 } else if (!ignore_case ||
732                         list_empty(&child->case_insensitive_conflict_list)) {
733                         return child;
734                 } else {
735                         /* Multiple dentries have the same case-insensitive
736                          * name, and a case-insensitive lookup is being
737                          * performed.  Choose the dentry with the same
738                          * case-sensitive name, if one exists; otherwise print a
739                          * warning and choose one arbitrarily.  */
740                         struct wim_dentry *alt = child;
741                         size_t num_alts = 0;
742
743                         do {
744                                 num_alts++;
745                                 if (0 == cmp_utf16le_strings(name,
746                                                              name_nbytes / 2,
747                                                              alt->file_name,
748                                                              alt->file_name_nbytes / 2,
749                                                              false))
750                                         return alt;
751                                 alt = list_entry(alt->case_insensitive_conflict_list.next,
752                                                  struct wim_dentry,
753                                                  case_insensitive_conflict_list);
754                         } while (alt != child);
755
756                         WARNING("Result of case-insensitive lookup is ambiguous\n"
757                                 "          (returning \"%"TS"\" of %zu "
758                                 "possible files, including \"%"TS"\")",
759                                 dentry_full_path(child),
760                                 num_alts,
761                                 dentry_full_path(list_entry(child->case_insensitive_conflict_list.next,
762                                                             struct wim_dentry,
763                                                             case_insensitive_conflict_list)));
764                         return child;
765                 }
766         }
767         return NULL;
768 }
769
770 /* Returns the child of @dentry that has the file name @name.  Returns NULL if
771  * no child has the name. */
772 struct wim_dentry *
773 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name,
774                            CASE_SENSITIVITY_TYPE case_type)
775 {
776 #if TCHAR_IS_UTF16LE
777         return get_dentry_child_with_utf16le_name(dentry, name,
778                                                   tstrlen(name) * sizeof(tchar),
779                                                   case_type);
780 #else
781         utf16lechar *utf16le_name;
782         size_t utf16le_name_nbytes;
783         int ret;
784         struct wim_dentry *child;
785
786         ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
787                               &utf16le_name, &utf16le_name_nbytes);
788         if (ret) {
789                 child = NULL;
790         } else {
791                 child = get_dentry_child_with_utf16le_name(dentry,
792                                                            utf16le_name,
793                                                            utf16le_name_nbytes,
794                                                            case_type);
795                 FREE(utf16le_name);
796         }
797         return child;
798 #endif
799 }
800
801 static struct wim_dentry *
802 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path,
803                    CASE_SENSITIVITY_TYPE case_type)
804 {
805         struct wim_dentry *cur_dentry, *parent_dentry;
806         const utf16lechar *p, *pp;
807
808         cur_dentry = parent_dentry = wim_root_dentry(wim);
809         if (cur_dentry == NULL) {
810                 errno = ENOENT;
811                 return NULL;
812         }
813         p = path;
814         while (1) {
815                 while (*p == cpu_to_le16(WIM_PATH_SEPARATOR))
816                         p++;
817                 if (*p == cpu_to_le16('\0'))
818                         break;
819                 pp = p;
820                 while (*pp != cpu_to_le16(WIM_PATH_SEPARATOR) &&
821                        *pp != cpu_to_le16('\0'))
822                         pp++;
823
824                 cur_dentry = get_dentry_child_with_utf16le_name(parent_dentry, p,
825                                                                 (u8*)pp - (u8*)p,
826                                                                 case_type);
827                 if (cur_dentry == NULL)
828                         break;
829                 p = pp;
830                 parent_dentry = cur_dentry;
831         }
832         if (cur_dentry == NULL) {
833                 if (dentry_is_directory(parent_dentry))
834                         errno = ENOENT;
835                 else
836                         errno = ENOTDIR;
837         }
838         return cur_dentry;
839 }
840
841 /*
842  * Returns the dentry in the currently selected WIM image named by @path
843  * starting from the root of the WIM image, or NULL if there is no such dentry.
844  */
845 struct wim_dentry *
846 get_dentry(WIMStruct *wim, const tchar *path, CASE_SENSITIVITY_TYPE case_type)
847 {
848 #if TCHAR_IS_UTF16LE
849         return get_dentry_utf16le(wim, path, case_type);
850 #else
851         utf16lechar *path_utf16le;
852         size_t path_utf16le_nbytes;
853         int ret;
854         struct wim_dentry *dentry;
855
856         ret = tstr_to_utf16le(path, tstrlen(path) * sizeof(tchar),
857                               &path_utf16le, &path_utf16le_nbytes);
858         if (ret)
859                 return NULL;
860         dentry = get_dentry_utf16le(wim, path_utf16le, case_type);
861         FREE(path_utf16le);
862         return dentry;
863 #endif
864 }
865
866 /* Takes in a path of length @len in @buf, and transforms it into a string for
867  * the path of its parent directory. */
868 static void
869 to_parent_name(tchar *buf, size_t len)
870 {
871         ssize_t i = (ssize_t)len - 1;
872         while (i >= 0 && buf[i] == WIM_PATH_SEPARATOR)
873                 i--;
874         while (i >= 0 && buf[i] != WIM_PATH_SEPARATOR)
875                 i--;
876         while (i >= 0 && buf[i] == WIM_PATH_SEPARATOR)
877                 i--;
878         buf[i + 1] = T('\0');
879 }
880
881 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
882  * if the dentry is not found. */
883 struct wim_dentry *
884 get_parent_dentry(WIMStruct *wim, const tchar *path,
885                   CASE_SENSITIVITY_TYPE case_type)
886 {
887         size_t path_len = tstrlen(path);
888         tchar buf[path_len + 1];
889
890         tmemcpy(buf, path, path_len + 1);
891         to_parent_name(buf, path_len);
892         return get_dentry(wim, buf, case_type);
893 }
894
895 /* Prints the full path of a dentry. */
896 int
897 print_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
898 {
899         int ret = calculate_dentry_full_path(dentry);
900         if (ret)
901                 return ret;
902         tprintf(T("%"TS"\n"), dentry->_full_path);
903         return 0;
904 }
905
906 /* We want to be able to show the names of the file attribute flags that are
907  * set. */
908 struct file_attr_flag {
909         u32 flag;
910         const tchar *name;
911 };
912 struct file_attr_flag file_attr_flags[] = {
913         {FILE_ATTRIBUTE_READONLY,           T("READONLY")},
914         {FILE_ATTRIBUTE_HIDDEN,             T("HIDDEN")},
915         {FILE_ATTRIBUTE_SYSTEM,             T("SYSTEM")},
916         {FILE_ATTRIBUTE_DIRECTORY,          T("DIRECTORY")},
917         {FILE_ATTRIBUTE_ARCHIVE,            T("ARCHIVE")},
918         {FILE_ATTRIBUTE_DEVICE,             T("DEVICE")},
919         {FILE_ATTRIBUTE_NORMAL,             T("NORMAL")},
920         {FILE_ATTRIBUTE_TEMPORARY,          T("TEMPORARY")},
921         {FILE_ATTRIBUTE_SPARSE_FILE,        T("SPARSE_FILE")},
922         {FILE_ATTRIBUTE_REPARSE_POINT,      T("REPARSE_POINT")},
923         {FILE_ATTRIBUTE_COMPRESSED,         T("COMPRESSED")},
924         {FILE_ATTRIBUTE_OFFLINE,            T("OFFLINE")},
925         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,T("NOT_CONTENT_INDEXED")},
926         {FILE_ATTRIBUTE_ENCRYPTED,          T("ENCRYPTED")},
927         {FILE_ATTRIBUTE_VIRTUAL,            T("VIRTUAL")},
928 };
929
930 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
931  * available.  If the dentry is unresolved and the lookup table is NULL, the
932  * lookup table entries will not be printed.  Otherwise, they will be. */
933 int
934 print_dentry(struct wim_dentry *dentry, void *lookup_table)
935 {
936         const u8 *hash;
937         struct wim_lookup_table_entry *lte;
938         const struct wim_inode *inode = dentry->d_inode;
939         tchar buf[50];
940
941         tprintf(T("[DENTRY]\n"));
942         tprintf(T("Length            = %"PRIu64"\n"), dentry->length);
943         tprintf(T("Attributes        = 0x%x\n"), inode->i_attributes);
944         for (size_t i = 0; i < ARRAY_LEN(file_attr_flags); i++)
945                 if (file_attr_flags[i].flag & inode->i_attributes)
946                         tprintf(T("    FILE_ATTRIBUTE_%"TS" is set\n"),
947                                 file_attr_flags[i].name);
948         tprintf(T("Security ID       = %d\n"), inode->i_security_id);
949         tprintf(T("Subdir offset     = %"PRIu64"\n"), dentry->subdir_offset);
950
951         wim_timestamp_to_str(inode->i_creation_time, buf, sizeof(buf));
952         tprintf(T("Creation Time     = %"TS"\n"), buf);
953
954         wim_timestamp_to_str(inode->i_last_access_time, buf, sizeof(buf));
955         tprintf(T("Last Access Time  = %"TS"\n"), buf);
956
957         wim_timestamp_to_str(inode->i_last_write_time, buf, sizeof(buf));
958         tprintf(T("Last Write Time   = %"TS"\n"), buf);
959
960         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
961                 tprintf(T("Reparse Tag       = 0x%"PRIx32"\n"), inode->i_reparse_tag);
962                 tprintf(T("Reparse Point Flags = 0x%"PRIx16"\n"),
963                         inode->i_not_rpfixed);
964                 tprintf(T("Reparse Point Unknown 2 = 0x%"PRIx32"\n"),
965                         inode->i_rp_unknown_2);
966         }
967         tprintf(T("Reparse Point Unknown 1 = 0x%"PRIx32"\n"),
968                 inode->i_rp_unknown_1);
969         tprintf(T("Hard Link Group   = 0x%"PRIx64"\n"), inode->i_ino);
970         tprintf(T("Hard Link Group Size = %"PRIu32"\n"), inode->i_nlink);
971         tprintf(T("Number of Alternate Data Streams = %hu\n"), inode->i_num_ads);
972         if (dentry_has_long_name(dentry))
973                 wimlib_printf(T("Filename = \"%"WS"\"\n"), dentry->file_name);
974         if (dentry_has_short_name(dentry))
975                 wimlib_printf(T("Short Name \"%"WS"\"\n"), dentry->short_name);
976         if (dentry->_full_path)
977                 tprintf(T("Full Path = \"%"TS"\"\n"), dentry->_full_path);
978
979         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
980         if (lte) {
981                 print_lookup_table_entry(lte, stdout);
982         } else {
983                 hash = inode_stream_hash(inode, 0);
984                 if (hash) {
985                         tprintf(T("Hash              = 0x"));
986                         print_hash(hash, stdout);
987                         tputchar(T('\n'));
988                         tputchar(T('\n'));
989                 }
990         }
991         for (u16 i = 0; i < inode->i_num_ads; i++) {
992                 tprintf(T("[Alternate Stream Entry %u]\n"), i);
993                 wimlib_printf(T("Name = \"%"WS"\"\n"),
994                               inode->i_ads_entries[i].stream_name);
995                 tprintf(T("Name Length (UTF16 bytes) = %hu\n"),
996                        inode->i_ads_entries[i].stream_name_nbytes);
997                 hash = inode_stream_hash(inode, i + 1);
998                 if (hash) {
999                         tprintf(T("Hash              = 0x"));
1000                         print_hash(hash, stdout);
1001                         tputchar(T('\n'));
1002                 }
1003                 print_lookup_table_entry(inode_stream_lte(inode, i + 1, lookup_table),
1004                                          stdout);
1005         }
1006         return 0;
1007 }
1008
1009 /* Initializations done on every `struct wim_dentry'. */
1010 static void
1011 dentry_common_init(struct wim_dentry *dentry)
1012 {
1013         memset(dentry, 0, sizeof(struct wim_dentry));
1014 }
1015
1016 struct wim_inode *
1017 new_timeless_inode(void)
1018 {
1019         struct wim_inode *inode = CALLOC(1, sizeof(struct wim_inode));
1020         if (inode) {
1021                 inode->i_security_id = -1;
1022                 inode->i_nlink = 1;
1023                 inode->i_next_stream_id = 1;
1024                 inode->i_not_rpfixed = 1;
1025                 inode->i_canonical_streams = 1;
1026                 INIT_LIST_HEAD(&inode->i_list);
1027                 INIT_LIST_HEAD(&inode->i_dentry);
1028         }
1029         return inode;
1030 }
1031
1032 static struct wim_inode *
1033 new_inode(void)
1034 {
1035         struct wim_inode *inode = new_timeless_inode();
1036         if (inode) {
1037                 u64 now = get_wim_timestamp();
1038                 inode->i_creation_time = now;
1039                 inode->i_last_access_time = now;
1040                 inode->i_last_write_time = now;
1041         }
1042         return inode;
1043 }
1044
1045 /* Creates an unlinked directory entry. */
1046 int
1047 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
1048 {
1049         struct wim_dentry *dentry;
1050         int ret;
1051
1052         dentry = MALLOC(sizeof(struct wim_dentry));
1053         if (dentry == NULL)
1054                 return WIMLIB_ERR_NOMEM;
1055
1056         dentry_common_init(dentry);
1057         ret = set_dentry_name(dentry, name);
1058         if (ret == 0) {
1059                 dentry->parent = dentry;
1060                 *dentry_ret = dentry;
1061         } else {
1062                 FREE(dentry);
1063                 ERROR("Failed to set name on new dentry with name \"%"TS"\"",
1064                       name);
1065         }
1066         return ret;
1067 }
1068
1069
1070 static int
1071 _new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret,
1072                         bool timeless)
1073 {
1074         struct wim_dentry *dentry;
1075         int ret;
1076
1077         ret = new_dentry(name, &dentry);
1078         if (ret)
1079                 return ret;
1080
1081         if (timeless)
1082                 dentry->d_inode = new_timeless_inode();
1083         else
1084                 dentry->d_inode = new_inode();
1085         if (dentry->d_inode == NULL) {
1086                 free_dentry(dentry);
1087                 return WIMLIB_ERR_NOMEM;
1088         }
1089
1090         inode_add_dentry(dentry, dentry->d_inode);
1091         *dentry_ret = dentry;
1092         return 0;
1093 }
1094
1095 int
1096 new_dentry_with_timeless_inode(const tchar *name, struct wim_dentry **dentry_ret)
1097 {
1098         return _new_dentry_with_inode(name, dentry_ret, true);
1099 }
1100
1101 int
1102 new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret)
1103 {
1104         return _new_dentry_with_inode(name, dentry_ret, false);
1105 }
1106
1107 int
1108 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
1109 {
1110         int ret;
1111         struct wim_dentry *dentry;
1112
1113         DEBUG("Creating filler directory \"%"TS"\"", name);
1114         ret = new_dentry_with_inode(name, &dentry);
1115         if (ret)
1116                 return ret;
1117         /* Leave the inode number as 0; this is allowed for non
1118          * hard-linked files. */
1119         dentry->d_inode->i_resolved = 1;
1120         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
1121         *dentry_ret = dentry;
1122         return 0;
1123 }
1124
1125 static int
1126 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1127 {
1128         dentry->d_inode->i_visited = 0;
1129         return 0;
1130 }
1131
1132 void
1133 dentry_tree_clear_inode_visited(struct wim_dentry *root)
1134 {
1135         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1136 }
1137
1138 static int
1139 init_ads_entry(struct wim_ads_entry *ads_entry, const void *name,
1140                size_t name_nbytes, bool is_utf16le)
1141 {
1142         int ret = 0;
1143         memset(ads_entry, 0, sizeof(*ads_entry));
1144
1145         if (is_utf16le) {
1146                 utf16lechar *p = MALLOC(name_nbytes + sizeof(utf16lechar));
1147                 if (p == NULL)
1148                         return WIMLIB_ERR_NOMEM;
1149                 memcpy(p, name, name_nbytes);
1150                 p[name_nbytes / 2] = cpu_to_le16(0);
1151                 ads_entry->stream_name = p;
1152                 ads_entry->stream_name_nbytes = name_nbytes;
1153         } else {
1154                 if (name && *(const tchar*)name != T('\0')) {
1155                         ret = get_utf16le_name(name, &ads_entry->stream_name,
1156                                                &ads_entry->stream_name_nbytes);
1157                 }
1158         }
1159         return ret;
1160 }
1161
1162 static void
1163 destroy_ads_entry(struct wim_ads_entry *ads_entry)
1164 {
1165         FREE(ads_entry->stream_name);
1166 }
1167
1168 /* Frees an inode. */
1169 void
1170 free_inode(struct wim_inode *inode)
1171 {
1172         if (inode) {
1173                 if (inode->i_ads_entries) {
1174                         for (u16 i = 0; i < inode->i_num_ads; i++)
1175                                 destroy_ads_entry(&inode->i_ads_entries[i]);
1176                         FREE(inode->i_ads_entries);
1177                 }
1178                 /* HACK: This may instead delete the inode from i_list, but the
1179                  * hlist_del() behaves the same as list_del(). */
1180                 if (!hlist_unhashed(&inode->i_hlist))
1181                         hlist_del(&inode->i_hlist);
1182                 FREE(inode);
1183         }
1184 }
1185
1186 /* Decrements link count on an inode and frees it if the link count reaches 0.
1187  * */
1188 static void
1189 put_inode(struct wim_inode *inode)
1190 {
1191         wimlib_assert(inode->i_nlink != 0);
1192         if (--inode->i_nlink == 0) {
1193         #ifdef WITH_FUSE
1194                 if (inode->i_num_opened_fds == 0)
1195         #endif
1196                 {
1197                         free_inode(inode);
1198                 }
1199         }
1200 }
1201
1202 /* Frees a WIM dentry.
1203  *
1204  * The corresponding inode (if any) is freed only if its link count is
1205  * decremented to 0.
1206  */
1207 void
1208 free_dentry(struct wim_dentry *dentry)
1209 {
1210         if (dentry) {
1211                 FREE(dentry->file_name);
1212                 FREE(dentry->short_name);
1213                 FREE(dentry->_full_path);
1214                 if (dentry->d_inode)
1215                         put_inode(dentry->d_inode);
1216                 FREE(dentry);
1217         }
1218 }
1219
1220 /* This function is passed as an argument to for_dentry_in_tree_depth() in order
1221  * to free a directory tree. */
1222 static int
1223 do_free_dentry(struct wim_dentry *dentry, void *_lookup_table)
1224 {
1225         struct wim_lookup_table *lookup_table = _lookup_table;
1226
1227         if (lookup_table) {
1228                 struct wim_inode *inode = dentry->d_inode;
1229                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1230                         struct wim_lookup_table_entry *lte;
1231
1232                         lte = inode_stream_lte(inode, i, lookup_table);
1233                         if (lte)
1234                                 lte_decrement_refcnt(lte, lookup_table);
1235                 }
1236         }
1237         free_dentry(dentry);
1238         return 0;
1239 }
1240
1241 /*
1242  * Unlinks and frees a dentry tree.
1243  *
1244  * @root:
1245  *      The root of the tree.
1246  *
1247  * @lookup_table:
1248  *      The lookup table for dentries.  If non-NULL, the reference counts in the
1249  *      lookup table for the lookup table entries corresponding to the dentries
1250  *      will be decremented.
1251  */
1252 void
1253 free_dentry_tree(struct wim_dentry *root, struct wim_lookup_table *lookup_table)
1254 {
1255         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1256 }
1257
1258 /* Insert a dentry into the case insensitive index for a directory.
1259  *
1260  * This is a red-black tree, but when multiple dentries share the same
1261  * case-insensitive name, only one is inserted into the tree itself; the rest
1262  * are connected in a list.
1263  */
1264 static struct wim_dentry *
1265 dentry_add_child_case_insensitive(struct wim_dentry *parent,
1266                                   struct wim_dentry *child)
1267 {
1268         struct rb_root *root;
1269         struct rb_node **new;
1270         struct rb_node *rb_parent;
1271
1272         root = &parent->d_inode->i_children_case_insensitive;
1273         new = &root->rb_node;
1274         rb_parent = NULL;
1275         while (*new) {
1276                 struct wim_dentry *this = container_of(*new, struct wim_dentry,
1277                                                        rb_node_case_insensitive);
1278                 int result = dentry_compare_names_case_insensitive(child, this);
1279
1280                 rb_parent = *new;
1281
1282                 if (result < 0)
1283                         new = &((*new)->rb_left);
1284                 else if (result > 0)
1285                         new = &((*new)->rb_right);
1286                 else
1287                         return this;
1288         }
1289         rb_link_node(&child->rb_node_case_insensitive, rb_parent, new);
1290         rb_insert_color(&child->rb_node_case_insensitive, root);
1291         return NULL;
1292 }
1293
1294 /*
1295  * Links a dentry into the directory tree.
1296  *
1297  * @parent: The dentry that will be the parent of @child.
1298  * @child: The dentry to link.
1299  *
1300  * Returns NULL if successful.  If @parent already contains a dentry with the
1301  * same case-sensitive name as @child, the pointer to this duplicate dentry is
1302  * returned.
1303  */
1304 struct wim_dentry *
1305 dentry_add_child(struct wim_dentry * restrict parent,
1306                  struct wim_dentry * restrict child)
1307 {
1308         struct rb_root *root;
1309         struct rb_node **new;
1310         struct rb_node *rb_parent;
1311
1312         wimlib_assert(dentry_is_directory(parent));
1313         wimlib_assert(parent != child);
1314
1315         /* Case sensitive child dentry index */
1316         root = &parent->d_inode->i_children;
1317         new = &root->rb_node;
1318         rb_parent = NULL;
1319         while (*new) {
1320                 struct wim_dentry *this = rbnode_dentry(*new);
1321                 int result = dentry_compare_names_case_sensitive(child, this);
1322
1323                 rb_parent = *new;
1324
1325                 if (result < 0)
1326                         new = &((*new)->rb_left);
1327                 else if (result > 0)
1328                         new = &((*new)->rb_right);
1329                 else
1330                         return this;
1331         }
1332         child->parent = parent;
1333         rb_link_node(&child->rb_node, rb_parent, new);
1334         rb_insert_color(&child->rb_node, root);
1335
1336         /* Case insensitive child dentry index */
1337         {
1338                 struct wim_dentry *existing;
1339                 existing = dentry_add_child_case_insensitive(parent, child);
1340                 if (existing) {
1341                         list_add(&child->case_insensitive_conflict_list,
1342                                  &existing->case_insensitive_conflict_list);
1343                         child->rb_node_case_insensitive.__rb_parent_color = 0;
1344                 } else {
1345                         INIT_LIST_HEAD(&child->case_insensitive_conflict_list);
1346                 }
1347         }
1348         return NULL;
1349 }
1350
1351 /* Unlink a WIM dentry from the directory entry tree. */
1352 void
1353 unlink_dentry(struct wim_dentry *dentry)
1354 {
1355         struct wim_dentry *parent = dentry->parent;
1356
1357         if (parent == dentry)
1358                 return;
1359         rb_erase(&dentry->rb_node, &parent->d_inode->i_children);
1360
1361         if (dentry->rb_node_case_insensitive.__rb_parent_color) {
1362                 /* This dentry was in the case-insensitive red-black tree. */
1363                 rb_erase(&dentry->rb_node_case_insensitive,
1364                          &parent->d_inode->i_children_case_insensitive);
1365                 if (!list_empty(&dentry->case_insensitive_conflict_list)) {
1366                         /* Make a different case-insensitively-the-same dentry
1367                          * be the "representative" in the red-black tree. */
1368                         struct list_head *next;
1369                         struct wim_dentry *other;
1370                         struct wim_dentry *existing;
1371
1372                         next = dentry->case_insensitive_conflict_list.next;
1373                         other = list_entry(next, struct wim_dentry, case_insensitive_conflict_list);
1374                         existing = dentry_add_child_case_insensitive(parent, other);
1375                         wimlib_assert(existing == NULL);
1376                 }
1377         }
1378         list_del(&dentry->case_insensitive_conflict_list);
1379 }
1380
1381 static int
1382 free_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
1383 {
1384         FREE(dentry->_full_path);
1385         dentry->_full_path = NULL;
1386         return 0;
1387 }
1388
1389 /* Rename a file or directory in the WIM.  */
1390 int
1391 rename_wim_path(WIMStruct *wim, const tchar *from, const tchar *to,
1392                 CASE_SENSITIVITY_TYPE case_type)
1393 {
1394         struct wim_dentry *src;
1395         struct wim_dentry *dst;
1396         struct wim_dentry *parent_of_dst;
1397         int ret;
1398
1399         /* This rename() implementation currently only supports actual files
1400          * (not alternate data streams) */
1401
1402         src = get_dentry(wim, from, case_type);
1403         if (!src)
1404                 return -errno;
1405
1406         dst = get_dentry(wim, to, case_type);
1407
1408         if (dst) {
1409                 /* Destination file exists */
1410
1411                 if (src == dst) /* Same file */
1412                         return 0;
1413
1414                 if (!dentry_is_directory(src)) {
1415                         /* Cannot rename non-directory to directory. */
1416                         if (dentry_is_directory(dst))
1417                                 return -EISDIR;
1418                 } else {
1419                         /* Cannot rename directory to a non-directory or a non-empty
1420                          * directory */
1421                         if (!dentry_is_directory(dst))
1422                                 return -ENOTDIR;
1423                         if (dentry_has_children(dst))
1424                                 return -ENOTEMPTY;
1425                 }
1426                 parent_of_dst = dst->parent;
1427         } else {
1428                 /* Destination does not exist */
1429                 parent_of_dst = get_parent_dentry(wim, to, case_type);
1430                 if (!parent_of_dst)
1431                         return -errno;
1432
1433                 if (!dentry_is_directory(parent_of_dst))
1434                         return -ENOTDIR;
1435         }
1436
1437         ret = set_dentry_name(src, path_basename(to));
1438         if (ret)
1439                 return -ENOMEM;
1440         if (dst) {
1441                 unlink_dentry(dst);
1442                 free_dentry_tree(dst, wim->lookup_table);
1443         }
1444         unlink_dentry(src);
1445         dentry_add_child(parent_of_dst, src);
1446         if (src->_full_path)
1447                 for_dentry_in_tree(src, free_dentry_full_path, NULL);
1448         return 0;
1449 }
1450
1451 /*
1452  * Returns the alternate data stream entry belonging to @inode that has the
1453  * stream name @stream_name, or NULL if the inode has no alternate data stream
1454  * with that name.
1455  *
1456  * If @p stream_name is the empty string, NULL is returned --- that is, this
1457  * function will not return "unnamed" alternate data stream entries.
1458  */
1459 struct wim_ads_entry *
1460 inode_get_ads_entry(struct wim_inode *inode, const tchar *stream_name,
1461                     u16 *idx_ret)
1462 {
1463         if (inode->i_num_ads == 0) {
1464                 return NULL;
1465         } else {
1466                 size_t stream_name_utf16le_nbytes;
1467                 u16 i;
1468                 struct wim_ads_entry *result;
1469
1470                 if (stream_name[0] == T('\0'))
1471                         return NULL;
1472
1473         #if TCHAR_IS_UTF16LE
1474                 const utf16lechar *stream_name_utf16le;
1475
1476                 stream_name_utf16le = stream_name;
1477                 stream_name_utf16le_nbytes = tstrlen(stream_name) * sizeof(tchar);
1478         #else
1479                 utf16lechar *stream_name_utf16le;
1480
1481                 {
1482                         int ret = tstr_to_utf16le(stream_name,
1483                                                   tstrlen(stream_name) *
1484                                                       sizeof(tchar),
1485                                                   &stream_name_utf16le,
1486                                                   &stream_name_utf16le_nbytes);
1487                         if (ret)
1488                                 return NULL;
1489                 }
1490         #endif
1491                 i = 0;
1492                 result = NULL;
1493                 do {
1494                         if (ads_entry_has_name(&inode->i_ads_entries[i],
1495                                                stream_name_utf16le,
1496                                                stream_name_utf16le_nbytes,
1497                                                false))
1498                         {
1499                                 if (idx_ret)
1500                                         *idx_ret = i;
1501                                 result = &inode->i_ads_entries[i];
1502                                 break;
1503                         }
1504                 } while (++i != inode->i_num_ads);
1505         #if !TCHAR_IS_UTF16LE
1506                 FREE(stream_name_utf16le);
1507         #endif
1508                 return result;
1509         }
1510 }
1511
1512 static struct wim_ads_entry *
1513 do_inode_add_ads(struct wim_inode *inode, const void *stream_name,
1514                  size_t stream_name_nbytes, bool is_utf16le)
1515 {
1516         u16 num_ads;
1517         struct wim_ads_entry *ads_entries;
1518         struct wim_ads_entry *new_entry;
1519
1520         wimlib_assert(stream_name_nbytes != 0);
1521
1522         if (inode->i_num_ads >= 0xfffe) {
1523                 ERROR("Too many alternate data streams in one inode!");
1524                 return NULL;
1525         }
1526         num_ads = inode->i_num_ads + 1;
1527         ads_entries = REALLOC(inode->i_ads_entries,
1528                               num_ads * sizeof(inode->i_ads_entries[0]));
1529         if (ads_entries == NULL) {
1530                 ERROR("Failed to allocate memory for new alternate data stream");
1531                 return NULL;
1532         }
1533         inode->i_ads_entries = ads_entries;
1534
1535         new_entry = &inode->i_ads_entries[num_ads - 1];
1536         if (init_ads_entry(new_entry, stream_name, stream_name_nbytes, is_utf16le))
1537                 return NULL;
1538         new_entry->stream_id = inode->i_next_stream_id++;
1539         inode->i_num_ads = num_ads;
1540         return new_entry;
1541 }
1542
1543 struct wim_ads_entry *
1544 inode_add_ads_utf16le(struct wim_inode *inode,
1545                       const utf16lechar *stream_name,
1546                       size_t stream_name_nbytes)
1547 {
1548         DEBUG("Add alternate data stream \"%"WS"\"", stream_name);
1549         return do_inode_add_ads(inode, stream_name, stream_name_nbytes, true);
1550 }
1551
1552 /*
1553  * Add an alternate stream entry to a WIM inode.  On success, returns a pointer
1554  * to the new entry; on failure, returns NULL.
1555  *
1556  * @stream_name must be a nonempty string.
1557  */
1558 struct wim_ads_entry *
1559 inode_add_ads(struct wim_inode *inode, const tchar *stream_name)
1560 {
1561         DEBUG("Add alternate data stream \"%"TS"\"", stream_name);
1562         return do_inode_add_ads(inode, stream_name,
1563                                 tstrlen(stream_name) * sizeof(tchar),
1564                                 TCHAR_IS_UTF16LE);
1565 }
1566
1567 static struct wim_lookup_table_entry *
1568 add_stream_from_data_buffer(const void *buffer, size_t size,
1569                             struct wim_lookup_table *lookup_table)
1570 {
1571         u8 hash[SHA1_HASH_SIZE];
1572         struct wim_lookup_table_entry *lte, *existing_lte;
1573
1574         sha1_buffer(buffer, size, hash);
1575         existing_lte = lookup_resource(lookup_table, hash);
1576         if (existing_lte) {
1577                 wimlib_assert(existing_lte->size == size);
1578                 lte = existing_lte;
1579                 lte->refcnt++;
1580         } else {
1581                 void *buffer_copy;
1582                 lte = new_lookup_table_entry();
1583                 if (lte == NULL)
1584                         return NULL;
1585                 buffer_copy = memdup(buffer, size);
1586                 if (buffer_copy == NULL) {
1587                         free_lookup_table_entry(lte);
1588                         return NULL;
1589                 }
1590                 lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1591                 lte->attached_buffer    = buffer_copy;
1592                 lte->size               = size;
1593                 copy_hash(lte->hash, hash);
1594                 lookup_table_insert(lookup_table, lte);
1595         }
1596         return lte;
1597 }
1598
1599 int
1600 inode_add_ads_with_data(struct wim_inode *inode, const tchar *name,
1601                         const void *value, size_t size,
1602                         struct wim_lookup_table *lookup_table)
1603 {
1604         struct wim_ads_entry *new_ads_entry;
1605
1606         wimlib_assert(inode->i_resolved);
1607
1608         new_ads_entry = inode_add_ads(inode, name);
1609         if (new_ads_entry == NULL)
1610                 return WIMLIB_ERR_NOMEM;
1611
1612         new_ads_entry->lte = add_stream_from_data_buffer(value, size,
1613                                                          lookup_table);
1614         if (new_ads_entry->lte == NULL) {
1615                 inode_remove_ads(inode, new_ads_entry - inode->i_ads_entries,
1616                                  lookup_table);
1617                 return WIMLIB_ERR_NOMEM;
1618         }
1619         return 0;
1620 }
1621
1622 bool
1623 inode_has_named_stream(const struct wim_inode *inode)
1624 {
1625         for (u16 i = 0; i < inode->i_num_ads; i++)
1626                 if (ads_entry_is_named_stream(&inode->i_ads_entries[i]))
1627                         return true;
1628         return false;
1629 }
1630
1631 /* Set the unnamed stream of a WIM inode, given a data buffer containing the
1632  * stream contents. */
1633 int
1634 inode_set_unnamed_stream(struct wim_inode *inode, const void *data, size_t len,
1635                          struct wim_lookup_table *lookup_table)
1636 {
1637         inode->i_lte = add_stream_from_data_buffer(data, len, lookup_table);
1638         if (inode->i_lte == NULL)
1639                 return WIMLIB_ERR_NOMEM;
1640         inode->i_resolved = 1;
1641         return 0;
1642 }
1643
1644 /* Remove an alternate data stream from a WIM inode  */
1645 void
1646 inode_remove_ads(struct wim_inode *inode, u16 idx,
1647                  struct wim_lookup_table *lookup_table)
1648 {
1649         struct wim_ads_entry *ads_entry;
1650         struct wim_lookup_table_entry *lte;
1651
1652         wimlib_assert(idx < inode->i_num_ads);
1653         wimlib_assert(inode->i_resolved);
1654
1655         ads_entry = &inode->i_ads_entries[idx];
1656
1657         DEBUG("Remove alternate data stream \"%"WS"\"", ads_entry->stream_name);
1658
1659         lte = ads_entry->lte;
1660         if (lte)
1661                 lte_decrement_refcnt(lte, lookup_table);
1662
1663         destroy_ads_entry(ads_entry);
1664
1665         memmove(&inode->i_ads_entries[idx],
1666                 &inode->i_ads_entries[idx + 1],
1667                 (inode->i_num_ads - idx - 1) * sizeof(inode->i_ads_entries[0]));
1668         inode->i_num_ads--;
1669 }
1670
1671 bool
1672 inode_has_unix_data(const struct wim_inode *inode)
1673 {
1674         for (u16 i = 0; i < inode->i_num_ads; i++)
1675                 if (ads_entry_is_unix_data(&inode->i_ads_entries[i]))
1676                         return true;
1677         return false;
1678 }
1679
1680 #ifndef __WIN32__
1681 int
1682 inode_get_unix_data(const struct wim_inode *inode,
1683                     struct wimlib_unix_data *unix_data,
1684                     u16 *stream_idx_ret)
1685 {
1686         const struct wim_ads_entry *ads_entry;
1687         const struct wim_lookup_table_entry *lte;
1688         size_t size;
1689         int ret;
1690
1691         wimlib_assert(inode->i_resolved);
1692
1693         ads_entry = inode_get_ads_entry((struct wim_inode*)inode,
1694                                         WIMLIB_UNIX_DATA_TAG, NULL);
1695         if (ads_entry == NULL)
1696                 return NO_UNIX_DATA;
1697
1698         if (stream_idx_ret)
1699                 *stream_idx_ret = ads_entry - inode->i_ads_entries;
1700
1701         lte = ads_entry->lte;
1702         if (lte == NULL)
1703                 return NO_UNIX_DATA;
1704
1705         size = lte->size;
1706         if (size != sizeof(struct wimlib_unix_data))
1707                 return BAD_UNIX_DATA;
1708
1709         ret = read_full_stream_into_buf(lte, unix_data);
1710         if (ret)
1711                 return ret;
1712
1713         if (unix_data->version != 0)
1714                 return BAD_UNIX_DATA;
1715         return 0;
1716 }
1717
1718 int
1719 inode_set_unix_data(struct wim_inode *inode, uid_t uid, gid_t gid, mode_t mode,
1720                     struct wim_lookup_table *lookup_table, int which)
1721 {
1722         struct wimlib_unix_data unix_data;
1723         int ret;
1724         bool have_good_unix_data = false;
1725         bool have_unix_data = false;
1726         u16 stream_idx;
1727
1728         if (!(which & UNIX_DATA_CREATE)) {
1729                 ret = inode_get_unix_data(inode, &unix_data, &stream_idx);
1730                 if (ret == 0 || ret == BAD_UNIX_DATA || ret > 0)
1731                         have_unix_data = true;
1732                 if (ret == 0)
1733                         have_good_unix_data = true;
1734         }
1735         unix_data.version = 0;
1736         if (which & UNIX_DATA_UID || !have_good_unix_data)
1737                 unix_data.uid = uid;
1738         if (which & UNIX_DATA_GID || !have_good_unix_data)
1739                 unix_data.gid = gid;
1740         if (which & UNIX_DATA_MODE || !have_good_unix_data)
1741                 unix_data.mode = mode;
1742         ret = inode_add_ads_with_data(inode, WIMLIB_UNIX_DATA_TAG,
1743                                       &unix_data,
1744                                       sizeof(struct wimlib_unix_data),
1745                                       lookup_table);
1746         if (ret == 0 && have_unix_data)
1747                 inode_remove_ads(inode, stream_idx, lookup_table);
1748         return ret;
1749 }
1750 #endif /* !__WIN32__ */
1751
1752 /*
1753  * Reads the alternate data stream entries of a WIM dentry.
1754  *
1755  * @p:
1756  *      Pointer to buffer that starts with the first alternate stream entry.
1757  *
1758  * @inode:
1759  *      Inode to load the alternate data streams into.  @inode->i_num_ads must
1760  *      have been set to the number of alternate data streams that are expected.
1761  *
1762  * @remaining_size:
1763  *      Number of bytes of data remaining in the buffer pointed to by @p.
1764  *
1765  * On success, inode->i_ads_entries is set to an array of `struct
1766  * wim_ads_entry's of length inode->i_num_ads.  On failure, @inode is not
1767  * modified.
1768  *
1769  * Return values:
1770  *      WIMLIB_ERR_SUCCESS (0)
1771  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1772  *      WIMLIB_ERR_NOMEM
1773  */
1774 static int
1775 read_ads_entries(const u8 * restrict p, struct wim_inode * restrict inode,
1776                  size_t nbytes_remaining)
1777 {
1778         u16 num_ads;
1779         struct wim_ads_entry *ads_entries;
1780         int ret;
1781
1782         BUILD_BUG_ON(sizeof(struct wim_ads_entry_on_disk) != WIM_ADS_ENTRY_DISK_SIZE);
1783
1784         /* Allocate an array for our in-memory representation of the alternate
1785          * data stream entries. */
1786         num_ads = inode->i_num_ads;
1787         ads_entries = CALLOC(num_ads, sizeof(inode->i_ads_entries[0]));
1788         if (ads_entries == NULL)
1789                 goto out_of_memory;
1790
1791         /* Read the entries into our newly allocated buffer. */
1792         for (u16 i = 0; i < num_ads; i++) {
1793                 u64 length;
1794                 struct wim_ads_entry *cur_entry;
1795                 const struct wim_ads_entry_on_disk *disk_entry =
1796                         (const struct wim_ads_entry_on_disk*)p;
1797
1798                 cur_entry = &ads_entries[i];
1799                 ads_entries[i].stream_id = i + 1;
1800
1801                 /* Do we have at least the size of the fixed-length data we know
1802                  * need? */
1803                 if (nbytes_remaining < sizeof(struct wim_ads_entry_on_disk))
1804                         goto out_invalid;
1805
1806                 /* Read the length field */
1807                 length = le64_to_cpu(disk_entry->length);
1808
1809                 /* Make sure the length field is neither so small it doesn't
1810                  * include all the fixed-length data nor so large it overflows
1811                  * the metadata resource buffer. */
1812                 if (length < sizeof(struct wim_ads_entry_on_disk) ||
1813                     length > nbytes_remaining)
1814                         goto out_invalid;
1815
1816                 /* Read the rest of the fixed-length data. */
1817
1818                 cur_entry->reserved = le64_to_cpu(disk_entry->reserved);
1819                 copy_hash(cur_entry->hash, disk_entry->hash);
1820                 cur_entry->stream_name_nbytes = le16_to_cpu(disk_entry->stream_name_nbytes);
1821
1822                 /* If stream_name_nbytes != 0, this is a named stream.
1823                  * Otherwise this is an unnamed stream, or in some cases (bugs
1824                  * in Microsoft's software I guess) a meaningless entry
1825                  * distinguished from the real unnamed stream entry, if any, by
1826                  * the fact that the real unnamed stream entry has a nonzero
1827                  * hash field. */
1828                 if (cur_entry->stream_name_nbytes) {
1829                         /* The name is encoded in UTF16-LE, which uses 2-byte
1830                          * coding units, so the length of the name had better be
1831                          * an even number of bytes... */
1832                         if (cur_entry->stream_name_nbytes & 1)
1833                                 goto out_invalid;
1834
1835                         /* Add the length of the stream name to get the length
1836                          * we actually need to read.  Make sure this isn't more
1837                          * than the specified length of the entry. */
1838                         if (sizeof(struct wim_ads_entry_on_disk) +
1839                             cur_entry->stream_name_nbytes > length)
1840                                 goto out_invalid;
1841
1842                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_nbytes + 2);
1843                         if (cur_entry->stream_name == NULL)
1844                                 goto out_of_memory;
1845
1846                         memcpy(cur_entry->stream_name,
1847                                disk_entry->stream_name,
1848                                cur_entry->stream_name_nbytes);
1849                         cur_entry->stream_name[cur_entry->stream_name_nbytes / 2] = cpu_to_le16(0);
1850                 } else {
1851                         /* Mark inode as having weird stream entries.  */
1852                         inode->i_canonical_streams = 0;
1853                 }
1854
1855                 /* It's expected that the size of every ADS entry is a multiple
1856                  * of 8.  However, to be safe, I'm allowing the possibility of
1857                  * an ADS entry at the very end of the metadata resource ending
1858                  * un-aligned.  So although we still need to increment the input
1859                  * pointer by @length to reach the next ADS entry, it's possible
1860                  * that less than @length is actually remaining in the metadata
1861                  * resource. We should set the remaining bytes to 0 if this
1862                  * happens. */
1863                 length = (length + 7) & ~(u64)7;
1864                 p += length;
1865                 if (nbytes_remaining < length)
1866                         nbytes_remaining = 0;
1867                 else
1868                         nbytes_remaining -= length;
1869         }
1870         inode->i_ads_entries = ads_entries;
1871         inode->i_next_stream_id = inode->i_num_ads + 1;
1872         ret = 0;
1873         goto out;
1874 out_of_memory:
1875         ret = WIMLIB_ERR_NOMEM;
1876         goto out_free_ads_entries;
1877 out_invalid:
1878         ERROR("An alternate data stream entry is invalid");
1879         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1880 out_free_ads_entries:
1881         if (ads_entries) {
1882                 for (u16 i = 0; i < num_ads; i++)
1883                         destroy_ads_entry(&ads_entries[i]);
1884                 FREE(ads_entries);
1885         }
1886 out:
1887         return ret;
1888 }
1889
1890 /*
1891  * Reads a WIM directory entry, including all alternate data stream entries that
1892  * follow it, from the WIM image's metadata resource.
1893  *
1894  * @metadata_resource:
1895  *              Pointer to the metadata resource buffer.
1896  *
1897  * @metadata_resource_len:
1898  *              Length of the metadata resource buffer, in bytes.
1899  *
1900  * @offset:     Offset of the dentry within the metadata resource.
1901  *
1902  * @dentry:     A `struct wim_dentry' that will be filled in by this function.
1903  *
1904  * Return 0 on success or nonzero on failure.  On failure, @dentry will have
1905  * been modified, but it will not be left with pointers to any allocated
1906  * buffers.  On success, the dentry->length field must be examined.  If zero,
1907  * this was a special "end of directory" dentry and not a real dentry.  If
1908  * nonzero, this was a real dentry.
1909  *
1910  * Return values:
1911  *      WIMLIB_ERR_SUCCESS (0)
1912  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1913  *      WIMLIB_ERR_NOMEM
1914  */
1915 int
1916 read_dentry(const u8 * restrict metadata_resource, u64 metadata_resource_len,
1917             u64 offset, struct wim_dentry * restrict dentry)
1918 {
1919
1920         u64 calculated_size;
1921         utf16lechar *file_name;
1922         utf16lechar *short_name;
1923         u16 short_name_nbytes;
1924         u16 file_name_nbytes;
1925         int ret;
1926         struct wim_inode *inode;
1927         const u8 *p = &metadata_resource[offset];
1928         const struct wim_dentry_on_disk *disk_dentry =
1929                         (const struct wim_dentry_on_disk*)p;
1930
1931         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1932
1933         if ((uintptr_t)p & 7)
1934                 WARNING("WIM dentry is not 8-byte aligned");
1935
1936         dentry_common_init(dentry);
1937
1938         /* Before reading the whole dentry, we need to read just the length.
1939          * This is because a dentry of length 8 (that is, just the length field)
1940          * terminates the list of sibling directory entries. */
1941         if (offset + sizeof(u64) > metadata_resource_len ||
1942             offset + sizeof(u64) < offset)
1943         {
1944                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1945                       "end of the metadata resource (size %"PRIu64")",
1946                       offset, metadata_resource_len);
1947                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1948         }
1949         dentry->length = le64_to_cpu(disk_dentry->length);
1950
1951         /* A zero length field (really a length of 8, since that's how big the
1952          * directory entry is...) indicates that this is the end of directory
1953          * dentry.  We do not read it into memory as an actual dentry, so just
1954          * return successfully in this case. */
1955         if (dentry->length == 8)
1956                 dentry->length = 0;
1957         if (dentry->length == 0)
1958                 return 0;
1959
1960         /* Now that we have the actual length provided in the on-disk structure,
1961          * again make sure it doesn't overflow the metadata resource buffer. */
1962         if (offset + dentry->length > metadata_resource_len ||
1963             offset + dentry->length < offset)
1964         {
1965                 ERROR("Directory entry at offset %"PRIu64" and with size "
1966                       "%"PRIu64" ends past the end of the metadata resource "
1967                       "(size %"PRIu64")",
1968                       offset, dentry->length, metadata_resource_len);
1969                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1970         }
1971
1972         /* Make sure the dentry length is at least as large as the number of
1973          * fixed-length fields */
1974         if (dentry->length < sizeof(struct wim_dentry_on_disk)) {
1975                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1976                       dentry->length);
1977                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1978         }
1979
1980         /* Allocate a `struct wim_inode' for this `struct wim_dentry'. */
1981         inode = new_timeless_inode();
1982         if (inode == NULL)
1983                 return WIMLIB_ERR_NOMEM;
1984
1985         /* Read more fields; some into the dentry, and some into the inode. */
1986
1987         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1988         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1989         dentry->subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1990         dentry->d_unused_1 = le64_to_cpu(disk_dentry->unused_1);
1991         dentry->d_unused_2 = le64_to_cpu(disk_dentry->unused_2);
1992         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1993         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1994         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1995         copy_hash(inode->i_hash, disk_dentry->unnamed_stream_hash);
1996
1997         /* I don't know what's going on here.  It seems like M$ screwed up the
1998          * reparse points, then put the fields in the same place and didn't
1999          * document it.  So we have some fields we read for reparse points, and
2000          * some fields in the same place for non-reparse-point.s */
2001         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2002                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->reparse.rp_unknown_1);
2003                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
2004                 inode->i_rp_unknown_2 = le16_to_cpu(disk_dentry->reparse.rp_unknown_2);
2005                 inode->i_not_rpfixed = le16_to_cpu(disk_dentry->reparse.not_rpfixed);
2006                 /* Leave inode->i_ino at 0.  Note that this means the WIM file
2007                  * cannot archive hard-linked reparse points.  Such a thing
2008                  * doesn't really make sense anyway, although I believe it's
2009                  * theoretically possible to have them on NTFS. */
2010         } else {
2011                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->nonreparse.rp_unknown_1);
2012                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
2013         }
2014
2015         inode->i_num_ads = le16_to_cpu(disk_dentry->num_alternate_data_streams);
2016
2017         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
2018         file_name_nbytes = le16_to_cpu(disk_dentry->file_name_nbytes);
2019
2020         if ((short_name_nbytes & 1) | (file_name_nbytes & 1))
2021         {
2022                 ERROR("Dentry name is not valid UTF-16LE (odd number of bytes)!");
2023                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2024                 goto out_free_inode;
2025         }
2026
2027         /* We now know the length of the file name and short name.  Make sure
2028          * the length of the dentry is large enough to actually hold them.
2029          *
2030          * The calculated length here is unaligned to allow for the possibility
2031          * that the dentry->length names an unaligned length, although this
2032          * would be unexpected. */
2033         calculated_size = dentry_correct_length_unaligned(file_name_nbytes,
2034                                                           short_name_nbytes);
2035
2036         if (dentry->length < calculated_size) {
2037                 ERROR("Unexpected end of directory entry! (Expected "
2038                       "at least %"PRIu64" bytes, got %"PRIu64" bytes.)",
2039                       calculated_size, dentry->length);
2040                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2041                 goto out_free_inode;
2042         }
2043
2044         p += sizeof(struct wim_dentry_on_disk);
2045
2046         /* Read the filename if present.  Note: if the filename is empty, there
2047          * is no null terminator following it. */
2048         if (file_name_nbytes) {
2049                 file_name = MALLOC(file_name_nbytes + 2);
2050                 if (file_name == NULL) {
2051                         ERROR("Failed to allocate %d bytes for dentry file name",
2052                               file_name_nbytes + 2);
2053                         ret = WIMLIB_ERR_NOMEM;
2054                         goto out_free_inode;
2055                 }
2056                 memcpy(file_name, p, file_name_nbytes);
2057                 p += file_name_nbytes + 2;
2058                 file_name[file_name_nbytes / 2] = cpu_to_le16(0);
2059         } else {
2060                 file_name = NULL;
2061         }
2062
2063
2064         /* Read the short filename if present.  Note: if there is no short
2065          * filename, there is no null terminator following it. */
2066         if (short_name_nbytes) {
2067                 short_name = MALLOC(short_name_nbytes + 2);
2068                 if (short_name == NULL) {
2069                         ERROR("Failed to allocate %d bytes for dentry short name",
2070                               short_name_nbytes + 2);
2071                         ret = WIMLIB_ERR_NOMEM;
2072                         goto out_free_file_name;
2073                 }
2074                 memcpy(short_name, p, short_name_nbytes);
2075                 p += short_name_nbytes + 2;
2076                 short_name[short_name_nbytes / 2] = cpu_to_le16(0);
2077         } else {
2078                 short_name = NULL;
2079         }
2080
2081         /* Align the dentry length */
2082         dentry->length = (dentry->length + 7) & ~7;
2083
2084         /*
2085          * Read the alternate data streams, if present.  dentry->num_ads tells
2086          * us how many they are, and they will directly follow the dentry
2087          * on-disk.
2088          *
2089          * Note that each alternate data stream entry begins on an 8-byte
2090          * aligned boundary, and the alternate data stream entries seem to NOT
2091          * be included in the dentry->length field for some reason.
2092          */
2093         if (inode->i_num_ads != 0) {
2094                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2095                 if (offset + dentry->length > metadata_resource_len ||
2096                     (ret = read_ads_entries(&metadata_resource[offset + dentry->length],
2097                                             inode,
2098                                             metadata_resource_len - offset - dentry->length)))
2099                 {
2100                         ERROR("Failed to read alternate data stream "
2101                               "entries of WIM dentry \"%"WS"\"", file_name);
2102                         goto out_free_short_name;
2103                 }
2104         }
2105         /* We've read all the data for this dentry.  Set the names and their
2106          * lengths, and we've done. */
2107         dentry->d_inode           = inode;
2108         dentry->file_name         = file_name;
2109         dentry->short_name        = short_name;
2110         dentry->file_name_nbytes  = file_name_nbytes;
2111         dentry->short_name_nbytes = short_name_nbytes;
2112         ret = 0;
2113         goto out;
2114 out_free_short_name:
2115         FREE(short_name);
2116 out_free_file_name:
2117         FREE(file_name);
2118 out_free_inode:
2119         free_inode(inode);
2120 out:
2121         return ret;
2122 }
2123
2124 static const tchar *
2125 dentry_get_file_type_string(const struct wim_dentry *dentry)
2126 {
2127         const struct wim_inode *inode = dentry->d_inode;
2128         if (inode_is_directory(inode))
2129                 return T("directory");
2130         else if (inode_is_symlink(inode))
2131                 return T("symbolic link");
2132         else
2133                 return T("file");
2134 }
2135
2136 /* Reads the children of a dentry, and all their children, ..., etc. from the
2137  * metadata resource and into the dentry tree.
2138  *
2139  * @metadata_resource:
2140  *      An array that contains the uncompressed metadata resource for the WIM
2141  *      file.
2142  *
2143  * @metadata_resource_len:
2144  *      The length of the uncompressed metadata resource, in bytes.
2145  *
2146  * @dentry:
2147  *      A pointer to a `struct wim_dentry' that is the root of the directory
2148  *      tree and has already been read from the metadata resource.  It does not
2149  *      need to be the real root because this procedure is called recursively.
2150  *
2151  * Return values:
2152  *      WIMLIB_ERR_SUCCESS (0)
2153  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
2154  *      WIMLIB_ERR_NOMEM
2155  */
2156 int
2157 read_dentry_tree(const u8 * restrict metadata_resource,
2158                  u64 metadata_resource_len,
2159                  struct wim_dentry * restrict dentry)
2160 {
2161         u64 cur_offset = dentry->subdir_offset;
2162         struct wim_dentry *child;
2163         struct wim_dentry *duplicate;
2164         struct wim_dentry *parent;
2165         struct wim_dentry cur_child;
2166         int ret;
2167
2168         /*
2169          * If @dentry has no child dentries, nothing more needs to be done for
2170          * this branch.  This is the case for regular files, symbolic links, and
2171          * *possibly* empty directories (although an empty directory may also
2172          * have one child dentry that is the special end-of-directory dentry)
2173          */
2174         if (cur_offset == 0)
2175                 return 0;
2176
2177         /* Check for cyclic directory structure */
2178         for (parent = dentry->parent; !dentry_is_root(parent); parent = parent->parent)
2179         {
2180                 if (unlikely(parent->subdir_offset == cur_offset)) {
2181                         ERROR("Cyclic directory structure directed: children "
2182                               "of \"%"TS"\" coincide with children of \"%"TS"\"",
2183                               dentry_full_path(dentry),
2184                               dentry_full_path(parent));
2185                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2186                 }
2187         }
2188
2189         /* Find and read all the children of @dentry. */
2190         for (;;) {
2191
2192                 /* Read next child of @dentry into @cur_child. */
2193                 ret = read_dentry(metadata_resource, metadata_resource_len,
2194                                   cur_offset, &cur_child);
2195                 if (ret)
2196                         break;
2197
2198                 /* Check for end of directory. */
2199                 if (cur_child.length == 0)
2200                         break;
2201
2202                 /* Not end of directory.  Allocate this child permanently and
2203                  * link it to the parent and previous child. */
2204                 child = memdup(&cur_child, sizeof(struct wim_dentry));
2205                 if (child == NULL) {
2206                         ERROR("Failed to allocate new dentry!");
2207                         ret = WIMLIB_ERR_NOMEM;
2208                         break;
2209                 }
2210
2211                 /* Advance to the offset of the next child.  Note: We need to
2212                  * advance by the TOTAL length of the dentry, not by the length
2213                  * cur_child.length, which although it does take into account
2214                  * the padding, it DOES NOT take into account alternate stream
2215                  * entries. */
2216                 cur_offset += dentry_in_total_length(child);
2217
2218                 if (unlikely(!dentry_has_long_name(child))) {
2219                         WARNING("Ignoring unnamed dentry in "
2220                                 "directory \"%"TS"\"",
2221                                 dentry_full_path(dentry));
2222                         free_dentry(child);
2223                         continue;
2224                 }
2225
2226                 duplicate = dentry_add_child(dentry, child);
2227                 if (unlikely(duplicate)) {
2228                         const tchar *child_type, *duplicate_type;
2229                         child_type = dentry_get_file_type_string(child);
2230                         duplicate_type = dentry_get_file_type_string(duplicate);
2231                         WARNING("Ignoring duplicate %"TS" \"%"TS"\" "
2232                                 "(the WIM image already contains a %"TS" "
2233                                 "at that path with the exact same name)",
2234                                 child_type, dentry_full_path(duplicate),
2235                                 duplicate_type);
2236                         free_dentry(child);
2237                         continue;
2238                 }
2239
2240                 inode_add_dentry(child, child->d_inode);
2241                 /* If there are children of this child, call this
2242                  * procedure recursively. */
2243                 if (child->subdir_offset != 0) {
2244                         if (likely(dentry_is_directory(child))) {
2245                                 ret = read_dentry_tree(metadata_resource,
2246                                                        metadata_resource_len,
2247                                                        child);
2248                                 if (ret)
2249                                         break;
2250                         } else {
2251                                 WARNING("Ignoring children of non-directory \"%"TS"\"",
2252                                         dentry_full_path(child));
2253                         }
2254                 }
2255         }
2256         return ret;
2257 }
2258
2259 /*
2260  * Writes a WIM alternate data stream (ADS) entry to an output buffer.
2261  *
2262  * @ads_entry:  The ADS entry structure.
2263  * @hash:       The hash field to use (instead of the one in the ADS entry).
2264  * @p:          The memory location to write the data to.
2265  *
2266  * Returns a pointer to the byte after the last byte written.
2267  */
2268 static u8 *
2269 write_ads_entry(const struct wim_ads_entry *ads_entry,
2270                 const u8 *hash, u8 * restrict p)
2271 {
2272         struct wim_ads_entry_on_disk *disk_ads_entry =
2273                         (struct wim_ads_entry_on_disk*)p;
2274         u8 *orig_p = p;
2275
2276         disk_ads_entry->reserved = cpu_to_le64(ads_entry->reserved);
2277         copy_hash(disk_ads_entry->hash, hash);
2278         disk_ads_entry->stream_name_nbytes = cpu_to_le16(ads_entry->stream_name_nbytes);
2279         p += sizeof(struct wim_ads_entry_on_disk);
2280         if (ads_entry->stream_name_nbytes) {
2281                 p = mempcpy(p, ads_entry->stream_name,
2282                             ads_entry->stream_name_nbytes + 2);
2283         }
2284         /* Align to 8-byte boundary */
2285         while ((uintptr_t)p & 7)
2286                 *p++ = 0;
2287         disk_ads_entry->length = cpu_to_le64(p - orig_p);
2288         return p;
2289 }
2290
2291 /*
2292  * Writes a WIM dentry to an output buffer.
2293  *
2294  * @dentry:  The dentry structure.
2295  * @p:       The memory location to write the data to.
2296  *
2297  * Returns the pointer to the byte after the last byte we wrote as part of the
2298  * dentry, including any alternate data stream entries.
2299  */
2300 static u8 *
2301 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
2302 {
2303         const struct wim_inode *inode;
2304         struct wim_dentry_on_disk *disk_dentry;
2305         const u8 *orig_p;
2306         const u8 *hash;
2307         bool use_dummy_stream;
2308         u16 num_ads;
2309
2310         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
2311         orig_p = p;
2312
2313         inode = dentry->d_inode;
2314         use_dummy_stream = inode_needs_dummy_stream(inode);
2315         disk_dentry = (struct wim_dentry_on_disk*)p;
2316
2317         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
2318         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
2319         disk_dentry->subdir_offset = cpu_to_le64(dentry->subdir_offset);
2320         disk_dentry->unused_1 = cpu_to_le64(dentry->d_unused_1);
2321         disk_dentry->unused_2 = cpu_to_le64(dentry->d_unused_2);
2322         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
2323         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
2324         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
2325         if (use_dummy_stream)
2326                 hash = zero_hash;
2327         else
2328                 hash = inode_stream_hash(inode, 0);
2329         copy_hash(disk_dentry->unnamed_stream_hash, hash);
2330         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2331                 disk_dentry->reparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
2332                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
2333                 disk_dentry->reparse.rp_unknown_2 = cpu_to_le16(inode->i_rp_unknown_2);
2334                 disk_dentry->reparse.not_rpfixed = cpu_to_le16(inode->i_not_rpfixed);
2335         } else {
2336                 disk_dentry->nonreparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
2337                 disk_dentry->nonreparse.hard_link_group_id =
2338                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
2339         }
2340         num_ads = inode->i_num_ads;
2341         if (use_dummy_stream)
2342                 num_ads++;
2343         disk_dentry->num_alternate_data_streams = cpu_to_le16(num_ads);
2344         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->short_name_nbytes);
2345         disk_dentry->file_name_nbytes = cpu_to_le16(dentry->file_name_nbytes);
2346         p += sizeof(struct wim_dentry_on_disk);
2347
2348         wimlib_assert(dentry_is_root(dentry) != dentry_has_long_name(dentry));
2349
2350         if (dentry_has_long_name(dentry))
2351                 p = mempcpy(p, dentry->file_name, dentry->file_name_nbytes + 2);
2352
2353         if (dentry_has_short_name(dentry))
2354                 p = mempcpy(p, dentry->short_name, dentry->short_name_nbytes + 2);
2355
2356         /* Align to 8-byte boundary */
2357         while ((uintptr_t)p & 7)
2358                 *p++ = 0;
2359
2360         /* We calculate the correct length of the dentry ourselves because the
2361          * dentry->length field may been set to an unexpected value from when we
2362          * read the dentry in (for example, there may have been unknown data
2363          * appended to the end of the dentry...).  Furthermore, the dentry may
2364          * have been renamed, thus changing its needed length. */
2365         disk_dentry->length = cpu_to_le64(p - orig_p);
2366
2367         if (use_dummy_stream) {
2368                 hash = inode_unnamed_stream_hash(inode);
2369                 p = write_ads_entry(&(struct wim_ads_entry){}, hash, p);
2370         }
2371
2372         /* Write the alternate data streams entries, if any. */
2373         for (u16 i = 0; i < inode->i_num_ads; i++) {
2374                 hash = inode_stream_hash(inode, i + 1);
2375                 p = write_ads_entry(&inode->i_ads_entries[i], hash, p);
2376         }
2377
2378         return p;
2379 }
2380
2381 static int
2382 write_dentry_cb(struct wim_dentry *dentry, void *_p)
2383 {
2384         u8 **p = _p;
2385         *p = write_dentry(dentry, *p);
2386         return 0;
2387 }
2388
2389 static u8 *
2390 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p);
2391
2392 static int
2393 write_dentry_tree_recursive_cb(struct wim_dentry *dentry, void *_p)
2394 {
2395         u8 **p = _p;
2396         *p = write_dentry_tree_recursive(dentry, *p);
2397         return 0;
2398 }
2399
2400 /* Recursive function that writes a dentry tree rooted at @parent, not including
2401  * @parent itself, which has already been written. */
2402 static u8 *
2403 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p)
2404 {
2405         /* Nothing to do if this dentry has no children. */
2406         if (parent->subdir_offset == 0)
2407                 return p;
2408
2409         /* Write child dentries and end-of-directory entry.
2410          *
2411          * Note: we need to write all of this dentry's children before
2412          * recursively writing the directory trees rooted at each of the child
2413          * dentries, since the on-disk dentries for a dentry's children are
2414          * always located at consecutive positions in the metadata resource! */
2415         for_dentry_child(parent, write_dentry_cb, &p);
2416
2417         /* write end of directory entry */
2418         *(le64*)p = cpu_to_le64(0);
2419         p += 8;
2420
2421         /* Recurse on children. */
2422         for_dentry_child(parent, write_dentry_tree_recursive_cb, &p);
2423         return p;
2424 }
2425
2426 /* Writes a directory tree to the metadata resource.
2427  *
2428  * @root:       Root of the dentry tree.
2429  * @p:          Pointer to a buffer with enough space for the dentry tree.
2430  *
2431  * Returns pointer to the byte after the last byte we wrote.
2432  */
2433 u8 *
2434 write_dentry_tree(const struct wim_dentry * restrict root, u8 * restrict p)
2435 {
2436         DEBUG("Writing dentry tree.");
2437         wimlib_assert(dentry_is_root(root));
2438
2439         /* If we're the root dentry, we have no parent that already
2440          * wrote us, so we need to write ourselves. */
2441         p = write_dentry(root, p);
2442
2443         /* Write end of directory entry after the root dentry just to be safe;
2444          * however the root dentry obviously cannot have any siblings. */
2445         *(le64*)p = cpu_to_le64(0);
2446         p += 8;
2447
2448         /* Recursively write the rest of the dentry tree. */
2449         return write_dentry_tree_recursive(root, p);
2450 }
2451
2452
2453 static int
2454 init_wimlib_dentry(struct wimlib_dir_entry *wdentry,
2455                    struct wim_dentry *dentry,
2456                    const WIMStruct *wim,
2457                    int flags)
2458 {
2459         int ret;
2460         size_t dummy;
2461         const struct wim_inode *inode = dentry->d_inode;
2462         struct wim_lookup_table_entry *lte;
2463         const u8 *hash;
2464
2465 #if TCHAR_IS_UTF16LE
2466         wdentry->filename = dentry->file_name;
2467         wdentry->dos_name = dentry->short_name;
2468 #else
2469         if (dentry_has_long_name(dentry)) {
2470                 ret = utf16le_to_tstr(dentry->file_name,
2471                                       dentry->file_name_nbytes,
2472                                       (tchar**)&wdentry->filename,
2473                                       &dummy);
2474                 if (ret)
2475                         return ret;
2476         }
2477         if (dentry_has_short_name(dentry)) {
2478                 ret = utf16le_to_tstr(dentry->short_name,
2479                                       dentry->short_name_nbytes,
2480                                       (tchar**)&wdentry->dos_name,
2481                                       &dummy);
2482                 if (ret)
2483                         return ret;
2484         }
2485 #endif
2486         ret = calculate_dentry_full_path(dentry);
2487         if (ret)
2488                 return ret;
2489         wdentry->full_path = dentry->_full_path;
2490
2491         for (struct wim_dentry *d = dentry; !dentry_is_root(d); d = d->parent)
2492                 wdentry->depth++;
2493
2494         if (inode->i_security_id >= 0) {
2495                 const struct wim_security_data *sd = wim_const_security_data(wim);
2496                 wdentry->security_descriptor = sd->descriptors[inode->i_security_id];
2497                 wdentry->security_descriptor_size = sd->sizes[inode->i_security_id];
2498         }
2499         wdentry->reparse_tag = inode->i_reparse_tag;
2500         wdentry->num_links = inode->i_nlink;
2501         wdentry->attributes = inode->i_attributes;
2502         wdentry->hard_link_group_id = inode->i_ino;
2503         wdentry->creation_time = wim_timestamp_to_timespec(inode->i_creation_time);
2504         wdentry->last_write_time = wim_timestamp_to_timespec(inode->i_last_write_time);
2505         wdentry->last_access_time = wim_timestamp_to_timespec(inode->i_last_access_time);
2506
2507         lte = inode_unnamed_lte(inode, wim->lookup_table);
2508         if (lte) {
2509                 lte_to_wimlib_resource_entry(lte, &wdentry->streams[0].resource);
2510         } else if (!is_zero_hash(hash = inode_unnamed_stream_hash(inode))) {
2511                 if (flags & WIMLIB_ITERATE_DIR_TREE_FLAG_RESOURCES_NEEDED)
2512                         return resource_not_found_error(inode, hash);
2513                 copy_hash(wdentry->streams[0].resource.sha1_hash, hash);
2514                 wdentry->streams[0].resource.is_missing = 1;
2515         }
2516
2517         for (unsigned i = 0; i < inode->i_num_ads; i++) {
2518                 if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
2519                         continue;
2520                 lte = inode_stream_lte(inode, i + 1, wim->lookup_table);
2521                 wdentry->num_named_streams++;
2522                 if (lte) {
2523                         lte_to_wimlib_resource_entry(lte, &wdentry->streams[
2524                                                                 wdentry->num_named_streams].resource);
2525                 } else if (!is_zero_hash(hash = inode_stream_hash(inode, i + 1))) {
2526                         if (flags & WIMLIB_ITERATE_DIR_TREE_FLAG_RESOURCES_NEEDED)
2527                                 return resource_not_found_error(inode, hash);
2528                         copy_hash(wdentry->streams[
2529                                   wdentry->num_named_streams].resource.sha1_hash, hash);
2530                         wdentry->streams[
2531                                 wdentry->num_named_streams].resource.is_missing = 1;
2532                 }
2533         #if TCHAR_IS_UTF16LE
2534                 wdentry->streams[wdentry->num_named_streams].stream_name =
2535                                 inode->i_ads_entries[i].stream_name;
2536         #else
2537                 size_t dummy;
2538
2539                 ret = utf16le_to_tstr(inode->i_ads_entries[i].stream_name,
2540                                       inode->i_ads_entries[i].stream_name_nbytes,
2541                                       (tchar**)&wdentry->streams[
2542                                                 wdentry->num_named_streams].stream_name,
2543                                       &dummy);
2544                 if (ret)
2545                         return ret;
2546         #endif
2547         }
2548         return 0;
2549 }
2550
2551 static void
2552 free_wimlib_dentry(struct wimlib_dir_entry *wdentry)
2553 {
2554 #if !TCHAR_IS_UTF16LE
2555         FREE((tchar*)wdentry->filename);
2556         FREE((tchar*)wdentry->dos_name);
2557         for (unsigned i = 1; i <= wdentry->num_named_streams; i++)
2558                 FREE((tchar*)wdentry->streams[i].stream_name);
2559 #endif
2560         FREE(wdentry);
2561 }
2562
2563 struct iterate_dir_tree_ctx {
2564         WIMStruct *wim;
2565         int flags;
2566         wimlib_iterate_dir_tree_callback_t cb;
2567         void *user_ctx;
2568 };
2569
2570 static int
2571 do_iterate_dir_tree(WIMStruct *wim,
2572                     struct wim_dentry *dentry, int flags,
2573                     wimlib_iterate_dir_tree_callback_t cb,
2574                     void *user_ctx);
2575
2576 static int
2577 call_do_iterate_dir_tree(struct wim_dentry *dentry, void *_ctx)
2578 {
2579         struct iterate_dir_tree_ctx *ctx = _ctx;
2580         return do_iterate_dir_tree(ctx->wim, dentry, ctx->flags,
2581                                    ctx->cb, ctx->user_ctx);
2582 }
2583
2584 static int
2585 do_iterate_dir_tree(WIMStruct *wim,
2586                     struct wim_dentry *dentry, int flags,
2587                     wimlib_iterate_dir_tree_callback_t cb,
2588                     void *user_ctx)
2589 {
2590         struct wimlib_dir_entry *wdentry;
2591         int ret = WIMLIB_ERR_NOMEM;
2592
2593
2594         wdentry = CALLOC(1, sizeof(struct wimlib_dir_entry) +
2595                                   (1 + dentry->d_inode->i_num_ads) *
2596                                         sizeof(struct wimlib_stream_entry));
2597         if (wdentry == NULL)
2598                 goto out;
2599
2600         ret = init_wimlib_dentry(wdentry, dentry, wim, flags);
2601         if (ret)
2602                 goto out_free_wimlib_dentry;
2603
2604         if (!(flags & WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN)) {
2605                 ret = (*cb)(wdentry, user_ctx);
2606                 if (ret)
2607                         goto out_free_wimlib_dentry;
2608         }
2609
2610         if (flags & (WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE |
2611                      WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN))
2612         {
2613                 struct iterate_dir_tree_ctx ctx = {
2614                         .wim      = wim,
2615                         .flags    = flags &= ~WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN,
2616                         .cb       = cb,
2617                         .user_ctx = user_ctx,
2618                 };
2619                 ret = for_dentry_child(dentry, call_do_iterate_dir_tree, &ctx);
2620         }
2621 out_free_wimlib_dentry:
2622         free_wimlib_dentry(wdentry);
2623 out:
2624         return ret;
2625 }
2626
2627 struct image_iterate_dir_tree_ctx {
2628         const tchar *path;
2629         int flags;
2630         wimlib_iterate_dir_tree_callback_t cb;
2631         void *user_ctx;
2632 };
2633
2634
2635 static int
2636 image_do_iterate_dir_tree(WIMStruct *wim)
2637 {
2638         struct image_iterate_dir_tree_ctx *ctx = wim->private;
2639         struct wim_dentry *dentry;
2640
2641         dentry = get_dentry(wim, ctx->path, WIMLIB_CASE_PLATFORM_DEFAULT);
2642         if (dentry == NULL)
2643                 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
2644         return do_iterate_dir_tree(wim, dentry, ctx->flags, ctx->cb, ctx->user_ctx);
2645 }
2646
2647 /* API function documented in wimlib.h  */
2648 WIMLIBAPI int
2649 wimlib_iterate_dir_tree(WIMStruct *wim, int image, const tchar *path,
2650                         int flags,
2651                         wimlib_iterate_dir_tree_callback_t cb, void *user_ctx)
2652 {
2653         struct image_iterate_dir_tree_ctx ctx = {
2654                 .path = path,
2655                 .flags = flags,
2656                 .cb = cb,
2657                 .user_ctx = user_ctx,
2658         };
2659         wim->private = &ctx;
2660         return for_image(wim, image, image_do_iterate_dir_tree);
2661 }
2662
2663 /* Returns %true iff the metadata of @inode and @template_inode are reasonably
2664  * consistent with them being the same, unmodified file.  */
2665 static bool
2666 inode_metadata_consistent(const struct wim_inode *inode,
2667                           const struct wim_inode *template_inode,
2668                           const struct wim_lookup_table *template_lookup_table)
2669 {
2670         /* Must have exact same creation time and last write time.  */
2671         if (inode->i_creation_time != template_inode->i_creation_time ||
2672             inode->i_last_write_time != template_inode->i_last_write_time)
2673                 return false;
2674
2675         /* Last access time may have stayed the same or increased, but certainly
2676          * shouldn't have decreased.  */
2677         if (inode->i_last_access_time < template_inode->i_last_access_time)
2678                 return false;
2679
2680         /* Must have same number of alternate data stream entries.  */
2681         if (inode->i_num_ads != template_inode->i_num_ads)
2682                 return false;
2683
2684         /* If the stream entries for the inode are for some reason not resolved,
2685          * then the hashes are already available and the point of this function
2686          * is defeated.  */
2687         if (!inode->i_resolved)
2688                 return false;
2689
2690         /* Iterate through each stream and do some more checks.  */
2691         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2692                 const struct wim_lookup_table_entry *lte, *template_lte;
2693
2694                 lte = inode_stream_lte_resolved(inode, i);
2695                 template_lte = inode_stream_lte(template_inode, i,
2696                                                 template_lookup_table);
2697
2698                 /* Compare stream sizes.  */
2699                 if (lte && template_lte) {
2700                         if (lte->size != template_lte->size)
2701                                 return false;
2702
2703                         /* If hash happens to be available, compare with template.  */
2704                         if (!lte->unhashed && !template_lte->unhashed &&
2705                             !hashes_equal(lte->hash, template_lte->hash))
2706                                 return false;
2707
2708                 } else if (lte && lte->size) {
2709                         return false;
2710                 } else if (template_lte && template_lte->size) {
2711                         return false;
2712                 }
2713         }
2714
2715         /* All right, barring a full checksum and given that the inodes share a
2716          * path and the user isn't trying to trick us, these inodes most likely
2717          * refer to the same file.  */
2718         return true;
2719 }
2720
2721 /**
2722  * Given an inode @inode that has been determined to be "the same" as another
2723  * inode @template_inode in either the same WIM or another WIM, retrieve some
2724  * useful stream information (e.g. checksums) from @template_inode.
2725  *
2726  * This assumes that the streams for @inode have been resolved (to point
2727  * directly to the appropriate `struct wim_lookup_table_entry's)  but do not
2728  * necessarily have checksum information filled in.
2729  */
2730 static int
2731 inode_copy_checksums(struct wim_inode *inode,
2732                      struct wim_inode *template_inode,
2733                      WIMStruct *wim,
2734                      WIMStruct *template_wim)
2735 {
2736         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2737                 struct wim_lookup_table_entry *lte, *template_lte;
2738                 struct wim_lookup_table_entry *replace_lte;
2739
2740                 lte = inode_stream_lte_resolved(inode, i);
2741                 template_lte = inode_stream_lte(template_inode, i,
2742                                                 template_wim->lookup_table);
2743
2744                 /* Only take action if both entries exist, the entry for @inode
2745                  * has no checksum calculated, but the entry for @template_inode
2746                  * does.  */
2747                 if (lte == NULL || template_lte == NULL ||
2748                     !lte->unhashed || template_lte->unhashed)
2749                         continue;
2750
2751                 wimlib_assert(lte->refcnt == inode->i_nlink);
2752
2753                 /* If the WIM of the template image is the same as the WIM of
2754                  * the new image, then @template_lte can be used directly.
2755                  *
2756                  * Otherwise, look for a stream with the same hash in the WIM of
2757                  * the new image.  If found, use it; otherwise re-use the entry
2758                  * being discarded, filling in the hash.  */
2759
2760                 if (wim == template_wim)
2761                         replace_lte = template_lte;
2762                 else
2763                         replace_lte = lookup_resource(wim->lookup_table,
2764                                                       template_lte->hash);
2765
2766                 list_del(&lte->unhashed_list);
2767                 if (replace_lte) {
2768                         free_lookup_table_entry(lte);
2769                 } else {
2770                         copy_hash(lte->hash, template_lte->hash);
2771                         lte->unhashed = 0;
2772                         lookup_table_insert(wim->lookup_table, lte);
2773                         lte->refcnt = 0;
2774                         replace_lte = lte;
2775                 }
2776
2777                 if (i == 0)
2778                         inode->i_lte = replace_lte;
2779                 else
2780                         inode->i_ads_entries[i - 1].lte = replace_lte;
2781
2782                 replace_lte->refcnt += inode->i_nlink;
2783         }
2784         return 0;
2785 }
2786
2787 struct reference_template_args {
2788         WIMStruct *wim;
2789         WIMStruct *template_wim;
2790 };
2791
2792 static int
2793 dentry_reference_template(struct wim_dentry *dentry, void *_args)
2794 {
2795         int ret;
2796         struct wim_dentry *template_dentry;
2797         struct wim_inode *inode, *template_inode;
2798         struct reference_template_args *args = _args;
2799         WIMStruct *wim = args->wim;
2800         WIMStruct *template_wim = args->template_wim;
2801
2802         if (dentry->d_inode->i_visited)
2803                 return 0;
2804
2805         ret = calculate_dentry_full_path(dentry);
2806         if (ret)
2807                 return ret;
2808
2809         template_dentry = get_dentry(template_wim, dentry->_full_path,
2810                                      WIMLIB_CASE_SENSITIVE);
2811         if (template_dentry == NULL) {
2812                 DEBUG("\"%"TS"\": newly added file", dentry->_full_path);
2813                 return 0;
2814         }
2815
2816         inode = dentry->d_inode;
2817         template_inode = template_dentry->d_inode;
2818
2819         if (inode_metadata_consistent(inode, template_inode,
2820                                       template_wim->lookup_table)) {
2821                 /*DEBUG("\"%"TS"\": No change detected", dentry->_full_path);*/
2822                 ret = inode_copy_checksums(inode, template_inode,
2823                                            wim, template_wim);
2824                 inode->i_visited = 1;
2825         } else {
2826                 DEBUG("\"%"TS"\": change detected!", dentry->_full_path);
2827                 ret = 0;
2828         }
2829         return ret;
2830 }
2831
2832 /* API function documented in wimlib.h  */
2833 WIMLIBAPI int
2834 wimlib_reference_template_image(WIMStruct *wim, int new_image,
2835                                 WIMStruct *template_wim, int template_image,
2836                                 int flags, wimlib_progress_func_t progress_func)
2837 {
2838         int ret;
2839         struct wim_image_metadata *new_imd;
2840
2841         if (wim == NULL || template_wim == NULL)
2842                 return WIMLIB_ERR_INVALID_PARAM;
2843
2844         if (wim == template_wim && new_image == template_image)
2845                 return WIMLIB_ERR_INVALID_PARAM;
2846
2847         if (new_image < 1 || new_image > wim->hdr.image_count)
2848                 return WIMLIB_ERR_INVALID_IMAGE;
2849
2850         if (!wim_has_metadata(wim))
2851                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2852
2853         new_imd = wim->image_metadata[new_image - 1];
2854         if (!new_imd->modified)
2855                 return WIMLIB_ERR_INVALID_PARAM;
2856
2857         ret = select_wim_image(template_wim, template_image);
2858         if (ret)
2859                 return ret;
2860
2861         struct reference_template_args args = {
2862                 .wim = wim,
2863                 .template_wim = template_wim,
2864         };
2865
2866         ret = for_dentry_in_tree(new_imd->root_dentry,
2867                                  dentry_reference_template, &args);
2868         dentry_tree_clear_inode_visited(new_imd->root_dentry);
2869         return ret;
2870 }