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