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