]> wimlib.net Git - wimlib/blob - src/dentry.c
Document handling of invalid filenames
[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/sha1.h"
42 #include "wimlib/timestamp.h"
43
44 #include <errno.h>
45
46 /* WIM alternate data stream entry (on-disk format) */
47 struct wim_ads_entry_on_disk {
48         /*  Length of the entry, in bytes.  This apparently includes all
49          *  fixed-length fields, plus the stream name and null terminator if
50          *  present, and the padding up to an 8 byte boundary.  wimlib is a
51          *  little less strict when reading the entries, and only requires that
52          *  the number of bytes from this field is at least as large as the size
53          *  of the fixed length fields and stream name without null terminator.
54          *  */
55         le64  length;
56
57         le64  reserved;
58
59         /* SHA1 message digest of the uncompressed stream; or, alternatively,
60          * can be all zeroes if the stream has zero length. */
61         u8 hash[SHA1_HASH_SIZE];
62
63         /* Length of the stream name, in bytes.  0 if the stream is unnamed.  */
64         le16 stream_name_nbytes;
65
66         /* Stream name in UTF-16LE.  It is @stream_name_nbytes bytes long,
67          * excluding the the null terminator.  There is a null terminator
68          * character if @stream_name_nbytes != 0; i.e., if this stream is named.
69          * */
70         utf16lechar stream_name[];
71 } _packed_attribute;
72
73 #define WIM_ADS_ENTRY_DISK_SIZE 38
74
75 /* WIM directory entry (on-disk format) */
76 struct wim_dentry_on_disk {
77         le64 length;
78         le32 attributes;
79         sle32 security_id;
80         le64 subdir_offset;
81         le64 unused_1;
82         le64 unused_2;
83         le64 creation_time;
84         le64 last_access_time;
85         le64 last_write_time;
86         u8 unnamed_stream_hash[SHA1_HASH_SIZE];
87         union {
88                 struct {
89                         le32 rp_unknown_1;
90                         le32 reparse_tag;
91                         le16 rp_unknown_2;
92                         le16 not_rpfixed;
93                 } _packed_attribute reparse;
94                 struct {
95                         le32 rp_unknown_1;
96                         le64 hard_link_group_id;
97                 } _packed_attribute nonreparse;
98         };
99         le16 num_alternate_data_streams;
100         le16 short_name_nbytes;
101         le16 file_name_nbytes;
102
103         /* Follewed by variable length file name, if file_name_nbytes != 0 */
104         utf16lechar file_name[];
105
106         /* Followed by variable length short name, if short_name_nbytes != 0 */
107         /*utf16lechar short_name[];*/
108 } _packed_attribute;
109
110 #define WIM_DENTRY_DISK_SIZE 102
111
112 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
113  * a file name and short name that take the specified numbers of bytes.  This
114  * excludes any alternate data stream entries that may follow the dentry. */
115 static u64
116 _dentry_correct_length_unaligned(u16 file_name_nbytes, u16 short_name_nbytes)
117 {
118         u64 length = sizeof(struct wim_dentry_on_disk);
119         if (file_name_nbytes)
120                 length += file_name_nbytes + 2;
121         if (short_name_nbytes)
122                 length += short_name_nbytes + 2;
123         return length;
124 }
125
126 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
127  * the file name length and short name length.  Note that dentry->length is
128  * ignored; also, this excludes any alternate data stream entries that may
129  * follow the dentry. */
130 static u64
131 dentry_correct_length_unaligned(const struct wim_dentry *dentry)
132 {
133         return _dentry_correct_length_unaligned(dentry->file_name_nbytes,
134                                                 dentry->short_name_nbytes);
135 }
136
137 /* Duplicates a string of system-dependent encoding into a UTF-16LE string and
138  * returns the string and its length, in bytes, in the pointer arguments.  Frees
139  * any existing string at the return location before overwriting it. */
140 static int
141 get_utf16le_name(const tchar *name, utf16lechar **name_utf16le_ret,
142                  u16 *name_utf16le_nbytes_ret)
143 {
144         utf16lechar *name_utf16le;
145         size_t name_utf16le_nbytes;
146         int ret;
147 #if TCHAR_IS_UTF16LE
148         name_utf16le_nbytes = tstrlen(name) * sizeof(utf16lechar);
149         name_utf16le = MALLOC(name_utf16le_nbytes + sizeof(utf16lechar));
150         if (!name_utf16le)
151                 return WIMLIB_ERR_NOMEM;
152         memcpy(name_utf16le, name, name_utf16le_nbytes + sizeof(utf16lechar));
153         ret = 0;
154 #else
155
156         ret = tstr_to_utf16le(name, tstrlen(name), &name_utf16le,
157                               &name_utf16le_nbytes);
158         if (ret == 0) {
159                 if (name_utf16le_nbytes > 0xffff) {
160                         FREE(name_utf16le);
161                         ERROR("Multibyte string \"%"TS"\" is too long!", name);
162                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
163                 }
164         }
165 #endif
166         if (ret == 0) {
167                 FREE(*name_utf16le_ret);
168                 *name_utf16le_ret = name_utf16le;
169                 *name_utf16le_nbytes_ret = name_utf16le_nbytes;
170         }
171         return ret;
172 }
173
174 /* Sets the name of a WIM dentry from a multibyte string. */
175 int
176 set_dentry_name(struct wim_dentry *dentry, const tchar *new_name)
177 {
178         int ret;
179         ret = get_utf16le_name(new_name, &dentry->file_name,
180                                &dentry->file_name_nbytes);
181         if (ret == 0) {
182                 /* Clear the short name and recalculate the dentry length */
183                 if (dentry_has_short_name(dentry)) {
184                         FREE(dentry->short_name);
185                         dentry->short_name = NULL;
186                         dentry->short_name_nbytes = 0;
187                 }
188         }
189         return ret;
190 }
191
192 /* Returns the total length of a WIM alternate data stream entry on-disk,
193  * including the stream name, the null terminator, AND the padding after the
194  * entry to align the next ADS entry or dentry on an 8-byte boundary. */
195 static u64
196 ads_entry_total_length(const struct wim_ads_entry *entry)
197 {
198         u64 len = sizeof(struct wim_ads_entry_on_disk);
199         if (entry->stream_name_nbytes)
200                 len += entry->stream_name_nbytes + 2;
201         return (len + 7) & ~7;
202 }
203
204
205 static u64
206 _dentry_total_length(const struct wim_dentry *dentry, u64 length)
207 {
208         const struct wim_inode *inode = dentry->d_inode;
209         for (u16 i = 0; i < inode->i_num_ads; i++)
210                 length += ads_entry_total_length(&inode->i_ads_entries[i]);
211         return (length + 7) & ~7;
212 }
213
214 /* Calculate the aligned *total* length of an on-disk WIM dentry.  This includes
215  * all alternate data streams. */
216 u64
217 dentry_correct_total_length(const struct wim_dentry *dentry)
218 {
219         return _dentry_total_length(dentry,
220                                     dentry_correct_length_unaligned(dentry));
221 }
222
223 /* Like dentry_correct_total_length(), but use the existing dentry->length field
224  * instead of calculating its "correct" value. */
225 static u64
226 dentry_total_length(const struct wim_dentry *dentry)
227 {
228         return _dentry_total_length(dentry, dentry->length);
229 }
230
231 int
232 for_dentry_in_rbtree(struct rb_node *root,
233                      int (*visitor)(struct wim_dentry *, void *),
234                      void *arg)
235 {
236         int ret;
237         struct rb_node *node = root;
238         LIST_HEAD(stack);
239         while (1) {
240                 if (node) {
241                         list_add(&rbnode_dentry(node)->tmp_list, &stack);
242                         node = node->rb_left;
243                 } else {
244                         struct list_head *next;
245                         struct wim_dentry *dentry;
246
247                         next = stack.next;
248                         if (next == &stack)
249                                 return 0;
250                         dentry = container_of(next, struct wim_dentry, tmp_list);
251                         list_del(next);
252                         ret = visitor(dentry, arg);
253                         if (ret != 0)
254                                 return ret;
255                         node = dentry->rb_node.rb_right;
256                 }
257         }
258 }
259
260 static int
261 for_dentry_tree_in_rbtree_depth(struct rb_node *node,
262                                 int (*visitor)(struct wim_dentry*, void*),
263                                 void *arg)
264 {
265         int ret;
266         if (node) {
267                 ret = for_dentry_tree_in_rbtree_depth(node->rb_left,
268                                                       visitor, arg);
269                 if (ret != 0)
270                         return ret;
271                 ret = for_dentry_tree_in_rbtree_depth(node->rb_right,
272                                                       visitor, arg);
273                 if (ret != 0)
274                         return ret;
275                 ret = for_dentry_in_tree_depth(rbnode_dentry(node), visitor, arg);
276                 if (ret != 0)
277                         return ret;
278         }
279         return 0;
280 }
281
282 static int
283 for_dentry_tree_in_rbtree(struct rb_node *node,
284                           int (*visitor)(struct wim_dentry*, void*),
285                           void *arg)
286 {
287         int ret;
288         if (node) {
289                 ret = for_dentry_tree_in_rbtree(node->rb_left, visitor, arg);
290                 if (ret)
291                         return ret;
292                 ret = for_dentry_in_tree(rbnode_dentry(node), visitor, arg);
293                 if (ret)
294                         return ret;
295                 ret = for_dentry_tree_in_rbtree(node->rb_right, visitor, arg);
296                 if (ret)
297                         return ret;
298         }
299         return 0;
300 }
301
302 /* Calls a function on all directory entries in a WIM dentry tree.  Logically,
303  * this is a pre-order traversal (the function is called on a parent dentry
304  * before its children), but sibling dentries will be visited in order as well.
305  * */
306 int
307 for_dentry_in_tree(struct wim_dentry *root,
308                    int (*visitor)(struct wim_dentry*, void*), void *arg)
309 {
310         int ret;
311
312         if (!root)
313                 return 0;
314         ret = (*visitor)(root, arg);
315         if (ret)
316                 return ret;
317         return for_dentry_tree_in_rbtree(root->d_inode->i_children.rb_node,
318                                          visitor,
319                                          arg);
320 }
321
322 /* Like for_dentry_in_tree(), but the visitor function is always called on a
323  * dentry's children before on itself. */
324 int
325 for_dentry_in_tree_depth(struct wim_dentry *root,
326                          int (*visitor)(struct wim_dentry*, void*), void *arg)
327 {
328         int ret;
329
330         if (!root)
331                 return 0;
332         ret = for_dentry_tree_in_rbtree_depth(root->d_inode->i_children.rb_node,
333                                               visitor, arg);
334         if (ret)
335                 return ret;
336         return (*visitor)(root, arg);
337 }
338
339 /* Calculate the full path of @dentry.  The full path of its parent must have
340  * already been calculated, or it must be the root dentry. */
341 int
342 calculate_dentry_full_path(struct wim_dentry *dentry)
343 {
344         tchar *full_path;
345         u32 full_path_nbytes;
346         int ret;
347
348         if (dentry->_full_path)
349                 return 0;
350
351         if (dentry_is_root(dentry)) {
352                 full_path = TSTRDUP(T("/"));
353                 if (!full_path)
354                         return WIMLIB_ERR_NOMEM;
355                 full_path_nbytes = 1 * sizeof(tchar);
356         } else {
357                 struct wim_dentry *parent;
358                 tchar *parent_full_path;
359                 u32 parent_full_path_nbytes;
360                 size_t filename_nbytes;
361
362                 parent = dentry->parent;
363                 if (dentry_is_root(parent)) {
364                         parent_full_path = T("");
365                         parent_full_path_nbytes = 0;
366                 } else {
367                         if (!parent->_full_path) {
368                                 ret = calculate_dentry_full_path(parent);
369                                 if (ret)
370                                         return ret;
371                         }
372                         parent_full_path = parent->_full_path;
373                         parent_full_path_nbytes = parent->full_path_nbytes;
374                 }
375
376                 /* Append this dentry's name as a tchar string to the full path
377                  * of the parent followed by the path separator */
378         #if TCHAR_IS_UTF16LE
379                 filename_nbytes = dentry->file_name_nbytes;
380         #else
381                 {
382                         int ret = utf16le_to_tstr_nbytes(dentry->file_name,
383                                                          dentry->file_name_nbytes,
384                                                          &filename_nbytes);
385                         if (ret)
386                                 return ret;
387                 }
388         #endif
389
390                 full_path_nbytes = parent_full_path_nbytes + sizeof(tchar) +
391                                    filename_nbytes;
392                 full_path = MALLOC(full_path_nbytes + sizeof(tchar));
393                 if (!full_path)
394                         return WIMLIB_ERR_NOMEM;
395                 memcpy(full_path, parent_full_path, parent_full_path_nbytes);
396                 full_path[parent_full_path_nbytes / sizeof(tchar)] = T('/');
397         #if TCHAR_IS_UTF16LE
398                 memcpy(&full_path[parent_full_path_nbytes / sizeof(tchar) + 1],
399                        dentry->file_name,
400                        filename_nbytes + sizeof(tchar));
401         #else
402                 utf16le_to_tstr_buf(dentry->file_name,
403                                     dentry->file_name_nbytes,
404                                     &full_path[parent_full_path_nbytes /
405                                                sizeof(tchar) + 1]);
406         #endif
407         }
408         dentry->_full_path = full_path;
409         dentry->full_path_nbytes= full_path_nbytes;
410         return 0;
411 }
412
413 static int
414 do_calculate_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
415 {
416         return calculate_dentry_full_path(dentry);
417 }
418
419 int
420 calculate_dentry_tree_full_paths(struct wim_dentry *root)
421 {
422         return for_dentry_in_tree(root, do_calculate_dentry_full_path, NULL);
423 }
424
425 tchar *
426 dentry_full_path(struct wim_dentry *dentry)
427 {
428         calculate_dentry_full_path(dentry);
429         return dentry->_full_path;
430 }
431
432 static int
433 increment_subdir_offset(struct wim_dentry *dentry, void *subdir_offset_p)
434 {
435         *(u64*)subdir_offset_p += dentry_correct_total_length(dentry);
436         return 0;
437 }
438
439 static int
440 call_calculate_subdir_offsets(struct wim_dentry *dentry, void *subdir_offset_p)
441 {
442         calculate_subdir_offsets(dentry, subdir_offset_p);
443         return 0;
444 }
445
446 /*
447  * Recursively calculates the subdir offsets for a directory tree.
448  *
449  * @dentry:  The root of the directory tree.
450  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
451  *                    offset for @dentry.
452  */
453 void
454 calculate_subdir_offsets(struct wim_dentry *dentry, u64 *subdir_offset_p)
455 {
456         struct rb_node *node;
457
458         dentry->subdir_offset = *subdir_offset_p;
459         node = dentry->d_inode->i_children.rb_node;
460         if (node) {
461                 /* Advance the subdir offset by the amount of space the children
462                  * of this dentry take up. */
463                 for_dentry_in_rbtree(node, increment_subdir_offset, subdir_offset_p);
464
465                 /* End-of-directory dentry on disk. */
466                 *subdir_offset_p += 8;
467
468                 /* Recursively call calculate_subdir_offsets() on all the
469                  * children. */
470                 for_dentry_in_rbtree(node, call_calculate_subdir_offsets, subdir_offset_p);
471         } else {
472                 /* On disk, childless directories have a valid subdir_offset
473                  * that points to an 8-byte end-of-directory dentry.  Regular
474                  * files or reparse points have a subdir_offset of 0. */
475                 if (dentry_is_directory(dentry))
476                         *subdir_offset_p += 8;
477                 else
478                         dentry->subdir_offset = 0;
479         }
480 }
481
482 /* UNIX: Case-sensitive UTF-16LE dentry or stream name comparison.  We call this
483  * on Windows as well to distinguish true duplicates from names differing by
484  * case only. */
485 static int
486 compare_utf16le_names_case_sensitive(const utf16lechar *name1, size_t nbytes1,
487                                      const utf16lechar *name2, size_t nbytes2)
488 {
489         /* Return the result if the strings differ up to their minimum length.
490          * Note that we cannot use strcmp() or strncmp() here, as the strings
491          * are in UTF-16LE format. */
492         int result = memcmp(name1, name2, min(nbytes1, nbytes2));
493         if (result)
494                 return result;
495
496         /* The strings are the same up to their minimum length, so return a
497          * result based on their lengths. */
498         if (nbytes1 < nbytes2)
499                 return -1;
500         else if (nbytes1 > nbytes2)
501                 return 1;
502         else
503                 return 0;
504 }
505
506 #ifdef __WIN32__
507 /* Windoze: Case-insensitive UTF-16LE dentry or stream name comparison */
508 static int
509 compare_utf16le_names_case_insensitive(const utf16lechar *name1, size_t nbytes1,
510                                        const utf16lechar *name2, size_t nbytes2)
511 {
512         /* Return the result if the strings differ up to their minimum length.
513          * */
514         int result = _wcsnicmp((const wchar_t*)name1, (const wchar_t*)name2,
515                                min(nbytes1 / 2, nbytes2 / 2));
516         if (result)
517                 return result;
518
519         /* The strings are the same up to their minimum length, so return a
520          * result based on their lengths. */
521         if (nbytes1 < nbytes2)
522                 return -1;
523         else if (nbytes1 > nbytes2)
524                 return 1;
525         else
526                 return 0;
527 }
528 #endif /* __WIN32__ */
529
530 #ifdef __WIN32__
531 #  define compare_utf16le_names compare_utf16le_names_case_insensitive
532 #else
533 #  define compare_utf16le_names compare_utf16le_names_case_sensitive
534 #endif
535
536
537 #ifdef __WIN32__
538 static int
539 dentry_compare_names_case_insensitive(const struct wim_dentry *d1,
540                                       const struct wim_dentry *d2)
541 {
542         return compare_utf16le_names_case_insensitive(d1->file_name,
543                                                       d1->file_name_nbytes,
544                                                       d2->file_name,
545                                                       d2->file_name_nbytes);
546 }
547 #endif /* __WIN32__ */
548
549 static int
550 dentry_compare_names_case_sensitive(const struct wim_dentry *d1,
551                                     const struct wim_dentry *d2)
552 {
553         return compare_utf16le_names_case_sensitive(d1->file_name,
554                                                     d1->file_name_nbytes,
555                                                     d2->file_name,
556                                                     d2->file_name_nbytes);
557 }
558
559 #ifdef __WIN32__
560 #  define dentry_compare_names dentry_compare_names_case_insensitive
561 #else
562 #  define dentry_compare_names dentry_compare_names_case_sensitive
563 #endif
564
565 /* Return %true iff the alternate data stream entry @entry has the UTF-16LE
566  * stream name @name that has length @name_nbytes bytes. */
567 static inline bool
568 ads_entry_has_name(const struct wim_ads_entry *entry,
569                    const utf16lechar *name, size_t name_nbytes)
570 {
571         return !compare_utf16le_names(name, name_nbytes,
572                                       entry->stream_name,
573                                       entry->stream_name_nbytes);
574 }
575
576 struct wim_dentry *
577 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
578                                    const utf16lechar *name,
579                                    size_t name_nbytes)
580 {
581         struct rb_node *node = dentry->d_inode->i_children.rb_node;
582         struct wim_dentry *child;
583         while (node) {
584                 child = rbnode_dentry(node);
585                 int result = compare_utf16le_names(name, name_nbytes,
586                                                    child->file_name,
587                                                    child->file_name_nbytes);
588                 if (result < 0)
589                         node = node->rb_left;
590                 else if (result > 0)
591                         node = node->rb_right;
592                 else {
593                 #ifdef __WIN32__
594                         if (!list_empty(&child->case_insensitive_conflict_list))
595                         {
596                                 WARNING("Result of case-insensitive lookup is ambiguous "
597                                         "(returning \"%ls\" instead of \"%ls\")",
598                                         child->file_name,
599                                         container_of(child->case_insensitive_conflict_list.next,
600                                                      struct wim_dentry,
601                                                      case_insensitive_conflict_list)->file_name);
602                         }
603                 #endif
604                         return child;
605                 }
606         }
607         return NULL;
608 }
609
610 /* Returns the child of @dentry that has the file name @name.  Returns NULL if
611  * no child has the name. */
612 struct wim_dentry *
613 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name)
614 {
615 #if TCHAR_IS_UTF16LE
616         return get_dentry_child_with_utf16le_name(dentry, name,
617                                                   tstrlen(name) * sizeof(tchar));
618 #else
619         utf16lechar *utf16le_name;
620         size_t utf16le_name_nbytes;
621         int ret;
622         struct wim_dentry *child;
623
624         ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
625                               &utf16le_name, &utf16le_name_nbytes);
626         if (ret) {
627                 child = NULL;
628         } else {
629                 child = get_dentry_child_with_utf16le_name(dentry,
630                                                            utf16le_name,
631                                                            utf16le_name_nbytes);
632                 FREE(utf16le_name);
633         }
634         return child;
635 #endif
636 }
637
638 static struct wim_dentry *
639 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path)
640 {
641         struct wim_dentry *cur_dentry, *parent_dentry;
642         const utf16lechar *p, *pp;
643
644         cur_dentry = parent_dentry = wim_root_dentry(wim);
645         if (!cur_dentry) {
646                 errno = ENOENT;
647                 return NULL;
648         }
649         p = path;
650         while (1) {
651                 while (*p == cpu_to_le16('/'))
652                         p++;
653                 if (*p == cpu_to_le16('\0'))
654                         break;
655                 pp = p;
656                 while (*pp != cpu_to_le16('/') && *pp != cpu_to_le16('\0'))
657                         pp++;
658
659                 cur_dentry = get_dentry_child_with_utf16le_name(parent_dentry, p,
660                                                                 (void*)pp - (void*)p);
661                 if (cur_dentry == NULL)
662                         break;
663                 p = pp;
664                 parent_dentry = cur_dentry;
665         }
666         if (cur_dentry == NULL) {
667                 if (dentry_is_directory(parent_dentry))
668                         errno = ENOENT;
669                 else
670                         errno = ENOTDIR;
671         }
672         return cur_dentry;
673 }
674
675 /* Returns the dentry corresponding to the @path, or NULL if there is no such
676  * dentry. */
677 struct wim_dentry *
678 get_dentry(WIMStruct *wim, const tchar *path)
679 {
680 #if TCHAR_IS_UTF16LE
681         return get_dentry_utf16le(wim, path);
682 #else
683         utf16lechar *path_utf16le;
684         size_t path_utf16le_nbytes;
685         int ret;
686         struct wim_dentry *dentry;
687
688         ret = tstr_to_utf16le(path, tstrlen(path) * sizeof(tchar),
689                               &path_utf16le, &path_utf16le_nbytes);
690         if (ret)
691                 return NULL;
692         dentry = get_dentry_utf16le(wim, path_utf16le);
693         FREE(path_utf16le);
694         return dentry;
695 #endif
696 }
697
698 struct wim_inode *
699 wim_pathname_to_inode(WIMStruct *wim, const tchar *path)
700 {
701         struct wim_dentry *dentry;
702         dentry = get_dentry(wim, path);
703         if (dentry)
704                 return dentry->d_inode;
705         else
706                 return NULL;
707 }
708
709 /* Takes in a path of length @len in @buf, and transforms it into a string for
710  * the path of its parent directory. */
711 static void
712 to_parent_name(tchar *buf, size_t len)
713 {
714         ssize_t i = (ssize_t)len - 1;
715         while (i >= 0 && buf[i] == T('/'))
716                 i--;
717         while (i >= 0 && buf[i] != T('/'))
718                 i--;
719         while (i >= 0 && buf[i] == T('/'))
720                 i--;
721         buf[i + 1] = T('\0');
722 }
723
724 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
725  * if the dentry is not found. */
726 struct wim_dentry *
727 get_parent_dentry(WIMStruct *wim, const tchar *path)
728 {
729         size_t path_len = tstrlen(path);
730         tchar buf[path_len + 1];
731
732         tmemcpy(buf, path, path_len + 1);
733         to_parent_name(buf, path_len);
734         return get_dentry(wim, buf);
735 }
736
737 /* Prints the full path of a dentry. */
738 int
739 print_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
740 {
741         int ret = calculate_dentry_full_path(dentry);
742         if (ret)
743                 return ret;
744         tprintf(T("%"TS"\n"), dentry->_full_path);
745         return 0;
746 }
747
748 /* We want to be able to show the names of the file attribute flags that are
749  * set. */
750 struct file_attr_flag {
751         u32 flag;
752         const tchar *name;
753 };
754 struct file_attr_flag file_attr_flags[] = {
755         {FILE_ATTRIBUTE_READONLY,           T("READONLY")},
756         {FILE_ATTRIBUTE_HIDDEN,             T("HIDDEN")},
757         {FILE_ATTRIBUTE_SYSTEM,             T("SYSTEM")},
758         {FILE_ATTRIBUTE_DIRECTORY,          T("DIRECTORY")},
759         {FILE_ATTRIBUTE_ARCHIVE,            T("ARCHIVE")},
760         {FILE_ATTRIBUTE_DEVICE,             T("DEVICE")},
761         {FILE_ATTRIBUTE_NORMAL,             T("NORMAL")},
762         {FILE_ATTRIBUTE_TEMPORARY,          T("TEMPORARY")},
763         {FILE_ATTRIBUTE_SPARSE_FILE,        T("SPARSE_FILE")},
764         {FILE_ATTRIBUTE_REPARSE_POINT,      T("REPARSE_POINT")},
765         {FILE_ATTRIBUTE_COMPRESSED,         T("COMPRESSED")},
766         {FILE_ATTRIBUTE_OFFLINE,            T("OFFLINE")},
767         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,T("NOT_CONTENT_INDEXED")},
768         {FILE_ATTRIBUTE_ENCRYPTED,          T("ENCRYPTED")},
769         {FILE_ATTRIBUTE_VIRTUAL,            T("VIRTUAL")},
770 };
771
772 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
773  * available.  If the dentry is unresolved and the lookup table is NULL, the
774  * lookup table entries will not be printed.  Otherwise, they will be. */
775 int
776 print_dentry(struct wim_dentry *dentry, void *lookup_table)
777 {
778         const u8 *hash;
779         struct wim_lookup_table_entry *lte;
780         const struct wim_inode *inode = dentry->d_inode;
781         tchar buf[50];
782
783         tprintf(T("[DENTRY]\n"));
784         tprintf(T("Length            = %"PRIu64"\n"), dentry->length);
785         tprintf(T("Attributes        = 0x%x\n"), inode->i_attributes);
786         for (size_t i = 0; i < ARRAY_LEN(file_attr_flags); i++)
787                 if (file_attr_flags[i].flag & inode->i_attributes)
788                         tprintf(T("    FILE_ATTRIBUTE_%"TS" is set\n"),
789                                 file_attr_flags[i].name);
790         tprintf(T("Security ID       = %d\n"), inode->i_security_id);
791         tprintf(T("Subdir offset     = %"PRIu64"\n"), dentry->subdir_offset);
792
793         wim_timestamp_to_str(inode->i_creation_time, buf, sizeof(buf));
794         tprintf(T("Creation Time     = %"TS"\n"), buf);
795
796         wim_timestamp_to_str(inode->i_last_access_time, buf, sizeof(buf));
797         tprintf(T("Last Access Time  = %"TS"\n"), buf);
798
799         wim_timestamp_to_str(inode->i_last_write_time, buf, sizeof(buf));
800         tprintf(T("Last Write Time   = %"TS"\n"), buf);
801
802         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
803                 tprintf(T("Reparse Tag       = 0x%"PRIx32"\n"), inode->i_reparse_tag);
804                 tprintf(T("Reparse Point Flags = 0x%"PRIx16"\n"),
805                         inode->i_not_rpfixed);
806                 tprintf(T("Reparse Point Unknown 2 = 0x%"PRIx32"\n"),
807                         inode->i_rp_unknown_2);
808         }
809         tprintf(T("Reparse Point Unknown 1 = 0x%"PRIx32"\n"),
810                 inode->i_rp_unknown_1);
811         tprintf(T("Hard Link Group   = 0x%"PRIx64"\n"), inode->i_ino);
812         tprintf(T("Hard Link Group Size = %"PRIu32"\n"), inode->i_nlink);
813         tprintf(T("Number of Alternate Data Streams = %hu\n"), inode->i_num_ads);
814         if (dentry_has_long_name(dentry))
815                 wimlib_printf(T("Filename = \"%"WS"\"\n"), dentry->file_name);
816         if (dentry_has_short_name(dentry))
817                 wimlib_printf(T("Short Name \"%"WS"\"\n"), dentry->short_name);
818         if (dentry->_full_path)
819                 tprintf(T("Full Path = \"%"TS"\"\n"), dentry->_full_path);
820
821         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
822         if (lte) {
823                 print_lookup_table_entry(lte, stdout);
824         } else {
825                 hash = inode_stream_hash(inode, 0);
826                 if (hash) {
827                         tprintf(T("Hash              = 0x"));
828                         print_hash(hash, stdout);
829                         tputchar(T('\n'));
830                         tputchar(T('\n'));
831                 }
832         }
833         for (u16 i = 0; i < inode->i_num_ads; i++) {
834                 tprintf(T("[Alternate Stream Entry %u]\n"), i);
835                 wimlib_printf(T("Name = \"%"WS"\"\n"),
836                               inode->i_ads_entries[i].stream_name);
837                 tprintf(T("Name Length (UTF16 bytes) = %hu\n"),
838                        inode->i_ads_entries[i].stream_name_nbytes);
839                 hash = inode_stream_hash(inode, i + 1);
840                 if (hash) {
841                         tprintf(T("Hash              = 0x"));
842                         print_hash(hash, stdout);
843                         tputchar(T('\n'));
844                 }
845                 print_lookup_table_entry(inode_stream_lte(inode, i + 1, lookup_table),
846                                          stdout);
847         }
848         return 0;
849 }
850
851 /* Initializations done on every `struct wim_dentry'. */
852 static void
853 dentry_common_init(struct wim_dentry *dentry)
854 {
855         memset(dentry, 0, sizeof(struct wim_dentry));
856 }
857
858 struct wim_inode *
859 new_timeless_inode(void)
860 {
861         struct wim_inode *inode = CALLOC(1, sizeof(struct wim_inode));
862         if (inode) {
863                 inode->i_security_id = -1;
864                 inode->i_nlink = 1;
865                 inode->i_next_stream_id = 1;
866                 inode->i_not_rpfixed = 1;
867                 INIT_LIST_HEAD(&inode->i_list);
868         #ifdef WITH_FUSE
869                 if (pthread_mutex_init(&inode->i_mutex, NULL) != 0) {
870                         ERROR_WITH_ERRNO("Error initializing mutex");
871                         FREE(inode);
872                         return NULL;
873                 }
874         #endif
875                 INIT_LIST_HEAD(&inode->i_dentry);
876         }
877         return inode;
878 }
879
880 static struct wim_inode *
881 new_inode(void)
882 {
883         struct wim_inode *inode = new_timeless_inode();
884         if (inode) {
885                 u64 now = get_wim_timestamp();
886                 inode->i_creation_time = now;
887                 inode->i_last_access_time = now;
888                 inode->i_last_write_time = now;
889         }
890         return inode;
891 }
892
893 /* Creates an unlinked directory entry. */
894 int
895 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
896 {
897         struct wim_dentry *dentry;
898         int ret;
899
900         dentry = MALLOC(sizeof(struct wim_dentry));
901         if (!dentry)
902                 return WIMLIB_ERR_NOMEM;
903
904         dentry_common_init(dentry);
905         ret = set_dentry_name(dentry, name);
906         if (ret == 0) {
907                 dentry->parent = dentry;
908                 *dentry_ret = dentry;
909         } else {
910                 FREE(dentry);
911                 ERROR("Failed to set name on new dentry with name \"%"TS"\"",
912                       name);
913         }
914         return ret;
915 }
916
917
918 static int
919 _new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret,
920                         bool timeless)
921 {
922         struct wim_dentry *dentry;
923         int ret;
924
925         ret = new_dentry(name, &dentry);
926         if (ret)
927                 return ret;
928
929         if (timeless)
930                 dentry->d_inode = new_timeless_inode();
931         else
932                 dentry->d_inode = new_inode();
933         if (!dentry->d_inode) {
934                 free_dentry(dentry);
935                 return WIMLIB_ERR_NOMEM;
936         }
937
938         inode_add_dentry(dentry, dentry->d_inode);
939         *dentry_ret = dentry;
940         return 0;
941 }
942
943 int
944 new_dentry_with_timeless_inode(const tchar *name, struct wim_dentry **dentry_ret)
945 {
946         return _new_dentry_with_inode(name, dentry_ret, true);
947 }
948
949 int
950 new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret)
951 {
952         return _new_dentry_with_inode(name, dentry_ret, false);
953 }
954
955 int
956 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
957 {
958         int ret;
959         struct wim_dentry *dentry;
960
961         DEBUG("Creating filler directory \"%"TS"\"", name);
962         ret = new_dentry_with_inode(name, &dentry);
963         if (ret)
964                 return ret;
965         /* Leave the inode number as 0; this is allowed for non
966          * hard-linked files. */
967         dentry->d_inode->i_resolved = 1;
968         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
969         *dentry_ret = dentry;
970         return 0;
971 }
972
973 static int
974 init_ads_entry(struct wim_ads_entry *ads_entry, const void *name,
975                size_t name_nbytes, bool is_utf16le)
976 {
977         int ret = 0;
978         memset(ads_entry, 0, sizeof(*ads_entry));
979
980         if (is_utf16le) {
981                 utf16lechar *p = MALLOC(name_nbytes + sizeof(utf16lechar));
982                 if (!p)
983                         return WIMLIB_ERR_NOMEM;
984                 memcpy(p, name, name_nbytes);
985                 p[name_nbytes / 2] = cpu_to_le16(0);
986                 ads_entry->stream_name = p;
987                 ads_entry->stream_name_nbytes = name_nbytes;
988         } else {
989                 if (name && *(const tchar*)name != T('\0')) {
990                         ret = get_utf16le_name(name, &ads_entry->stream_name,
991                                                &ads_entry->stream_name_nbytes);
992                 }
993         }
994         return ret;
995 }
996
997 static void
998 destroy_ads_entry(struct wim_ads_entry *ads_entry)
999 {
1000         FREE(ads_entry->stream_name);
1001 }
1002
1003 /* Frees an inode. */
1004 void
1005 free_inode(struct wim_inode *inode)
1006 {
1007         if (inode) {
1008                 if (inode->i_ads_entries) {
1009                         for (u16 i = 0; i < inode->i_num_ads; i++)
1010                                 destroy_ads_entry(&inode->i_ads_entries[i]);
1011                         FREE(inode->i_ads_entries);
1012                 }
1013         #ifdef WITH_FUSE
1014                 wimlib_assert(inode->i_num_opened_fds == 0);
1015                 FREE(inode->i_fds);
1016                 pthread_mutex_destroy(&inode->i_mutex);
1017         #endif
1018                 /* HACK: This may instead delete the inode from i_list, but the
1019                  * hlist_del() behaves the same as list_del(). */
1020                 hlist_del(&inode->i_hlist);
1021                 FREE(inode->i_extracted_file);
1022                 FREE(inode);
1023         }
1024 }
1025
1026 /* Decrements link count on an inode and frees it if the link count reaches 0.
1027  * */
1028 static void
1029 put_inode(struct wim_inode *inode)
1030 {
1031         wimlib_assert(inode->i_nlink != 0);
1032         if (--inode->i_nlink == 0) {
1033         #ifdef WITH_FUSE
1034                 if (inode->i_num_opened_fds == 0)
1035         #endif
1036                 {
1037                         free_inode(inode);
1038                 }
1039         }
1040 }
1041
1042 /* Frees a WIM dentry.
1043  *
1044  * The corresponding inode (if any) is freed only if its link count is
1045  * decremented to 0.
1046  */
1047 void
1048 free_dentry(struct wim_dentry *dentry)
1049 {
1050         if (dentry) {
1051                 FREE(dentry->file_name);
1052                 FREE(dentry->short_name);
1053                 FREE(dentry->_full_path);
1054                 if (dentry->d_inode)
1055                         put_inode(dentry->d_inode);
1056                 FREE(dentry);
1057         }
1058 }
1059
1060 /* This function is passed as an argument to for_dentry_in_tree_depth() in order
1061  * to free a directory tree. */
1062 static int
1063 do_free_dentry(struct wim_dentry *dentry, void *_lookup_table)
1064 {
1065         struct wim_lookup_table *lookup_table = _lookup_table;
1066
1067         if (lookup_table) {
1068                 struct wim_inode *inode = dentry->d_inode;
1069                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1070                         struct wim_lookup_table_entry *lte;
1071
1072                         lte = inode_stream_lte(inode, i, lookup_table);
1073                         if (lte)
1074                                 lte_decrement_refcnt(lte, lookup_table);
1075                 }
1076         }
1077         free_dentry(dentry);
1078         return 0;
1079 }
1080
1081 /*
1082  * Unlinks and frees a dentry tree.
1083  *
1084  * @root:               The root of the tree.
1085  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
1086  *                      reference counts in the lookup table for the lookup
1087  *                      table entries corresponding to the dentries will be
1088  *                      decremented.
1089  */
1090 void
1091 free_dentry_tree(struct wim_dentry *root, struct wim_lookup_table *lookup_table)
1092 {
1093         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1094 }
1095
1096 /*
1097  * Links a dentry into the directory tree.
1098  *
1099  * @parent: The dentry that will be the parent of @child.
1100  * @child: The dentry to link.
1101  *
1102  * Returns NULL if successful.  If @parent already contains a dentry with the
1103  * same case-sensitive name as @child, the pointer to this duplicate dentry is
1104  * returned.
1105  */
1106 struct wim_dentry *
1107 dentry_add_child(struct wim_dentry * restrict parent,
1108                  struct wim_dentry * restrict child)
1109 {
1110         struct rb_root *root;
1111         struct rb_node **new;
1112         struct rb_node *rb_parent;
1113
1114         wimlib_assert(dentry_is_directory(parent));
1115         wimlib_assert(parent != child);
1116
1117         /* Case sensitive child dentry index */
1118         root = &parent->d_inode->i_children;
1119         new = &root->rb_node;
1120         rb_parent = NULL;
1121         while (*new) {
1122                 struct wim_dentry *this = rbnode_dentry(*new);
1123                 int result = dentry_compare_names_case_sensitive(child, this);
1124
1125                 rb_parent = *new;
1126
1127                 if (result < 0)
1128                         new = &((*new)->rb_left);
1129                 else if (result > 0)
1130                         new = &((*new)->rb_right);
1131                 else
1132                         return this;
1133         }
1134         child->parent = parent;
1135         rb_link_node(&child->rb_node, rb_parent, new);
1136         rb_insert_color(&child->rb_node, root);
1137
1138 #ifdef __WIN32__
1139         /* Case insensitive child dentry index */
1140         root = &parent->d_inode->i_children_case_insensitive;
1141         new = &root->rb_node;
1142         rb_parent = NULL;
1143         while (*new) {
1144                 struct wim_dentry *this = container_of(*new, struct wim_dentry,
1145                                                        rb_node_case_insensitive);
1146                 int result = dentry_compare_names_case_insensitive(child, this);
1147
1148                 rb_parent = *new;
1149
1150                 if (result < 0)
1151                         new = &((*new)->rb_left);
1152                 else if (result > 0)
1153                         new = &((*new)->rb_right);
1154                 else {
1155                         list_add(&child->case_insensitive_conflict_list,
1156                                  &this->case_insensitive_conflict_list);
1157                         return NULL;
1158
1159                 }
1160         }
1161         rb_link_node(&child->rb_node_case_insensitive, rb_parent, new);
1162         rb_insert_color(&child->rb_node_case_insensitive, root);
1163         INIT_LIST_HEAD(&child->case_insensitive_conflict_list);
1164 #endif
1165         return NULL;
1166 }
1167
1168 /* Unlink a WIM dentry from the directory entry tree. */
1169 void
1170 unlink_dentry(struct wim_dentry *dentry)
1171 {
1172         if (!dentry_is_root(dentry)) {
1173                 rb_erase(&dentry->rb_node, &dentry->parent->d_inode->i_children);
1174         #ifdef __WIN32__
1175                 rb_erase(&dentry->rb_node_case_insensitive,
1176                          &dentry->parent->d_inode->i_children_case_insensitive);
1177                 list_del(&dentry->case_insensitive_conflict_list);
1178         #endif
1179         }
1180 }
1181
1182 /*
1183  * Returns the alternate data stream entry belonging to @inode that has the
1184  * stream name @stream_name.
1185  */
1186 struct wim_ads_entry *
1187 inode_get_ads_entry(struct wim_inode *inode, const tchar *stream_name,
1188                     u16 *idx_ret)
1189 {
1190         if (inode->i_num_ads == 0) {
1191                 return NULL;
1192         } else {
1193                 size_t stream_name_utf16le_nbytes;
1194                 u16 i;
1195                 struct wim_ads_entry *result;
1196
1197         #if TCHAR_IS_UTF16LE
1198                 const utf16lechar *stream_name_utf16le;
1199
1200                 stream_name_utf16le = stream_name;
1201                 stream_name_utf16le_nbytes = tstrlen(stream_name) * sizeof(tchar);
1202         #else
1203                 utf16lechar *stream_name_utf16le;
1204
1205                 {
1206                         int ret = tstr_to_utf16le(stream_name,
1207                                                   tstrlen(stream_name) *
1208                                                       sizeof(tchar),
1209                                                   &stream_name_utf16le,
1210                                                   &stream_name_utf16le_nbytes);
1211                         if (ret)
1212                                 return NULL;
1213                 }
1214         #endif
1215                 i = 0;
1216                 result = NULL;
1217                 do {
1218                         if (ads_entry_has_name(&inode->i_ads_entries[i],
1219                                                stream_name_utf16le,
1220                                                stream_name_utf16le_nbytes))
1221                         {
1222                                 if (idx_ret)
1223                                         *idx_ret = i;
1224                                 result = &inode->i_ads_entries[i];
1225                                 break;
1226                         }
1227                 } while (++i != inode->i_num_ads);
1228         #if !TCHAR_IS_UTF16LE
1229                 FREE(stream_name_utf16le);
1230         #endif
1231                 return result;
1232         }
1233 }
1234
1235 static struct wim_ads_entry *
1236 do_inode_add_ads(struct wim_inode *inode, const void *stream_name,
1237                  size_t stream_name_nbytes, bool is_utf16le)
1238 {
1239         u16 num_ads;
1240         struct wim_ads_entry *ads_entries;
1241         struct wim_ads_entry *new_entry;
1242
1243         if (inode->i_num_ads >= 0xfffe) {
1244                 ERROR("Too many alternate data streams in one inode!");
1245                 return NULL;
1246         }
1247         num_ads = inode->i_num_ads + 1;
1248         ads_entries = REALLOC(inode->i_ads_entries,
1249                               num_ads * sizeof(inode->i_ads_entries[0]));
1250         if (!ads_entries) {
1251                 ERROR("Failed to allocate memory for new alternate data stream");
1252                 return NULL;
1253         }
1254         inode->i_ads_entries = ads_entries;
1255
1256         new_entry = &inode->i_ads_entries[num_ads - 1];
1257         if (init_ads_entry(new_entry, stream_name, stream_name_nbytes, is_utf16le))
1258                 return NULL;
1259         new_entry->stream_id = inode->i_next_stream_id++;
1260         inode->i_num_ads = num_ads;
1261         return new_entry;
1262 }
1263
1264 struct wim_ads_entry *
1265 inode_add_ads_utf16le(struct wim_inode *inode,
1266                       const utf16lechar *stream_name,
1267                       size_t stream_name_nbytes)
1268 {
1269         DEBUG("Add alternate data stream \"%"WS"\"", stream_name);
1270         return do_inode_add_ads(inode, stream_name, stream_name_nbytes, true);
1271 }
1272
1273 /*
1274  * Add an alternate stream entry to a WIM inode and return a pointer to it, or
1275  * NULL if memory could not be allocated.
1276  */
1277 struct wim_ads_entry *
1278 inode_add_ads(struct wim_inode *inode, const tchar *stream_name)
1279 {
1280         DEBUG("Add alternate data stream \"%"TS"\"", stream_name);
1281         return do_inode_add_ads(inode, stream_name,
1282                                 tstrlen(stream_name) * sizeof(tchar),
1283                                 TCHAR_IS_UTF16LE);
1284 }
1285
1286 static struct wim_lookup_table_entry *
1287 add_stream_from_data_buffer(const void *buffer, size_t size,
1288                             struct wim_lookup_table *lookup_table)
1289 {
1290         u8 hash[SHA1_HASH_SIZE];
1291         struct wim_lookup_table_entry *lte, *existing_lte;
1292
1293         sha1_buffer(buffer, size, hash);
1294         existing_lte = __lookup_resource(lookup_table, hash);
1295         if (existing_lte) {
1296                 wimlib_assert(wim_resource_size(existing_lte) == size);
1297                 lte = existing_lte;
1298                 lte->refcnt++;
1299         } else {
1300                 void *buffer_copy;
1301                 lte = new_lookup_table_entry();
1302                 if (!lte)
1303                         return NULL;
1304                 buffer_copy = memdup(buffer, size);
1305                 if (!buffer_copy) {
1306                         free_lookup_table_entry(lte);
1307                         return NULL;
1308                 }
1309                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1310                 lte->attached_buffer              = buffer_copy;
1311                 lte->resource_entry.original_size = size;
1312                 copy_hash(lte->hash, hash);
1313                 lookup_table_insert(lookup_table, lte);
1314         }
1315         return lte;
1316 }
1317
1318 int
1319 inode_add_ads_with_data(struct wim_inode *inode, const tchar *name,
1320                         const void *value, size_t size,
1321                         struct wim_lookup_table *lookup_table)
1322 {
1323         struct wim_ads_entry *new_ads_entry;
1324
1325         wimlib_assert(inode->i_resolved);
1326
1327         new_ads_entry = inode_add_ads(inode, name);
1328         if (!new_ads_entry)
1329                 return WIMLIB_ERR_NOMEM;
1330
1331         new_ads_entry->lte = add_stream_from_data_buffer(value, size,
1332                                                          lookup_table);
1333         if (!new_ads_entry->lte) {
1334                 inode_remove_ads(inode, new_ads_entry - inode->i_ads_entries,
1335                                  lookup_table);
1336                 return WIMLIB_ERR_NOMEM;
1337         }
1338         return 0;
1339 }
1340
1341 /* Set the unnamed stream of a WIM inode, given a data buffer containing the
1342  * stream contents. */
1343 int
1344 inode_set_unnamed_stream(struct wim_inode *inode, const void *data, size_t len,
1345                          struct wim_lookup_table *lookup_table)
1346 {
1347         inode->i_lte = add_stream_from_data_buffer(data, len, lookup_table);
1348         if (!inode->i_lte)
1349                 return WIMLIB_ERR_NOMEM;
1350         inode->i_resolved = 1;
1351         return 0;
1352 }
1353
1354 /* Remove an alternate data stream from a WIM inode  */
1355 void
1356 inode_remove_ads(struct wim_inode *inode, u16 idx,
1357                  struct wim_lookup_table *lookup_table)
1358 {
1359         struct wim_ads_entry *ads_entry;
1360         struct wim_lookup_table_entry *lte;
1361
1362         wimlib_assert(idx < inode->i_num_ads);
1363         wimlib_assert(inode->i_resolved);
1364
1365         ads_entry = &inode->i_ads_entries[idx];
1366
1367         DEBUG("Remove alternate data stream \"%"WS"\"", ads_entry->stream_name);
1368
1369         lte = ads_entry->lte;
1370         if (lte)
1371                 lte_decrement_refcnt(lte, lookup_table);
1372
1373         destroy_ads_entry(ads_entry);
1374
1375         memmove(&inode->i_ads_entries[idx],
1376                 &inode->i_ads_entries[idx + 1],
1377                 (inode->i_num_ads - idx - 1) * sizeof(inode->i_ads_entries[0]));
1378         inode->i_num_ads--;
1379 }
1380
1381 #ifndef __WIN32__
1382 int
1383 inode_get_unix_data(const struct wim_inode *inode,
1384                     struct wimlib_unix_data *unix_data,
1385                     u16 *stream_idx_ret)
1386 {
1387         const struct wim_ads_entry *ads_entry;
1388         const struct wim_lookup_table_entry *lte;
1389         size_t size;
1390         int ret;
1391
1392         wimlib_assert(inode->i_resolved);
1393
1394         ads_entry = inode_get_ads_entry((struct wim_inode*)inode,
1395                                         WIMLIB_UNIX_DATA_TAG, NULL);
1396         if (!ads_entry)
1397                 return NO_UNIX_DATA;
1398
1399         if (stream_idx_ret)
1400                 *stream_idx_ret = ads_entry - inode->i_ads_entries;
1401
1402         lte = ads_entry->lte;
1403         if (!lte)
1404                 return NO_UNIX_DATA;
1405
1406         size = wim_resource_size(lte);
1407         if (size != sizeof(struct wimlib_unix_data))
1408                 return BAD_UNIX_DATA;
1409
1410         ret = read_full_resource_into_buf(lte, unix_data);
1411         if (ret)
1412                 return ret;
1413
1414         if (unix_data->version != 0)
1415                 return BAD_UNIX_DATA;
1416         return 0;
1417 }
1418
1419 int
1420 inode_set_unix_data(struct wim_inode *inode, uid_t uid, gid_t gid, mode_t mode,
1421                     struct wim_lookup_table *lookup_table, int which)
1422 {
1423         struct wimlib_unix_data unix_data;
1424         int ret;
1425         bool have_good_unix_data = false;
1426         bool have_unix_data = false;
1427         u16 stream_idx;
1428
1429         if (!(which & UNIX_DATA_CREATE)) {
1430                 ret = inode_get_unix_data(inode, &unix_data, &stream_idx);
1431                 if (ret == 0 || ret == BAD_UNIX_DATA || ret > 0)
1432                         have_unix_data = true;
1433                 if (ret == 0)
1434                         have_good_unix_data = true;
1435         }
1436         unix_data.version = 0;
1437         if (which & UNIX_DATA_UID || !have_good_unix_data)
1438                 unix_data.uid = uid;
1439         if (which & UNIX_DATA_GID || !have_good_unix_data)
1440                 unix_data.gid = gid;
1441         if (which & UNIX_DATA_MODE || !have_good_unix_data)
1442                 unix_data.mode = mode;
1443         ret = inode_add_ads_with_data(inode, WIMLIB_UNIX_DATA_TAG,
1444                                       &unix_data,
1445                                       sizeof(struct wimlib_unix_data),
1446                                       lookup_table);
1447         if (ret == 0 && have_unix_data)
1448                 inode_remove_ads(inode, stream_idx, lookup_table);
1449         return ret;
1450 }
1451 #endif /* !__WIN32__ */
1452
1453 /*
1454  * Reads the alternate data stream entries of a WIM dentry.
1455  *
1456  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1457  *
1458  * @inode:      Inode to load the alternate data streams into.
1459  *              @inode->i_num_ads must have been set to the number of
1460  *              alternate data streams that are expected.
1461  *
1462  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1463  *                      to by @p.
1464  *
1465  *
1466  * Return 0 on success or nonzero on failure.  On success, inode->i_ads_entries
1467  * is set to an array of `struct wim_ads_entry's of length inode->i_num_ads.  On
1468  * failure, @inode is not modified.
1469  */
1470 static int
1471 read_ads_entries(const u8 * restrict p, struct wim_inode * restrict inode,
1472                  size_t nbytes_remaining)
1473 {
1474         u16 num_ads;
1475         struct wim_ads_entry *ads_entries;
1476         int ret;
1477
1478         BUILD_BUG_ON(sizeof(struct wim_ads_entry_on_disk) != WIM_ADS_ENTRY_DISK_SIZE);
1479
1480         /* Allocate an array for our in-memory representation of the alternate
1481          * data stream entries. */
1482         num_ads = inode->i_num_ads;
1483         ads_entries = CALLOC(num_ads, sizeof(inode->i_ads_entries[0]));
1484         if (!ads_entries)
1485                 goto out_of_memory;
1486
1487         /* Read the entries into our newly allocated buffer. */
1488         for (u16 i = 0; i < num_ads; i++) {
1489                 u64 length;
1490                 struct wim_ads_entry *cur_entry;
1491                 const struct wim_ads_entry_on_disk *disk_entry =
1492                         (const struct wim_ads_entry_on_disk*)p;
1493
1494                 cur_entry = &ads_entries[i];
1495                 ads_entries[i].stream_id = i + 1;
1496
1497                 /* Do we have at least the size of the fixed-length data we know
1498                  * need? */
1499                 if (nbytes_remaining < sizeof(struct wim_ads_entry_on_disk))
1500                         goto out_invalid;
1501
1502                 /* Read the length field */
1503                 length = le64_to_cpu(disk_entry->length);
1504
1505                 /* Make sure the length field is neither so small it doesn't
1506                  * include all the fixed-length data nor so large it overflows
1507                  * the metadata resource buffer. */
1508                 if (length < sizeof(struct wim_ads_entry_on_disk) ||
1509                     length > nbytes_remaining)
1510                         goto out_invalid;
1511
1512                 /* Read the rest of the fixed-length data. */
1513
1514                 cur_entry->reserved = le64_to_cpu(disk_entry->reserved);
1515                 copy_hash(cur_entry->hash, disk_entry->hash);
1516                 cur_entry->stream_name_nbytes = le16_to_cpu(disk_entry->stream_name_nbytes);
1517
1518                 /* If stream_name_nbytes != 0, this is a named stream.
1519                  * Otherwise this is an unnamed stream, or in some cases (bugs
1520                  * in Microsoft's software I guess) a meaningless entry
1521                  * distinguished from the real unnamed stream entry, if any, by
1522                  * the fact that the real unnamed stream entry has a nonzero
1523                  * hash field. */
1524                 if (cur_entry->stream_name_nbytes) {
1525                         /* The name is encoded in UTF16-LE, which uses 2-byte
1526                          * coding units, so the length of the name had better be
1527                          * an even number of bytes... */
1528                         if (cur_entry->stream_name_nbytes & 1)
1529                                 goto out_invalid;
1530
1531                         /* Add the length of the stream name to get the length
1532                          * we actually need to read.  Make sure this isn't more
1533                          * than the specified length of the entry. */
1534                         if (sizeof(struct wim_ads_entry_on_disk) +
1535                             cur_entry->stream_name_nbytes > length)
1536                                 goto out_invalid;
1537
1538                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_nbytes + 2);
1539                         if (!cur_entry->stream_name)
1540                                 goto out_of_memory;
1541
1542                         memcpy(cur_entry->stream_name,
1543                                disk_entry->stream_name,
1544                                cur_entry->stream_name_nbytes);
1545                         cur_entry->stream_name[cur_entry->stream_name_nbytes / 2] = cpu_to_le16(0);
1546                 }
1547
1548                 /* It's expected that the size of every ADS entry is a multiple
1549                  * of 8.  However, to be safe, I'm allowing the possibility of
1550                  * an ADS entry at the very end of the metadata resource ending
1551                  * un-aligned.  So although we still need to increment the input
1552                  * pointer by @length to reach the next ADS entry, it's possible
1553                  * that less than @length is actually remaining in the metadata
1554                  * resource. We should set the remaining bytes to 0 if this
1555                  * happens. */
1556                 length = (length + 7) & ~(u64)7;
1557                 p += length;
1558                 if (nbytes_remaining < length)
1559                         nbytes_remaining = 0;
1560                 else
1561                         nbytes_remaining -= length;
1562         }
1563         inode->i_ads_entries = ads_entries;
1564         inode->i_next_stream_id = inode->i_num_ads + 1;
1565         ret = 0;
1566         goto out;
1567 out_of_memory:
1568         ret = WIMLIB_ERR_NOMEM;
1569         goto out_free_ads_entries;
1570 out_invalid:
1571         ERROR("An alternate data stream entry is invalid");
1572         ret = WIMLIB_ERR_INVALID_DENTRY;
1573 out_free_ads_entries:
1574         if (ads_entries) {
1575                 for (u16 i = 0; i < num_ads; i++)
1576                         destroy_ads_entry(&ads_entries[i]);
1577                 FREE(ads_entries);
1578         }
1579 out:
1580         return ret;
1581 }
1582
1583 /*
1584  * Reads a WIM directory entry, including all alternate data stream entries that
1585  * follow it, from the WIM image's metadata resource.
1586  *
1587  * @metadata_resource:
1588  *              Pointer to the metadata resource buffer.
1589  *
1590  * @metadata_resource_len:
1591  *              Length of the metadata resource buffer, in bytes.
1592  *
1593  * @offset:     Offset of the dentry within the metadata resource.
1594  *
1595  * @dentry:     A `struct wim_dentry' that will be filled in by this function.
1596  *
1597  * Return 0 on success or nonzero on failure.  On failure, @dentry will have
1598  * been modified, but it will not be left with pointers to any allocated
1599  * buffers.  On success, the dentry->length field must be examined.  If zero,
1600  * this was a special "end of directory" dentry and not a real dentry.  If
1601  * nonzero, this was a real dentry.
1602  *
1603  * Possible errors include:
1604  *      WIMLIB_ERR_NOMEM
1605  *      WIMLIB_ERR_INVALID_DENTRY
1606  */
1607 int
1608 read_dentry(const u8 * restrict metadata_resource, u64 metadata_resource_len,
1609             u64 offset, struct wim_dentry * restrict dentry)
1610 {
1611
1612         u64 calculated_size;
1613         utf16lechar *file_name;
1614         utf16lechar *short_name;
1615         u16 short_name_nbytes;
1616         u16 file_name_nbytes;
1617         int ret;
1618         struct wim_inode *inode;
1619         const u8 *p = &metadata_resource[offset];
1620         const struct wim_dentry_on_disk *disk_dentry =
1621                         (const struct wim_dentry_on_disk*)p;
1622
1623         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1624
1625         if ((uintptr_t)p & 7)
1626                 WARNING("WIM dentry is not 8-byte aligned");
1627
1628         dentry_common_init(dentry);
1629
1630         /* Before reading the whole dentry, we need to read just the length.
1631          * This is because a dentry of length 8 (that is, just the length field)
1632          * terminates the list of sibling directory entries. */
1633         if (offset + sizeof(u64) > metadata_resource_len ||
1634             offset + sizeof(u64) < offset)
1635         {
1636                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1637                       "end of the metadata resource (size %"PRIu64")",
1638                       offset, metadata_resource_len);
1639                 return WIMLIB_ERR_INVALID_DENTRY;
1640         }
1641         dentry->length = le64_to_cpu(disk_dentry->length);
1642
1643         /* A zero length field (really a length of 8, since that's how big the
1644          * directory entry is...) indicates that this is the end of directory
1645          * dentry.  We do not read it into memory as an actual dentry, so just
1646          * return successfully in this case. */
1647         if (dentry->length == 8)
1648                 dentry->length = 0;
1649         if (dentry->length == 0)
1650                 return 0;
1651
1652         /* Now that we have the actual length provided in the on-disk structure,
1653          * again make sure it doesn't overflow the metadata resource buffer. */
1654         if (offset + dentry->length > metadata_resource_len ||
1655             offset + dentry->length < offset)
1656         {
1657                 ERROR("Directory entry at offset %"PRIu64" and with size "
1658                       "%"PRIu64" ends past the end of the metadata resource "
1659                       "(size %"PRIu64")",
1660                       offset, dentry->length, metadata_resource_len);
1661                 return WIMLIB_ERR_INVALID_DENTRY;
1662         }
1663
1664         /* Make sure the dentry length is at least as large as the number of
1665          * fixed-length fields */
1666         if (dentry->length < sizeof(struct wim_dentry_on_disk)) {
1667                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1668                       dentry->length);
1669                 return WIMLIB_ERR_INVALID_DENTRY;
1670         }
1671
1672         /* Allocate a `struct wim_inode' for this `struct wim_dentry'. */
1673         inode = new_timeless_inode();
1674         if (!inode)
1675                 return WIMLIB_ERR_NOMEM;
1676
1677         /* Read more fields; some into the dentry, and some into the inode. */
1678
1679         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1680         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1681         dentry->subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1682         dentry->d_unused_1 = le64_to_cpu(disk_dentry->unused_1);
1683         dentry->d_unused_2 = le64_to_cpu(disk_dentry->unused_2);
1684         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1685         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1686         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1687         copy_hash(inode->i_hash, disk_dentry->unnamed_stream_hash);
1688
1689         /* I don't know what's going on here.  It seems like M$ screwed up the
1690          * reparse points, then put the fields in the same place and didn't
1691          * document it.  So we have some fields we read for reparse points, and
1692          * some fields in the same place for non-reparse-point.s */
1693         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1694                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->reparse.rp_unknown_1);
1695                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
1696                 inode->i_rp_unknown_2 = le16_to_cpu(disk_dentry->reparse.rp_unknown_2);
1697                 inode->i_not_rpfixed = le16_to_cpu(disk_dentry->reparse.not_rpfixed);
1698                 /* Leave inode->i_ino at 0.  Note that this means the WIM file
1699                  * cannot archive hard-linked reparse points.  Such a thing
1700                  * doesn't really make sense anyway, although I believe it's
1701                  * theoretically possible to have them on NTFS. */
1702         } else {
1703                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->nonreparse.rp_unknown_1);
1704                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
1705         }
1706
1707         inode->i_num_ads = le16_to_cpu(disk_dentry->num_alternate_data_streams);
1708
1709         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
1710         file_name_nbytes = le16_to_cpu(disk_dentry->file_name_nbytes);
1711
1712         if ((short_name_nbytes & 1) | (file_name_nbytes & 1))
1713         {
1714                 ERROR("Dentry name is not valid UTF-16LE (odd number of bytes)!");
1715                 ret = WIMLIB_ERR_INVALID_DENTRY;
1716                 goto out_free_inode;
1717         }
1718
1719         /* We now know the length of the file name and short name.  Make sure
1720          * the length of the dentry is large enough to actually hold them.
1721          *
1722          * The calculated length here is unaligned to allow for the possibility
1723          * that the dentry->length names an unaligned length, although this
1724          * would be unexpected. */
1725         calculated_size = _dentry_correct_length_unaligned(file_name_nbytes,
1726                                                            short_name_nbytes);
1727
1728         if (dentry->length < calculated_size) {
1729                 ERROR("Unexpected end of directory entry! (Expected "
1730                       "at least %"PRIu64" bytes, got %"PRIu64" bytes.)",
1731                       calculated_size, dentry->length);
1732                 ret = WIMLIB_ERR_INVALID_DENTRY;
1733                 goto out_free_inode;
1734         }
1735
1736         p += sizeof(struct wim_dentry_on_disk);
1737
1738         /* Read the filename if present.  Note: if the filename is empty, there
1739          * is no null terminator following it. */
1740         if (file_name_nbytes) {
1741                 file_name = MALLOC(file_name_nbytes + 2);
1742                 if (!file_name) {
1743                         ERROR("Failed to allocate %d bytes for dentry file name",
1744                               file_name_nbytes + 2);
1745                         ret = WIMLIB_ERR_NOMEM;
1746                         goto out_free_inode;
1747                 }
1748                 memcpy(file_name, p, file_name_nbytes);
1749                 p += file_name_nbytes + 2;
1750                 file_name[file_name_nbytes / 2] = cpu_to_le16(0);
1751         } else {
1752                 file_name = NULL;
1753         }
1754
1755
1756         /* Read the short filename if present.  Note: if there is no short
1757          * filename, there is no null terminator following it. */
1758         if (short_name_nbytes) {
1759                 short_name = MALLOC(short_name_nbytes + 2);
1760                 if (!short_name) {
1761                         ERROR("Failed to allocate %d bytes for dentry short name",
1762                               short_name_nbytes + 2);
1763                         ret = WIMLIB_ERR_NOMEM;
1764                         goto out_free_file_name;
1765                 }
1766                 memcpy(short_name, p, short_name_nbytes);
1767                 p += short_name_nbytes + 2;
1768                 short_name[short_name_nbytes / 2] = cpu_to_le16(0);
1769         } else {
1770                 short_name = NULL;
1771         }
1772
1773         /* Align the dentry length */
1774         dentry->length = (dentry->length + 7) & ~7;
1775
1776         /*
1777          * Read the alternate data streams, if present.  dentry->num_ads tells
1778          * us how many they are, and they will directly follow the dentry
1779          * on-disk.
1780          *
1781          * Note that each alternate data stream entry begins on an 8-byte
1782          * aligned boundary, and the alternate data stream entries seem to NOT
1783          * be included in the dentry->length field for some reason.
1784          */
1785         if (inode->i_num_ads != 0) {
1786                 ret = WIMLIB_ERR_INVALID_DENTRY;
1787                 if (offset + dentry->length > metadata_resource_len ||
1788                     (ret = read_ads_entries(&metadata_resource[offset + dentry->length],
1789                                             inode,
1790                                             metadata_resource_len - offset - dentry->length)))
1791                 {
1792                         ERROR("Failed to read alternate data stream "
1793                               "entries of WIM dentry \"%"WS"\"", file_name);
1794                         goto out_free_short_name;
1795                 }
1796         }
1797         /* We've read all the data for this dentry.  Set the names and their
1798          * lengths, and we've done. */
1799         dentry->d_inode           = inode;
1800         dentry->file_name         = file_name;
1801         dentry->short_name        = short_name;
1802         dentry->file_name_nbytes  = file_name_nbytes;
1803         dentry->short_name_nbytes = short_name_nbytes;
1804         ret = 0;
1805         goto out;
1806 out_free_short_name:
1807         FREE(short_name);
1808 out_free_file_name:
1809         FREE(file_name);
1810 out_free_inode:
1811         free_inode(inode);
1812 out:
1813         return ret;
1814 }
1815
1816 static const tchar *
1817 dentry_get_file_type_string(const struct wim_dentry *dentry)
1818 {
1819         const struct wim_inode *inode = dentry->d_inode;
1820         if (inode_is_directory(inode))
1821                 return T("directory");
1822         else if (inode_is_symlink(inode))
1823                 return T("symbolic link");
1824         else
1825                 return T("file");
1826 }
1827
1828 /* Reads the children of a dentry, and all their children, ..., etc. from the
1829  * metadata resource and into the dentry tree.
1830  *
1831  * @metadata_resource:  An array that contains the uncompressed metadata
1832  *                      resource for the WIM file.
1833  *
1834  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1835  *                          bytes.
1836  *
1837  * @dentry:     A pointer to a `struct wim_dentry' that is the root of the directory
1838  *              tree and has already been read from the metadata resource.  It
1839  *              does not need to be the real root because this procedure is
1840  *              called recursively.
1841  *
1842  * Returns zero on success; nonzero on failure.
1843  */
1844 int
1845 read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1846                  struct wim_dentry *dentry)
1847 {
1848         u64 cur_offset = dentry->subdir_offset;
1849         struct wim_dentry *child;
1850         struct wim_dentry *duplicate;
1851         struct wim_dentry cur_child;
1852         int ret;
1853
1854         /*
1855          * If @dentry has no child dentries, nothing more needs to be done for
1856          * this branch.  This is the case for regular files, symbolic links, and
1857          * *possibly* empty directories (although an empty directory may also
1858          * have one child dentry that is the special end-of-directory dentry)
1859          */
1860         if (cur_offset == 0)
1861                 return 0;
1862
1863         /* Find and read all the children of @dentry. */
1864         for (;;) {
1865
1866                 /* Read next child of @dentry into @cur_child. */
1867                 ret = read_dentry(metadata_resource, metadata_resource_len,
1868                                   cur_offset, &cur_child);
1869                 if (ret)
1870                         break;
1871
1872                 /* Check for end of directory. */
1873                 if (cur_child.length == 0)
1874                         break;
1875
1876                 /* Not end of directory.  Allocate this child permanently and
1877                  * link it to the parent and previous child. */
1878                 child = memdup(&cur_child, sizeof(struct wim_dentry));
1879                 if (!child) {
1880                         ERROR("Failed to allocate new dentry!");
1881                         ret = WIMLIB_ERR_NOMEM;
1882                         break;
1883                 }
1884
1885                 /* Advance to the offset of the next child.  Note: We need to
1886                  * advance by the TOTAL length of the dentry, not by the length
1887                  * cur_child.length, which although it does take into account
1888                  * the padding, it DOES NOT take into account alternate stream
1889                  * entries. */
1890                 cur_offset += dentry_total_length(child);
1891
1892                 duplicate = dentry_add_child(dentry, child);
1893                 if (duplicate) {
1894                         const tchar *child_type, *duplicate_type;
1895                         child_type = dentry_get_file_type_string(child);
1896                         duplicate_type = dentry_get_file_type_string(duplicate);
1897                         WARNING("Ignoring duplicate %"TS" \"%"TS"\" "
1898                                 "(the WIM image already contains a %"TS" "
1899                                 "at that path with the exact same name)",
1900                                 child_type, dentry_full_path(duplicate),
1901                                 duplicate_type);
1902                 } else {
1903                         inode_add_dentry(child, child->d_inode);
1904                         /* If there are children of this child, call this
1905                          * procedure recursively. */
1906                         if (child->subdir_offset != 0) {
1907                                 if (dentry_is_directory(child)) {
1908                                         ret = read_dentry_tree(metadata_resource,
1909                                                                metadata_resource_len,
1910                                                                child);
1911                                         if (ret)
1912                                                 break;
1913                                 } else {
1914                                         WARNING("Ignoring children of non-directory \"%"TS"\"",
1915                                                 dentry_full_path(child));
1916                                 }
1917                         }
1918
1919                 }
1920         }
1921         return ret;
1922 }
1923
1924 /*
1925  * Writes a WIM dentry to an output buffer.
1926  *
1927  * @dentry:  The dentry structure.
1928  * @p:       The memory location to write the data to.
1929  *
1930  * Returns the pointer to the byte after the last byte we wrote as part of the
1931  * dentry, including any alternate data stream entries.
1932  */
1933 static u8 *
1934 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
1935 {
1936         const struct wim_inode *inode;
1937         struct wim_dentry_on_disk *disk_dentry;
1938         const u8 *orig_p;
1939         const u8 *hash;
1940
1941         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
1942         orig_p = p;
1943
1944         inode = dentry->d_inode;
1945         disk_dentry = (struct wim_dentry_on_disk*)p;
1946
1947         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
1948         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
1949         disk_dentry->subdir_offset = cpu_to_le64(dentry->subdir_offset);
1950         disk_dentry->unused_1 = cpu_to_le64(dentry->d_unused_1);
1951         disk_dentry->unused_2 = cpu_to_le64(dentry->d_unused_2);
1952         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
1953         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
1954         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
1955         hash = inode_stream_hash(inode, 0);
1956         copy_hash(disk_dentry->unnamed_stream_hash, hash);
1957         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1958                 disk_dentry->reparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1959                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
1960                 disk_dentry->reparse.rp_unknown_2 = cpu_to_le16(inode->i_rp_unknown_2);
1961                 disk_dentry->reparse.not_rpfixed = cpu_to_le16(inode->i_not_rpfixed);
1962         } else {
1963                 disk_dentry->nonreparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1964                 disk_dentry->nonreparse.hard_link_group_id =
1965                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
1966         }
1967         disk_dentry->num_alternate_data_streams = cpu_to_le16(inode->i_num_ads);
1968         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->short_name_nbytes);
1969         disk_dentry->file_name_nbytes = cpu_to_le16(dentry->file_name_nbytes);
1970         p += sizeof(struct wim_dentry_on_disk);
1971
1972         if (dentry_has_long_name(dentry))
1973                 p = mempcpy(p, dentry->file_name, dentry->file_name_nbytes + 2);
1974
1975         if (dentry_has_short_name(dentry))
1976                 p = mempcpy(p, dentry->short_name, dentry->short_name_nbytes + 2);
1977
1978         /* Align to 8-byte boundary */
1979         while ((uintptr_t)p & 7)
1980                 *p++ = 0;
1981
1982         /* We calculate the correct length of the dentry ourselves because the
1983          * dentry->length field may been set to an unexpected value from when we
1984          * read the dentry in (for example, there may have been unknown data
1985          * appended to the end of the dentry...).  Furthermore, the dentry may
1986          * have been renamed, thus changing its needed length. */
1987         disk_dentry->length = cpu_to_le64(p - orig_p);
1988
1989         /* Write the alternate data streams entries, if any. */
1990         for (u16 i = 0; i < inode->i_num_ads; i++) {
1991                 const struct wim_ads_entry *ads_entry =
1992                                 &inode->i_ads_entries[i];
1993                 struct wim_ads_entry_on_disk *disk_ads_entry =
1994                                 (struct wim_ads_entry_on_disk*)p;
1995                 orig_p = p;
1996
1997                 disk_ads_entry->reserved = cpu_to_le64(ads_entry->reserved);
1998
1999                 hash = inode_stream_hash(inode, i + 1);
2000                 copy_hash(disk_ads_entry->hash, hash);
2001                 disk_ads_entry->stream_name_nbytes = cpu_to_le16(ads_entry->stream_name_nbytes);
2002                 p += sizeof(struct wim_ads_entry_on_disk);
2003                 if (ads_entry->stream_name_nbytes) {
2004                         p = mempcpy(p, ads_entry->stream_name,
2005                                     ads_entry->stream_name_nbytes + 2);
2006                 }
2007                 /* Align to 8-byte boundary */
2008                 while ((uintptr_t)p & 7)
2009                         *p++ = 0;
2010                 disk_ads_entry->length = cpu_to_le64(p - orig_p);
2011         }
2012         return p;
2013 }
2014
2015 static int
2016 write_dentry_cb(struct wim_dentry *dentry, void *_p)
2017 {
2018         u8 **p = _p;
2019         *p = write_dentry(dentry, *p);
2020         return 0;
2021 }
2022
2023 static u8 *
2024 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p);
2025
2026 static int
2027 write_dentry_tree_recursive_cb(struct wim_dentry *dentry, void *_p)
2028 {
2029         u8 **p = _p;
2030         *p = write_dentry_tree_recursive(dentry, *p);
2031         return 0;
2032 }
2033
2034 /* Recursive function that writes a dentry tree rooted at @parent, not including
2035  * @parent itself, which has already been written. */
2036 static u8 *
2037 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p)
2038 {
2039         /* Nothing to do if this dentry has no children. */
2040         if (parent->subdir_offset == 0)
2041                 return p;
2042
2043         /* Write child dentries and end-of-directory entry.
2044          *
2045          * Note: we need to write all of this dentry's children before
2046          * recursively writing the directory trees rooted at each of the child
2047          * dentries, since the on-disk dentries for a dentry's children are
2048          * always located at consecutive positions in the metadata resource! */
2049         for_dentry_child(parent, write_dentry_cb, &p);
2050
2051         /* write end of directory entry */
2052         *(le64*)p = cpu_to_le64(0);
2053         p += 8;
2054
2055         /* Recurse on children. */
2056         for_dentry_child(parent, write_dentry_tree_recursive_cb, &p);
2057         return p;
2058 }
2059
2060 /* Writes a directory tree to the metadata resource.
2061  *
2062  * @root:       Root of the dentry tree.
2063  * @p:          Pointer to a buffer with enough space for the dentry tree.
2064  *
2065  * Returns pointer to the byte after the last byte we wrote.
2066  */
2067 u8 *
2068 write_dentry_tree(const struct wim_dentry *root, u8 *p)
2069 {
2070         DEBUG("Writing dentry tree.");
2071         wimlib_assert(dentry_is_root(root));
2072
2073         /* If we're the root dentry, we have no parent that already
2074          * wrote us, so we need to write ourselves. */
2075         p = write_dentry(root, p);
2076
2077         /* Write end of directory entry after the root dentry just to be safe;
2078          * however the root dentry obviously cannot have any siblings. */
2079         *(le64*)p = cpu_to_le64(0);
2080         p += 8;
2081
2082         /* Recursively write the rest of the dentry tree. */
2083         return write_dentry_tree_recursive(root, p);
2084 }