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