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