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