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