Allow configurable case sensitivity
[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 bool default_ignore_case =
675 #ifdef __WIN32__
676         true
677 #else
678         false
679 #endif
680 ;
681
682 static bool
683 will_ignore_case(CASE_SENSITIVITY_TYPE case_type)
684 {
685         if (case_type == WIMLIB_CASE_SENSITIVE)
686                 return false;
687         if (case_type == WIMLIB_CASE_INSENSITIVE)
688                 return true;
689
690         return default_ignore_case;
691 }
692
693
694 /* Given a UTF-16LE filename and a directory, look up the dentry for the file.
695  * Return it if found, otherwise NULL.  This is case-sensitive on UNIX and
696  * case-insensitive on Windows. */
697 struct wim_dentry *
698 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
699                                    const utf16lechar *name,
700                                    size_t name_nbytes,
701                                    CASE_SENSITIVITY_TYPE case_ctype)
702 {
703         struct rb_node *node;
704
705         bool ignore_case = will_ignore_case(case_ctype);
706
707         if (ignore_case)
708                 node = dentry->d_inode->i_children_case_insensitive.rb_node;
709         else
710                 node = dentry->d_inode->i_children.rb_node;
711
712         struct wim_dentry *child;
713         while (node) {
714                 if (ignore_case)
715                         child = rb_entry(node, struct wim_dentry, rb_node_case_insensitive);
716                 else
717                         child = rb_entry(node, struct wim_dentry, rb_node);
718
719                 int result = cmp_utf16le_strings(name,
720                                                  name_nbytes / 2,
721                                                  child->file_name,
722                                                  child->file_name_nbytes / 2,
723                                                  ignore_case);
724                 if (result < 0) {
725                         node = node->rb_left;
726                 } else if (result > 0) {
727                         node = node->rb_right;
728                 } else if (!ignore_case ||
729                         list_empty(&child->case_insensitive_conflict_list)) {
730                         return child;
731                 } else {
732                         /* Multiple dentries have the same case-insensitive
733                          * name, and a case-insensitive lookup is being
734                          * performed.  Choose the dentry with the same
735                          * case-sensitive name, if one exists; otherwise print a
736                          * warning and choose one arbitrarily.  */
737                         struct wim_dentry *alt = child;
738                         size_t num_alts = 0;
739
740                         do {
741                                 num_alts++;
742                                 if (0 == cmp_utf16le_strings(name,
743                                                              name_nbytes / 2,
744                                                              alt->file_name,
745                                                              alt->file_name_nbytes / 2,
746                                                              false))
747                                         return alt;
748                                 alt = list_entry(alt->case_insensitive_conflict_list.next,
749                                                  struct wim_dentry,
750                                                  case_insensitive_conflict_list);
751                         } while (alt != child);
752
753                         WARNING("Result of case-insensitive lookup is ambiguous\n"
754                                 "          (returning \"%"TS"\" of %zu "
755                                 "possible files, including \"%"TS"\")",
756                                 dentry_full_path(child),
757                                 num_alts,
758                                 dentry_full_path(list_entry(child->case_insensitive_conflict_list.next,
759                                                             struct wim_dentry,
760                                                             case_insensitive_conflict_list)));
761                         return child;
762                 }
763         }
764         return NULL;
765 }
766
767 /* Returns the child of @dentry that has the file name @name.  Returns NULL if
768  * no child has the name. */
769 struct wim_dentry *
770 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name,
771                            CASE_SENSITIVITY_TYPE case_type)
772 {
773 #if TCHAR_IS_UTF16LE
774         return get_dentry_child_with_utf16le_name(dentry, name,
775                                                   tstrlen(name) * sizeof(tchar),
776                                                   case_type);
777 #else
778         utf16lechar *utf16le_name;
779         size_t utf16le_name_nbytes;
780         int ret;
781         struct wim_dentry *child;
782
783         ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
784                               &utf16le_name, &utf16le_name_nbytes);
785         if (ret) {
786                 child = NULL;
787         } else {
788                 child = get_dentry_child_with_utf16le_name(dentry,
789                                                            utf16le_name,
790                                                            utf16le_name_nbytes,
791                                                            case_type);
792                 FREE(utf16le_name);
793         }
794         return child;
795 #endif
796 }
797
798 static struct wim_dentry *
799 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path,
800                    CASE_SENSITIVITY_TYPE case_type)
801 {
802         struct wim_dentry *cur_dentry, *parent_dentry;
803         const utf16lechar *p, *pp;
804
805         cur_dentry = parent_dentry = wim_root_dentry(wim);
806         if (cur_dentry == NULL) {
807                 errno = ENOENT;
808                 return NULL;
809         }
810         p = path;
811         while (1) {
812                 while (*p == cpu_to_le16(WIM_PATH_SEPARATOR))
813                         p++;
814                 if (*p == cpu_to_le16('\0'))
815                         break;
816                 pp = p;
817                 while (*pp != cpu_to_le16(WIM_PATH_SEPARATOR) &&
818                        *pp != cpu_to_le16('\0'))
819                         pp++;
820
821                 cur_dentry = get_dentry_child_with_utf16le_name(parent_dentry, p,
822                                                                 (u8*)pp - (u8*)p,
823                                                                 case_type);
824                 if (cur_dentry == NULL)
825                         break;
826                 p = pp;
827                 parent_dentry = cur_dentry;
828         }
829         if (cur_dentry == NULL) {
830                 if (dentry_is_directory(parent_dentry))
831                         errno = ENOENT;
832                 else
833                         errno = ENOTDIR;
834         }
835         return cur_dentry;
836 }
837
838 /*
839  * Returns the dentry in the currently selected WIM image named by @path
840  * starting from the root of the WIM image, or NULL if there is no such dentry.
841  */
842 struct wim_dentry *
843 get_dentry(WIMStruct *wim, const tchar *path, CASE_SENSITIVITY_TYPE case_type)
844 {
845 #if TCHAR_IS_UTF16LE
846         return get_dentry_utf16le(wim, path, case_type);
847 #else
848         utf16lechar *path_utf16le;
849         size_t path_utf16le_nbytes;
850         int ret;
851         struct wim_dentry *dentry;
852
853         ret = tstr_to_utf16le(path, tstrlen(path) * sizeof(tchar),
854                               &path_utf16le, &path_utf16le_nbytes);
855         if (ret)
856                 return NULL;
857         dentry = get_dentry_utf16le(wim, path_utf16le, case_type);
858         FREE(path_utf16le);
859         return dentry;
860 #endif
861 }
862
863 /* Takes in a path of length @len in @buf, and transforms it into a string for
864  * the path of its parent directory. */
865 static void
866 to_parent_name(tchar *buf, size_t len)
867 {
868         ssize_t i = (ssize_t)len - 1;
869         while (i >= 0 && buf[i] == WIM_PATH_SEPARATOR)
870                 i--;
871         while (i >= 0 && buf[i] != WIM_PATH_SEPARATOR)
872                 i--;
873         while (i >= 0 && buf[i] == WIM_PATH_SEPARATOR)
874                 i--;
875         buf[i + 1] = T('\0');
876 }
877
878 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
879  * if the dentry is not found. */
880 struct wim_dentry *
881 get_parent_dentry(WIMStruct *wim, const tchar *path,
882                   CASE_SENSITIVITY_TYPE case_type)
883 {
884         size_t path_len = tstrlen(path);
885         tchar buf[path_len + 1];
886
887         tmemcpy(buf, path, path_len + 1);
888         to_parent_name(buf, path_len);
889         return get_dentry(wim, buf, case_type);
890 }
891
892 /* Prints the full path of a dentry. */
893 int
894 print_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
895 {
896         int ret = calculate_dentry_full_path(dentry);
897         if (ret)
898                 return ret;
899         tprintf(T("%"TS"\n"), dentry->_full_path);
900         return 0;
901 }
902
903 /* We want to be able to show the names of the file attribute flags that are
904  * set. */
905 struct file_attr_flag {
906         u32 flag;
907         const tchar *name;
908 };
909 struct file_attr_flag file_attr_flags[] = {
910         {FILE_ATTRIBUTE_READONLY,           T("READONLY")},
911         {FILE_ATTRIBUTE_HIDDEN,             T("HIDDEN")},
912         {FILE_ATTRIBUTE_SYSTEM,             T("SYSTEM")},
913         {FILE_ATTRIBUTE_DIRECTORY,          T("DIRECTORY")},
914         {FILE_ATTRIBUTE_ARCHIVE,            T("ARCHIVE")},
915         {FILE_ATTRIBUTE_DEVICE,             T("DEVICE")},
916         {FILE_ATTRIBUTE_NORMAL,             T("NORMAL")},
917         {FILE_ATTRIBUTE_TEMPORARY,          T("TEMPORARY")},
918         {FILE_ATTRIBUTE_SPARSE_FILE,        T("SPARSE_FILE")},
919         {FILE_ATTRIBUTE_REPARSE_POINT,      T("REPARSE_POINT")},
920         {FILE_ATTRIBUTE_COMPRESSED,         T("COMPRESSED")},
921         {FILE_ATTRIBUTE_OFFLINE,            T("OFFLINE")},
922         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,T("NOT_CONTENT_INDEXED")},
923         {FILE_ATTRIBUTE_ENCRYPTED,          T("ENCRYPTED")},
924         {FILE_ATTRIBUTE_VIRTUAL,            T("VIRTUAL")},
925 };
926
927 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
928  * available.  If the dentry is unresolved and the lookup table is NULL, the
929  * lookup table entries will not be printed.  Otherwise, they will be. */
930 int
931 print_dentry(struct wim_dentry *dentry, void *lookup_table)
932 {
933         const u8 *hash;
934         struct wim_lookup_table_entry *lte;
935         const struct wim_inode *inode = dentry->d_inode;
936         tchar buf[50];
937
938         tprintf(T("[DENTRY]\n"));
939         tprintf(T("Length            = %"PRIu64"\n"), dentry->length);
940         tprintf(T("Attributes        = 0x%x\n"), inode->i_attributes);
941         for (size_t i = 0; i < ARRAY_LEN(file_attr_flags); i++)
942                 if (file_attr_flags[i].flag & inode->i_attributes)
943                         tprintf(T("    FILE_ATTRIBUTE_%"TS" is set\n"),
944                                 file_attr_flags[i].name);
945         tprintf(T("Security ID       = %d\n"), inode->i_security_id);
946         tprintf(T("Subdir offset     = %"PRIu64"\n"), dentry->subdir_offset);
947
948         wim_timestamp_to_str(inode->i_creation_time, buf, sizeof(buf));
949         tprintf(T("Creation Time     = %"TS"\n"), buf);
950
951         wim_timestamp_to_str(inode->i_last_access_time, buf, sizeof(buf));
952         tprintf(T("Last Access Time  = %"TS"\n"), buf);
953
954         wim_timestamp_to_str(inode->i_last_write_time, buf, sizeof(buf));
955         tprintf(T("Last Write Time   = %"TS"\n"), buf);
956
957         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
958                 tprintf(T("Reparse Tag       = 0x%"PRIx32"\n"), inode->i_reparse_tag);
959                 tprintf(T("Reparse Point Flags = 0x%"PRIx16"\n"),
960                         inode->i_not_rpfixed);
961                 tprintf(T("Reparse Point Unknown 2 = 0x%"PRIx32"\n"),
962                         inode->i_rp_unknown_2);
963         }
964         tprintf(T("Reparse Point Unknown 1 = 0x%"PRIx32"\n"),
965                 inode->i_rp_unknown_1);
966         tprintf(T("Hard Link Group   = 0x%"PRIx64"\n"), inode->i_ino);
967         tprintf(T("Hard Link Group Size = %"PRIu32"\n"), inode->i_nlink);
968         tprintf(T("Number of Alternate Data Streams = %hu\n"), inode->i_num_ads);
969         if (dentry_has_long_name(dentry))
970                 wimlib_printf(T("Filename = \"%"WS"\"\n"), dentry->file_name);
971         if (dentry_has_short_name(dentry))
972                 wimlib_printf(T("Short Name \"%"WS"\"\n"), dentry->short_name);
973         if (dentry->_full_path)
974                 tprintf(T("Full Path = \"%"TS"\"\n"), dentry->_full_path);
975
976         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
977         if (lte) {
978                 print_lookup_table_entry(lte, stdout);
979         } else {
980                 hash = inode_stream_hash(inode, 0);
981                 if (hash) {
982                         tprintf(T("Hash              = 0x"));
983                         print_hash(hash, stdout);
984                         tputchar(T('\n'));
985                         tputchar(T('\n'));
986                 }
987         }
988         for (u16 i = 0; i < inode->i_num_ads; i++) {
989                 tprintf(T("[Alternate Stream Entry %u]\n"), i);
990                 wimlib_printf(T("Name = \"%"WS"\"\n"),
991                               inode->i_ads_entries[i].stream_name);
992                 tprintf(T("Name Length (UTF16 bytes) = %hu\n"),
993                        inode->i_ads_entries[i].stream_name_nbytes);
994                 hash = inode_stream_hash(inode, i + 1);
995                 if (hash) {
996                         tprintf(T("Hash              = 0x"));
997                         print_hash(hash, stdout);
998                         tputchar(T('\n'));
999                 }
1000                 print_lookup_table_entry(inode_stream_lte(inode, i + 1, lookup_table),
1001                                          stdout);
1002         }
1003         return 0;
1004 }
1005
1006 /* Initializations done on every `struct wim_dentry'. */
1007 static void
1008 dentry_common_init(struct wim_dentry *dentry)
1009 {
1010         memset(dentry, 0, sizeof(struct wim_dentry));
1011 }
1012
1013 struct wim_inode *
1014 new_timeless_inode(void)
1015 {
1016         struct wim_inode *inode = CALLOC(1, sizeof(struct wim_inode));
1017         if (inode) {
1018                 inode->i_security_id = -1;
1019                 inode->i_nlink = 1;
1020                 inode->i_next_stream_id = 1;
1021                 inode->i_not_rpfixed = 1;
1022                 inode->i_canonical_streams = 1;
1023                 INIT_LIST_HEAD(&inode->i_list);
1024                 INIT_LIST_HEAD(&inode->i_dentry);
1025         }
1026         return inode;
1027 }
1028
1029 static struct wim_inode *
1030 new_inode(void)
1031 {
1032         struct wim_inode *inode = new_timeless_inode();
1033         if (inode) {
1034                 u64 now = get_wim_timestamp();
1035                 inode->i_creation_time = now;
1036                 inode->i_last_access_time = now;
1037                 inode->i_last_write_time = now;
1038         }
1039         return inode;
1040 }
1041
1042 /* Creates an unlinked directory entry. */
1043 int
1044 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
1045 {
1046         struct wim_dentry *dentry;
1047         int ret;
1048
1049         dentry = MALLOC(sizeof(struct wim_dentry));
1050         if (dentry == NULL)
1051                 return WIMLIB_ERR_NOMEM;
1052
1053         dentry_common_init(dentry);
1054         ret = set_dentry_name(dentry, name);
1055         if (ret == 0) {
1056                 dentry->parent = dentry;
1057                 *dentry_ret = dentry;
1058         } else {
1059                 FREE(dentry);
1060                 ERROR("Failed to set name on new dentry with name \"%"TS"\"",
1061                       name);
1062         }
1063         return ret;
1064 }
1065
1066
1067 static int
1068 _new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret,
1069                         bool timeless)
1070 {
1071         struct wim_dentry *dentry;
1072         int ret;
1073
1074         ret = new_dentry(name, &dentry);
1075         if (ret)
1076                 return ret;
1077
1078         if (timeless)
1079                 dentry->d_inode = new_timeless_inode();
1080         else
1081                 dentry->d_inode = new_inode();
1082         if (dentry->d_inode == NULL) {
1083                 free_dentry(dentry);
1084                 return WIMLIB_ERR_NOMEM;
1085         }
1086
1087         inode_add_dentry(dentry, dentry->d_inode);
1088         *dentry_ret = dentry;
1089         return 0;
1090 }
1091
1092 int
1093 new_dentry_with_timeless_inode(const tchar *name, struct wim_dentry **dentry_ret)
1094 {
1095         return _new_dentry_with_inode(name, dentry_ret, true);
1096 }
1097
1098 int
1099 new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret)
1100 {
1101         return _new_dentry_with_inode(name, dentry_ret, false);
1102 }
1103
1104 int
1105 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
1106 {
1107         int ret;
1108         struct wim_dentry *dentry;
1109
1110         DEBUG("Creating filler directory \"%"TS"\"", name);
1111         ret = new_dentry_with_inode(name, &dentry);
1112         if (ret)
1113                 return ret;
1114         /* Leave the inode number as 0; this is allowed for non
1115          * hard-linked files. */
1116         dentry->d_inode->i_resolved = 1;
1117         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
1118         *dentry_ret = dentry;
1119         return 0;
1120 }
1121
1122 static int
1123 dentry_clear_inode_visited(struct wim_dentry *dentry, void *_ignore)
1124 {
1125         dentry->d_inode->i_visited = 0;
1126         return 0;
1127 }
1128
1129 void
1130 dentry_tree_clear_inode_visited(struct wim_dentry *root)
1131 {
1132         for_dentry_in_tree(root, dentry_clear_inode_visited, NULL);
1133 }
1134
1135 static int
1136 init_ads_entry(struct wim_ads_entry *ads_entry, const void *name,
1137                size_t name_nbytes, bool is_utf16le)
1138 {
1139         int ret = 0;
1140         memset(ads_entry, 0, sizeof(*ads_entry));
1141
1142         if (is_utf16le) {
1143                 utf16lechar *p = MALLOC(name_nbytes + sizeof(utf16lechar));
1144                 if (p == NULL)
1145                         return WIMLIB_ERR_NOMEM;
1146                 memcpy(p, name, name_nbytes);
1147                 p[name_nbytes / 2] = cpu_to_le16(0);
1148                 ads_entry->stream_name = p;
1149                 ads_entry->stream_name_nbytes = name_nbytes;
1150         } else {
1151                 if (name && *(const tchar*)name != T('\0')) {
1152                         ret = get_utf16le_name(name, &ads_entry->stream_name,
1153                                                &ads_entry->stream_name_nbytes);
1154                 }
1155         }
1156         return ret;
1157 }
1158
1159 static void
1160 destroy_ads_entry(struct wim_ads_entry *ads_entry)
1161 {
1162         FREE(ads_entry->stream_name);
1163 }
1164
1165 /* Frees an inode. */
1166 void
1167 free_inode(struct wim_inode *inode)
1168 {
1169         if (inode) {
1170                 if (inode->i_ads_entries) {
1171                         for (u16 i = 0; i < inode->i_num_ads; i++)
1172                                 destroy_ads_entry(&inode->i_ads_entries[i]);
1173                         FREE(inode->i_ads_entries);
1174                 }
1175                 /* HACK: This may instead delete the inode from i_list, but the
1176                  * hlist_del() behaves the same as list_del(). */
1177                 if (!hlist_unhashed(&inode->i_hlist))
1178                         hlist_del(&inode->i_hlist);
1179                 FREE(inode);
1180         }
1181 }
1182
1183 /* Decrements link count on an inode and frees it if the link count reaches 0.
1184  * */
1185 static void
1186 put_inode(struct wim_inode *inode)
1187 {
1188         wimlib_assert(inode->i_nlink != 0);
1189         if (--inode->i_nlink == 0) {
1190         #ifdef WITH_FUSE
1191                 if (inode->i_num_opened_fds == 0)
1192         #endif
1193                 {
1194                         free_inode(inode);
1195                 }
1196         }
1197 }
1198
1199 /* Frees a WIM dentry.
1200  *
1201  * The corresponding inode (if any) is freed only if its link count is
1202  * decremented to 0.
1203  */
1204 void
1205 free_dentry(struct wim_dentry *dentry)
1206 {
1207         if (dentry) {
1208                 FREE(dentry->file_name);
1209                 FREE(dentry->short_name);
1210                 FREE(dentry->_full_path);
1211                 if (dentry->d_inode)
1212                         put_inode(dentry->d_inode);
1213                 FREE(dentry);
1214         }
1215 }
1216
1217 /* This function is passed as an argument to for_dentry_in_tree_depth() in order
1218  * to free a directory tree. */
1219 static int
1220 do_free_dentry(struct wim_dentry *dentry, void *_lookup_table)
1221 {
1222         struct wim_lookup_table *lookup_table = _lookup_table;
1223
1224         if (lookup_table) {
1225                 struct wim_inode *inode = dentry->d_inode;
1226                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1227                         struct wim_lookup_table_entry *lte;
1228
1229                         lte = inode_stream_lte(inode, i, lookup_table);
1230                         if (lte)
1231                                 lte_decrement_refcnt(lte, lookup_table);
1232                 }
1233         }
1234         free_dentry(dentry);
1235         return 0;
1236 }
1237
1238 /*
1239  * Unlinks and frees a dentry tree.
1240  *
1241  * @root:
1242  *      The root of the tree.
1243  *
1244  * @lookup_table:
1245  *      The lookup table for dentries.  If non-NULL, the reference counts in the
1246  *      lookup table for the lookup table entries corresponding to the dentries
1247  *      will be decremented.
1248  */
1249 void
1250 free_dentry_tree(struct wim_dentry *root, struct wim_lookup_table *lookup_table)
1251 {
1252         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1253 }
1254
1255 /* Insert a dentry into the case insensitive index for a directory.
1256  *
1257  * This is a red-black tree, but when multiple dentries share the same
1258  * case-insensitive name, only one is inserted into the tree itself; the rest
1259  * are connected in a list.
1260  */
1261 static struct wim_dentry *
1262 dentry_add_child_case_insensitive(struct wim_dentry *parent,
1263                                   struct wim_dentry *child)
1264 {
1265         struct rb_root *root;
1266         struct rb_node **new;
1267         struct rb_node *rb_parent;
1268
1269         root = &parent->d_inode->i_children_case_insensitive;
1270         new = &root->rb_node;
1271         rb_parent = NULL;
1272         while (*new) {
1273                 struct wim_dentry *this = container_of(*new, struct wim_dentry,
1274                                                        rb_node_case_insensitive);
1275                 int result = dentry_compare_names_case_insensitive(child, this);
1276
1277                 rb_parent = *new;
1278
1279                 if (result < 0)
1280                         new = &((*new)->rb_left);
1281                 else if (result > 0)
1282                         new = &((*new)->rb_right);
1283                 else
1284                         return this;
1285         }
1286         rb_link_node(&child->rb_node_case_insensitive, rb_parent, new);
1287         rb_insert_color(&child->rb_node_case_insensitive, root);
1288         return NULL;
1289 }
1290
1291 /*
1292  * Links a dentry into the directory tree.
1293  *
1294  * @parent: The dentry that will be the parent of @child.
1295  * @child: The dentry to link.
1296  *
1297  * Returns NULL if successful.  If @parent already contains a dentry with the
1298  * same case-sensitive name as @child, the pointer to this duplicate dentry is
1299  * returned.
1300  */
1301 struct wim_dentry *
1302 dentry_add_child(struct wim_dentry * restrict parent,
1303                  struct wim_dentry * restrict child)
1304 {
1305         struct rb_root *root;
1306         struct rb_node **new;
1307         struct rb_node *rb_parent;
1308
1309         wimlib_assert(dentry_is_directory(parent));
1310         wimlib_assert(parent != child);
1311
1312         /* Case sensitive child dentry index */
1313         root = &parent->d_inode->i_children;
1314         new = &root->rb_node;
1315         rb_parent = NULL;
1316         while (*new) {
1317                 struct wim_dentry *this = rbnode_dentry(*new);
1318                 int result = dentry_compare_names_case_sensitive(child, this);
1319
1320                 rb_parent = *new;
1321
1322                 if (result < 0)
1323                         new = &((*new)->rb_left);
1324                 else if (result > 0)
1325                         new = &((*new)->rb_right);
1326                 else
1327                         return this;
1328         }
1329         child->parent = parent;
1330         rb_link_node(&child->rb_node, rb_parent, new);
1331         rb_insert_color(&child->rb_node, root);
1332
1333         /* Case insensitive child dentry index */
1334         {
1335                 struct wim_dentry *existing;
1336                 existing = dentry_add_child_case_insensitive(parent, child);
1337                 if (existing) {
1338                         list_add(&child->case_insensitive_conflict_list,
1339                                  &existing->case_insensitive_conflict_list);
1340                         child->rb_node_case_insensitive.__rb_parent_color = 0;
1341                 } else {
1342                         INIT_LIST_HEAD(&child->case_insensitive_conflict_list);
1343                 }
1344         }
1345         return NULL;
1346 }
1347
1348 /* Unlink a WIM dentry from the directory entry tree. */
1349 void
1350 unlink_dentry(struct wim_dentry *dentry)
1351 {
1352         struct wim_dentry *parent = dentry->parent;
1353
1354         if (parent == dentry)
1355                 return;
1356         rb_erase(&dentry->rb_node, &parent->d_inode->i_children);
1357
1358         if (dentry->rb_node_case_insensitive.__rb_parent_color) {
1359                 /* This dentry was in the case-insensitive red-black tree. */
1360                 rb_erase(&dentry->rb_node_case_insensitive,
1361                          &parent->d_inode->i_children_case_insensitive);
1362                 if (!list_empty(&dentry->case_insensitive_conflict_list)) {
1363                         /* Make a different case-insensitively-the-same dentry
1364                          * be the "representative" in the red-black tree. */
1365                         struct list_head *next;
1366                         struct wim_dentry *other;
1367                         struct wim_dentry *existing;
1368
1369                         next = dentry->case_insensitive_conflict_list.next;
1370                         other = list_entry(next, struct wim_dentry, case_insensitive_conflict_list);
1371                         existing = dentry_add_child_case_insensitive(parent, other);
1372                         wimlib_assert(existing == NULL);
1373                 }
1374         }
1375         list_del(&dentry->case_insensitive_conflict_list);
1376 }
1377
1378 static int
1379 free_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
1380 {
1381         FREE(dentry->_full_path);
1382         dentry->_full_path = NULL;
1383         return 0;
1384 }
1385
1386 /* Rename a file or directory in the WIM.  */
1387 int
1388 rename_wim_path(WIMStruct *wim, const tchar *from, const tchar *to,
1389                 CASE_SENSITIVITY_TYPE case_type)
1390 {
1391         struct wim_dentry *src;
1392         struct wim_dentry *dst;
1393         struct wim_dentry *parent_of_dst;
1394         int ret;
1395
1396         /* This rename() implementation currently only supports actual files
1397          * (not alternate data streams) */
1398
1399         src = get_dentry(wim, from, case_type);
1400         if (!src)
1401                 return -errno;
1402
1403         dst = get_dentry(wim, to, case_type);
1404
1405         if (dst) {
1406                 /* Destination file exists */
1407
1408                 if (src == dst) /* Same file */
1409                         return 0;
1410
1411                 if (!dentry_is_directory(src)) {
1412                         /* Cannot rename non-directory to directory. */
1413                         if (dentry_is_directory(dst))
1414                                 return -EISDIR;
1415                 } else {
1416                         /* Cannot rename directory to a non-directory or a non-empty
1417                          * directory */
1418                         if (!dentry_is_directory(dst))
1419                                 return -ENOTDIR;
1420                         if (dentry_has_children(dst))
1421                                 return -ENOTEMPTY;
1422                 }
1423                 parent_of_dst = dst->parent;
1424         } else {
1425                 /* Destination does not exist */
1426                 parent_of_dst = get_parent_dentry(wim, to, case_type);
1427                 if (!parent_of_dst)
1428                         return -errno;
1429
1430                 if (!dentry_is_directory(parent_of_dst))
1431                         return -ENOTDIR;
1432         }
1433
1434         ret = set_dentry_name(src, path_basename(to));
1435         if (ret)
1436                 return -ENOMEM;
1437         if (dst) {
1438                 unlink_dentry(dst);
1439                 free_dentry_tree(dst, wim->lookup_table);
1440         }
1441         unlink_dentry(src);
1442         dentry_add_child(parent_of_dst, src);
1443         if (src->_full_path)
1444                 for_dentry_in_tree(src, free_dentry_full_path, NULL);
1445         return 0;
1446 }
1447
1448 /*
1449  * Returns the alternate data stream entry belonging to @inode that has the
1450  * stream name @stream_name, or NULL if the inode has no alternate data stream
1451  * with that name.
1452  *
1453  * If @p stream_name is the empty string, NULL is returned --- that is, this
1454  * function will not return "unnamed" alternate data stream entries.
1455  */
1456 struct wim_ads_entry *
1457 inode_get_ads_entry(struct wim_inode *inode, const tchar *stream_name,
1458                     u16 *idx_ret)
1459 {
1460         if (inode->i_num_ads == 0) {
1461                 return NULL;
1462         } else {
1463                 size_t stream_name_utf16le_nbytes;
1464                 u16 i;
1465                 struct wim_ads_entry *result;
1466
1467                 if (stream_name[0] == T('\0'))
1468                         return NULL;
1469
1470         #if TCHAR_IS_UTF16LE
1471                 const utf16lechar *stream_name_utf16le;
1472
1473                 stream_name_utf16le = stream_name;
1474                 stream_name_utf16le_nbytes = tstrlen(stream_name) * sizeof(tchar);
1475         #else
1476                 utf16lechar *stream_name_utf16le;
1477
1478                 {
1479                         int ret = tstr_to_utf16le(stream_name,
1480                                                   tstrlen(stream_name) *
1481                                                       sizeof(tchar),
1482                                                   &stream_name_utf16le,
1483                                                   &stream_name_utf16le_nbytes);
1484                         if (ret)
1485                                 return NULL;
1486                 }
1487         #endif
1488                 i = 0;
1489                 result = NULL;
1490                 do {
1491                         if (ads_entry_has_name(&inode->i_ads_entries[i],
1492                                                stream_name_utf16le,
1493                                                stream_name_utf16le_nbytes,
1494                                                false))
1495                         {
1496                                 if (idx_ret)
1497                                         *idx_ret = i;
1498                                 result = &inode->i_ads_entries[i];
1499                                 break;
1500                         }
1501                 } while (++i != inode->i_num_ads);
1502         #if !TCHAR_IS_UTF16LE
1503                 FREE(stream_name_utf16le);
1504         #endif
1505                 return result;
1506         }
1507 }
1508
1509 static struct wim_ads_entry *
1510 do_inode_add_ads(struct wim_inode *inode, const void *stream_name,
1511                  size_t stream_name_nbytes, bool is_utf16le)
1512 {
1513         u16 num_ads;
1514         struct wim_ads_entry *ads_entries;
1515         struct wim_ads_entry *new_entry;
1516
1517         wimlib_assert(stream_name_nbytes != 0);
1518
1519         if (inode->i_num_ads >= 0xfffe) {
1520                 ERROR("Too many alternate data streams in one inode!");
1521                 return NULL;
1522         }
1523         num_ads = inode->i_num_ads + 1;
1524         ads_entries = REALLOC(inode->i_ads_entries,
1525                               num_ads * sizeof(inode->i_ads_entries[0]));
1526         if (ads_entries == NULL) {
1527                 ERROR("Failed to allocate memory for new alternate data stream");
1528                 return NULL;
1529         }
1530         inode->i_ads_entries = ads_entries;
1531
1532         new_entry = &inode->i_ads_entries[num_ads - 1];
1533         if (init_ads_entry(new_entry, stream_name, stream_name_nbytes, is_utf16le))
1534                 return NULL;
1535         new_entry->stream_id = inode->i_next_stream_id++;
1536         inode->i_num_ads = num_ads;
1537         return new_entry;
1538 }
1539
1540 struct wim_ads_entry *
1541 inode_add_ads_utf16le(struct wim_inode *inode,
1542                       const utf16lechar *stream_name,
1543                       size_t stream_name_nbytes)
1544 {
1545         DEBUG("Add alternate data stream \"%"WS"\"", stream_name);
1546         return do_inode_add_ads(inode, stream_name, stream_name_nbytes, true);
1547 }
1548
1549 /*
1550  * Add an alternate stream entry to a WIM inode.  On success, returns a pointer
1551  * to the new entry; on failure, returns NULL.
1552  *
1553  * @stream_name must be a nonempty string.
1554  */
1555 struct wim_ads_entry *
1556 inode_add_ads(struct wim_inode *inode, const tchar *stream_name)
1557 {
1558         DEBUG("Add alternate data stream \"%"TS"\"", stream_name);
1559         return do_inode_add_ads(inode, stream_name,
1560                                 tstrlen(stream_name) * sizeof(tchar),
1561                                 TCHAR_IS_UTF16LE);
1562 }
1563
1564 static struct wim_lookup_table_entry *
1565 add_stream_from_data_buffer(const void *buffer, size_t size,
1566                             struct wim_lookup_table *lookup_table)
1567 {
1568         u8 hash[SHA1_HASH_SIZE];
1569         struct wim_lookup_table_entry *lte, *existing_lte;
1570
1571         sha1_buffer(buffer, size, hash);
1572         existing_lte = lookup_resource(lookup_table, hash);
1573         if (existing_lte) {
1574                 wimlib_assert(existing_lte->size == size);
1575                 lte = existing_lte;
1576                 lte->refcnt++;
1577         } else {
1578                 void *buffer_copy;
1579                 lte = new_lookup_table_entry();
1580                 if (lte == NULL)
1581                         return NULL;
1582                 buffer_copy = memdup(buffer, size);
1583                 if (buffer_copy == NULL) {
1584                         free_lookup_table_entry(lte);
1585                         return NULL;
1586                 }
1587                 lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1588                 lte->attached_buffer    = buffer_copy;
1589                 lte->size               = size;
1590                 copy_hash(lte->hash, hash);
1591                 lookup_table_insert(lookup_table, lte);
1592         }
1593         return lte;
1594 }
1595
1596 int
1597 inode_add_ads_with_data(struct wim_inode *inode, const tchar *name,
1598                         const void *value, size_t size,
1599                         struct wim_lookup_table *lookup_table)
1600 {
1601         struct wim_ads_entry *new_ads_entry;
1602
1603         wimlib_assert(inode->i_resolved);
1604
1605         new_ads_entry = inode_add_ads(inode, name);
1606         if (new_ads_entry == NULL)
1607                 return WIMLIB_ERR_NOMEM;
1608
1609         new_ads_entry->lte = add_stream_from_data_buffer(value, size,
1610                                                          lookup_table);
1611         if (new_ads_entry->lte == NULL) {
1612                 inode_remove_ads(inode, new_ads_entry - inode->i_ads_entries,
1613                                  lookup_table);
1614                 return WIMLIB_ERR_NOMEM;
1615         }
1616         return 0;
1617 }
1618
1619 bool
1620 inode_has_named_stream(const struct wim_inode *inode)
1621 {
1622         for (u16 i = 0; i < inode->i_num_ads; i++)
1623                 if (ads_entry_is_named_stream(&inode->i_ads_entries[i]))
1624                         return true;
1625         return false;
1626 }
1627
1628 /* Set the unnamed stream of a WIM inode, given a data buffer containing the
1629  * stream contents. */
1630 int
1631 inode_set_unnamed_stream(struct wim_inode *inode, const void *data, size_t len,
1632                          struct wim_lookup_table *lookup_table)
1633 {
1634         inode->i_lte = add_stream_from_data_buffer(data, len, lookup_table);
1635         if (inode->i_lte == NULL)
1636                 return WIMLIB_ERR_NOMEM;
1637         inode->i_resolved = 1;
1638         return 0;
1639 }
1640
1641 /* Remove an alternate data stream from a WIM inode  */
1642 void
1643 inode_remove_ads(struct wim_inode *inode, u16 idx,
1644                  struct wim_lookup_table *lookup_table)
1645 {
1646         struct wim_ads_entry *ads_entry;
1647         struct wim_lookup_table_entry *lte;
1648
1649         wimlib_assert(idx < inode->i_num_ads);
1650         wimlib_assert(inode->i_resolved);
1651
1652         ads_entry = &inode->i_ads_entries[idx];
1653
1654         DEBUG("Remove alternate data stream \"%"WS"\"", ads_entry->stream_name);
1655
1656         lte = ads_entry->lte;
1657         if (lte)
1658                 lte_decrement_refcnt(lte, lookup_table);
1659
1660         destroy_ads_entry(ads_entry);
1661
1662         memmove(&inode->i_ads_entries[idx],
1663                 &inode->i_ads_entries[idx + 1],
1664                 (inode->i_num_ads - idx - 1) * sizeof(inode->i_ads_entries[0]));
1665         inode->i_num_ads--;
1666 }
1667
1668 bool
1669 inode_has_unix_data(const struct wim_inode *inode)
1670 {
1671         for (u16 i = 0; i < inode->i_num_ads; i++)
1672                 if (ads_entry_is_unix_data(&inode->i_ads_entries[i]))
1673                         return true;
1674         return false;
1675 }
1676
1677 #ifndef __WIN32__
1678 int
1679 inode_get_unix_data(const struct wim_inode *inode,
1680                     struct wimlib_unix_data *unix_data,
1681                     u16 *stream_idx_ret)
1682 {
1683         const struct wim_ads_entry *ads_entry;
1684         const struct wim_lookup_table_entry *lte;
1685         size_t size;
1686         int ret;
1687
1688         wimlib_assert(inode->i_resolved);
1689
1690         ads_entry = inode_get_ads_entry((struct wim_inode*)inode,
1691                                         WIMLIB_UNIX_DATA_TAG, NULL);
1692         if (ads_entry == NULL)
1693                 return NO_UNIX_DATA;
1694
1695         if (stream_idx_ret)
1696                 *stream_idx_ret = ads_entry - inode->i_ads_entries;
1697
1698         lte = ads_entry->lte;
1699         if (lte == NULL)
1700                 return NO_UNIX_DATA;
1701
1702         size = lte->size;
1703         if (size != sizeof(struct wimlib_unix_data))
1704                 return BAD_UNIX_DATA;
1705
1706         ret = read_full_stream_into_buf(lte, unix_data);
1707         if (ret)
1708                 return ret;
1709
1710         if (unix_data->version != 0)
1711                 return BAD_UNIX_DATA;
1712         return 0;
1713 }
1714
1715 int
1716 inode_set_unix_data(struct wim_inode *inode, uid_t uid, gid_t gid, mode_t mode,
1717                     struct wim_lookup_table *lookup_table, int which)
1718 {
1719         struct wimlib_unix_data unix_data;
1720         int ret;
1721         bool have_good_unix_data = false;
1722         bool have_unix_data = false;
1723         u16 stream_idx;
1724
1725         if (!(which & UNIX_DATA_CREATE)) {
1726                 ret = inode_get_unix_data(inode, &unix_data, &stream_idx);
1727                 if (ret == 0 || ret == BAD_UNIX_DATA || ret > 0)
1728                         have_unix_data = true;
1729                 if (ret == 0)
1730                         have_good_unix_data = true;
1731         }
1732         unix_data.version = 0;
1733         if (which & UNIX_DATA_UID || !have_good_unix_data)
1734                 unix_data.uid = uid;
1735         if (which & UNIX_DATA_GID || !have_good_unix_data)
1736                 unix_data.gid = gid;
1737         if (which & UNIX_DATA_MODE || !have_good_unix_data)
1738                 unix_data.mode = mode;
1739         ret = inode_add_ads_with_data(inode, WIMLIB_UNIX_DATA_TAG,
1740                                       &unix_data,
1741                                       sizeof(struct wimlib_unix_data),
1742                                       lookup_table);
1743         if (ret == 0 && have_unix_data)
1744                 inode_remove_ads(inode, stream_idx, lookup_table);
1745         return ret;
1746 }
1747 #endif /* !__WIN32__ */
1748
1749 /*
1750  * Reads the alternate data stream entries of a WIM dentry.
1751  *
1752  * @p:
1753  *      Pointer to buffer that starts with the first alternate stream entry.
1754  *
1755  * @inode:
1756  *      Inode to load the alternate data streams into.  @inode->i_num_ads must
1757  *      have been set to the number of alternate data streams that are expected.
1758  *
1759  * @remaining_size:
1760  *      Number of bytes of data remaining in the buffer pointed to by @p.
1761  *
1762  * On success, inode->i_ads_entries is set to an array of `struct
1763  * wim_ads_entry's of length inode->i_num_ads.  On failure, @inode is not
1764  * modified.
1765  *
1766  * Return values:
1767  *      WIMLIB_ERR_SUCCESS (0)
1768  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1769  *      WIMLIB_ERR_NOMEM
1770  */
1771 static int
1772 read_ads_entries(const u8 * restrict p, struct wim_inode * restrict inode,
1773                  size_t nbytes_remaining)
1774 {
1775         u16 num_ads;
1776         struct wim_ads_entry *ads_entries;
1777         int ret;
1778
1779         BUILD_BUG_ON(sizeof(struct wim_ads_entry_on_disk) != WIM_ADS_ENTRY_DISK_SIZE);
1780
1781         /* Allocate an array for our in-memory representation of the alternate
1782          * data stream entries. */
1783         num_ads = inode->i_num_ads;
1784         ads_entries = CALLOC(num_ads, sizeof(inode->i_ads_entries[0]));
1785         if (ads_entries == NULL)
1786                 goto out_of_memory;
1787
1788         /* Read the entries into our newly allocated buffer. */
1789         for (u16 i = 0; i < num_ads; i++) {
1790                 u64 length;
1791                 struct wim_ads_entry *cur_entry;
1792                 const struct wim_ads_entry_on_disk *disk_entry =
1793                         (const struct wim_ads_entry_on_disk*)p;
1794
1795                 cur_entry = &ads_entries[i];
1796                 ads_entries[i].stream_id = i + 1;
1797
1798                 /* Do we have at least the size of the fixed-length data we know
1799                  * need? */
1800                 if (nbytes_remaining < sizeof(struct wim_ads_entry_on_disk))
1801                         goto out_invalid;
1802
1803                 /* Read the length field */
1804                 length = le64_to_cpu(disk_entry->length);
1805
1806                 /* Make sure the length field is neither so small it doesn't
1807                  * include all the fixed-length data nor so large it overflows
1808                  * the metadata resource buffer. */
1809                 if (length < sizeof(struct wim_ads_entry_on_disk) ||
1810                     length > nbytes_remaining)
1811                         goto out_invalid;
1812
1813                 /* Read the rest of the fixed-length data. */
1814
1815                 cur_entry->reserved = le64_to_cpu(disk_entry->reserved);
1816                 copy_hash(cur_entry->hash, disk_entry->hash);
1817                 cur_entry->stream_name_nbytes = le16_to_cpu(disk_entry->stream_name_nbytes);
1818
1819                 /* If stream_name_nbytes != 0, this is a named stream.
1820                  * Otherwise this is an unnamed stream, or in some cases (bugs
1821                  * in Microsoft's software I guess) a meaningless entry
1822                  * distinguished from the real unnamed stream entry, if any, by
1823                  * the fact that the real unnamed stream entry has a nonzero
1824                  * hash field. */
1825                 if (cur_entry->stream_name_nbytes) {
1826                         /* The name is encoded in UTF16-LE, which uses 2-byte
1827                          * coding units, so the length of the name had better be
1828                          * an even number of bytes... */
1829                         if (cur_entry->stream_name_nbytes & 1)
1830                                 goto out_invalid;
1831
1832                         /* Add the length of the stream name to get the length
1833                          * we actually need to read.  Make sure this isn't more
1834                          * than the specified length of the entry. */
1835                         if (sizeof(struct wim_ads_entry_on_disk) +
1836                             cur_entry->stream_name_nbytes > length)
1837                                 goto out_invalid;
1838
1839                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_nbytes + 2);
1840                         if (cur_entry->stream_name == NULL)
1841                                 goto out_of_memory;
1842
1843                         memcpy(cur_entry->stream_name,
1844                                disk_entry->stream_name,
1845                                cur_entry->stream_name_nbytes);
1846                         cur_entry->stream_name[cur_entry->stream_name_nbytes / 2] = cpu_to_le16(0);
1847                 } else {
1848                         /* Mark inode as having weird stream entries.  */
1849                         inode->i_canonical_streams = 0;
1850                 }
1851
1852                 /* It's expected that the size of every ADS entry is a multiple
1853                  * of 8.  However, to be safe, I'm allowing the possibility of
1854                  * an ADS entry at the very end of the metadata resource ending
1855                  * un-aligned.  So although we still need to increment the input
1856                  * pointer by @length to reach the next ADS entry, it's possible
1857                  * that less than @length is actually remaining in the metadata
1858                  * resource. We should set the remaining bytes to 0 if this
1859                  * happens. */
1860                 length = (length + 7) & ~(u64)7;
1861                 p += length;
1862                 if (nbytes_remaining < length)
1863                         nbytes_remaining = 0;
1864                 else
1865                         nbytes_remaining -= length;
1866         }
1867         inode->i_ads_entries = ads_entries;
1868         inode->i_next_stream_id = inode->i_num_ads + 1;
1869         ret = 0;
1870         goto out;
1871 out_of_memory:
1872         ret = WIMLIB_ERR_NOMEM;
1873         goto out_free_ads_entries;
1874 out_invalid:
1875         ERROR("An alternate data stream entry is invalid");
1876         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1877 out_free_ads_entries:
1878         if (ads_entries) {
1879                 for (u16 i = 0; i < num_ads; i++)
1880                         destroy_ads_entry(&ads_entries[i]);
1881                 FREE(ads_entries);
1882         }
1883 out:
1884         return ret;
1885 }
1886
1887 /*
1888  * Reads a WIM directory entry, including all alternate data stream entries that
1889  * follow it, from the WIM image's metadata resource.
1890  *
1891  * @metadata_resource:
1892  *              Pointer to the metadata resource buffer.
1893  *
1894  * @metadata_resource_len:
1895  *              Length of the metadata resource buffer, in bytes.
1896  *
1897  * @offset:     Offset of the dentry within the metadata resource.
1898  *
1899  * @dentry:     A `struct wim_dentry' that will be filled in by this function.
1900  *
1901  * Return 0 on success or nonzero on failure.  On failure, @dentry will have
1902  * been modified, but it will not be left with pointers to any allocated
1903  * buffers.  On success, the dentry->length field must be examined.  If zero,
1904  * this was a special "end of directory" dentry and not a real dentry.  If
1905  * nonzero, this was a real dentry.
1906  *
1907  * Return values:
1908  *      WIMLIB_ERR_SUCCESS (0)
1909  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1910  *      WIMLIB_ERR_NOMEM
1911  */
1912 int
1913 read_dentry(const u8 * restrict metadata_resource, u64 metadata_resource_len,
1914             u64 offset, struct wim_dentry * restrict dentry)
1915 {
1916
1917         u64 calculated_size;
1918         utf16lechar *file_name;
1919         utf16lechar *short_name;
1920         u16 short_name_nbytes;
1921         u16 file_name_nbytes;
1922         int ret;
1923         struct wim_inode *inode;
1924         const u8 *p = &metadata_resource[offset];
1925         const struct wim_dentry_on_disk *disk_dentry =
1926                         (const struct wim_dentry_on_disk*)p;
1927
1928         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1929
1930         if ((uintptr_t)p & 7)
1931                 WARNING("WIM dentry is not 8-byte aligned");
1932
1933         dentry_common_init(dentry);
1934
1935         /* Before reading the whole dentry, we need to read just the length.
1936          * This is because a dentry of length 8 (that is, just the length field)
1937          * terminates the list of sibling directory entries. */
1938         if (offset + sizeof(u64) > metadata_resource_len ||
1939             offset + sizeof(u64) < offset)
1940         {
1941                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1942                       "end of the metadata resource (size %"PRIu64")",
1943                       offset, metadata_resource_len);
1944                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1945         }
1946         dentry->length = le64_to_cpu(disk_dentry->length);
1947
1948         /* A zero length field (really a length of 8, since that's how big the
1949          * directory entry is...) indicates that this is the end of directory
1950          * dentry.  We do not read it into memory as an actual dentry, so just
1951          * return successfully in this case. */
1952         if (dentry->length == 8)
1953                 dentry->length = 0;
1954         if (dentry->length == 0)
1955                 return 0;
1956
1957         /* Now that we have the actual length provided in the on-disk structure,
1958          * again make sure it doesn't overflow the metadata resource buffer. */
1959         if (offset + dentry->length > metadata_resource_len ||
1960             offset + dentry->length < offset)
1961         {
1962                 ERROR("Directory entry at offset %"PRIu64" and with size "
1963                       "%"PRIu64" ends past the end of the metadata resource "
1964                       "(size %"PRIu64")",
1965                       offset, dentry->length, metadata_resource_len);
1966                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1967         }
1968
1969         /* Make sure the dentry length is at least as large as the number of
1970          * fixed-length fields */
1971         if (dentry->length < sizeof(struct wim_dentry_on_disk)) {
1972                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1973                       dentry->length);
1974                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1975         }
1976
1977         /* Allocate a `struct wim_inode' for this `struct wim_dentry'. */
1978         inode = new_timeless_inode();
1979         if (inode == NULL)
1980                 return WIMLIB_ERR_NOMEM;
1981
1982         /* Read more fields; some into the dentry, and some into the inode. */
1983
1984         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1985         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1986         dentry->subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1987         dentry->d_unused_1 = le64_to_cpu(disk_dentry->unused_1);
1988         dentry->d_unused_2 = le64_to_cpu(disk_dentry->unused_2);
1989         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1990         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1991         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1992         copy_hash(inode->i_hash, disk_dentry->unnamed_stream_hash);
1993
1994         /* I don't know what's going on here.  It seems like M$ screwed up the
1995          * reparse points, then put the fields in the same place and didn't
1996          * document it.  So we have some fields we read for reparse points, and
1997          * some fields in the same place for non-reparse-point.s */
1998         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1999                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->reparse.rp_unknown_1);
2000                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
2001                 inode->i_rp_unknown_2 = le16_to_cpu(disk_dentry->reparse.rp_unknown_2);
2002                 inode->i_not_rpfixed = le16_to_cpu(disk_dentry->reparse.not_rpfixed);
2003                 /* Leave inode->i_ino at 0.  Note that this means the WIM file
2004                  * cannot archive hard-linked reparse points.  Such a thing
2005                  * doesn't really make sense anyway, although I believe it's
2006                  * theoretically possible to have them on NTFS. */
2007         } else {
2008                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->nonreparse.rp_unknown_1);
2009                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
2010         }
2011
2012         inode->i_num_ads = le16_to_cpu(disk_dentry->num_alternate_data_streams);
2013
2014         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
2015         file_name_nbytes = le16_to_cpu(disk_dentry->file_name_nbytes);
2016
2017         if ((short_name_nbytes & 1) | (file_name_nbytes & 1))
2018         {
2019                 ERROR("Dentry name is not valid UTF-16LE (odd number of bytes)!");
2020                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2021                 goto out_free_inode;
2022         }
2023
2024         /* We now know the length of the file name and short name.  Make sure
2025          * the length of the dentry is large enough to actually hold them.
2026          *
2027          * The calculated length here is unaligned to allow for the possibility
2028          * that the dentry->length names an unaligned length, although this
2029          * would be unexpected. */
2030         calculated_size = dentry_correct_length_unaligned(file_name_nbytes,
2031                                                           short_name_nbytes);
2032
2033         if (dentry->length < calculated_size) {
2034                 ERROR("Unexpected end of directory entry! (Expected "
2035                       "at least %"PRIu64" bytes, got %"PRIu64" bytes.)",
2036                       calculated_size, dentry->length);
2037                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2038                 goto out_free_inode;
2039         }
2040
2041         p += sizeof(struct wim_dentry_on_disk);
2042
2043         /* Read the filename if present.  Note: if the filename is empty, there
2044          * is no null terminator following it. */
2045         if (file_name_nbytes) {
2046                 file_name = MALLOC(file_name_nbytes + 2);
2047                 if (file_name == NULL) {
2048                         ERROR("Failed to allocate %d bytes for dentry file name",
2049                               file_name_nbytes + 2);
2050                         ret = WIMLIB_ERR_NOMEM;
2051                         goto out_free_inode;
2052                 }
2053                 memcpy(file_name, p, file_name_nbytes);
2054                 p += file_name_nbytes + 2;
2055                 file_name[file_name_nbytes / 2] = cpu_to_le16(0);
2056         } else {
2057                 file_name = NULL;
2058         }
2059
2060
2061         /* Read the short filename if present.  Note: if there is no short
2062          * filename, there is no null terminator following it. */
2063         if (short_name_nbytes) {
2064                 short_name = MALLOC(short_name_nbytes + 2);
2065                 if (short_name == NULL) {
2066                         ERROR("Failed to allocate %d bytes for dentry short name",
2067                               short_name_nbytes + 2);
2068                         ret = WIMLIB_ERR_NOMEM;
2069                         goto out_free_file_name;
2070                 }
2071                 memcpy(short_name, p, short_name_nbytes);
2072                 p += short_name_nbytes + 2;
2073                 short_name[short_name_nbytes / 2] = cpu_to_le16(0);
2074         } else {
2075                 short_name = NULL;
2076         }
2077
2078         /* Align the dentry length */
2079         dentry->length = (dentry->length + 7) & ~7;
2080
2081         /*
2082          * Read the alternate data streams, if present.  dentry->num_ads tells
2083          * us how many they are, and they will directly follow the dentry
2084          * on-disk.
2085          *
2086          * Note that each alternate data stream entry begins on an 8-byte
2087          * aligned boundary, and the alternate data stream entries seem to NOT
2088          * be included in the dentry->length field for some reason.
2089          */
2090         if (inode->i_num_ads != 0) {
2091                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2092                 if (offset + dentry->length > metadata_resource_len ||
2093                     (ret = read_ads_entries(&metadata_resource[offset + dentry->length],
2094                                             inode,
2095                                             metadata_resource_len - offset - dentry->length)))
2096                 {
2097                         ERROR("Failed to read alternate data stream "
2098                               "entries of WIM dentry \"%"WS"\"", file_name);
2099                         goto out_free_short_name;
2100                 }
2101         }
2102         /* We've read all the data for this dentry.  Set the names and their
2103          * lengths, and we've done. */
2104         dentry->d_inode           = inode;
2105         dentry->file_name         = file_name;
2106         dentry->short_name        = short_name;
2107         dentry->file_name_nbytes  = file_name_nbytes;
2108         dentry->short_name_nbytes = short_name_nbytes;
2109         ret = 0;
2110         goto out;
2111 out_free_short_name:
2112         FREE(short_name);
2113 out_free_file_name:
2114         FREE(file_name);
2115 out_free_inode:
2116         free_inode(inode);
2117 out:
2118         return ret;
2119 }
2120
2121 static const tchar *
2122 dentry_get_file_type_string(const struct wim_dentry *dentry)
2123 {
2124         const struct wim_inode *inode = dentry->d_inode;
2125         if (inode_is_directory(inode))
2126                 return T("directory");
2127         else if (inode_is_symlink(inode))
2128                 return T("symbolic link");
2129         else
2130                 return T("file");
2131 }
2132
2133 /* Reads the children of a dentry, and all their children, ..., etc. from the
2134  * metadata resource and into the dentry tree.
2135  *
2136  * @metadata_resource:
2137  *      An array that contains the uncompressed metadata resource for the WIM
2138  *      file.
2139  *
2140  * @metadata_resource_len:
2141  *      The length of the uncompressed metadata resource, in bytes.
2142  *
2143  * @dentry:
2144  *      A pointer to a `struct wim_dentry' that is the root of the directory
2145  *      tree and has already been read from the metadata resource.  It does not
2146  *      need to be the real root because this procedure is called recursively.
2147  *
2148  * Return values:
2149  *      WIMLIB_ERR_SUCCESS (0)
2150  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
2151  *      WIMLIB_ERR_NOMEM
2152  */
2153 int
2154 read_dentry_tree(const u8 * restrict metadata_resource,
2155                  u64 metadata_resource_len,
2156                  struct wim_dentry * restrict dentry)
2157 {
2158         u64 cur_offset = dentry->subdir_offset;
2159         struct wim_dentry *child;
2160         struct wim_dentry *duplicate;
2161         struct wim_dentry *parent;
2162         struct wim_dentry cur_child;
2163         int ret;
2164
2165         /*
2166          * If @dentry has no child dentries, nothing more needs to be done for
2167          * this branch.  This is the case for regular files, symbolic links, and
2168          * *possibly* empty directories (although an empty directory may also
2169          * have one child dentry that is the special end-of-directory dentry)
2170          */
2171         if (cur_offset == 0)
2172                 return 0;
2173
2174         /* Check for cyclic directory structure */
2175         for (parent = dentry->parent; !dentry_is_root(parent); parent = parent->parent)
2176         {
2177                 if (unlikely(parent->subdir_offset == cur_offset)) {
2178                         ERROR("Cyclic directory structure directed: children "
2179                               "of \"%"TS"\" coincide with children of \"%"TS"\"",
2180                               dentry_full_path(dentry),
2181                               dentry_full_path(parent));
2182                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
2183                 }
2184         }
2185
2186         /* Find and read all the children of @dentry. */
2187         for (;;) {
2188
2189                 /* Read next child of @dentry into @cur_child. */
2190                 ret = read_dentry(metadata_resource, metadata_resource_len,
2191                                   cur_offset, &cur_child);
2192                 if (ret)
2193                         break;
2194
2195                 /* Check for end of directory. */
2196                 if (cur_child.length == 0)
2197                         break;
2198
2199                 /* Not end of directory.  Allocate this child permanently and
2200                  * link it to the parent and previous child. */
2201                 child = memdup(&cur_child, sizeof(struct wim_dentry));
2202                 if (child == NULL) {
2203                         ERROR("Failed to allocate new dentry!");
2204                         ret = WIMLIB_ERR_NOMEM;
2205                         break;
2206                 }
2207
2208                 /* Advance to the offset of the next child.  Note: We need to
2209                  * advance by the TOTAL length of the dentry, not by the length
2210                  * cur_child.length, which although it does take into account
2211                  * the padding, it DOES NOT take into account alternate stream
2212                  * entries. */
2213                 cur_offset += dentry_in_total_length(child);
2214
2215                 if (unlikely(!dentry_has_long_name(child))) {
2216                         WARNING("Ignoring unnamed dentry in "
2217                                 "directory \"%"TS"\"",
2218                                 dentry_full_path(dentry));
2219                         free_dentry(child);
2220                         continue;
2221                 }
2222
2223                 duplicate = dentry_add_child(dentry, child);
2224                 if (unlikely(duplicate)) {
2225                         const tchar *child_type, *duplicate_type;
2226                         child_type = dentry_get_file_type_string(child);
2227                         duplicate_type = dentry_get_file_type_string(duplicate);
2228                         WARNING("Ignoring duplicate %"TS" \"%"TS"\" "
2229                                 "(the WIM image already contains a %"TS" "
2230                                 "at that path with the exact same name)",
2231                                 child_type, dentry_full_path(duplicate),
2232                                 duplicate_type);
2233                         free_dentry(child);
2234                         continue;
2235                 }
2236
2237                 inode_add_dentry(child, child->d_inode);
2238                 /* If there are children of this child, call this
2239                  * procedure recursively. */
2240                 if (child->subdir_offset != 0) {
2241                         if (likely(dentry_is_directory(child))) {
2242                                 ret = read_dentry_tree(metadata_resource,
2243                                                        metadata_resource_len,
2244                                                        child);
2245                                 if (ret)
2246                                         break;
2247                         } else {
2248                                 WARNING("Ignoring children of non-directory \"%"TS"\"",
2249                                         dentry_full_path(child));
2250                         }
2251                 }
2252         }
2253         return ret;
2254 }
2255
2256 /*
2257  * Writes a WIM alternate data stream (ADS) entry to an output buffer.
2258  *
2259  * @ads_entry:  The ADS entry structure.
2260  * @hash:       The hash field to use (instead of the one in the ADS entry).
2261  * @p:          The memory location to write the data to.
2262  *
2263  * Returns a pointer to the byte after the last byte written.
2264  */
2265 static u8 *
2266 write_ads_entry(const struct wim_ads_entry *ads_entry,
2267                 const u8 *hash, u8 * restrict p)
2268 {
2269         struct wim_ads_entry_on_disk *disk_ads_entry =
2270                         (struct wim_ads_entry_on_disk*)p;
2271         u8 *orig_p = p;
2272
2273         disk_ads_entry->reserved = cpu_to_le64(ads_entry->reserved);
2274         copy_hash(disk_ads_entry->hash, hash);
2275         disk_ads_entry->stream_name_nbytes = cpu_to_le16(ads_entry->stream_name_nbytes);
2276         p += sizeof(struct wim_ads_entry_on_disk);
2277         if (ads_entry->stream_name_nbytes) {
2278                 p = mempcpy(p, ads_entry->stream_name,
2279                             ads_entry->stream_name_nbytes + 2);
2280         }
2281         /* Align to 8-byte boundary */
2282         while ((uintptr_t)p & 7)
2283                 *p++ = 0;
2284         disk_ads_entry->length = cpu_to_le64(p - orig_p);
2285         return p;
2286 }
2287
2288 /*
2289  * Writes a WIM dentry to an output buffer.
2290  *
2291  * @dentry:  The dentry structure.
2292  * @p:       The memory location to write the data to.
2293  *
2294  * Returns the pointer to the byte after the last byte we wrote as part of the
2295  * dentry, including any alternate data stream entries.
2296  */
2297 static u8 *
2298 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
2299 {
2300         const struct wim_inode *inode;
2301         struct wim_dentry_on_disk *disk_dentry;
2302         const u8 *orig_p;
2303         const u8 *hash;
2304         bool use_dummy_stream;
2305         u16 num_ads;
2306
2307         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
2308         orig_p = p;
2309
2310         inode = dentry->d_inode;
2311         use_dummy_stream = inode_needs_dummy_stream(inode);
2312         disk_dentry = (struct wim_dentry_on_disk*)p;
2313
2314         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
2315         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
2316         disk_dentry->subdir_offset = cpu_to_le64(dentry->subdir_offset);
2317         disk_dentry->unused_1 = cpu_to_le64(dentry->d_unused_1);
2318         disk_dentry->unused_2 = cpu_to_le64(dentry->d_unused_2);
2319         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
2320         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
2321         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
2322         if (use_dummy_stream)
2323                 hash = zero_hash;
2324         else
2325                 hash = inode_stream_hash(inode, 0);
2326         copy_hash(disk_dentry->unnamed_stream_hash, hash);
2327         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2328                 disk_dentry->reparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
2329                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
2330                 disk_dentry->reparse.rp_unknown_2 = cpu_to_le16(inode->i_rp_unknown_2);
2331                 disk_dentry->reparse.not_rpfixed = cpu_to_le16(inode->i_not_rpfixed);
2332         } else {
2333                 disk_dentry->nonreparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
2334                 disk_dentry->nonreparse.hard_link_group_id =
2335                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
2336         }
2337         num_ads = inode->i_num_ads;
2338         if (use_dummy_stream)
2339                 num_ads++;
2340         disk_dentry->num_alternate_data_streams = cpu_to_le16(num_ads);
2341         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->short_name_nbytes);
2342         disk_dentry->file_name_nbytes = cpu_to_le16(dentry->file_name_nbytes);
2343         p += sizeof(struct wim_dentry_on_disk);
2344
2345         wimlib_assert(dentry_is_root(dentry) != dentry_has_long_name(dentry));
2346
2347         if (dentry_has_long_name(dentry))
2348                 p = mempcpy(p, dentry->file_name, dentry->file_name_nbytes + 2);
2349
2350         if (dentry_has_short_name(dentry))
2351                 p = mempcpy(p, dentry->short_name, dentry->short_name_nbytes + 2);
2352
2353         /* Align to 8-byte boundary */
2354         while ((uintptr_t)p & 7)
2355                 *p++ = 0;
2356
2357         /* We calculate the correct length of the dentry ourselves because the
2358          * dentry->length field may been set to an unexpected value from when we
2359          * read the dentry in (for example, there may have been unknown data
2360          * appended to the end of the dentry...).  Furthermore, the dentry may
2361          * have been renamed, thus changing its needed length. */
2362         disk_dentry->length = cpu_to_le64(p - orig_p);
2363
2364         if (use_dummy_stream) {
2365                 hash = inode_unnamed_stream_hash(inode);
2366                 p = write_ads_entry(&(struct wim_ads_entry){}, hash, p);
2367         }
2368
2369         /* Write the alternate data streams entries, if any. */
2370         for (u16 i = 0; i < inode->i_num_ads; i++) {
2371                 hash = inode_stream_hash(inode, i + 1);
2372                 p = write_ads_entry(&inode->i_ads_entries[i], hash, p);
2373         }
2374
2375         return p;
2376 }
2377
2378 static int
2379 write_dentry_cb(struct wim_dentry *dentry, void *_p)
2380 {
2381         u8 **p = _p;
2382         *p = write_dentry(dentry, *p);
2383         return 0;
2384 }
2385
2386 static u8 *
2387 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p);
2388
2389 static int
2390 write_dentry_tree_recursive_cb(struct wim_dentry *dentry, void *_p)
2391 {
2392         u8 **p = _p;
2393         *p = write_dentry_tree_recursive(dentry, *p);
2394         return 0;
2395 }
2396
2397 /* Recursive function that writes a dentry tree rooted at @parent, not including
2398  * @parent itself, which has already been written. */
2399 static u8 *
2400 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p)
2401 {
2402         /* Nothing to do if this dentry has no children. */
2403         if (parent->subdir_offset == 0)
2404                 return p;
2405
2406         /* Write child dentries and end-of-directory entry.
2407          *
2408          * Note: we need to write all of this dentry's children before
2409          * recursively writing the directory trees rooted at each of the child
2410          * dentries, since the on-disk dentries for a dentry's children are
2411          * always located at consecutive positions in the metadata resource! */
2412         for_dentry_child(parent, write_dentry_cb, &p);
2413
2414         /* write end of directory entry */
2415         *(le64*)p = cpu_to_le64(0);
2416         p += 8;
2417
2418         /* Recurse on children. */
2419         for_dentry_child(parent, write_dentry_tree_recursive_cb, &p);
2420         return p;
2421 }
2422
2423 /* Writes a directory tree to the metadata resource.
2424  *
2425  * @root:       Root of the dentry tree.
2426  * @p:          Pointer to a buffer with enough space for the dentry tree.
2427  *
2428  * Returns pointer to the byte after the last byte we wrote.
2429  */
2430 u8 *
2431 write_dentry_tree(const struct wim_dentry * restrict root, u8 * restrict p)
2432 {
2433         DEBUG("Writing dentry tree.");
2434         wimlib_assert(dentry_is_root(root));
2435
2436         /* If we're the root dentry, we have no parent that already
2437          * wrote us, so we need to write ourselves. */
2438         p = write_dentry(root, p);
2439
2440         /* Write end of directory entry after the root dentry just to be safe;
2441          * however the root dentry obviously cannot have any siblings. */
2442         *(le64*)p = cpu_to_le64(0);
2443         p += 8;
2444
2445         /* Recursively write the rest of the dentry tree. */
2446         return write_dentry_tree_recursive(root, p);
2447 }
2448
2449
2450 static int
2451 init_wimlib_dentry(struct wimlib_dir_entry *wdentry,
2452                    struct wim_dentry *dentry,
2453                    const WIMStruct *wim,
2454                    int flags)
2455 {
2456         int ret;
2457         size_t dummy;
2458         const struct wim_inode *inode = dentry->d_inode;
2459         struct wim_lookup_table_entry *lte;
2460         const u8 *hash;
2461
2462 #if TCHAR_IS_UTF16LE
2463         wdentry->filename = dentry->file_name;
2464         wdentry->dos_name = dentry->short_name;
2465 #else
2466         if (dentry_has_long_name(dentry)) {
2467                 ret = utf16le_to_tstr(dentry->file_name,
2468                                       dentry->file_name_nbytes,
2469                                       (tchar**)&wdentry->filename,
2470                                       &dummy);
2471                 if (ret)
2472                         return ret;
2473         }
2474         if (dentry_has_short_name(dentry)) {
2475                 ret = utf16le_to_tstr(dentry->short_name,
2476                                       dentry->short_name_nbytes,
2477                                       (tchar**)&wdentry->dos_name,
2478                                       &dummy);
2479                 if (ret)
2480                         return ret;
2481         }
2482 #endif
2483         ret = calculate_dentry_full_path(dentry);
2484         if (ret)
2485                 return ret;
2486         wdentry->full_path = dentry->_full_path;
2487
2488         for (struct wim_dentry *d = dentry; !dentry_is_root(d); d = d->parent)
2489                 wdentry->depth++;
2490
2491         if (inode->i_security_id >= 0) {
2492                 const struct wim_security_data *sd = wim_const_security_data(wim);
2493                 wdentry->security_descriptor = sd->descriptors[inode->i_security_id];
2494                 wdentry->security_descriptor_size = sd->sizes[inode->i_security_id];
2495         }
2496         wdentry->reparse_tag = inode->i_reparse_tag;
2497         wdentry->num_links = inode->i_nlink;
2498         wdentry->attributes = inode->i_attributes;
2499         wdentry->hard_link_group_id = inode->i_ino;
2500         wdentry->creation_time = wim_timestamp_to_timespec(inode->i_creation_time);
2501         wdentry->last_write_time = wim_timestamp_to_timespec(inode->i_last_write_time);
2502         wdentry->last_access_time = wim_timestamp_to_timespec(inode->i_last_access_time);
2503
2504         lte = inode_unnamed_lte(inode, wim->lookup_table);
2505         if (lte) {
2506                 lte_to_wimlib_resource_entry(lte, &wdentry->streams[0].resource);
2507         } else if (!is_zero_hash(hash = inode_unnamed_stream_hash(inode))) {
2508                 if (flags & WIMLIB_ITERATE_DIR_TREE_FLAG_RESOURCES_NEEDED)
2509                         return resource_not_found_error(inode, hash);
2510                 copy_hash(wdentry->streams[0].resource.sha1_hash, hash);
2511                 wdentry->streams[0].resource.is_missing = 1;
2512         }
2513
2514         for (unsigned i = 0; i < inode->i_num_ads; i++) {
2515                 if (!ads_entry_is_named_stream(&inode->i_ads_entries[i]))
2516                         continue;
2517                 lte = inode_stream_lte(inode, i + 1, wim->lookup_table);
2518                 wdentry->num_named_streams++;
2519                 if (lte) {
2520                         lte_to_wimlib_resource_entry(lte, &wdentry->streams[
2521                                                                 wdentry->num_named_streams].resource);
2522                 } else if (!is_zero_hash(hash = inode_stream_hash(inode, i + 1))) {
2523                         if (flags & WIMLIB_ITERATE_DIR_TREE_FLAG_RESOURCES_NEEDED)
2524                                 return resource_not_found_error(inode, hash);
2525                         copy_hash(wdentry->streams[
2526                                   wdentry->num_named_streams].resource.sha1_hash, hash);
2527                         wdentry->streams[
2528                                 wdentry->num_named_streams].resource.is_missing = 1;
2529                 }
2530         #if TCHAR_IS_UTF16LE
2531                 wdentry->streams[wdentry->num_named_streams].stream_name =
2532                                 inode->i_ads_entries[i].stream_name;
2533         #else
2534                 size_t dummy;
2535
2536                 ret = utf16le_to_tstr(inode->i_ads_entries[i].stream_name,
2537                                       inode->i_ads_entries[i].stream_name_nbytes,
2538                                       (tchar**)&wdentry->streams[
2539                                                 wdentry->num_named_streams].stream_name,
2540                                       &dummy);
2541                 if (ret)
2542                         return ret;
2543         #endif
2544         }
2545         return 0;
2546 }
2547
2548 static void
2549 free_wimlib_dentry(struct wimlib_dir_entry *wdentry)
2550 {
2551 #if !TCHAR_IS_UTF16LE
2552         FREE((tchar*)wdentry->filename);
2553         FREE((tchar*)wdentry->dos_name);
2554         for (unsigned i = 1; i <= wdentry->num_named_streams; i++)
2555                 FREE((tchar*)wdentry->streams[i].stream_name);
2556 #endif
2557         FREE(wdentry);
2558 }
2559
2560 struct iterate_dir_tree_ctx {
2561         WIMStruct *wim;
2562         int flags;
2563         wimlib_iterate_dir_tree_callback_t cb;
2564         void *user_ctx;
2565 };
2566
2567 static int
2568 do_iterate_dir_tree(WIMStruct *wim,
2569                     struct wim_dentry *dentry, int flags,
2570                     wimlib_iterate_dir_tree_callback_t cb,
2571                     void *user_ctx);
2572
2573 static int
2574 call_do_iterate_dir_tree(struct wim_dentry *dentry, void *_ctx)
2575 {
2576         struct iterate_dir_tree_ctx *ctx = _ctx;
2577         return do_iterate_dir_tree(ctx->wim, dentry, ctx->flags,
2578                                    ctx->cb, ctx->user_ctx);
2579 }
2580
2581 static int
2582 do_iterate_dir_tree(WIMStruct *wim,
2583                     struct wim_dentry *dentry, int flags,
2584                     wimlib_iterate_dir_tree_callback_t cb,
2585                     void *user_ctx)
2586 {
2587         struct wimlib_dir_entry *wdentry;
2588         int ret = WIMLIB_ERR_NOMEM;
2589
2590
2591         wdentry = CALLOC(1, sizeof(struct wimlib_dir_entry) +
2592                                   (1 + dentry->d_inode->i_num_ads) *
2593                                         sizeof(struct wimlib_stream_entry));
2594         if (wdentry == NULL)
2595                 goto out;
2596
2597         ret = init_wimlib_dentry(wdentry, dentry, wim, flags);
2598         if (ret)
2599                 goto out_free_wimlib_dentry;
2600
2601         if (!(flags & WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN)) {
2602                 ret = (*cb)(wdentry, user_ctx);
2603                 if (ret)
2604                         goto out_free_wimlib_dentry;
2605         }
2606
2607         if (flags & (WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE |
2608                      WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN))
2609         {
2610                 struct iterate_dir_tree_ctx ctx = {
2611                         .wim      = wim,
2612                         .flags    = flags &= ~WIMLIB_ITERATE_DIR_TREE_FLAG_CHILDREN,
2613                         .cb       = cb,
2614                         .user_ctx = user_ctx,
2615                 };
2616                 ret = for_dentry_child(dentry, call_do_iterate_dir_tree, &ctx);
2617         }
2618 out_free_wimlib_dentry:
2619         free_wimlib_dentry(wdentry);
2620 out:
2621         return ret;
2622 }
2623
2624 struct image_iterate_dir_tree_ctx {
2625         const tchar *path;
2626         int flags;
2627         wimlib_iterate_dir_tree_callback_t cb;
2628         void *user_ctx;
2629 };
2630
2631
2632 static int
2633 image_do_iterate_dir_tree(WIMStruct *wim)
2634 {
2635         struct image_iterate_dir_tree_ctx *ctx = wim->private;
2636         struct wim_dentry *dentry;
2637
2638         dentry = get_dentry(wim, ctx->path, WIMLIB_CASE_PLATFORM_DEFAULT);
2639         if (dentry == NULL)
2640                 return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
2641         return do_iterate_dir_tree(wim, dentry, ctx->flags, ctx->cb, ctx->user_ctx);
2642 }
2643
2644 /* API function documented in wimlib.h  */
2645 WIMLIBAPI int
2646 wimlib_iterate_dir_tree(WIMStruct *wim, int image, const tchar *path,
2647                         int flags,
2648                         wimlib_iterate_dir_tree_callback_t cb, void *user_ctx)
2649 {
2650         struct image_iterate_dir_tree_ctx ctx = {
2651                 .path = path,
2652                 .flags = flags,
2653                 .cb = cb,
2654                 .user_ctx = user_ctx,
2655         };
2656         wim->private = &ctx;
2657         return for_image(wim, image, image_do_iterate_dir_tree);
2658 }
2659
2660 /* Returns %true iff the metadata of @inode and @template_inode are reasonably
2661  * consistent with them being the same, unmodified file.  */
2662 static bool
2663 inode_metadata_consistent(const struct wim_inode *inode,
2664                           const struct wim_inode *template_inode,
2665                           const struct wim_lookup_table *template_lookup_table)
2666 {
2667         /* Must have exact same creation time and last write time.  */
2668         if (inode->i_creation_time != template_inode->i_creation_time ||
2669             inode->i_last_write_time != template_inode->i_last_write_time)
2670                 return false;
2671
2672         /* Last access time may have stayed the same or increased, but certainly
2673          * shouldn't have decreased.  */
2674         if (inode->i_last_access_time < template_inode->i_last_access_time)
2675                 return false;
2676
2677         /* Must have same number of alternate data stream entries.  */
2678         if (inode->i_num_ads != template_inode->i_num_ads)
2679                 return false;
2680
2681         /* If the stream entries for the inode are for some reason not resolved,
2682          * then the hashes are already available and the point of this function
2683          * is defeated.  */
2684         if (!inode->i_resolved)
2685                 return false;
2686
2687         /* Iterate through each stream and do some more checks.  */
2688         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2689                 const struct wim_lookup_table_entry *lte, *template_lte;
2690
2691                 lte = inode_stream_lte_resolved(inode, i);
2692                 template_lte = inode_stream_lte(template_inode, i,
2693                                                 template_lookup_table);
2694
2695                 /* Compare stream sizes.  */
2696                 if (lte && template_lte) {
2697                         if (lte->size != template_lte->size)
2698                                 return false;
2699
2700                         /* If hash happens to be available, compare with template.  */
2701                         if (!lte->unhashed && !template_lte->unhashed &&
2702                             !hashes_equal(lte->hash, template_lte->hash))
2703                                 return false;
2704
2705                 } else if (lte && lte->size) {
2706                         return false;
2707                 } else if (template_lte && template_lte->size) {
2708                         return false;
2709                 }
2710         }
2711
2712         /* All right, barring a full checksum and given that the inodes share a
2713          * path and the user isn't trying to trick us, these inodes most likely
2714          * refer to the same file.  */
2715         return true;
2716 }
2717
2718 /**
2719  * Given an inode @inode that has been determined to be "the same" as another
2720  * inode @template_inode in either the same WIM or another WIM, retrieve some
2721  * useful stream information (e.g. checksums) from @template_inode.
2722  *
2723  * This assumes that the streams for @inode have been resolved (to point
2724  * directly to the appropriate `struct wim_lookup_table_entry's)  but do not
2725  * necessarily have checksum information filled in.
2726  */
2727 static int
2728 inode_copy_checksums(struct wim_inode *inode,
2729                      struct wim_inode *template_inode,
2730                      WIMStruct *wim,
2731                      WIMStruct *template_wim)
2732 {
2733         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
2734                 struct wim_lookup_table_entry *lte, *template_lte;
2735                 struct wim_lookup_table_entry *replace_lte;
2736
2737                 lte = inode_stream_lte_resolved(inode, i);
2738                 template_lte = inode_stream_lte(template_inode, i,
2739                                                 template_wim->lookup_table);
2740
2741                 /* Only take action if both entries exist, the entry for @inode
2742                  * has no checksum calculated, but the entry for @template_inode
2743                  * does.  */
2744                 if (lte == NULL || template_lte == NULL ||
2745                     !lte->unhashed || template_lte->unhashed)
2746                         continue;
2747
2748                 wimlib_assert(lte->refcnt == inode->i_nlink);
2749
2750                 /* If the WIM of the template image is the same as the WIM of
2751                  * the new image, then @template_lte can be used directly.
2752                  *
2753                  * Otherwise, look for a stream with the same hash in the WIM of
2754                  * the new image.  If found, use it; otherwise re-use the entry
2755                  * being discarded, filling in the hash.  */
2756
2757                 if (wim == template_wim)
2758                         replace_lte = template_lte;
2759                 else
2760                         replace_lte = lookup_resource(wim->lookup_table,
2761                                                       template_lte->hash);
2762
2763                 list_del(&lte->unhashed_list);
2764                 if (replace_lte) {
2765                         free_lookup_table_entry(lte);
2766                 } else {
2767                         copy_hash(lte->hash, template_lte->hash);
2768                         lte->unhashed = 0;
2769                         lookup_table_insert(wim->lookup_table, lte);
2770                         lte->refcnt = 0;
2771                         replace_lte = lte;
2772                 }
2773
2774                 if (i == 0)
2775                         inode->i_lte = replace_lte;
2776                 else
2777                         inode->i_ads_entries[i - 1].lte = replace_lte;
2778
2779                 replace_lte->refcnt += inode->i_nlink;
2780         }
2781         return 0;
2782 }
2783
2784 struct reference_template_args {
2785         WIMStruct *wim;
2786         WIMStruct *template_wim;
2787 };
2788
2789 static int
2790 dentry_reference_template(struct wim_dentry *dentry, void *_args)
2791 {
2792         int ret;
2793         struct wim_dentry *template_dentry;
2794         struct wim_inode *inode, *template_inode;
2795         struct reference_template_args *args = _args;
2796         WIMStruct *wim = args->wim;
2797         WIMStruct *template_wim = args->template_wim;
2798
2799         if (dentry->d_inode->i_visited)
2800                 return 0;
2801
2802         ret = calculate_dentry_full_path(dentry);
2803         if (ret)
2804                 return ret;
2805
2806         template_dentry = get_dentry(template_wim, dentry->_full_path,
2807                                      WIMLIB_CASE_SENSITIVE);
2808         if (template_dentry == NULL) {
2809                 DEBUG("\"%"TS"\": newly added file", dentry->_full_path);
2810                 return 0;
2811         }
2812
2813         inode = dentry->d_inode;
2814         template_inode = template_dentry->d_inode;
2815
2816         if (inode_metadata_consistent(inode, template_inode,
2817                                       template_wim->lookup_table)) {
2818                 /*DEBUG("\"%"TS"\": No change detected", dentry->_full_path);*/
2819                 ret = inode_copy_checksums(inode, template_inode,
2820                                            wim, template_wim);
2821                 inode->i_visited = 1;
2822         } else {
2823                 DEBUG("\"%"TS"\": change detected!", dentry->_full_path);
2824                 ret = 0;
2825         }
2826         return ret;
2827 }
2828
2829 /* API function documented in wimlib.h  */
2830 WIMLIBAPI int
2831 wimlib_reference_template_image(WIMStruct *wim, int new_image,
2832                                 WIMStruct *template_wim, int template_image,
2833                                 int flags, wimlib_progress_func_t progress_func)
2834 {
2835         int ret;
2836         struct wim_image_metadata *new_imd;
2837
2838         if (wim == NULL || template_wim == NULL)
2839                 return WIMLIB_ERR_INVALID_PARAM;
2840
2841         if (wim == template_wim && new_image == template_image)
2842                 return WIMLIB_ERR_INVALID_PARAM;
2843
2844         if (new_image < 1 || new_image > wim->hdr.image_count)
2845                 return WIMLIB_ERR_INVALID_IMAGE;
2846
2847         if (!wim_has_metadata(wim))
2848                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2849
2850         new_imd = wim->image_metadata[new_image - 1];
2851         if (!new_imd->modified)
2852                 return WIMLIB_ERR_INVALID_PARAM;
2853
2854         ret = select_wim_image(template_wim, template_image);
2855         if (ret)
2856                 return ret;
2857
2858         struct reference_template_args args = {
2859                 .wim = wim,
2860                 .template_wim = template_wim,
2861         };
2862
2863         ret = for_dentry_in_tree(new_imd->root_dentry,
2864                                  dentry_reference_template, &args);
2865         dentry_tree_clear_inode_visited(new_imd->root_dentry);
2866         return ret;
2867 }