]> wimlib.net Git - wimlib/blob - src/dentry.c
f46e628c07e957fd300ea54c2eea2eeded00f033
[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 #include "buffer_io.h"
30 #include "dentry.h"
31 #include "lookup_table.h"
32 #include "timestamp.h"
33 #include "wimlib_internal.h"
34 #include <errno.h>
35
36 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
37  * a file name and short name that take the specified numbers of bytes.  This
38  * excludes any alternate data stream entries that may follow the dentry. */
39 static u64
40 __dentry_correct_length_unaligned(u16 file_name_nbytes, u16 short_name_nbytes)
41 {
42         u64 length = WIM_DENTRY_DISK_SIZE;
43         if (file_name_nbytes)
44                 length += file_name_nbytes + 2;
45         if (short_name_nbytes)
46                 length += short_name_nbytes + 2;
47         return length;
48 }
49
50 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
51  * the file name length and short name length.  Note that dentry->length is
52  * ignored; also, this excludes any alternate data stream entries that may
53  * follow the dentry. */
54 static u64
55 dentry_correct_length_unaligned(const struct wim_dentry *dentry)
56 {
57         return __dentry_correct_length_unaligned(dentry->file_name_nbytes,
58                                                  dentry->short_name_nbytes);
59 }
60
61 /* Return the "correct" value to write in the length field of a WIM dentry,
62  * based on the file name length and short name length. */
63 static u64
64 dentry_correct_length(const struct wim_dentry *dentry)
65 {
66         return (dentry_correct_length_unaligned(dentry) + 7) & ~7;
67 }
68
69 /* Return %true iff the alternate data stream entry @entry has the UTF-16LE
70  * stream name @name that has length @name_nbytes bytes. */
71 static inline bool
72 ads_entry_has_name(const struct wim_ads_entry *entry,
73                    const utf16lechar *name, size_t name_nbytes)
74 {
75         return entry->stream_name_nbytes == name_nbytes &&
76                memcmp(entry->stream_name, name, name_nbytes) == 0;
77 }
78
79 /* Duplicates a multibyte string into a UTF-16LE string and returns the string
80  * and its length, in bytes, in the pointer arguments.  Frees any existing
81  * string at the return location before overwriting it. */
82 static int
83 get_utf16le_name(const mbchar *name, utf16lechar **name_utf16le_ret,
84                  u16 *name_utf16le_nbytes_ret)
85 {
86         utf16lechar *name_utf16le;
87         size_t name_utf16le_nbytes;
88         int ret;
89
90         ret = mbs_to_utf16le(name, strlen(name), &name_utf16le,
91                              &name_utf16le_nbytes);
92         if (ret == 0) {
93                 if (name_utf16le_nbytes > 0xffff) {
94                         FREE(name_utf16le);
95                         ERROR("Multibyte string \"%s\" is too long!", name);
96                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
97                 } else {
98                         FREE(*name_utf16le_ret);
99                         *name_utf16le_ret = name_utf16le;
100                         *name_utf16le_nbytes_ret = name_utf16le_nbytes;
101                 }
102         }
103         return ret;
104 }
105
106 /* Sets the name of a WIM dentry from a multibyte string. */
107 int
108 set_dentry_name(struct wim_dentry *dentry, const mbchar *new_name)
109 {
110         int ret;
111         ret = get_utf16le_name(new_name, &dentry->file_name,
112                                &dentry->file_name_nbytes);
113         if (ret == 0) {
114                 /* Clear the short name and recalculate the dentry length */
115                 if (dentry_has_short_name(dentry)) {
116                         FREE(dentry->short_name);
117                         dentry->short_name = NULL;
118                         dentry->short_name_nbytes = 0;
119                 }
120                 dentry->length = dentry_correct_length(dentry);
121         }
122         return ret;
123 }
124
125 /* Returns the total length of a WIM alternate data stream entry on-disk,
126  * including the stream name, the null terminator, AND the padding after the
127  * entry to align the next ADS entry or dentry on an 8-byte boundary. */
128 static u64
129 ads_entry_total_length(const struct wim_ads_entry *entry)
130 {
131         u64 len = WIM_ADS_ENTRY_DISK_SIZE;
132         if (entry->stream_name_nbytes)
133                 len += entry->stream_name_nbytes + 2;
134         return (len + 7) & ~7;
135 }
136
137
138 static u64
139 __dentry_total_length(const struct wim_dentry *dentry, u64 length)
140 {
141         const struct wim_inode *inode = dentry->d_inode;
142         for (u16 i = 0; i < inode->i_num_ads; i++)
143                 length += ads_entry_total_length(&inode->i_ads_entries[i]);
144         return (length + 7) & ~7;
145 }
146
147 /* Calculate the aligned *total* length of an on-disk WIM dentry.  This includes
148  * all alternate data streams. */
149 u64
150 dentry_correct_total_length(const struct wim_dentry *dentry)
151 {
152         return __dentry_total_length(dentry,
153                                      dentry_correct_length_unaligned(dentry));
154 }
155
156 /* Like dentry_correct_total_length(), but use the existing dentry->length field
157  * instead of calculating its "correct" value. */
158 static u64
159 dentry_total_length(const struct wim_dentry *dentry)
160 {
161         return __dentry_total_length(dentry, dentry->length);
162 }
163
164 int
165 for_dentry_in_rbtree(struct rb_node *root,
166                      int (*visitor)(struct wim_dentry *, void *),
167                      void *arg)
168 {
169         int ret;
170         struct rb_node *node = root;
171         LIST_HEAD(stack);
172         while (1) {
173                 if (node) {
174                         list_add(&rbnode_dentry(node)->tmp_list, &stack);
175                         node = node->rb_left;
176                 } else {
177                         struct list_head *next;
178                         struct wim_dentry *dentry;
179
180                         next = stack.next;
181                         if (next == &stack)
182                                 return 0;
183                         dentry = container_of(next, struct wim_dentry, tmp_list);
184                         list_del(next);
185                         ret = visitor(dentry, arg);
186                         if (ret != 0)
187                                 return ret;
188                         node = dentry->rb_node.rb_right;
189                 }
190         }
191 }
192
193 static int
194 for_dentry_tree_in_rbtree_depth(struct rb_node *node,
195                                 int (*visitor)(struct wim_dentry*, void*),
196                                 void *arg)
197 {
198         int ret;
199         if (node) {
200                 ret = for_dentry_tree_in_rbtree_depth(node->rb_left,
201                                                       visitor, arg);
202                 if (ret != 0)
203                         return ret;
204                 ret = for_dentry_tree_in_rbtree_depth(node->rb_right,
205                                                       visitor, arg);
206                 if (ret != 0)
207                         return ret;
208                 ret = for_dentry_in_tree_depth(rbnode_dentry(node), visitor, arg);
209                 if (ret != 0)
210                         return ret;
211         }
212         return 0;
213 }
214
215 static int
216 for_dentry_tree_in_rbtree(struct rb_node *node,
217                           int (*visitor)(struct wim_dentry*, void*),
218                           void *arg)
219 {
220         int ret;
221         if (node) {
222                 ret = for_dentry_tree_in_rbtree(node->rb_left, visitor, arg);
223                 if (ret != 0)
224                         return ret;
225                 ret = for_dentry_in_tree(rbnode_dentry(node), visitor, arg);
226                 if (ret != 0)
227                         return ret;
228                 ret = for_dentry_tree_in_rbtree(node->rb_right, visitor, arg);
229                 if (ret != 0)
230                         return ret;
231         }
232         return 0;
233 }
234
235 /* Calls a function on all directory entries in a WIM dentry tree.  Logically,
236  * this is a pre-order traversal (the function is called on a parent dentry
237  * before its children), but sibling dentries will be visited in order as well.
238  * */
239 int
240 for_dentry_in_tree(struct wim_dentry *root,
241                    int (*visitor)(struct wim_dentry*, void*), void *arg)
242 {
243         int ret = visitor(root, arg);
244         if (ret == 0) {
245                 ret = for_dentry_tree_in_rbtree(root->d_inode->i_children.rb_node,
246                                                 visitor,
247                                                 arg);
248         }
249         return ret;
250 }
251
252 /* Like for_dentry_in_tree(), but the visitor function is always called on a
253  * dentry's children before on itself. */
254 int
255 for_dentry_in_tree_depth(struct wim_dentry *root,
256                          int (*visitor)(struct wim_dentry*, void*), void *arg)
257 {
258         int ret;
259         ret = for_dentry_tree_in_rbtree_depth(root->d_inode->i_children.rb_node,
260                                               visitor, arg);
261         if (ret == 0)
262                 ret = visitor(root, arg);
263         return ret;
264 }
265
266 /* Calculate the full path of @dentry.  The full path of its parent must have
267  * already been calculated. */
268 int
269 calculate_dentry_full_path(struct wim_dentry *dentry, void *ignore)
270 {
271         char *full_path;
272         u32 full_path_nbytes;
273
274         wimlib_assert(dentry_is_root(dentry) ||
275                       dentry->parent->full_path != NULL);
276
277         if (dentry_is_root(dentry)) {
278                 full_path = MALLOC(2);
279                 if (!full_path)
280                         return WIMLIB_ERR_NOMEM;
281                 full_path[0] = '/';
282                 full_path[1] = '\0';
283                 full_path_nbytes = 1;
284         } else {
285                 char *parent_full_path;
286                 u32 parent_full_path_nbytes;
287                 const struct wim_dentry *parent;
288                 size_t name_mbs_nbytes;
289                 int ret;
290
291                 ret = utf16le_to_mbs_nbytes(dentry->file_name,
292                                             dentry->file_name_nbytes,
293                                             &name_mbs_nbytes);
294                 if (ret)
295                         return ret;
296                 parent = dentry->parent;
297                 if (dentry_is_root(parent)) {
298                         parent_full_path = "";
299                         parent_full_path_nbytes = 0;
300                 } else {
301                         parent_full_path = parent->full_path;
302                         parent_full_path_nbytes = parent->full_path_nbytes;
303                 }
304                 full_path_nbytes = parent_full_path_nbytes + 1 +
305                                    name_mbs_nbytes;
306                 full_path = MALLOC(full_path_nbytes + 1);
307                 if (!full_path)
308                         return WIMLIB_ERR_NOMEM;
309                 memcpy(full_path, parent_full_path, parent_full_path_nbytes);
310                 full_path[parent_full_path_nbytes] = '/';
311
312                 utf16le_to_mbs_buf(dentry->file_name,
313                                    dentry->file_name_nbytes,
314                                    &full_path[parent_full_path_nbytes + 1]);
315         }
316         FREE(dentry->full_path);
317         dentry->full_path = full_path;
318         dentry->full_path_nbytes= full_path_nbytes;
319         return 0;
320 }
321
322 static int
323 increment_subdir_offset(struct wim_dentry *dentry, void *subdir_offset_p)
324 {
325         *(u64*)subdir_offset_p += dentry_correct_total_length(dentry);
326         return 0;
327 }
328
329 static int
330 call_calculate_subdir_offsets(struct wim_dentry *dentry, void *subdir_offset_p)
331 {
332         calculate_subdir_offsets(dentry, subdir_offset_p);
333         return 0;
334 }
335
336 /*
337  * Recursively calculates the subdir offsets for a directory tree.
338  *
339  * @dentry:  The root of the directory tree.
340  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
341  *                    offset for @dentry.
342  */
343 void
344 calculate_subdir_offsets(struct wim_dentry *dentry, u64 *subdir_offset_p)
345 {
346         struct rb_node *node;
347
348         dentry->subdir_offset = *subdir_offset_p;
349         node = dentry->d_inode->i_children.rb_node;
350         if (node) {
351                 /* Advance the subdir offset by the amount of space the children
352                  * of this dentry take up. */
353                 for_dentry_in_rbtree(node, increment_subdir_offset, subdir_offset_p);
354
355                 /* End-of-directory dentry on disk. */
356                 *subdir_offset_p += 8;
357
358                 /* Recursively call calculate_subdir_offsets() on all the
359                  * children. */
360                 for_dentry_in_rbtree(node, call_calculate_subdir_offsets, subdir_offset_p);
361         } else {
362                 /* On disk, childless directories have a valid subdir_offset
363                  * that points to an 8-byte end-of-directory dentry.  Regular
364                  * files or reparse points have a subdir_offset of 0. */
365                 if (dentry_is_directory(dentry))
366                         *subdir_offset_p += 8;
367                 else
368                         dentry->subdir_offset = 0;
369         }
370 }
371
372 static int
373 compare_utf16le_names(const utf16lechar *name1, size_t nbytes1,
374                       const utf16lechar *name2, size_t nbytes2)
375 {
376         int result = memcmp(name1, name2, min(nbytes1, nbytes2));
377         if (result)
378                 return result;
379         else
380                 return (int)nbytes1 - (int)nbytes2;
381 }
382
383 static int
384 dentry_compare_names(const struct wim_dentry *d1, const struct wim_dentry *d2)
385 {
386         return compare_utf16le_names(d1->file_name, d1->file_name_nbytes,
387                                      d2->file_name, d2->file_name_nbytes);
388 }
389
390
391 struct wim_dentry *
392 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
393                                    const utf16lechar *name,
394                                    size_t name_nbytes)
395 {
396         struct rb_node *node = dentry->d_inode->i_children.rb_node;
397         struct wim_dentry *child;
398         while (node) {
399                 child = rbnode_dentry(node);
400                 int result = compare_utf16le_names(name, name_nbytes,
401                                                    child->file_name,
402                                                    child->file_name_nbytes);
403                 if (result < 0)
404                         node = node->rb_left;
405                 else if (result > 0)
406                         node = node->rb_right;
407                 else
408                         return child;
409         }
410         return NULL;
411 }
412
413 /* Returns the child of @dentry that has the file name @name.  Returns NULL if
414  * no child has the name. */
415 struct wim_dentry *
416 get_dentry_child_with_name(const struct wim_dentry *dentry, const mbchar *name)
417 {
418         utf16lechar *utf16le_name;
419         size_t utf16le_name_nbytes;
420         int ret;
421         struct wim_dentry *child;
422
423         ret = mbs_to_utf16le(name, strlen(name),
424                              &utf16le_name, &utf16le_name_nbytes);
425         if (ret) {
426                 child = NULL;
427         } else {
428                 child = get_dentry_child_with_utf16le_name(dentry,
429                                                            utf16le_name,
430                                                            utf16le_name_nbytes);
431                 FREE(utf16le_name);
432         }
433         return child;
434 }
435
436 /* Returns the dentry corresponding to the @path, or NULL if there is no such
437  * dentry. */
438 struct wim_dentry *
439 get_dentry(WIMStruct *w, const mbchar *path)
440 {
441         utf16lechar *path_utf16le;
442         size_t path_utf16le_nbytes;
443         int ret;
444         struct wim_dentry *cur_dentry, *parent_dentry;
445         utf16lechar *p, *pp;
446
447         ret = mbs_to_utf16le(path, strlen(path), &path_utf16le,
448                              &path_utf16le_nbytes);
449         if (ret)
450                 return NULL;
451
452         parent_dentry = wim_root_dentry(w);
453         p = path_utf16le;
454
455         while (1) {
456                 while (*p == cpu_to_le16('/'))
457                         p++;
458                 cur_dentry = parent_dentry;
459                 if (*p == '\0')
460                         break;
461                 pp = p;
462                 while (*pp != cpu_to_le16('/') && *pp != '\0')
463                         pp++;
464
465                 cur_dentry = get_dentry_child_with_utf16le_name(parent_dentry, p,
466                                                                 (void*)pp - (void*)p);
467                 if (cur_dentry == NULL)
468                         break;
469                 p = pp;
470                 parent_dentry = cur_dentry;
471         }
472         FREE(path_utf16le);
473         if (cur_dentry == NULL) {
474                 if (dentry_is_directory(parent_dentry))
475                         errno = ENOENT;
476                 else
477                         errno = ENOTDIR;
478         }
479         return cur_dentry;
480 }
481
482 struct wim_inode *
483 wim_pathname_to_inode(WIMStruct *w, const mbchar *path)
484 {
485         struct wim_dentry *dentry;
486         dentry = get_dentry(w, path);
487         if (dentry)
488                 return dentry->d_inode;
489         else
490                 return NULL;
491 }
492
493 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
494  * if the dentry is not found. */
495 struct wim_dentry *
496 get_parent_dentry(WIMStruct *w, const mbchar *path)
497 {
498         size_t path_len = strlen(path);
499         mbchar buf[path_len + 1];
500
501         memcpy(buf, path, path_len + 1);
502         to_parent_name(buf, path_len);
503         return get_dentry(w, buf);
504 }
505
506 /* Prints the full path of a dentry. */
507 int
508 print_dentry_full_path(struct wim_dentry *dentry, void *ignore)
509 {
510         if (dentry->full_path)
511                 puts(dentry->full_path);
512         return 0;
513 }
514
515 /* We want to be able to show the names of the file attribute flags that are
516  * set. */
517 struct file_attr_flag {
518         u32 flag;
519         const char *name;
520 };
521 struct file_attr_flag file_attr_flags[] = {
522         {FILE_ATTRIBUTE_READONLY,           "READONLY"},
523         {FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
524         {FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
525         {FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
526         {FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
527         {FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
528         {FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
529         {FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
530         {FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
531         {FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
532         {FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
533         {FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
534         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
535         {FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
536         {FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
537 };
538
539 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
540  * available.  If the dentry is unresolved and the lookup table is NULL, the
541  * lookup table entries will not be printed.  Otherwise, they will be. */
542 int
543 print_dentry(struct wim_dentry *dentry, void *lookup_table)
544 {
545         const u8 *hash;
546         struct wim_lookup_table_entry *lte;
547         const struct wim_inode *inode = dentry->d_inode;
548         char buf[50];
549
550         printf("[DENTRY]\n");
551         printf("Length            = %"PRIu64"\n", dentry->length);
552         printf("Attributes        = 0x%x\n", inode->i_attributes);
553         for (size_t i = 0; i < ARRAY_LEN(file_attr_flags); i++)
554                 if (file_attr_flags[i].flag & inode->i_attributes)
555                         printf("    FILE_ATTRIBUTE_%s is set\n",
556                                 file_attr_flags[i].name);
557         printf("Security ID       = %d\n", inode->i_security_id);
558         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
559
560         wim_timestamp_to_str(inode->i_creation_time, buf, sizeof(buf));
561         printf("Creation Time     = %s\n", buf);
562
563         wim_timestamp_to_str(inode->i_last_access_time, buf, sizeof(buf));
564         printf("Last Access Time  = %s\n", buf);
565
566         wim_timestamp_to_str(inode->i_last_write_time, buf, sizeof(buf));
567         printf("Last Write Time   = %s\n", buf);
568
569         printf("Reparse Tag       = 0x%"PRIx32"\n", inode->i_reparse_tag);
570         printf("Hard Link Group   = 0x%"PRIx64"\n", inode->i_ino);
571         printf("Hard Link Group Size = %"PRIu32"\n", inode->i_nlink);
572         printf("Number of Alternate Data Streams = %hu\n", inode->i_num_ads);
573         if (dentry_has_long_name(dentry))
574                 wimlib_printf("Filename = \"%W\"\n", dentry->file_name);
575         if (dentry_has_short_name(dentry))
576                 wimlib_printf("Short Name \"%W\"\n", dentry->short_name);
577         if (dentry->full_path)
578                 printf("Full Path = \"%s\"\n", dentry->full_path);
579
580         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
581         if (lte) {
582                 print_lookup_table_entry(lte, stdout);
583         } else {
584                 hash = inode_stream_hash(inode, 0);
585                 if (hash) {
586                         printf("Hash              = 0x");
587                         print_hash(hash);
588                         putchar('\n');
589                         putchar('\n');
590                 }
591         }
592         for (u16 i = 0; i < inode->i_num_ads; i++) {
593                 printf("[Alternate Stream Entry %u]\n", i);
594                 wimlib_printf("Name = \"%W\"\n", inode->i_ads_entries[i].stream_name);
595                 printf("Name Length (UTF16 bytes) = %hu\n",
596                        inode->i_ads_entries[i].stream_name_nbytes);
597                 hash = inode_stream_hash(inode, i + 1);
598                 if (hash) {
599                         printf("Hash              = 0x");
600                         print_hash(hash);
601                         putchar('\n');
602                 }
603                 print_lookup_table_entry(inode_stream_lte(inode, i + 1, lookup_table),
604                                          stdout);
605         }
606         return 0;
607 }
608
609 /* Initializations done on every `struct wim_dentry'. */
610 static void
611 dentry_common_init(struct wim_dentry *dentry)
612 {
613         memset(dentry, 0, sizeof(struct wim_dentry));
614         dentry->refcnt = 1;
615 }
616
617 static struct wim_inode *
618 new_timeless_inode()
619 {
620         struct wim_inode *inode = CALLOC(1, sizeof(struct wim_inode));
621         if (inode) {
622                 inode->i_security_id = -1;
623                 inode->i_nlink = 1;
624         #ifdef WITH_FUSE
625                 inode->i_next_stream_id = 1;
626                 if (pthread_mutex_init(&inode->i_mutex, NULL) != 0) {
627                         ERROR_WITH_ERRNO("Error initializing mutex");
628                         FREE(inode);
629                         return NULL;
630                 }
631         #endif
632                 INIT_LIST_HEAD(&inode->i_dentry);
633         }
634         return inode;
635 }
636
637 static struct wim_inode *
638 new_inode()
639 {
640         struct wim_inode *inode = new_timeless_inode();
641         if (inode) {
642                 u64 now = get_wim_timestamp();
643                 inode->i_creation_time = now;
644                 inode->i_last_access_time = now;
645                 inode->i_last_write_time = now;
646         }
647         return inode;
648 }
649
650 /* Creates an unlinked directory entry. */
651 int new_dentry(const mbchar *name, struct wim_dentry **dentry_ret)
652 {
653         struct wim_dentry *dentry;
654         int ret;
655
656         dentry = MALLOC(sizeof(struct wim_dentry));
657         if (!dentry)
658                 return WIMLIB_ERR_NOMEM;
659
660         dentry_common_init(dentry);
661         ret = set_dentry_name(dentry, name);
662         if (ret == 0) {
663                 dentry->parent = dentry;
664                 *dentry_ret = dentry;
665         } else {
666                 FREE(dentry);
667                 ERROR("Failed to set name on new dentry with name \"%s\"", name);
668         }
669         return ret;
670 }
671
672
673 static int
674 __new_dentry_with_inode(const mbchar *name, struct wim_dentry **dentry_ret,
675                         bool timeless)
676 {
677         struct wim_dentry *dentry;
678         int ret;
679
680         ret = new_dentry(name, &dentry);
681         if (ret)
682                 return ret;
683
684         if (timeless)
685                 dentry->d_inode = new_timeless_inode();
686         else
687                 dentry->d_inode = new_inode();
688         if (!dentry->d_inode) {
689                 free_dentry(dentry);
690                 return WIMLIB_ERR_NOMEM;
691         }
692
693         inode_add_dentry(dentry, dentry->d_inode);
694         *dentry_ret = dentry;
695         return 0;
696 }
697
698 int
699 new_dentry_with_timeless_inode(const mbchar *name, struct wim_dentry **dentry_ret)
700 {
701         return __new_dentry_with_inode(name, dentry_ret, true);
702 }
703
704 int
705 new_dentry_with_inode(const mbchar *name, struct wim_dentry **dentry_ret)
706 {
707         return __new_dentry_with_inode(name, dentry_ret, false);
708 }
709
710
711 static int
712 init_ads_entry(struct wim_ads_entry *ads_entry, const void *name,
713                size_t name_nbytes, bool is_utf16le)
714 {
715         int ret = 0;
716         memset(ads_entry, 0, sizeof(*ads_entry));
717
718         if (is_utf16le) {
719                 utf16lechar *p = MALLOC(name_nbytes + sizeof(utf16lechar));
720                 if (!p)
721                         return WIMLIB_ERR_NOMEM;
722                 memcpy(p, name, name_nbytes);
723                 p[name_nbytes / 2] = 0;
724                 ads_entry->stream_name = p;
725                 ads_entry->stream_name_nbytes = name_nbytes;
726         } else {
727                 if (name && *(const char*)name) {
728                         ret = get_utf16le_name(name, &ads_entry->stream_name,
729                                                &ads_entry->stream_name_nbytes);
730                 }
731         }
732         return ret;
733 }
734
735 static void
736 destroy_ads_entry(struct wim_ads_entry *ads_entry)
737 {
738         FREE(ads_entry->stream_name);
739 }
740
741 /* Frees an inode. */
742 void free_inode(struct wim_inode *inode)
743 {
744         if (inode) {
745                 if (inode->i_ads_entries) {
746                         for (u16 i = 0; i < inode->i_num_ads; i++)
747                                 destroy_ads_entry(&inode->i_ads_entries[i]);
748                         FREE(inode->i_ads_entries);
749                 }
750         #ifdef WITH_FUSE
751                 wimlib_assert(inode->i_num_opened_fds == 0);
752                 FREE(inode->i_fds);
753                 pthread_mutex_destroy(&inode->i_mutex);
754                 if (inode->i_hlist.pprev)
755                         hlist_del(&inode->i_hlist);
756         #endif
757                 FREE(inode->i_extracted_file);
758                 FREE(inode);
759         }
760 }
761
762 /* Decrements link count on an inode and frees it if the link count reaches 0.
763  * */
764 static void put_inode(struct wim_inode *inode)
765 {
766         wimlib_assert(inode->i_nlink != 0);
767         if (--inode->i_nlink == 0) {
768         #ifdef WITH_FUSE
769                 if (inode->i_num_opened_fds == 0)
770         #endif
771                 {
772                         free_inode(inode);
773                 }
774         }
775 }
776
777 /* Frees a WIM dentry.
778  *
779  * The corresponding inode (if any) is freed only if its link count is
780  * decremented to 0.
781  */
782 void free_dentry(struct wim_dentry *dentry)
783 {
784         FREE(dentry->file_name);
785         FREE(dentry->short_name);
786         FREE(dentry->full_path);
787         if (dentry->d_inode)
788                 put_inode(dentry->d_inode);
789         FREE(dentry);
790 }
791
792 void put_dentry(struct wim_dentry *dentry)
793 {
794         wimlib_assert(dentry->refcnt != 0);
795         if (--dentry->refcnt == 0)
796                 free_dentry(dentry);
797 }
798
799 /* This function is passed as an argument to for_dentry_in_tree_depth() in order
800  * to free a directory tree. */
801 static int do_free_dentry(struct wim_dentry *dentry, void *__lookup_table)
802 {
803         struct wim_lookup_table *lookup_table = __lookup_table;
804         unsigned i;
805
806         if (lookup_table) {
807                 struct wim_lookup_table_entry *lte;
808                 struct wim_inode *inode = dentry->d_inode;
809                 wimlib_assert(inode->i_nlink != 0);
810                 for (i = 0; i <= inode->i_num_ads; i++) {
811                         lte = inode_stream_lte(inode, i, lookup_table);
812                         if (lte)
813                                 lte_decrement_refcnt(lte, lookup_table);
814                 }
815         }
816
817         put_dentry(dentry);
818         return 0;
819 }
820
821 /*
822  * Unlinks and frees a dentry tree.
823  *
824  * @root:               The root of the tree.
825  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
826  *                      reference counts in the lookup table for the lookup
827  *                      table entries corresponding to the dentries will be
828  *                      decremented.
829  */
830 void free_dentry_tree(struct wim_dentry *root, struct wim_lookup_table *lookup_table)
831 {
832         if (root)
833                 for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
834 }
835
836 int increment_dentry_refcnt(struct wim_dentry *dentry, void *ignore)
837 {
838         dentry->refcnt++;
839         return 0;
840 }
841
842 /*
843  * Links a dentry into the directory tree.
844  *
845  * @parent: The dentry that will be the parent of @dentry.
846  * @dentry: The dentry to link.
847  */
848 bool
849 dentry_add_child(struct wim_dentry * restrict parent,
850                  struct wim_dentry * restrict child)
851 {
852         wimlib_assert(dentry_is_directory(parent));
853
854         struct rb_root *root = &parent->d_inode->i_children;
855         struct rb_node **new = &(root->rb_node);
856         struct rb_node *rb_parent = NULL;
857
858         while (*new) {
859                 struct wim_dentry *this = rbnode_dentry(*new);
860                 int result = dentry_compare_names(child, this);
861
862                 rb_parent = *new;
863
864                 if (result < 0)
865                         new = &((*new)->rb_left);
866                 else if (result > 0)
867                         new = &((*new)->rb_right);
868                 else
869                         return false;
870         }
871         child->parent = parent;
872         rb_link_node(&child->rb_node, rb_parent, new);
873         rb_insert_color(&child->rb_node, root);
874         return true;
875 }
876
877 /* Unlink a WIM dentry from the directory entry tree. */
878 void
879 unlink_dentry(struct wim_dentry *dentry)
880 {
881         struct wim_dentry *parent = dentry->parent;
882         if (parent == dentry)
883                 return;
884         rb_erase(&dentry->rb_node, &parent->d_inode->i_children);
885 }
886
887 /*
888  * Returns the alternate data stream entry belonging to @inode that has the
889  * stream name @stream_name.
890  */
891 struct wim_ads_entry *
892 inode_get_ads_entry(struct wim_inode *inode, const mbchar *stream_name,
893                     u16 *idx_ret)
894 {
895         if (inode->i_num_ads == 0) {
896                 return NULL;
897         } else {
898                 int ret;
899                 utf16lechar *stream_name_utf16le;
900                 size_t stream_name_utf16le_nbytes;
901                 u16 i;
902                 struct wim_ads_entry *result;
903
904                 ret = mbs_to_utf16le(stream_name, strlen(stream_name),
905                                      &stream_name_utf16le,
906                                      &stream_name_utf16le_nbytes);
907                 if (ret)
908                         return NULL;
909
910                 i = 0;
911                 result = NULL;
912                 do {
913                         if (ads_entry_has_name(&inode->i_ads_entries[i],
914                                                stream_name_utf16le,
915                                                stream_name_utf16le_nbytes))
916                         {
917                                 if (idx_ret)
918                                         *idx_ret = i;
919                                 result = &inode->i_ads_entries[i];
920                                 break;
921                         }
922                 } while (++i != inode->i_num_ads);
923                 FREE(stream_name_utf16le);
924                 return result;
925         }
926 }
927
928 static struct wim_ads_entry *
929 do_inode_add_ads(struct wim_inode *inode, const void *stream_name,
930                  size_t stream_name_nbytes, bool is_utf16le)
931 {
932         u16 num_ads;
933         struct wim_ads_entry *ads_entries;
934         struct wim_ads_entry *new_entry;
935
936         DEBUG("Add alternate data stream \"%s\"", stream_name);
937
938         if (inode->i_num_ads >= 0xfffe) {
939                 ERROR("Too many alternate data streams in one inode!");
940                 return NULL;
941         }
942         num_ads = inode->i_num_ads + 1;
943         ads_entries = REALLOC(inode->i_ads_entries,
944                               num_ads * sizeof(inode->i_ads_entries[0]));
945         if (!ads_entries) {
946                 ERROR("Failed to allocate memory for new alternate data stream");
947                 return NULL;
948         }
949         inode->i_ads_entries = ads_entries;
950
951         new_entry = &inode->i_ads_entries[num_ads - 1];
952         if (init_ads_entry(new_entry, stream_name, stream_name_nbytes, is_utf16le))
953                 return NULL;
954 #ifdef WITH_FUSE
955         new_entry->stream_id = inode->i_next_stream_id++;
956 #endif
957         inode->i_num_ads = num_ads;
958         return new_entry;
959 }
960
961 struct wim_ads_entry *
962 inode_add_ads_utf16le(struct wim_inode *inode,
963                       const utf16lechar *stream_name,
964                       size_t stream_name_nbytes)
965 {
966         return do_inode_add_ads(inode, stream_name, stream_name_nbytes, true);
967 }
968
969 /*
970  * Add an alternate stream entry to a WIM inode and return a pointer to it, or
971  * NULL if memory could not be allocated.
972  */
973 struct wim_ads_entry *
974 inode_add_ads(struct wim_inode *inode, const char *stream_name)
975 {
976         return do_inode_add_ads(inode, stream_name, strlen(stream_name), false);
977 }
978
979 int
980 inode_add_ads_with_data(struct wim_inode *inode, const mbchar *name,
981                         const void *value, size_t size,
982                         struct wim_lookup_table *lookup_table)
983 {
984         int ret = WIMLIB_ERR_NOMEM;
985         struct wim_ads_entry *new_ads_entry;
986         struct wim_lookup_table_entry *existing_lte;
987         struct wim_lookup_table_entry *lte;
988         u8 value_hash[SHA1_HASH_SIZE];
989
990         wimlib_assert(inode->i_resolved);
991         new_ads_entry = inode_add_ads(inode, name);
992         if (!new_ads_entry)
993                 goto out;
994         sha1_buffer((const u8*)value, size, value_hash);
995         existing_lte = __lookup_resource(lookup_table, value_hash);
996         if (existing_lte) {
997                 lte = existing_lte;
998                 lte->refcnt++;
999         } else {
1000                 u8 *value_copy;
1001                 lte = new_lookup_table_entry();
1002                 if (!lte)
1003                         goto out_free_ads_entry;
1004                 value_copy = MALLOC(size);
1005                 if (!value_copy) {
1006                         FREE(lte);
1007                         goto out_free_ads_entry;
1008                 }
1009                 memcpy(value_copy, value, size);
1010                 lte->resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
1011                 lte->attached_buffer              = value_copy;
1012                 lte->resource_entry.original_size = size;
1013                 lte->resource_entry.size          = size;
1014                 lte->resource_entry.flags         = 0;
1015                 copy_hash(lte->hash, value_hash);
1016                 lookup_table_insert(lookup_table, lte);
1017         }
1018         new_ads_entry->lte = lte;
1019         ret = 0;
1020         goto out;
1021 out_free_ads_entry:
1022         inode_remove_ads(inode, new_ads_entry - inode->i_ads_entries,
1023                          lookup_table);
1024 out:
1025         return ret;
1026 }
1027
1028 /* Remove an alternate data stream from a WIM inode  */
1029 void
1030 inode_remove_ads(struct wim_inode *inode, u16 idx,
1031                  struct wim_lookup_table *lookup_table)
1032 {
1033         struct wim_ads_entry *ads_entry;
1034         struct wim_lookup_table_entry *lte;
1035
1036         wimlib_assert(idx < inode->i_num_ads);
1037         wimlib_assert(inode->i_resolved);
1038
1039         ads_entry = &inode->i_ads_entries[idx];
1040
1041         DEBUG("Remove alternate data stream \"%W\"", ads_entry->stream_name);
1042
1043         lte = ads_entry->lte;
1044         if (lte)
1045                 lte_decrement_refcnt(lte, lookup_table);
1046
1047         destroy_ads_entry(ads_entry);
1048
1049         memmove(&inode->i_ads_entries[idx],
1050                 &inode->i_ads_entries[idx + 1],
1051                 (inode->i_num_ads - idx - 1) * sizeof(inode->i_ads_entries[0]));
1052         inode->i_num_ads--;
1053 }
1054
1055 #ifndef __WIN32__
1056 int
1057 inode_get_unix_data(const struct wim_inode *inode,
1058                     struct wimlib_unix_data *unix_data,
1059                     u16 *stream_idx_ret)
1060 {
1061         const struct wim_ads_entry *ads_entry;
1062         const struct wim_lookup_table_entry *lte;
1063         size_t size;
1064         int ret;
1065
1066         wimlib_assert(inode->i_resolved);
1067
1068         ads_entry = inode_get_ads_entry((struct wim_inode*)inode,
1069                                         WIMLIB_UNIX_DATA_TAG, NULL);
1070         if (!ads_entry)
1071                 return NO_UNIX_DATA;
1072
1073         if (stream_idx_ret)
1074                 *stream_idx_ret = ads_entry - inode->i_ads_entries;
1075
1076         lte = ads_entry->lte;
1077         if (!lte)
1078                 return NO_UNIX_DATA;
1079
1080         size = wim_resource_size(lte);
1081         if (size != sizeof(struct wimlib_unix_data))
1082                 return BAD_UNIX_DATA;
1083
1084         ret = read_full_wim_resource(lte, (u8*)unix_data, 0);
1085         if (ret)
1086                 return ret;
1087
1088         if (unix_data->version != 0)
1089                 return BAD_UNIX_DATA;
1090         return 0;
1091 }
1092
1093 int
1094 inode_set_unix_data(struct wim_inode *inode, uid_t uid, gid_t gid, mode_t mode,
1095                     struct wim_lookup_table *lookup_table, int which)
1096 {
1097         struct wimlib_unix_data unix_data;
1098         int ret;
1099         bool have_good_unix_data = false;
1100         bool have_unix_data = false;
1101         u16 stream_idx;
1102
1103         if (!(which & UNIX_DATA_CREATE)) {
1104                 ret = inode_get_unix_data(inode, &unix_data, &stream_idx);
1105                 if (ret == 0 || ret == BAD_UNIX_DATA || ret > 0)
1106                         have_unix_data = true;
1107                 if (ret == 0)
1108                         have_good_unix_data = true;
1109         }
1110         unix_data.version = 0;
1111         if (which & UNIX_DATA_UID || !have_good_unix_data)
1112                 unix_data.uid = uid;
1113         if (which & UNIX_DATA_GID || !have_good_unix_data)
1114                 unix_data.gid = gid;
1115         if (which & UNIX_DATA_MODE || !have_good_unix_data)
1116                 unix_data.mode = mode;
1117         ret = inode_add_ads_with_data(inode, WIMLIB_UNIX_DATA_TAG,
1118                                       (const u8*)&unix_data,
1119                                       sizeof(struct wimlib_unix_data),
1120                                       lookup_table);
1121         if (ret == 0 && have_unix_data)
1122                 inode_remove_ads(inode, stream_idx, lookup_table);
1123         return ret;
1124 }
1125 #endif /* !__WIN32__ */
1126
1127 /*
1128  * Reads the alternate data stream entries of a WIM dentry.
1129  *
1130  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1131  *
1132  * @inode:      Inode to load the alternate data streams into.
1133  *                      @inode->i_num_ads must have been set to the number of
1134  *                      alternate data streams that are expected.
1135  *
1136  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1137  *                              to by @p.
1138  *
1139  * The format of the on-disk alternate stream entries is as follows:
1140  *
1141  * struct wim_ads_entry_on_disk {
1142  *      u64  length;          // Length of the entry, in bytes.  This includes
1143  *                                  all fields (including the stream name and
1144  *                                  null terminator if present, AND the padding!).
1145  *      u64  reserved;        // Seems to be unused
1146  *      u8   hash[20];        // SHA1 message digest of the uncompressed stream
1147  *      u16  stream_name_len; // Length of the stream name, in bytes
1148  *      char stream_name[];   // Stream name in UTF-16LE, @stream_name_len bytes long,
1149  *                                  not including null terminator
1150  *      u16  zero;            // UTF-16 null terminator for the stream name, NOT
1151  *                                  included in @stream_name_len.  Based on what
1152  *                                  I've observed from filenames in dentries,
1153  *                                  this field should not exist when
1154  *                                  (@stream_name_len == 0), but you can't
1155  *                                  actually tell because of the padding anyway
1156  *                                  (provided that the padding is zeroed, which
1157  *                                  it always seems to be).
1158  *      char padding[];       // Padding to make the size a multiple of 8 bytes.
1159  * };
1160  *
1161  * In addition, the entries are 8-byte aligned.
1162  *
1163  * Return 0 on success or nonzero on failure.  On success, inode->i_ads_entries
1164  * is set to an array of `struct wim_ads_entry's of length inode->i_num_ads.  On
1165  * failure, @inode is not modified.
1166  */
1167 static int
1168 read_ads_entries(const u8 *p, struct wim_inode *inode, u64 remaining_size)
1169 {
1170         u16 num_ads;
1171         struct wim_ads_entry *ads_entries;
1172         int ret;
1173
1174         num_ads = inode->i_num_ads;
1175         ads_entries = CALLOC(num_ads, sizeof(inode->i_ads_entries[0]));
1176         if (!ads_entries) {
1177                 ERROR("Could not allocate memory for %"PRIu16" "
1178                       "alternate data stream entries", num_ads);
1179                 return WIMLIB_ERR_NOMEM;
1180         }
1181
1182         for (u16 i = 0; i < num_ads; i++) {
1183                 struct wim_ads_entry *cur_entry;
1184                 u64 length;
1185                 u64 length_no_padding;
1186                 u64 total_length;
1187                 const u8 *p_save = p;
1188
1189                 cur_entry = &ads_entries[i];
1190
1191         #ifdef WITH_FUSE
1192                 ads_entries[i].stream_id = i + 1;
1193         #endif
1194
1195                 /* Read the base stream entry, excluding the stream name. */
1196                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
1197                         ERROR("Stream entries go past end of metadata resource");
1198                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
1199                         ret = WIMLIB_ERR_INVALID_DENTRY;
1200                         goto out_free_ads_entries;
1201                 }
1202
1203                 p = get_u64(p, &length);
1204                 p += 8; /* Skip the reserved field */
1205                 p = get_bytes(p, SHA1_HASH_SIZE, cur_entry->hash);
1206                 p = get_u16(p, &cur_entry->stream_name_nbytes);
1207
1208                 cur_entry->stream_name = NULL;
1209
1210                 /* Length including neither the null terminator nor the padding
1211                  * */
1212                 length_no_padding = WIM_ADS_ENTRY_DISK_SIZE +
1213                                     cur_entry->stream_name_nbytes;
1214
1215                 /* Length including the null terminator and the padding */
1216                 total_length = ((length_no_padding + 2) + 7) & ~7;
1217
1218                 wimlib_assert(total_length == ads_entry_total_length(cur_entry));
1219
1220                 if (remaining_size < length_no_padding) {
1221                         ERROR("Stream entries go past end of metadata resource");
1222                         ERROR("(remaining_size = %"PRIu64" bytes, "
1223                               "length_no_padding = %"PRIu64" bytes)",
1224                               remaining_size, length_no_padding);
1225                         ret = WIMLIB_ERR_INVALID_DENTRY;
1226                         goto out_free_ads_entries;
1227                 }
1228
1229                 /* The @length field in the on-disk ADS entry is expected to be
1230                  * equal to @total_length, which includes all of the entry and
1231                  * the padding that follows it to align the next ADS entry to an
1232                  * 8-byte boundary.  However, to be safe, we'll accept the
1233                  * length field as long as it's not less than the un-padded
1234                  * total length and not more than the padded total length. */
1235                 if (length < length_no_padding || length > total_length) {
1236                         ERROR("Stream entry has unexpected length "
1237                               "field (length field = %"PRIu64", "
1238                               "unpadded total length = %"PRIu64", "
1239                               "padded total length = %"PRIu64")",
1240                               length, length_no_padding, total_length);
1241                         ret = WIMLIB_ERR_INVALID_DENTRY;
1242                         goto out_free_ads_entries;
1243                 }
1244
1245                 if (cur_entry->stream_name_nbytes) {
1246                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_nbytes + 2);
1247                         if (!cur_entry->stream_name) {
1248                                 ret = WIMLIB_ERR_NOMEM;
1249                                 goto out_free_ads_entries;
1250                         }
1251                         get_bytes(p, cur_entry->stream_name_nbytes,
1252                                   cur_entry->stream_name);
1253                         cur_entry->stream_name[cur_entry->stream_name_nbytes / 2] = 0;
1254                 }
1255                 /* It's expected that the size of every ADS entry is a multiple
1256                  * of 8.  However, to be safe, I'm allowing the possibility of
1257                  * an ADS entry at the very end of the metadata resource ending
1258                  * un-aligned.  So although we still need to increment the input
1259                  * pointer by @total_length to reach the next ADS entry, it's
1260                  * possible that less than @total_length is actually remaining
1261                  * in the metadata resource. We should set the remaining size to
1262                  * 0 bytes if this happens. */
1263                 p = p_save + total_length;
1264                 if (remaining_size < total_length)
1265                         remaining_size = 0;
1266                 else
1267                         remaining_size -= total_length;
1268         }
1269         inode->i_ads_entries = ads_entries;
1270 #ifdef WITH_FUSE
1271         inode->i_next_stream_id = inode->i_num_ads + 1;
1272 #endif
1273         return 0;
1274 out_free_ads_entries:
1275         for (u16 i = 0; i < num_ads; i++)
1276                 destroy_ads_entry(&ads_entries[i]);
1277         FREE(ads_entries);
1278         return ret;
1279 }
1280
1281 /*
1282  * Reads a WIM directory entry, including all alternate data stream entries that
1283  * follow it, from the WIM image's metadata resource.
1284  *
1285  * @metadata_resource:  Buffer containing the uncompressed metadata resource.
1286  * @metadata_resource_len:   Length of the metadata resource.
1287  * @offset:     Offset of this directory entry in the metadata resource.
1288  * @dentry:     A `struct wim_dentry' that will be filled in by this function.
1289  *
1290  * Return 0 on success or nonzero on failure.  On failure, @dentry will have
1291  * been modified, but it will not be left with pointers to any allocated
1292  * buffers.  On success, the dentry->length field must be examined.  If zero,
1293  * this was a special "end of directory" dentry and not a real dentry.  If
1294  * nonzero, this was a real dentry.
1295  */
1296 int
1297 read_dentry(const u8 metadata_resource[], u64 metadata_resource_len,
1298             u64 offset, struct wim_dentry *dentry)
1299 {
1300         const u8 *p;
1301         u64 calculated_size;
1302         utf16lechar *file_name = NULL;
1303         utf16lechar *short_name = NULL;
1304         u16 short_name_nbytes;
1305         u16 file_name_nbytes;
1306         int ret;
1307         struct wim_inode *inode = NULL;
1308
1309         dentry_common_init(dentry);
1310
1311         /*Make sure the dentry really fits into the metadata resource.*/
1312         if (offset + 8 > metadata_resource_len || offset + 8 < offset) {
1313                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1314                       "end of the metadata resource (size %"PRIu64")",
1315                       offset, metadata_resource_len);
1316                 return WIMLIB_ERR_INVALID_DENTRY;
1317         }
1318
1319         /* Before reading the whole dentry, we need to read just the length.
1320          * This is because a dentry of length 8 (that is, just the length field)
1321          * terminates the list of sibling directory entries. */
1322
1323         p = get_u64(&metadata_resource[offset], &dentry->length);
1324
1325         /* A zero length field (really a length of 8, since that's how big the
1326          * directory entry is...) indicates that this is the end of directory
1327          * dentry.  We do not read it into memory as an actual dentry, so just
1328          * return successfully in that case. */
1329         if (dentry->length == 0)
1330                 return 0;
1331
1332         /* If the dentry does not overflow the metadata resource buffer and is
1333          * not too short, read the rest of it (excluding the alternate data
1334          * streams, but including the file name and short name variable-length
1335          * fields) into memory. */
1336         if (offset + dentry->length >= metadata_resource_len
1337             || offset + dentry->length < offset)
1338         {
1339                 ERROR("Directory entry at offset %"PRIu64" and with size "
1340                       "%"PRIu64" ends past the end of the metadata resource "
1341                       "(size %"PRIu64")",
1342                       offset, dentry->length, metadata_resource_len);
1343                 return WIMLIB_ERR_INVALID_DENTRY;
1344         }
1345
1346         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
1347                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1348                       dentry->length);
1349                 return WIMLIB_ERR_INVALID_DENTRY;
1350         }
1351
1352         inode = new_timeless_inode();
1353         if (!inode)
1354                 return WIMLIB_ERR_NOMEM;
1355
1356         p = get_u32(p, &inode->i_attributes);
1357         p = get_u32(p, (u32*)&inode->i_security_id);
1358         p = get_u64(p, &dentry->subdir_offset);
1359
1360         /* 2 unused fields */
1361         p += 2 * sizeof(u64);
1362         /*p = get_u64(p, &dentry->unused1);*/
1363         /*p = get_u64(p, &dentry->unused2);*/
1364
1365         p = get_u64(p, &inode->i_creation_time);
1366         p = get_u64(p, &inode->i_last_access_time);
1367         p = get_u64(p, &inode->i_last_write_time);
1368
1369         p = get_bytes(p, SHA1_HASH_SIZE, inode->i_hash);
1370
1371         /*
1372          * I don't know what's going on here.  It seems like M$ screwed up the
1373          * reparse points, then put the fields in the same place and didn't
1374          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1375          * have something to do with this, but it's not documented.
1376          */
1377         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1378                 /* ??? */
1379                 p += 4;
1380                 p = get_u32(p, &inode->i_reparse_tag);
1381                 p += 4;
1382         } else {
1383                 p = get_u32(p, &inode->i_reparse_tag);
1384                 p = get_u64(p, &inode->i_ino);
1385         }
1386
1387         /* By the way, the reparse_reserved field does not actually exist (at
1388          * least when the file is not a reparse point) */
1389
1390         p = get_u16(p, &inode->i_num_ads);
1391
1392         p = get_u16(p, &short_name_nbytes);
1393         p = get_u16(p, &file_name_nbytes);
1394
1395         /* We now know the length of the file name and short name.  Make sure
1396          * the length of the dentry is large enough to actually hold them.
1397          *
1398          * The calculated length here is unaligned to allow for the possibility
1399          * that the dentry->length names an unaligned length, although this
1400          * would be unexpected. */
1401         calculated_size = __dentry_correct_length_unaligned(file_name_nbytes,
1402                                                             short_name_nbytes);
1403
1404         if (dentry->length < calculated_size) {
1405                 ERROR("Unexpected end of directory entry! (Expected "
1406                       "at least %"PRIu64" bytes, got %"PRIu64" bytes. "
1407                       "short_name_nbytes = %hu, file_name_nbytes = %hu)",
1408                       calculated_size, dentry->length,
1409                       short_name_nbytes, file_name_nbytes);
1410                 ret = WIMLIB_ERR_INVALID_DENTRY;
1411                 goto out_free_inode;
1412         }
1413
1414         /* Read the filename if present.  Note: if the filename is empty, there
1415          * is no null terminator following it. */
1416         if (file_name_nbytes) {
1417                 file_name = MALLOC(file_name_nbytes + 2);
1418                 if (!file_name) {
1419                         ERROR("Failed to allocate %d bytes for dentry file name",
1420                               file_name_nbytes + 2);
1421                         ret = WIMLIB_ERR_NOMEM;
1422                         goto out_free_inode;
1423                 }
1424                 p = get_bytes(p, file_name_nbytes + 2, file_name);
1425                 if (file_name[file_name_nbytes / 2] != 0) {
1426                         file_name[file_name_nbytes / 2] = 0;
1427                         WARNING("File name in WIM dentry \"%W\" is not "
1428                                 "null-terminated!", file_name);
1429                 }
1430         }
1431
1432         /* Align the calculated size */
1433         calculated_size = (calculated_size + 7) & ~7;
1434
1435         if (dentry->length > calculated_size) {
1436                 /* Weird; the dentry says it's longer than it should be.  Note
1437                  * that the length field does NOT include the size of the
1438                  * alternate stream entries. */
1439
1440                 /* Strangely, some directory entries inexplicably have a little
1441                  * over 70 bytes of extra data.  The exact amount of data seems
1442                  * to be 72 bytes, but it is aligned on the next 8-byte
1443                  * boundary.  It does NOT seem to be alternate data stream
1444                  * entries.  Here's an example of the aligned data:
1445                  *
1446                  * 01000000 40000000 6c786bba c58ede11 b0bb0026 1870892a b6adb76f
1447                  * e63a3e46 8fca8653 0d2effa1 6c786bba c58ede11 b0bb0026 1870892a
1448                  * 00000000 00000000 00000000 00000000
1449                  *
1450                  * Here's one interpretation of how the data is laid out.
1451                  *
1452                  * struct unknown {
1453                  *      u32 field1; (always 0x00000001)
1454                  *      u32 field2; (always 0x40000000)
1455                  *      u8  data[48]; (???)
1456                  *      u64 reserved1; (always 0)
1457                  *      u64 reserved2; (always 0)
1458                  * };*/
1459                 /*DEBUG("Dentry for file or directory `%s' has %"PRIu64" extra "*/
1460                       /*"bytes of data",*/
1461                       /*file_name_utf8, dentry->length - calculated_size);*/
1462         }
1463
1464         /* Read the short filename if present.  Note: if there is no short
1465          * filename, there is no null terminator following it. */
1466         if (short_name_nbytes) {
1467                 short_name = MALLOC(short_name_nbytes + 2);
1468                 if (!short_name) {
1469                         ERROR("Failed to allocate %d bytes for dentry short name",
1470                               short_name_nbytes + 2);
1471                         ret = WIMLIB_ERR_NOMEM;
1472                         goto out_free_file_name;
1473                 }
1474                 p = get_bytes(p, short_name_nbytes + 2, short_name);
1475                 if (short_name[short_name_nbytes / 2] != 0) {
1476                         short_name[short_name_nbytes / 2] = 0;
1477                         WARNING("Short name in WIM dentry \"%W\" is not "
1478                                 "null-terminated!", file_name);
1479                 }
1480         }
1481
1482         /*
1483          * Read the alternate data streams, if present.  dentry->num_ads tells
1484          * us how many they are, and they will directly follow the dentry
1485          * on-disk.
1486          *
1487          * Note that each alternate data stream entry begins on an 8-byte
1488          * aligned boundary, and the alternate data stream entries are NOT
1489          * included in the dentry->length field for some reason.
1490          */
1491         if (inode->i_num_ads != 0) {
1492
1493                 /* Trying different lengths is just a hack to make sure we have
1494                  * a chance of reading the ADS entries correctly despite the
1495                  * poor documentation. */
1496
1497                 if (calculated_size != dentry->length) {
1498                         WARNING("Trying calculated dentry length (%"PRIu64") "
1499                                 "instead of dentry->length field (%"PRIu64") "
1500                                 "to read ADS entries",
1501                                 calculated_size, dentry->length);
1502                 }
1503                 u64 lengths_to_try[3] = {calculated_size,
1504                                          (dentry->length + 7) & ~7,
1505                                          dentry->length};
1506                 ret = WIMLIB_ERR_INVALID_DENTRY;
1507                 for (size_t i = 0; i < ARRAY_LEN(lengths_to_try); i++) {
1508                         if (lengths_to_try[i] > metadata_resource_len - offset)
1509                                 continue;
1510                         ret = read_ads_entries(&metadata_resource[offset + lengths_to_try[i]],
1511                                                inode,
1512                                                metadata_resource_len - offset - lengths_to_try[i]);
1513                         if (ret == 0)
1514                                 goto out;
1515                 }
1516                 ERROR("Failed to read alternate data stream "
1517                       "entries of WIM dentry \"%W\"", file_name);
1518                 goto out_free_short_name;
1519         }
1520 out:
1521         /* We've read all the data for this dentry.  Set the names and their
1522          * lengths, and we've done. */
1523         dentry->d_inode           = inode;
1524         dentry->file_name         = file_name;
1525         dentry->short_name        = short_name;
1526         dentry->file_name_nbytes  = file_name_nbytes;
1527         dentry->short_name_nbytes = short_name_nbytes;
1528         return 0;
1529 out_free_short_name:
1530         FREE(short_name);
1531 out_free_file_name:
1532         FREE(file_name);
1533 out_free_inode:
1534         free_inode(inode);
1535         return ret;
1536 }
1537
1538 /* Reads the children of a dentry, and all their children, ..., etc. from the
1539  * metadata resource and into the dentry tree.
1540  *
1541  * @metadata_resource:  An array that contains the uncompressed metadata
1542  *                      resource for the WIM file.
1543  *
1544  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1545  *                          bytes.
1546  *
1547  * @dentry:     A pointer to a `struct wim_dentry' that is the root of the directory
1548  *              tree and has already been read from the metadata resource.  It
1549  *              does not need to be the real root because this procedure is
1550  *              called recursively.
1551  *
1552  * Returns zero on success; nonzero on failure.
1553  */
1554 int
1555 read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1556                  struct wim_dentry *dentry)
1557 {
1558         u64 cur_offset = dentry->subdir_offset;
1559         struct wim_dentry *child;
1560         struct wim_dentry cur_child;
1561         int ret;
1562
1563         /*
1564          * If @dentry has no child dentries, nothing more needs to be done for
1565          * this branch.  This is the case for regular files, symbolic links, and
1566          * *possibly* empty directories (although an empty directory may also
1567          * have one child dentry that is the special end-of-directory dentry)
1568          */
1569         if (cur_offset == 0)
1570                 return 0;
1571
1572         /* Find and read all the children of @dentry. */
1573         while (1) {
1574
1575                 /* Read next child of @dentry into @cur_child. */
1576                 ret = read_dentry(metadata_resource, metadata_resource_len,
1577                                   cur_offset, &cur_child);
1578                 if (ret != 0)
1579                         break;
1580
1581                 /* Check for end of directory. */
1582                 if (cur_child.length == 0)
1583                         break;
1584
1585                 /* Not end of directory.  Allocate this child permanently and
1586                  * link it to the parent and previous child. */
1587                 child = MALLOC(sizeof(struct wim_dentry));
1588                 if (!child) {
1589                         ERROR("Failed to allocate %zu bytes for new dentry",
1590                               sizeof(struct wim_dentry));
1591                         ret = WIMLIB_ERR_NOMEM;
1592                         break;
1593                 }
1594                 memcpy(child, &cur_child, sizeof(struct wim_dentry));
1595                 dentry_add_child(dentry, child);
1596                 inode_add_dentry(child, child->d_inode);
1597
1598                 /* If there are children of this child, call this procedure
1599                  * recursively. */
1600                 if (child->subdir_offset != 0) {
1601                         ret = read_dentry_tree(metadata_resource,
1602                                                metadata_resource_len, child);
1603                         if (ret != 0)
1604                                 break;
1605                 }
1606
1607                 /* Advance to the offset of the next child.  Note: We need to
1608                  * advance by the TOTAL length of the dentry, not by the length
1609                  * child->length, which although it does take into account the
1610                  * padding, it DOES NOT take into account alternate stream
1611                  * entries. */
1612                 cur_offset += dentry_total_length(child);
1613         }
1614         return ret;
1615 }
1616
1617 /*
1618  * Writes a WIM dentry to an output buffer.
1619  *
1620  * @dentry:  The dentry structure.
1621  * @p:       The memory location to write the data to.
1622  * @return:  Pointer to the byte after the last byte we wrote as part of the
1623  *              dentry.
1624  */
1625 static u8 *
1626 write_dentry(const struct wim_dentry *dentry, u8 *p)
1627 {
1628         u8 *orig_p = p;
1629         const u8 *hash;
1630         const struct wim_inode *inode = dentry->d_inode;
1631
1632         /* We calculate the correct length of the dentry ourselves because the
1633          * dentry->length field may been set to an unexpected value from when we
1634          * read the dentry in (for example, there may have been unknown data
1635          * appended to the end of the dentry...) */
1636         u64 length = dentry_correct_length(dentry);
1637
1638         p = put_u64(p, length);
1639         p = put_u32(p, inode->i_attributes);
1640         p = put_u32(p, inode->i_security_id);
1641         p = put_u64(p, dentry->subdir_offset);
1642         p = put_u64(p, 0); /* unused1 */
1643         p = put_u64(p, 0); /* unused2 */
1644         p = put_u64(p, inode->i_creation_time);
1645         p = put_u64(p, inode->i_last_access_time);
1646         p = put_u64(p, inode->i_last_write_time);
1647         hash = inode_stream_hash(inode, 0);
1648         p = put_bytes(p, SHA1_HASH_SIZE, hash);
1649         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1650                 p = put_zeroes(p, 4);
1651                 p = put_u32(p, inode->i_reparse_tag);
1652                 p = put_zeroes(p, 4);
1653         } else {
1654                 u64 link_group_id;
1655                 p = put_u32(p, 0);
1656                 if (inode->i_nlink == 1)
1657                         link_group_id = 0;
1658                 else
1659                         link_group_id = inode->i_ino;
1660                 p = put_u64(p, link_group_id);
1661         }
1662         p = put_u16(p, inode->i_num_ads);
1663         p = put_u16(p, dentry->short_name_nbytes);
1664         p = put_u16(p, dentry->file_name_nbytes);
1665         if (dentry_has_long_name(dentry)) {
1666                 p = put_bytes(p, dentry->file_name_nbytes + 2,
1667                               dentry->file_name);
1668         }
1669         if (dentry_has_short_name(dentry)) {
1670                 p = put_bytes(p, dentry->short_name_nbytes + 2,
1671                               dentry->short_name);
1672         }
1673
1674         /* Align to 8-byte boundary */
1675         wimlib_assert(length >= (p - orig_p) && length - (p - orig_p) <= 7);
1676         p = put_zeroes(p, length - (p - orig_p));
1677
1678         /* Write the alternate data streams, if there are any.  Please see
1679          * read_ads_entries() for comments about the format of the on-disk
1680          * alternate data stream entries. */
1681         for (u16 i = 0; i < inode->i_num_ads; i++) {
1682                 p = put_u64(p, ads_entry_total_length(&inode->i_ads_entries[i]));
1683                 p = put_u64(p, 0); /* Unused */
1684                 hash = inode_stream_hash(inode, i + 1);
1685                 p = put_bytes(p, SHA1_HASH_SIZE, hash);
1686                 p = put_u16(p, inode->i_ads_entries[i].stream_name_nbytes);
1687                 if (inode->i_ads_entries[i].stream_name_nbytes) {
1688                         p = put_bytes(p,
1689                                       inode->i_ads_entries[i].stream_name_nbytes + 2,
1690                                       inode->i_ads_entries[i].stream_name);
1691                 }
1692                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1693         }
1694         wimlib_assert(p - orig_p == __dentry_total_length(dentry, length));
1695         return p;
1696 }
1697
1698 static int
1699 write_dentry_cb(struct wim_dentry *dentry, void *_p)
1700 {
1701         u8 **p = _p;
1702         *p = write_dentry(dentry, *p);
1703         return 0;
1704 }
1705
1706 static u8 *
1707 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p);
1708
1709 static int
1710 write_dentry_tree_recursive_cb(struct wim_dentry *dentry, void *_p)
1711 {
1712         u8 **p = _p;
1713         *p = write_dentry_tree_recursive(dentry, *p);
1714         return 0;
1715 }
1716
1717 /* Recursive function that writes a dentry tree rooted at @parent, not including
1718  * @parent itself, which has already been written. */
1719 static u8 *
1720 write_dentry_tree_recursive(const struct wim_dentry *parent, u8 *p)
1721 {
1722         /* Nothing to do if this dentry has no children. */
1723         if (parent->subdir_offset == 0)
1724                 return p;
1725
1726         /* Write child dentries and end-of-directory entry.
1727          *
1728          * Note: we need to write all of this dentry's children before
1729          * recursively writing the directory trees rooted at each of the child
1730          * dentries, since the on-disk dentries for a dentry's children are
1731          * always located at consecutive positions in the metadata resource! */
1732         for_dentry_child(parent, write_dentry_cb, &p);
1733
1734         /* write end of directory entry */
1735         p = put_u64(p, 0);
1736
1737         /* Recurse on children. */
1738         for_dentry_child(parent, write_dentry_tree_recursive_cb, &p);
1739         return p;
1740 }
1741
1742 /* Writes a directory tree to the metadata resource.
1743  *
1744  * @root:       Root of the dentry tree.
1745  * @p:          Pointer to a buffer with enough space for the dentry tree.
1746  *
1747  * Returns pointer to the byte after the last byte we wrote.
1748  */
1749 u8 *
1750 write_dentry_tree(const struct wim_dentry *root, u8 *p)
1751 {
1752         DEBUG("Writing dentry tree.");
1753         wimlib_assert(dentry_is_root(root));
1754
1755         /* If we're the root dentry, we have no parent that already
1756          * wrote us, so we need to write ourselves. */
1757         p = write_dentry(root, p);
1758
1759         /* Write end of directory entry after the root dentry just to be safe;
1760          * however the root dentry obviously cannot have any siblings. */
1761         p = put_u64(p, 0);
1762
1763         /* Recursively write the rest of the dentry tree. */
1764         return write_dentry_tree_recursive(root, p);
1765 }