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