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