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