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