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