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