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