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