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