d93d8ac739af64a8254b994fc078b227aaac14d4
[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 static 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                         return child;
594         }
595         return NULL;
596 }
597
598 /* Returns the child of @dentry that has the file name @name.  Returns NULL if
599  * no child has the name. */
600 struct wim_dentry *
601 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name)
602 {
603 #if TCHAR_IS_UTF16LE
604         return get_dentry_child_with_utf16le_name(dentry, name,
605                                                   tstrlen(name) * sizeof(tchar));
606 #else
607         utf16lechar *utf16le_name;
608         size_t utf16le_name_nbytes;
609         int ret;
610         struct wim_dentry *child;
611
612         ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
613                               &utf16le_name, &utf16le_name_nbytes);
614         if (ret) {
615                 child = NULL;
616         } else {
617                 child = get_dentry_child_with_utf16le_name(dentry,
618                                                            utf16le_name,
619                                                            utf16le_name_nbytes);
620                 FREE(utf16le_name);
621         }
622         return child;
623 #endif
624 }
625
626 static struct wim_dentry *
627 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path)
628 {
629         struct wim_dentry *cur_dentry, *parent_dentry;
630         const utf16lechar *p, *pp;
631
632         cur_dentry = parent_dentry = wim_root_dentry(wim);
633         if (!cur_dentry) {
634                 errno = ENOENT;
635                 return NULL;
636         }
637         p = path;
638         while (1) {
639                 while (*p == cpu_to_le16('/'))
640                         p++;
641                 if (*p == cpu_to_le16('\0'))
642                         break;
643                 pp = p;
644                 while (*pp != cpu_to_le16('/') && *pp != cpu_to_le16('\0'))
645                         pp++;
646
647                 cur_dentry = get_dentry_child_with_utf16le_name(parent_dentry, p,
648                                                                 (void*)pp - (void*)p);
649                 if (cur_dentry == NULL)
650                         break;
651                 p = pp;
652                 parent_dentry = cur_dentry;
653         }
654         if (cur_dentry == NULL) {
655                 if (dentry_is_directory(parent_dentry))
656                         errno = ENOENT;
657                 else
658                         errno = ENOTDIR;
659         }
660         return cur_dentry;
661 }
662
663 /* Returns the dentry corresponding to the @path, or NULL if there is no such
664  * dentry. */
665 struct wim_dentry *
666 get_dentry(WIMStruct *wim, const tchar *path)
667 {
668 #if TCHAR_IS_UTF16LE
669         return get_dentry_utf16le(wim, path);
670 #else
671         utf16lechar *path_utf16le;
672         size_t path_utf16le_nbytes;
673         int ret;
674         struct wim_dentry *dentry;
675
676         ret = tstr_to_utf16le(path, tstrlen(path) * sizeof(tchar),
677                               &path_utf16le, &path_utf16le_nbytes);
678         if (ret)
679                 return NULL;
680         dentry = get_dentry_utf16le(wim, path_utf16le);
681         FREE(path_utf16le);
682         return dentry;
683 #endif
684 }
685
686 struct wim_inode *
687 wim_pathname_to_inode(WIMStruct *wim, const tchar *path)
688 {
689         struct wim_dentry *dentry;
690         dentry = get_dentry(wim, path);
691         if (dentry)
692                 return dentry->d_inode;
693         else
694                 return NULL;
695 }
696
697 /* Takes in a path of length @len in @buf, and transforms it into a string for
698  * the path of its parent directory. */
699 static void
700 to_parent_name(tchar *buf, size_t len)
701 {
702         ssize_t i = (ssize_t)len - 1;
703         while (i >= 0 && buf[i] == T('/'))
704                 i--;
705         while (i >= 0 && buf[i] != T('/'))
706                 i--;
707         while (i >= 0 && buf[i] == T('/'))
708                 i--;
709         buf[i + 1] = T('\0');
710 }
711
712 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
713  * if the dentry is not found. */
714 struct wim_dentry *
715 get_parent_dentry(WIMStruct *wim, const tchar *path)
716 {
717         size_t path_len = tstrlen(path);
718         tchar buf[path_len + 1];
719
720         tmemcpy(buf, path, path_len + 1);
721         to_parent_name(buf, path_len);
722         return get_dentry(wim, buf);
723 }
724
725 /* Prints the full path of a dentry. */
726 int
727 print_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
728 {
729         int ret = calculate_dentry_full_path(dentry);
730         if (ret)
731                 return ret;
732         tprintf(T("%"TS"\n"), dentry->_full_path);
733         return 0;
734 }
735
736 /* We want to be able to show the names of the file attribute flags that are
737  * set. */
738 struct file_attr_flag {
739         u32 flag;
740         const tchar *name;
741 };
742 struct file_attr_flag file_attr_flags[] = {
743         {FILE_ATTRIBUTE_READONLY,           T("READONLY")},
744         {FILE_ATTRIBUTE_HIDDEN,             T("HIDDEN")},
745         {FILE_ATTRIBUTE_SYSTEM,             T("SYSTEM")},
746         {FILE_ATTRIBUTE_DIRECTORY,          T("DIRECTORY")},
747         {FILE_ATTRIBUTE_ARCHIVE,            T("ARCHIVE")},
748         {FILE_ATTRIBUTE_DEVICE,             T("DEVICE")},
749         {FILE_ATTRIBUTE_NORMAL,             T("NORMAL")},
750         {FILE_ATTRIBUTE_TEMPORARY,          T("TEMPORARY")},
751         {FILE_ATTRIBUTE_SPARSE_FILE,        T("SPARSE_FILE")},
752         {FILE_ATTRIBUTE_REPARSE_POINT,      T("REPARSE_POINT")},
753         {FILE_ATTRIBUTE_COMPRESSED,         T("COMPRESSED")},
754         {FILE_ATTRIBUTE_OFFLINE,            T("OFFLINE")},
755         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,T("NOT_CONTENT_INDEXED")},
756         {FILE_ATTRIBUTE_ENCRYPTED,          T("ENCRYPTED")},
757         {FILE_ATTRIBUTE_VIRTUAL,            T("VIRTUAL")},
758 };
759
760 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
761  * available.  If the dentry is unresolved and the lookup table is NULL, the
762  * lookup table entries will not be printed.  Otherwise, they will be. */
763 int
764 print_dentry(struct wim_dentry *dentry, void *lookup_table)
765 {
766         const u8 *hash;
767         struct wim_lookup_table_entry *lte;
768         const struct wim_inode *inode = dentry->d_inode;
769         tchar buf[50];
770
771         tprintf(T("[DENTRY]\n"));
772         tprintf(T("Length            = %"PRIu64"\n"), dentry->length);
773         tprintf(T("Attributes        = 0x%x\n"), inode->i_attributes);
774         for (size_t i = 0; i < ARRAY_LEN(file_attr_flags); i++)
775                 if (file_attr_flags[i].flag & inode->i_attributes)
776                         tprintf(T("    FILE_ATTRIBUTE_%"TS" is set\n"),
777                                 file_attr_flags[i].name);
778         tprintf(T("Security ID       = %d\n"), inode->i_security_id);
779         tprintf(T("Subdir offset     = %"PRIu64"\n"), dentry->subdir_offset);
780
781         wim_timestamp_to_str(inode->i_creation_time, buf, sizeof(buf));
782         tprintf(T("Creation Time     = %"TS"\n"), buf);
783
784         wim_timestamp_to_str(inode->i_last_access_time, buf, sizeof(buf));
785         tprintf(T("Last Access Time  = %"TS"\n"), buf);
786
787         wim_timestamp_to_str(inode->i_last_write_time, buf, sizeof(buf));
788         tprintf(T("Last Write Time   = %"TS"\n"), buf);
789
790         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
791                 tprintf(T("Reparse Tag       = 0x%"PRIx32"\n"), inode->i_reparse_tag);
792                 tprintf(T("Reparse Point Flags = 0x%"PRIx16"\n"),
793                         inode->i_not_rpfixed);
794                 tprintf(T("Reparse Point Unknown 2 = 0x%"PRIx32"\n"),
795                         inode->i_rp_unknown_2);
796         }
797         tprintf(T("Reparse Point Unknown 1 = 0x%"PRIx32"\n"),
798                 inode->i_rp_unknown_1);
799         tprintf(T("Hard Link Group   = 0x%"PRIx64"\n"), inode->i_ino);
800         tprintf(T("Hard Link Group Size = %"PRIu32"\n"), inode->i_nlink);
801         tprintf(T("Number of Alternate Data Streams = %hu\n"), inode->i_num_ads);
802         if (dentry_has_long_name(dentry))
803                 wimlib_printf(T("Filename = \"%"WS"\"\n"), dentry->file_name);
804         if (dentry_has_short_name(dentry))
805                 wimlib_printf(T("Short Name \"%"WS"\"\n"), dentry->short_name);
806         if (dentry->_full_path)
807                 tprintf(T("Full Path = \"%"TS"\"\n"), dentry->_full_path);
808
809         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
810         if (lte) {
811                 print_lookup_table_entry(lte, stdout);
812         } else {
813                 hash = inode_stream_hash(inode, 0);
814                 if (hash) {
815                         tprintf(T("Hash              = 0x"));
816                         print_hash(hash, stdout);
817                         tputchar(T('\n'));
818                         tputchar(T('\n'));
819                 }
820         }
821         for (u16 i = 0; i < inode->i_num_ads; i++) {
822                 tprintf(T("[Alternate Stream Entry %u]\n"), i);
823                 wimlib_printf(T("Name = \"%"WS"\"\n"),
824                               inode->i_ads_entries[i].stream_name);
825                 tprintf(T("Name Length (UTF16 bytes) = %hu\n"),
826                        inode->i_ads_entries[i].stream_name_nbytes);
827                 hash = inode_stream_hash(inode, i + 1);
828                 if (hash) {
829                         tprintf(T("Hash              = 0x"));
830                         print_hash(hash, stdout);
831                         tputchar(T('\n'));
832                 }
833                 print_lookup_table_entry(inode_stream_lte(inode, i + 1, lookup_table),
834                                          stdout);
835         }
836         return 0;
837 }
838
839 /* Initializations done on every `struct wim_dentry'. */
840 static void
841 dentry_common_init(struct wim_dentry *dentry)
842 {
843         memset(dentry, 0, sizeof(struct wim_dentry));
844 }
845
846 struct wim_inode *
847 new_timeless_inode(void)
848 {
849         struct wim_inode *inode = CALLOC(1, sizeof(struct wim_inode));
850         if (inode) {
851                 inode->i_security_id = -1;
852                 inode->i_nlink = 1;
853                 inode->i_next_stream_id = 1;
854                 inode->i_not_rpfixed = 1;
855                 INIT_LIST_HEAD(&inode->i_list);
856         #ifdef WITH_FUSE
857                 if (pthread_mutex_init(&inode->i_mutex, NULL) != 0) {
858                         ERROR_WITH_ERRNO("Error initializing mutex");
859                         FREE(inode);
860                         return NULL;
861                 }
862         #endif
863                 INIT_LIST_HEAD(&inode->i_dentry);
864         }
865         return inode;
866 }
867
868 static struct wim_inode *
869 new_inode(void)
870 {
871         struct wim_inode *inode = new_timeless_inode();
872         if (inode) {
873                 u64 now = get_wim_timestamp();
874                 inode->i_creation_time = now;
875                 inode->i_last_access_time = now;
876                 inode->i_last_write_time = now;
877         }
878         return inode;
879 }
880
881 /* Creates an unlinked directory entry. */
882 int
883 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
884 {
885         struct wim_dentry *dentry;
886         int ret;
887
888         dentry = MALLOC(sizeof(struct wim_dentry));
889         if (!dentry)
890                 return WIMLIB_ERR_NOMEM;
891
892         dentry_common_init(dentry);
893         ret = set_dentry_name(dentry, name);
894         if (ret == 0) {
895                 dentry->parent = dentry;
896                 *dentry_ret = dentry;
897         } else {
898                 FREE(dentry);
899                 ERROR("Failed to set name on new dentry with name \"%"TS"\"",
900                       name);
901         }
902         return ret;
903 }
904
905
906 static int
907 _new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret,
908                         bool timeless)
909 {
910         struct wim_dentry *dentry;
911         int ret;
912
913         ret = new_dentry(name, &dentry);
914         if (ret)
915                 return ret;
916
917         if (timeless)
918                 dentry->d_inode = new_timeless_inode();
919         else
920                 dentry->d_inode = new_inode();
921         if (!dentry->d_inode) {
922                 free_dentry(dentry);
923                 return WIMLIB_ERR_NOMEM;
924         }
925
926         inode_add_dentry(dentry, dentry->d_inode);
927         *dentry_ret = dentry;
928         return 0;
929 }
930
931 int
932 new_dentry_with_timeless_inode(const tchar *name, struct wim_dentry **dentry_ret)
933 {
934         return _new_dentry_with_inode(name, dentry_ret, true);
935 }
936
937 int
938 new_dentry_with_inode(const tchar *name, struct wim_dentry **dentry_ret)
939 {
940         return _new_dentry_with_inode(name, dentry_ret, false);
941 }
942
943 int
944 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
945 {
946         int ret;
947         struct wim_dentry *dentry;
948
949         DEBUG("Creating filler directory \"%"TS"\"", name);
950         ret = new_dentry_with_inode(name, &dentry);
951         if (ret)
952                 return ret;
953         /* Leave the inode number as 0; this is allowed for non
954          * hard-linked files. */
955         dentry->d_inode->i_resolved = 1;
956         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
957         *dentry_ret = dentry;
958         return 0;
959 }
960
961 static int
962 init_ads_entry(struct wim_ads_entry *ads_entry, const void *name,
963                size_t name_nbytes, bool is_utf16le)
964 {
965         int ret = 0;
966         memset(ads_entry, 0, sizeof(*ads_entry));
967
968         if (is_utf16le) {
969                 utf16lechar *p = MALLOC(name_nbytes + sizeof(utf16lechar));
970                 if (!p)
971                         return WIMLIB_ERR_NOMEM;
972                 memcpy(p, name, name_nbytes);
973                 p[name_nbytes / 2] = cpu_to_le16(0);
974                 ads_entry->stream_name = p;
975                 ads_entry->stream_name_nbytes = name_nbytes;
976         } else {
977                 if (name && *(const tchar*)name != T('\0')) {
978                         ret = get_utf16le_name(name, &ads_entry->stream_name,
979                                                &ads_entry->stream_name_nbytes);
980                 }
981         }
982         return ret;
983 }
984
985 static void
986 destroy_ads_entry(struct wim_ads_entry *ads_entry)
987 {
988         FREE(ads_entry->stream_name);
989 }
990
991 /* Frees an inode. */
992 void
993 free_inode(struct wim_inode *inode)
994 {
995         if (inode) {
996                 if (inode->i_ads_entries) {
997                         for (u16 i = 0; i < inode->i_num_ads; i++)
998                                 destroy_ads_entry(&inode->i_ads_entries[i]);
999                         FREE(inode->i_ads_entries);
1000                 }
1001         #ifdef WITH_FUSE
1002                 wimlib_assert(inode->i_num_opened_fds == 0);
1003                 FREE(inode->i_fds);
1004                 pthread_mutex_destroy(&inode->i_mutex);
1005         #endif
1006                 /* HACK: This may instead delete the inode from i_list, but the
1007                  * hlist_del() behaves the same as list_del(). */
1008                 hlist_del(&inode->i_hlist);
1009                 FREE(inode->i_extracted_file);
1010                 FREE(inode);
1011         }
1012 }
1013
1014 /* Decrements link count on an inode and frees it if the link count reaches 0.
1015  * */
1016 static void
1017 put_inode(struct wim_inode *inode)
1018 {
1019         wimlib_assert(inode->i_nlink != 0);
1020         if (--inode->i_nlink == 0) {
1021         #ifdef WITH_FUSE
1022                 if (inode->i_num_opened_fds == 0)
1023         #endif
1024                 {
1025                         free_inode(inode);
1026                 }
1027         }
1028 }
1029
1030 /* Frees a WIM dentry.
1031  *
1032  * The corresponding inode (if any) is freed only if its link count is
1033  * decremented to 0.
1034  */
1035 void
1036 free_dentry(struct wim_dentry *dentry)
1037 {
1038         if (dentry) {
1039                 FREE(dentry->file_name);
1040                 FREE(dentry->short_name);
1041                 FREE(dentry->_full_path);
1042                 if (dentry->d_inode)
1043                         put_inode(dentry->d_inode);
1044                 FREE(dentry);
1045         }
1046 }
1047
1048 /* This function is passed as an argument to for_dentry_in_tree_depth() in order
1049  * to free a directory tree. */
1050 static int
1051 do_free_dentry(struct wim_dentry *dentry, void *_lookup_table)
1052 {
1053         struct wim_lookup_table *lookup_table = _lookup_table;
1054
1055         if (lookup_table) {
1056                 struct wim_inode *inode = dentry->d_inode;
1057                 for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1058                         struct wim_lookup_table_entry *lte;
1059
1060                         lte = inode_stream_lte(inode, i, lookup_table);
1061                         if (lte)
1062                                 lte_decrement_refcnt(lte, lookup_table);
1063                 }
1064         }
1065         free_dentry(dentry);
1066         return 0;
1067 }
1068
1069 /*
1070  * Unlinks and frees a dentry tree.
1071  *
1072  * @root:               The root of the tree.
1073  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
1074  *                      reference counts in the lookup table for the lookup
1075  *                      table entries corresponding to the dentries will be
1076  *                      decremented.
1077  */
1078 void
1079 free_dentry_tree(struct wim_dentry *root, struct wim_lookup_table *lookup_table)
1080 {
1081         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1082 }
1083
1084 /*
1085  * Links a dentry into the directory tree.
1086  *
1087  * @parent: The dentry that will be the parent of @child.
1088  * @child: The dentry to link.
1089  *
1090  * Returns NULL if successful.  If @parent already contains a dentry with the
1091  * same name as @child (see compare_utf16le_names() for what names are
1092  * considered the "same"), the pointer to this duplicate dentry is returned.
1093  */
1094 struct wim_dentry *
1095 dentry_add_child(struct wim_dentry * restrict parent,
1096                  struct wim_dentry * restrict child)
1097 {
1098         wimlib_assert(dentry_is_directory(parent));
1099         wimlib_assert(parent != child);
1100
1101         struct rb_root *root = &parent->d_inode->i_children;
1102         struct rb_node **new = &(root->rb_node);
1103         struct rb_node *rb_parent = NULL;
1104
1105         while (*new) {
1106                 struct wim_dentry *this = rbnode_dentry(*new);
1107                 int result = dentry_compare_names(child, this);
1108
1109                 rb_parent = *new;
1110
1111                 if (result < 0)
1112                         new = &((*new)->rb_left);
1113                 else if (result > 0)
1114                         new = &((*new)->rb_right);
1115                 else
1116                         return this;
1117         }
1118         child->parent = parent;
1119         rb_link_node(&child->rb_node, rb_parent, new);
1120         rb_insert_color(&child->rb_node, root);
1121         return NULL;
1122 }
1123
1124 /* Unlink a WIM dentry from the directory entry tree. */
1125 void
1126 unlink_dentry(struct wim_dentry *dentry)
1127 {
1128         if (!dentry_is_root(dentry))
1129                 rb_erase(&dentry->rb_node, &dentry->parent->d_inode->i_children);
1130 }
1131
1132 /*
1133  * Returns the alternate data stream entry belonging to @inode that has the
1134  * stream name @stream_name.
1135  */
1136 struct wim_ads_entry *
1137 inode_get_ads_entry(struct wim_inode *inode, const tchar *stream_name,
1138                     u16 *idx_ret)
1139 {
1140         if (inode->i_num_ads == 0) {
1141                 return NULL;
1142         } else {
1143                 size_t stream_name_utf16le_nbytes;
1144                 u16 i;
1145                 struct wim_ads_entry *result;
1146
1147         #if TCHAR_IS_UTF16LE
1148                 const utf16lechar *stream_name_utf16le;
1149
1150                 stream_name_utf16le = stream_name;
1151                 stream_name_utf16le_nbytes = tstrlen(stream_name) * sizeof(tchar);
1152         #else
1153                 utf16lechar *stream_name_utf16le;
1154
1155                 {
1156                         int ret = tstr_to_utf16le(stream_name,
1157                                                   tstrlen(stream_name) *
1158                                                       sizeof(tchar),
1159                                                   &stream_name_utf16le,
1160                                                   &stream_name_utf16le_nbytes);
1161                         if (ret)
1162                                 return NULL;
1163                 }
1164         #endif
1165                 i = 0;
1166                 result = NULL;
1167                 do {
1168                         if (ads_entry_has_name(&inode->i_ads_entries[i],
1169                                                stream_name_utf16le,
1170                                                stream_name_utf16le_nbytes))
1171                         {
1172                                 if (idx_ret)
1173                                         *idx_ret = i;
1174                                 result = &inode->i_ads_entries[i];
1175                                 break;
1176                         }
1177                 } while (++i != inode->i_num_ads);
1178         #if !TCHAR_IS_UTF16LE
1179                 FREE(stream_name_utf16le);
1180         #endif
1181                 return result;
1182         }
1183 }
1184
1185 static struct wim_ads_entry *
1186 do_inode_add_ads(struct wim_inode *inode, const void *stream_name,
1187                  size_t stream_name_nbytes, bool is_utf16le)
1188 {
1189         u16 num_ads;
1190         struct wim_ads_entry *ads_entries;
1191         struct wim_ads_entry *new_entry;
1192
1193         if (inode->i_num_ads >= 0xfffe) {
1194                 ERROR("Too many alternate data streams in one inode!");
1195                 return NULL;
1196         }
1197         num_ads = inode->i_num_ads + 1;
1198         ads_entries = REALLOC(inode->i_ads_entries,
1199                               num_ads * sizeof(inode->i_ads_entries[0]));
1200         if (!ads_entries) {
1201                 ERROR("Failed to allocate memory for new alternate data stream");
1202                 return NULL;
1203         }
1204         inode->i_ads_entries = ads_entries;
1205
1206         new_entry = &inode->i_ads_entries[num_ads - 1];
1207         if (init_ads_entry(new_entry, stream_name, stream_name_nbytes, is_utf16le))
1208                 return NULL;
1209         new_entry->stream_id = inode->i_next_stream_id++;
1210         inode->i_num_ads = num_ads;
1211         return new_entry;
1212 }
1213
1214 struct wim_ads_entry *
1215 inode_add_ads_utf16le(struct wim_inode *inode,
1216                       const utf16lechar *stream_name,
1217                       size_t stream_name_nbytes)
1218 {
1219         DEBUG("Add alternate data stream \"%"WS"\"", stream_name);
1220         return do_inode_add_ads(inode, stream_name, stream_name_nbytes, true);
1221 }
1222
1223 /*
1224  * Add an alternate stream entry to a WIM inode and return a pointer to it, or
1225  * NULL if memory could not be allocated.
1226  */
1227 struct wim_ads_entry *
1228 inode_add_ads(struct wim_inode *inode, const tchar *stream_name)
1229 {
1230         DEBUG("Add alternate data stream \"%"TS"\"", stream_name);
1231         return do_inode_add_ads(inode, stream_name,
1232                                 tstrlen(stream_name) * sizeof(tchar),
1233                                 TCHAR_IS_UTF16LE);
1234 }
1235
1236 static struct wim_lookup_table_entry *
1237 add_stream_from_data_buffer(const void *buffer, size_t size,
1238                             struct wim_lookup_table *lookup_table)
1239 {
1240         u8 hash[SHA1_HASH_SIZE];
1241         struct wim_lookup_table_entry *lte, *existing_lte;
1242
1243         sha1_buffer(buffer, size, hash);
1244         existing_lte = __lookup_resource(lookup_table, hash);
1245         if (existing_lte) {
1246                 wimlib_assert(wim_resource_size(existing_lte) == size);
1247                 lte = existing_lte;
1248                 lte->refcnt++;
1249         } else {
1250                 void *buffer_copy;
1251                 lte = new_lookup_table_entry();
1252                 if (!lte)
1253                         return NULL;
1254                 buffer_copy = memdup(buffer, size);
1255                 if (!buffer_copy) {
1256                         free_lookup_table_entry(lte);
1257                         return NULL;
1258                 }
1259                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1260                 lte->attached_buffer              = buffer_copy;
1261                 lte->resource_entry.original_size = size;
1262                 copy_hash(lte->hash, hash);
1263                 lookup_table_insert(lookup_table, lte);
1264         }
1265         return lte;
1266 }
1267
1268 int
1269 inode_add_ads_with_data(struct wim_inode *inode, const tchar *name,
1270                         const void *value, size_t size,
1271                         struct wim_lookup_table *lookup_table)
1272 {
1273         struct wim_ads_entry *new_ads_entry;
1274
1275         wimlib_assert(inode->i_resolved);
1276
1277         new_ads_entry = inode_add_ads(inode, name);
1278         if (!new_ads_entry)
1279                 return WIMLIB_ERR_NOMEM;
1280
1281         new_ads_entry->lte = add_stream_from_data_buffer(value, size,
1282                                                          lookup_table);
1283         if (!new_ads_entry->lte) {
1284                 inode_remove_ads(inode, new_ads_entry - inode->i_ads_entries,
1285                                  lookup_table);
1286                 return WIMLIB_ERR_NOMEM;
1287         }
1288         return 0;
1289 }
1290
1291 /* Set the unnamed stream of a WIM inode, given a data buffer containing the
1292  * stream contents. */
1293 int
1294 inode_set_unnamed_stream(struct wim_inode *inode, const void *data, size_t len,
1295                          struct wim_lookup_table *lookup_table)
1296 {
1297         inode->i_lte = add_stream_from_data_buffer(data, len, lookup_table);
1298         if (!inode->i_lte)
1299                 return WIMLIB_ERR_NOMEM;
1300         inode->i_resolved = 1;
1301         return 0;
1302 }
1303
1304 /* Remove an alternate data stream from a WIM inode  */
1305 void
1306 inode_remove_ads(struct wim_inode *inode, u16 idx,
1307                  struct wim_lookup_table *lookup_table)
1308 {
1309         struct wim_ads_entry *ads_entry;
1310         struct wim_lookup_table_entry *lte;
1311
1312         wimlib_assert(idx < inode->i_num_ads);
1313         wimlib_assert(inode->i_resolved);
1314
1315         ads_entry = &inode->i_ads_entries[idx];
1316
1317         DEBUG("Remove alternate data stream \"%"WS"\"", ads_entry->stream_name);
1318
1319         lte = ads_entry->lte;
1320         if (lte)
1321                 lte_decrement_refcnt(lte, lookup_table);
1322
1323         destroy_ads_entry(ads_entry);
1324
1325         memmove(&inode->i_ads_entries[idx],
1326                 &inode->i_ads_entries[idx + 1],
1327                 (inode->i_num_ads - idx - 1) * sizeof(inode->i_ads_entries[0]));
1328         inode->i_num_ads--;
1329 }
1330
1331 #ifndef __WIN32__
1332 int
1333 inode_get_unix_data(const struct wim_inode *inode,
1334                     struct wimlib_unix_data *unix_data,
1335                     u16 *stream_idx_ret)
1336 {
1337         const struct wim_ads_entry *ads_entry;
1338         const struct wim_lookup_table_entry *lte;
1339         size_t size;
1340         int ret;
1341
1342         wimlib_assert(inode->i_resolved);
1343
1344         ads_entry = inode_get_ads_entry((struct wim_inode*)inode,
1345                                         WIMLIB_UNIX_DATA_TAG, NULL);
1346         if (!ads_entry)
1347                 return NO_UNIX_DATA;
1348
1349         if (stream_idx_ret)
1350                 *stream_idx_ret = ads_entry - inode->i_ads_entries;
1351
1352         lte = ads_entry->lte;
1353         if (!lte)
1354                 return NO_UNIX_DATA;
1355
1356         size = wim_resource_size(lte);
1357         if (size != sizeof(struct wimlib_unix_data))
1358                 return BAD_UNIX_DATA;
1359
1360         ret = read_full_resource_into_buf(lte, unix_data);
1361         if (ret)
1362                 return ret;
1363
1364         if (unix_data->version != 0)
1365                 return BAD_UNIX_DATA;
1366         return 0;
1367 }
1368
1369 int
1370 inode_set_unix_data(struct wim_inode *inode, uid_t uid, gid_t gid, mode_t mode,
1371                     struct wim_lookup_table *lookup_table, int which)
1372 {
1373         struct wimlib_unix_data unix_data;
1374         int ret;
1375         bool have_good_unix_data = false;
1376         bool have_unix_data = false;
1377         u16 stream_idx;
1378
1379         if (!(which & UNIX_DATA_CREATE)) {
1380                 ret = inode_get_unix_data(inode, &unix_data, &stream_idx);
1381                 if (ret == 0 || ret == BAD_UNIX_DATA || ret > 0)
1382                         have_unix_data = true;
1383                 if (ret == 0)
1384                         have_good_unix_data = true;
1385         }
1386         unix_data.version = 0;
1387         if (which & UNIX_DATA_UID || !have_good_unix_data)
1388                 unix_data.uid = uid;
1389         if (which & UNIX_DATA_GID || !have_good_unix_data)
1390                 unix_data.gid = gid;
1391         if (which & UNIX_DATA_MODE || !have_good_unix_data)
1392                 unix_data.mode = mode;
1393         ret = inode_add_ads_with_data(inode, WIMLIB_UNIX_DATA_TAG,
1394                                       &unix_data,
1395                                       sizeof(struct wimlib_unix_data),
1396                                       lookup_table);
1397         if (ret == 0 && have_unix_data)
1398                 inode_remove_ads(inode, stream_idx, lookup_table);
1399         return ret;
1400 }
1401 #endif /* !__WIN32__ */
1402
1403 /* Replace weird characters in filenames and alternate data stream names.
1404  *
1405  * In particular we do not want the path separator to appear in any names, as
1406  * that would make it possible for a "malicious" WIM to extract itself to any
1407  * location it wanted to. */
1408 static void
1409 replace_forbidden_characters(utf16lechar *name)
1410 {
1411         utf16lechar *p;
1412
1413         for (p = name; *p; p++) {
1414         #ifdef __WIN32__
1415                 if (wcschr(L"<>:\"/\\|?*", (wchar_t)*p))
1416         #else
1417                 if (*p == cpu_to_le16('/'))
1418         #endif
1419                 {
1420                         if (name) {
1421                                 WARNING("File, directory, or stream name \"%"WS"\"\n"
1422                                         "          contains forbidden characters; "
1423                                         "substituting replacement characters.",
1424                                         name);
1425                                 name = NULL;
1426                         }
1427                 #ifdef __WIN32__
1428                         *p = cpu_to_le16(0xfffd);
1429                 #else
1430                         *p = cpu_to_le16('?');
1431                 #endif
1432                 }
1433         }
1434 }
1435
1436 /*
1437  * Reads the alternate data stream entries of a WIM dentry.
1438  *
1439  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1440  *
1441  * @inode:      Inode to load the alternate data streams into.
1442  *              @inode->i_num_ads must have been set to the number of
1443  *              alternate data streams that are expected.
1444  *
1445  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1446  *                      to by @p.
1447  *
1448  *
1449  * Return 0 on success or nonzero on failure.  On success, inode->i_ads_entries
1450  * is set to an array of `struct wim_ads_entry's of length inode->i_num_ads.  On
1451  * failure, @inode is not modified.
1452  */
1453 static int
1454 read_ads_entries(const u8 * restrict p, struct wim_inode * restrict inode,
1455                  size_t nbytes_remaining)
1456 {
1457         u16 num_ads;
1458         struct wim_ads_entry *ads_entries;
1459         int ret;
1460
1461         BUILD_BUG_ON(sizeof(struct wim_ads_entry_on_disk) != WIM_ADS_ENTRY_DISK_SIZE);
1462
1463         /* Allocate an array for our in-memory representation of the alternate
1464          * data stream entries. */
1465         num_ads = inode->i_num_ads;
1466         ads_entries = CALLOC(num_ads, sizeof(inode->i_ads_entries[0]));
1467         if (!ads_entries)
1468                 goto out_of_memory;
1469
1470         /* Read the entries into our newly allocated buffer. */
1471         for (u16 i = 0; i < num_ads; i++) {
1472                 u64 length;
1473                 struct wim_ads_entry *cur_entry;
1474                 const struct wim_ads_entry_on_disk *disk_entry =
1475                         (const struct wim_ads_entry_on_disk*)p;
1476
1477                 cur_entry = &ads_entries[i];
1478                 ads_entries[i].stream_id = i + 1;
1479
1480                 /* Do we have at least the size of the fixed-length data we know
1481                  * need? */
1482                 if (nbytes_remaining < sizeof(struct wim_ads_entry_on_disk))
1483                         goto out_invalid;
1484
1485                 /* Read the length field */
1486                 length = le64_to_cpu(disk_entry->length);
1487
1488                 /* Make sure the length field is neither so small it doesn't
1489                  * include all the fixed-length data nor so large it overflows
1490                  * the metadata resource buffer. */
1491                 if (length < sizeof(struct wim_ads_entry_on_disk) ||
1492                     length > nbytes_remaining)
1493                         goto out_invalid;
1494
1495                 /* Read the rest of the fixed-length data. */
1496
1497                 cur_entry->reserved = le64_to_cpu(disk_entry->reserved);
1498                 copy_hash(cur_entry->hash, disk_entry->hash);
1499                 cur_entry->stream_name_nbytes = le16_to_cpu(disk_entry->stream_name_nbytes);
1500
1501                 /* If stream_name_nbytes != 0, this is a named stream.
1502                  * Otherwise this is an unnamed stream, or in some cases (bugs
1503                  * in Microsoft's software I guess) a meaningless entry
1504                  * distinguished from the real unnamed stream entry, if any, by
1505                  * the fact that the real unnamed stream entry has a nonzero
1506                  * hash field. */
1507                 if (cur_entry->stream_name_nbytes) {
1508                         /* The name is encoded in UTF16-LE, which uses 2-byte
1509                          * coding units, so the length of the name had better be
1510                          * an even number of bytes... */
1511                         if (cur_entry->stream_name_nbytes & 1)
1512                                 goto out_invalid;
1513
1514                         /* Add the length of the stream name to get the length
1515                          * we actually need to read.  Make sure this isn't more
1516                          * than the specified length of the entry. */
1517                         if (sizeof(struct wim_ads_entry_on_disk) +
1518                             cur_entry->stream_name_nbytes > length)
1519                                 goto out_invalid;
1520
1521                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_nbytes + 2);
1522                         if (!cur_entry->stream_name)
1523                                 goto out_of_memory;
1524
1525                         memcpy(cur_entry->stream_name,
1526                                disk_entry->stream_name,
1527                                cur_entry->stream_name_nbytes);
1528                         cur_entry->stream_name[cur_entry->stream_name_nbytes / 2] = cpu_to_le16(0);
1529                         replace_forbidden_characters(cur_entry->stream_name);
1530                 }
1531
1532                 /* It's expected that the size of every ADS entry is a multiple
1533                  * of 8.  However, to be safe, I'm allowing the possibility of
1534                  * an ADS entry at the very end of the metadata resource ending
1535                  * un-aligned.  So although we still need to increment the input
1536                  * pointer by @length to reach the next ADS entry, it's possible
1537                  * that less than @length is actually remaining in the metadata
1538                  * resource. We should set the remaining bytes to 0 if this
1539                  * happens. */
1540                 length = (length + 7) & ~(u64)7;
1541                 p += length;
1542                 if (nbytes_remaining < length)
1543                         nbytes_remaining = 0;
1544                 else
1545                         nbytes_remaining -= length;
1546         }
1547         inode->i_ads_entries = ads_entries;
1548         inode->i_next_stream_id = inode->i_num_ads + 1;
1549         ret = 0;
1550         goto out;
1551 out_of_memory:
1552         ret = WIMLIB_ERR_NOMEM;
1553         goto out_free_ads_entries;
1554 out_invalid:
1555         ERROR("An alternate data stream entry is invalid");
1556         ret = WIMLIB_ERR_INVALID_DENTRY;
1557 out_free_ads_entries:
1558         if (ads_entries) {
1559                 for (u16 i = 0; i < num_ads; i++)
1560                         destroy_ads_entry(&ads_entries[i]);
1561                 FREE(ads_entries);
1562         }
1563 out:
1564         return ret;
1565 }
1566
1567 /*
1568  * Reads a WIM directory entry, including all alternate data stream entries that
1569  * follow it, from the WIM image's metadata resource.
1570  *
1571  * @metadata_resource:
1572  *              Pointer to the metadata resource buffer.
1573  *
1574  * @metadata_resource_len:
1575  *              Length of the metadata resource buffer, in bytes.
1576  *
1577  * @offset:     Offset of the dentry within the metadata resource.
1578  *
1579  * @dentry:     A `struct wim_dentry' that will be filled in by this function.
1580  *
1581  * Return 0 on success or nonzero on failure.  On failure, @dentry will have
1582  * been modified, but it will not be left with pointers to any allocated
1583  * buffers.  On success, the dentry->length field must be examined.  If zero,
1584  * this was a special "end of directory" dentry and not a real dentry.  If
1585  * nonzero, this was a real dentry.
1586  *
1587  * Possible errors include:
1588  *      WIMLIB_ERR_NOMEM
1589  *      WIMLIB_ERR_INVALID_DENTRY
1590  */
1591 int
1592 read_dentry(const u8 * restrict metadata_resource, u64 metadata_resource_len,
1593             u64 offset, struct wim_dentry * restrict dentry)
1594 {
1595
1596         u64 calculated_size;
1597         utf16lechar *file_name;
1598         utf16lechar *short_name;
1599         u16 short_name_nbytes;
1600         u16 file_name_nbytes;
1601         int ret;
1602         struct wim_inode *inode;
1603         const u8 *p = &metadata_resource[offset];
1604         const struct wim_dentry_on_disk *disk_dentry =
1605                         (const struct wim_dentry_on_disk*)p;
1606
1607         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1608
1609         if ((uintptr_t)p & 7)
1610                 WARNING("WIM dentry is not 8-byte aligned");
1611
1612         dentry_common_init(dentry);
1613
1614         /* Before reading the whole dentry, we need to read just the length.
1615          * This is because a dentry of length 8 (that is, just the length field)
1616          * terminates the list of sibling directory entries. */
1617         if (offset + sizeof(u64) > metadata_resource_len ||
1618             offset + sizeof(u64) < offset)
1619         {
1620                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1621                       "end of the metadata resource (size %"PRIu64")",
1622                       offset, metadata_resource_len);
1623                 return WIMLIB_ERR_INVALID_DENTRY;
1624         }
1625         dentry->length = le64_to_cpu(disk_dentry->length);
1626
1627         /* A zero length field (really a length of 8, since that's how big the
1628          * directory entry is...) indicates that this is the end of directory
1629          * dentry.  We do not read it into memory as an actual dentry, so just
1630          * return successfully in this case. */
1631         if (dentry->length == 8)
1632                 dentry->length = 0;
1633         if (dentry->length == 0)
1634                 return 0;
1635
1636         /* Now that we have the actual length provided in the on-disk structure,
1637          * again make sure it doesn't overflow the metadata resource buffer. */
1638         if (offset + dentry->length > metadata_resource_len ||
1639             offset + dentry->length < offset)
1640         {
1641                 ERROR("Directory entry at offset %"PRIu64" and with size "
1642                       "%"PRIu64" ends past the end of the metadata resource "
1643                       "(size %"PRIu64")",
1644                       offset, dentry->length, metadata_resource_len);
1645                 return WIMLIB_ERR_INVALID_DENTRY;
1646         }
1647
1648         /* Make sure the dentry length is at least as large as the number of
1649          * fixed-length fields */
1650         if (dentry->length < sizeof(struct wim_dentry_on_disk)) {
1651                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1652                       dentry->length);
1653                 return WIMLIB_ERR_INVALID_DENTRY;
1654         }
1655
1656         /* Allocate a `struct wim_inode' for this `struct wim_dentry'. */
1657         inode = new_timeless_inode();
1658         if (!inode)
1659                 return WIMLIB_ERR_NOMEM;
1660
1661         /* Read more fields; some into the dentry, and some into the inode. */
1662
1663         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1664         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1665         dentry->subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1666         dentry->d_unused_1 = le64_to_cpu(disk_dentry->unused_1);
1667         dentry->d_unused_2 = le64_to_cpu(disk_dentry->unused_2);
1668         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1669         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1670         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1671         copy_hash(inode->i_hash, disk_dentry->unnamed_stream_hash);
1672
1673         /* I don't know what's going on here.  It seems like M$ screwed up the
1674          * reparse points, then put the fields in the same place and didn't
1675          * document it.  So we have some fields we read for reparse points, and
1676          * some fields in the same place for non-reparse-point.s */
1677         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1678                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->reparse.rp_unknown_1);
1679                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
1680                 inode->i_rp_unknown_2 = le16_to_cpu(disk_dentry->reparse.rp_unknown_2);
1681                 inode->i_not_rpfixed = le16_to_cpu(disk_dentry->reparse.not_rpfixed);
1682                 /* Leave inode->i_ino at 0.  Note that this means the WIM file
1683                  * cannot archive hard-linked reparse points.  Such a thing
1684                  * doesn't really make sense anyway, although I believe it's
1685                  * theoretically possible to have them on NTFS. */
1686         } else {
1687                 inode->i_rp_unknown_1 = le32_to_cpu(disk_dentry->nonreparse.rp_unknown_1);
1688                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
1689         }
1690
1691         inode->i_num_ads = le16_to_cpu(disk_dentry->num_alternate_data_streams);
1692
1693         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
1694         file_name_nbytes = le16_to_cpu(disk_dentry->file_name_nbytes);
1695
1696         if ((short_name_nbytes & 1) | (file_name_nbytes & 1))
1697         {
1698                 ERROR("Dentry name is not valid UTF-16LE (odd number of bytes)!");
1699                 ret = WIMLIB_ERR_INVALID_DENTRY;
1700                 goto out_free_inode;
1701         }
1702
1703         /* We now know the length of the file name and short name.  Make sure
1704          * the length of the dentry is large enough to actually hold them.
1705          *
1706          * The calculated length here is unaligned to allow for the possibility
1707          * that the dentry->length names an unaligned length, although this
1708          * would be unexpected. */
1709         calculated_size = _dentry_correct_length_unaligned(file_name_nbytes,
1710                                                            short_name_nbytes);
1711
1712         if (dentry->length < calculated_size) {
1713                 ERROR("Unexpected end of directory entry! (Expected "
1714                       "at least %"PRIu64" bytes, got %"PRIu64" bytes.)",
1715                       calculated_size, dentry->length);
1716                 ret = WIMLIB_ERR_INVALID_DENTRY;
1717                 goto out_free_inode;
1718         }
1719
1720         p += sizeof(struct wim_dentry_on_disk);
1721
1722         /* Read the filename if present.  Note: if the filename is empty, there
1723          * is no null terminator following it. */
1724         if (file_name_nbytes) {
1725                 file_name = MALLOC(file_name_nbytes + 2);
1726                 if (!file_name) {
1727                         ERROR("Failed to allocate %d bytes for dentry file name",
1728                               file_name_nbytes + 2);
1729                         ret = WIMLIB_ERR_NOMEM;
1730                         goto out_free_inode;
1731                 }
1732                 memcpy(file_name, p, file_name_nbytes);
1733                 p += file_name_nbytes + 2;
1734                 file_name[file_name_nbytes / 2] = cpu_to_le16(0);
1735                 replace_forbidden_characters(file_name);
1736         } else {
1737                 file_name = NULL;
1738         }
1739
1740
1741         /* Read the short filename if present.  Note: if there is no short
1742          * filename, there is no null terminator following it. */
1743         if (short_name_nbytes) {
1744                 short_name = MALLOC(short_name_nbytes + 2);
1745                 if (!short_name) {
1746                         ERROR("Failed to allocate %d bytes for dentry short name",
1747                               short_name_nbytes + 2);
1748                         ret = WIMLIB_ERR_NOMEM;
1749                         goto out_free_file_name;
1750                 }
1751                 memcpy(short_name, p, short_name_nbytes);
1752                 p += short_name_nbytes + 2;
1753                 short_name[short_name_nbytes / 2] = cpu_to_le16(0);
1754                 replace_forbidden_characters(short_name);
1755         } else {
1756                 short_name = NULL;
1757         }
1758
1759         /* Align the dentry length */
1760         dentry->length = (dentry->length + 7) & ~7;
1761
1762         /*
1763          * Read the alternate data streams, if present.  dentry->num_ads tells
1764          * us how many they are, and they will directly follow the dentry
1765          * on-disk.
1766          *
1767          * Note that each alternate data stream entry begins on an 8-byte
1768          * aligned boundary, and the alternate data stream entries seem to NOT
1769          * be included in the dentry->length field for some reason.
1770          */
1771         if (inode->i_num_ads != 0) {
1772                 ret = WIMLIB_ERR_INVALID_DENTRY;
1773                 if (offset + dentry->length > metadata_resource_len ||
1774                     (ret = read_ads_entries(&metadata_resource[offset + dentry->length],
1775                                             inode,
1776                                             metadata_resource_len - offset - dentry->length)))
1777                 {
1778                         ERROR("Failed to read alternate data stream "
1779                               "entries of WIM dentry \"%"WS"\"", file_name);
1780                         goto out_free_short_name;
1781                 }
1782         }
1783         /* We've read all the data for this dentry.  Set the names and their
1784          * lengths, and we've done. */
1785         dentry->d_inode           = inode;
1786         dentry->file_name         = file_name;
1787         dentry->short_name        = short_name;
1788         dentry->file_name_nbytes  = file_name_nbytes;
1789         dentry->short_name_nbytes = short_name_nbytes;
1790         ret = 0;
1791         goto out;
1792 out_free_short_name:
1793         FREE(short_name);
1794 out_free_file_name:
1795         FREE(file_name);
1796 out_free_inode:
1797         free_inode(inode);
1798 out:
1799         return ret;
1800 }
1801
1802 static const tchar *
1803 dentry_get_file_type_string(const struct wim_dentry *dentry)
1804 {
1805         const struct wim_inode *inode = dentry->d_inode;
1806         if (inode_is_directory(inode))
1807                 return T("directory");
1808         else if (inode_is_symlink(inode))
1809                 return T("symbolic link");
1810         else
1811                 return T("file");
1812 }
1813
1814 /* Reads the children of a dentry, and all their children, ..., etc. from the
1815  * metadata resource and into the dentry tree.
1816  *
1817  * @metadata_resource:  An array that contains the uncompressed metadata
1818  *                      resource for the WIM file.
1819  *
1820  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1821  *                          bytes.
1822  *
1823  * @dentry:     A pointer to a `struct wim_dentry' that is the root of the directory
1824  *              tree and has already been read from the metadata resource.  It
1825  *              does not need to be the real root because this procedure is
1826  *              called recursively.
1827  *
1828  * Returns zero on success; nonzero on failure.
1829  */
1830 int
1831 read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1832                  struct wim_dentry *dentry)
1833 {
1834         u64 cur_offset = dentry->subdir_offset;
1835         struct wim_dentry *child;
1836         struct wim_dentry *duplicate;
1837         struct wim_dentry cur_child;
1838         int ret;
1839
1840         /*
1841          * If @dentry has no child dentries, nothing more needs to be done for
1842          * this branch.  This is the case for regular files, symbolic links, and
1843          * *possibly* empty directories (although an empty directory may also
1844          * have one child dentry that is the special end-of-directory dentry)
1845          */
1846         if (cur_offset == 0)
1847                 return 0;
1848
1849         /* Find and read all the children of @dentry. */
1850         for (;;) {
1851
1852                 /* Read next child of @dentry into @cur_child. */
1853                 ret = read_dentry(metadata_resource, metadata_resource_len,
1854                                   cur_offset, &cur_child);
1855                 if (ret)
1856                         break;
1857
1858                 /* Check for end of directory. */
1859                 if (cur_child.length == 0)
1860                         break;
1861
1862                 /* Not end of directory.  Allocate this child permanently and
1863                  * link it to the parent and previous child. */
1864                 child = memdup(&cur_child, sizeof(struct wim_dentry));
1865                 if (!child) {
1866                         ERROR("Failed to allocate new dentry!");
1867                         ret = WIMLIB_ERR_NOMEM;
1868                         break;
1869                 }
1870
1871                 /* Advance to the offset of the next child.  Note: We need to
1872                  * advance by the TOTAL length of the dentry, not by the length
1873                  * cur_child.length, which although it does take into account
1874                  * the padding, it DOES NOT take into account alternate stream
1875                  * entries. */
1876                 cur_offset += dentry_total_length(child);
1877
1878                 duplicate = dentry_add_child(dentry, child);
1879                 if (duplicate) {
1880                         const tchar *child_type, *duplicate_type;
1881                         child_type = dentry_get_file_type_string(child);
1882                         duplicate_type = dentry_get_file_type_string(duplicate);
1883                         /* On UNIX, duplicates are exact.  On Windows,
1884                          * duplicates may differ by case and we wish to provide
1885                          * a different warning message in this case. */
1886                 #ifdef __WIN32__
1887                         if (dentry_compare_names_case_sensitive(child, duplicate))
1888                         {
1889                                 child->parent = dentry;
1890                                 WARNING("Ignoring %ls \"%ls\", which differs "
1891                                         "only in case from %ls \"%ls\"",
1892                                         child_type,
1893                                         dentry_full_path(child),
1894                                         duplicate_type,
1895                                         dentry_full_path(duplicate));
1896                         }
1897                         else
1898                 #endif
1899                         {
1900                                 WARNING("Ignoring duplicate %"TS" \"%"TS"\" "
1901                                         "(the WIM image already contains a %"TS" "
1902                                         "at that path with the exact same name)",
1903                                         child_type, dentry_full_path(duplicate),
1904                                         duplicate_type);
1905                         }
1906                         free_dentry(child);
1907                 } else {
1908                         inode_add_dentry(child, child->d_inode);
1909                         /* If there are children of this child, call this
1910                          * procedure recursively. */
1911                         if (child->subdir_offset != 0) {
1912                                 if (dentry_is_directory(child)) {
1913                                         ret = read_dentry_tree(metadata_resource,
1914                                                                metadata_resource_len,
1915                                                                child);
1916                                         if (ret)
1917                                                 break;
1918                                 } else {
1919                                         WARNING("Ignoring children of non-directory \"%"TS"\"",
1920                                                 dentry_full_path(child));
1921                                 }
1922                         }
1923
1924                 }
1925         }
1926         return ret;
1927 }
1928
1929 /*
1930  * Writes a WIM dentry to an output buffer.
1931  *
1932  * @dentry:  The dentry structure.
1933  * @p:       The memory location to write the data to.
1934  *
1935  * Returns the pointer to the byte after the last byte we wrote as part of the
1936  * dentry, including any alternate data stream entries.
1937  */
1938 static u8 *
1939 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
1940 {
1941         const struct wim_inode *inode;
1942         struct wim_dentry_on_disk *disk_dentry;
1943         const u8 *orig_p;
1944         const u8 *hash;
1945
1946         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
1947         orig_p = p;
1948
1949         inode = dentry->d_inode;
1950         disk_dentry = (struct wim_dentry_on_disk*)p;
1951
1952         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
1953         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
1954         disk_dentry->subdir_offset = cpu_to_le64(dentry->subdir_offset);
1955         disk_dentry->unused_1 = cpu_to_le64(dentry->d_unused_1);
1956         disk_dentry->unused_2 = cpu_to_le64(dentry->d_unused_2);
1957         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
1958         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
1959         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
1960         hash = inode_stream_hash(inode, 0);
1961         copy_hash(disk_dentry->unnamed_stream_hash, hash);
1962         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1963                 disk_dentry->reparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1964                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
1965                 disk_dentry->reparse.rp_unknown_2 = cpu_to_le16(inode->i_rp_unknown_2);
1966                 disk_dentry->reparse.not_rpfixed = cpu_to_le16(inode->i_not_rpfixed);
1967         } else {
1968                 disk_dentry->nonreparse.rp_unknown_1 = cpu_to_le32(inode->i_rp_unknown_1);
1969                 disk_dentry->nonreparse.hard_link_group_id =
1970                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
1971         }
1972         disk_dentry->num_alternate_data_streams = cpu_to_le16(inode->i_num_ads);
1973         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->short_name_nbytes);
1974         disk_dentry->file_name_nbytes = cpu_to_le16(dentry->file_name_nbytes);
1975         p += sizeof(struct wim_dentry_on_disk);
1976
1977         if (dentry_has_long_name(dentry))
1978                 p = mempcpy(p, dentry->file_name, dentry->file_name_nbytes + 2);
1979
1980         if (dentry_has_short_name(dentry))
1981                 p = mempcpy(p, dentry->short_name, dentry->short_name_nbytes + 2);
1982
1983         /* Align to 8-byte boundary */
1984         while ((uintptr_t)p & 7)
1985                 *p++ = 0;
1986
1987         /* We calculate the correct length of the dentry ourselves because the
1988          * dentry->length field may been set to an unexpected value from when we
1989          * read the dentry in (for example, there may have been unknown data
1990          * appended to the end of the dentry...).  Furthermore, the dentry may
1991          * have been renamed, thus changing its needed length. */
1992         disk_dentry->length = cpu_to_le64(p - orig_p);
1993
1994         /* Write the alternate data streams entries, if any. */
1995         for (u16 i = 0; i < inode->i_num_ads; i++) {
1996                 const struct wim_ads_entry *ads_entry =
1997                                 &inode->i_ads_entries[i];
1998                 struct wim_ads_entry_on_disk *disk_ads_entry =
1999                                 (struct wim_ads_entry_on_disk*)p;
2000                 orig_p = p;
2001
2002                 disk_ads_entry->reserved = cpu_to_le64(ads_entry->reserved);
2003
2004                 hash = inode_stream_hash(inode, i + 1);
2005                 copy_hash(disk_ads_entry->hash, hash);
2006                 disk_ads_entry->stream_name_nbytes = cpu_to_le16(ads_entry->stream_name_nbytes);
2007                 p += sizeof(struct wim_ads_entry_on_disk);
2008                 if (ads_entry->stream_name_nbytes) {
2009                         p = mempcpy(p, ads_entry->stream_name,
2010                                     ads_entry->stream_name_nbytes + 2);
2011                 }
2012                 /* Align to 8-byte boundary */
2013                 while ((uintptr_t)p & 7)
2014                         *p++ = 0;
2015                 disk_ads_entry->length = cpu_to_le64(p - orig_p);
2016         }
2017         return p;
2018 }
2019
2020 static int
2021 write_dentry_cb(struct wim_dentry *dentry, void *_p)
2022 {
2023         u8 **p = _p;
2024         *p = write_dentry(dentry, *p);
2025         return 0;
2026 }
2027
2028 static u8 *
2029 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p);
2030
2031 static int
2032 write_dentry_tree_recursive_cb(struct wim_dentry *dentry, void *_p)
2033 {
2034         u8 **p = _p;
2035         *p = write_dentry_tree_recursive(dentry, *p);
2036         return 0;
2037 }
2038
2039 /* Recursive function that writes a dentry tree rooted at @parent, not including
2040  * @parent itself, which has already been written. */
2041 static u8 *
2042 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p)
2043 {
2044         /* Nothing to do if this dentry has no children. */
2045         if (parent->subdir_offset == 0)
2046                 return p;
2047
2048         /* Write child dentries and end-of-directory entry.
2049          *
2050          * Note: we need to write all of this dentry's children before
2051          * recursively writing the directory trees rooted at each of the child
2052          * dentries, since the on-disk dentries for a dentry's children are
2053          * always located at consecutive positions in the metadata resource! */
2054         for_dentry_child(parent, write_dentry_cb, &p);
2055
2056         /* write end of directory entry */
2057         *(le64*)p = cpu_to_le64(0);
2058         p += 8;
2059
2060         /* Recurse on children. */
2061         for_dentry_child(parent, write_dentry_tree_recursive_cb, &p);
2062         return p;
2063 }
2064
2065 /* Writes a directory tree to the metadata resource.
2066  *
2067  * @root:       Root of the dentry tree.
2068  * @p:          Pointer to a buffer with enough space for the dentry tree.
2069  *
2070  * Returns pointer to the byte after the last byte we wrote.
2071  */
2072 u8 *
2073 write_dentry_tree(const struct wim_dentry *root, u8 *p)
2074 {
2075         DEBUG("Writing dentry tree.");
2076         wimlib_assert(dentry_is_root(root));
2077
2078         /* If we're the root dentry, we have no parent that already
2079          * wrote us, so we need to write ourselves. */
2080         p = write_dentry(root, p);
2081
2082         /* Write end of directory entry after the root dentry just to be safe;
2083          * however the root dentry obviously cannot have any siblings. */
2084         *(le64*)p = cpu_to_le64(0);
2085         p += 8;
2086
2087         /* Recursively write the rest of the dentry tree. */
2088         return write_dentry_tree_recursive(root, p);
2089 }