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