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