4dd26ee0352ab8f71194ed2c46975fdf6e10aa2b
[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
43 /* Transfers file attributes from a `stat' buffer to a struct dentry. */
44 void stbuf_to_dentry(const struct stat *stbuf, struct dentry *dentry)
45 {
46         if (S_ISDIR(stbuf->st_mode))
47                 dentry->attributes = WIM_FILE_ATTRIBUTE_DIRECTORY;
48         else
49                 dentry->attributes = WIM_FILE_ATTRIBUTE_NORMAL;
50 }
51
52 /* Transfers file attributes from a struct dentry to a `stat' buffer. */
53 void dentry_to_stbuf(const struct dentry *dentry, struct stat *stbuf, 
54                      const struct lookup_table *table)
55 {
56         struct lookup_table_entry *lte;
57
58         if (dentry_is_directory(dentry))
59                 stbuf->st_mode = S_IFDIR | 0755;
60         else
61                 stbuf->st_mode = S_IFREG | 0644;
62
63         if (table)
64                 lte = lookup_resource(table, dentry->hash);
65         else
66                 lte = NULL;
67
68         if (lte) {
69                 stbuf->st_nlink = lte->refcnt;
70                 stbuf->st_size = lte->resource_entry.original_size;
71         } else {
72                 stbuf->st_nlink = 1;
73                 stbuf->st_size = 0;
74         }
75         stbuf->st_uid     = getuid();
76         stbuf->st_gid     = getgid();
77         stbuf->st_atime   = ms_timestamp_to_unix(dentry->last_access_time);
78         stbuf->st_mtime   = ms_timestamp_to_unix(dentry->last_write_time);
79         stbuf->st_ctime   = ms_timestamp_to_unix(dentry->creation_time);
80         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
81 }
82
83 /* Makes all timestamp fields for the dentry be the current time. */
84 void dentry_update_all_timestamps(struct dentry *dentry)
85 {
86         u64 now = get_timestamp();
87         dentry->creation_time       = now;
88         dentry->last_access_time    = now;
89         dentry->last_write_time     = now;
90 }
91
92 /* 
93  * Calls a function on all directory entries in a directory tree.  It is called
94  * on a parent before its children.
95  */
96 int for_dentry_in_tree(struct dentry *root, 
97                        int (*visitor)(struct dentry*, void*), void *arg)
98 {
99         int ret;
100         struct dentry *child;
101
102         ret = visitor(root, arg);
103
104         if (ret != 0)
105                 return ret;
106
107         child = root->children;
108
109         if (!child)
110                 return 0;
111
112         do {
113                 ret = for_dentry_in_tree(child, visitor, arg);
114                 if (ret != 0)
115                         return ret;
116                 child = child->next;
117         } while (child != root->children);
118         return 0;
119 }
120
121 /* 
122  * Like for_dentry_in_tree(), but the visitor function is always called on a
123  * dentry's children before on itself.
124  */
125 int for_dentry_in_tree_depth(struct dentry *root, 
126                              int (*visitor)(struct dentry*, void*), void *arg)
127 {
128         int ret;
129         struct dentry *child;
130         struct dentry *next;
131
132         child = root->children;
133         if (child) {
134                 do {
135                         next = child->next;
136                         ret = for_dentry_in_tree_depth(child, visitor, arg);
137                         if (ret != 0)
138                                 return ret;
139                         child = next;
140                 } while (child != root->children);
141         }
142         return visitor(root, arg);
143 }
144
145 /* 
146  * Calculate the full path of @dentry, based on its parent's full path and on
147  * its UTF-8 file name. 
148  */
149 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
150 {
151         int parent_len;
152         int len;
153         char *parent_full_path;
154         char *full_path;
155
156         FREE(dentry->full_path_utf8);
157
158         if (dentry_is_root(dentry)) {
159                 dentry->full_path_utf8 = MALLOC(2);
160                 if (!dentry->full_path_utf8) {
161                         ERROR("Out of memory!\n");
162                         return WIMLIB_ERR_NOMEM;
163                 }
164
165                 dentry->full_path_utf8[0] = '/';
166                 dentry->full_path_utf8[1] = '\0';
167                 dentry->full_path_utf8_len = 1;
168                 return 0;
169         }
170
171         if (dentry_is_root(dentry->parent)) {
172                 parent_len = 0;
173                 parent_full_path = "";
174         } else {
175                 parent_len = dentry->parent->full_path_utf8_len;
176                 parent_full_path = dentry->parent->full_path_utf8;
177         }
178
179         len = parent_len + 1 + dentry->file_name_utf8_len;
180         full_path = MALLOC(len + 1);
181         if (!full_path) {
182                 ERROR("Out of memory!\n");
183                 return WIMLIB_ERR_NOMEM;
184         }
185
186         memcpy(full_path, parent_full_path, parent_len);
187         full_path[parent_len] = '/';
188         memcpy(full_path + parent_len + 1, dentry->file_name_utf8, 
189                                 dentry->file_name_utf8_len);
190         full_path[len] = '\0';
191         dentry->full_path_utf8 = full_path;
192         dentry->full_path_utf8_len = len;
193         return 0;
194 }
195
196 /* 
197  * Recursively calculates the subdir offsets for a directory tree. 
198  *
199  * @dentry:  The root of the directory tree.
200  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
201  *      offset for @dentry. 
202  */
203 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
204 {
205         struct dentry *child;
206
207         child = dentry->children;
208         dentry->subdir_offset = *subdir_offset_p;
209         if (child) {
210
211                 /* Advance the subdir offset by the amount of space the children
212                  * of this dentry take up. */
213                 do {
214                         *subdir_offset_p += child->length;
215                         child = child->next;
216                 } while (child != dentry->children);
217
218                 /* End-of-directory dentry on disk. */
219                 *subdir_offset_p += 8;
220
221                 /* Recursively call calculate_subdir_offsets() on all the
222                  * children. */
223                 do {
224                         calculate_subdir_offsets(child, subdir_offset_p);
225                         child = child->next;
226                 } while (child != dentry->children);
227         } else {
228                 /* On disk, childless directories have a valid subdir_offset
229                  * that points to an 8-byte end-of-directory dentry.  Regular
230                  * files have a subdir_offset of 0. */
231                 if (dentry_is_directory(dentry))
232                         *subdir_offset_p += 8;
233                 else
234                         dentry->subdir_offset = 0;
235         }
236 }
237
238
239 /* Returns the child of @dentry that has the file name @name.  
240  * Returns NULL if no child has the name. */
241 struct dentry *get_dentry_child_with_name(const struct dentry *dentry, 
242                                                         const char *name)
243 {
244         struct dentry *child;
245         size_t name_len;
246         
247         child = dentry->children;
248         if (child) {
249                 name_len = strlen(name);
250                 do {
251                         if (dentry_has_name(child, name, name_len))
252                                 return child;
253                         child = child->next;
254                 } while (child != dentry->children);
255         }
256         return NULL;
257 }
258
259 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
260  * @cur_dir.  Returns NULL if no dentry having the path is found. */
261 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir, const char *path)
262 {
263         struct dentry *child;
264         size_t base_len;
265         const char *new_path;
266
267         if (*path == '\0')
268                 return cur_dir;
269
270         child = cur_dir->children;
271         if (child) {
272                 new_path = path_next_part(path, &base_len);
273                 do {
274                         if (dentry_has_name(child, path, base_len))
275                                 return get_dentry_relative_path(child, new_path);
276                         child = child->next;
277                 } while (child != cur_dir->children);
278         }
279         return NULL;
280 }
281
282 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
283  * such dentry. */
284 struct dentry *get_dentry(WIMStruct *w, const char *path)
285 {
286         struct dentry *root = wim_root_dentry(w);
287         while (*path == '/')
288                 path++;
289         return get_dentry_relative_path(root, path);
290 }
291
292 /* Returns the parent directory for the @path. */
293 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
294 {
295         size_t path_len = strlen(path);
296         char buf[path_len + 1];
297
298         memcpy(buf, path, path_len + 1);
299
300         to_parent_name(buf, path_len);
301
302         return get_dentry(w, buf);
303 }
304
305 /* Prints the full path of a dentry. */
306 int print_dentry_full_path(struct dentry *dentry, void *ignore)
307 {
308         if (dentry->full_path_utf8)
309                 puts(dentry->full_path_utf8);
310         return 0;
311 }
312
313 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, or
314  * NULL if the resource entry for the dentry is not to be printed. */
315 int print_dentry(struct dentry *dentry, void *lookup_table)
316 {
317         struct lookup_table_entry *lte;
318         printf("[DENTRY]\n");
319         printf("Length            = %"PRIu64"\n", dentry->length);
320         printf("Attributes        = 0x%x\n", dentry->attributes);
321 #ifdef ENABLE_SECURITY_DATA
322         printf("Security ID       = %d\n", dentry->security_id);
323 #endif
324         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
325         /*printf("Unused1           = %"PRIu64"\n", dentry->unused1);*/
326         /*printf("Unused2           = %"PRIu64"\n", dentry->unused2);*/
327         printf("Creation Time     = %"PRIu64"\n", dentry->creation_time);
328         printf("Last Access Time  = %"PRIu64"\n", dentry->last_access_time);
329         printf("Last Write Time   = %"PRIu64"\n", dentry->last_write_time);
330         printf("Creation Time     = 0x%"PRIx64"\n", dentry->creation_time);
331         printf("Hash              = "); 
332         print_hash(dentry->hash); 
333         putchar('\n');
334         /*printf("Reparse Tag       = %u\n", dentry->reparse_tag);*/
335         printf("Hard Link Group   = %"PRIu64"\n", dentry->hard_link);
336         /*printf("Number of Streams = %hu\n", dentry->streams);*/
337         printf("Filename          = \"");
338         print_string(dentry->file_name, dentry->file_name_len);
339         puts("\"");
340         printf("Filename Length   = %hu\n", dentry->file_name_len);
341         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
342         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
343         printf("Short Name        = \"");
344         print_string(dentry->short_name, dentry->short_name_len);
345         puts("\"");
346         printf("Short Name Length = %hu\n", dentry->short_name_len);
347         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
348         if (lookup_table) {
349                 lte = lookup_resource(lookup_table, dentry->hash);
350                 if (lte)
351                         print_lookup_table_entry(lte, NULL);
352                 else
353                         putchar('\n');
354         } else {
355                 putchar('\n');
356         }
357         return 0;
358 }
359
360 static inline void dentry_common_init(struct dentry *dentry)
361 {
362         memset(dentry, 0, sizeof(struct dentry));
363         dentry->refcnt = 1;
364 #ifdef ENABLE_SECURITY_DATA
365         dentry->security_id = -1;
366 #endif
367 }
368
369 /* 
370  * Creates an unlinked directory entry.
371  *
372  * @name:    The base name of the new dentry.
373  * @return:  A pointer to the new dentry, or NULL if out of memory.
374  */
375 struct dentry *new_dentry(const char *name)
376 {
377         struct dentry *dentry;
378         
379         dentry = MALLOC(sizeof(struct dentry));
380         if (!dentry)
381                 return NULL;
382
383         dentry_common_init(dentry);
384         if (change_dentry_name(dentry, name) != 0) {
385                 FREE(dentry);
386                 return NULL;
387         }
388
389         dentry_update_all_timestamps(dentry);
390         dentry->next   = dentry;
391         dentry->prev   = dentry;
392         dentry->parent = dentry;
393         return dentry;
394 }
395
396
397 void free_dentry(struct dentry *dentry)
398 {
399         FREE(dentry->file_name);
400         FREE(dentry->file_name_utf8);
401         FREE(dentry->short_name);
402         FREE(dentry->full_path_utf8);
403         FREE(dentry);
404 }
405
406 /* Arguments for do_free_dentry(). */
407 struct free_dentry_args {
408         struct lookup_table *lookup_table;
409         bool decrement_refcnt;
410 };
411
412 /* 
413  * This function is passed as an argument to for_dentry_in_tree_depth() in order
414  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
415  */
416 static int do_free_dentry(struct dentry *dentry, void *__args)
417 {
418         struct free_dentry_args *args = (struct free_dentry_args*)__args;
419
420         if (args->decrement_refcnt && !dentry_is_directory(dentry)) {
421                 lookup_table_decrement_refcnt(args->lookup_table, 
422                                               dentry->hash);
423         }
424
425         wimlib_assert(dentry->refcnt >= 1);
426         if (--dentry->refcnt == 0)
427                 free_dentry(dentry);
428         return 0;
429 }
430
431 /* 
432  * Unlinks and frees a dentry tree.
433  *
434  * @root:               The root of the tree.
435  * @lookup_table:       The lookup table for dentries.
436  * @decrement_refcnt:   True if the dentries in the tree are to have their 
437  *                      reference counts in the lookup table decremented.
438  */
439 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table, 
440                       bool decrement_refcnt)
441 {
442         if (!root || !root->parent)
443                 return;
444
445         struct free_dentry_args args;
446         args.lookup_table        = lookup_table;
447         args.decrement_refcnt    = decrement_refcnt;
448         for_dentry_in_tree_depth(root, do_free_dentry, &args);
449 }
450
451 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
452 {
453         dentry->refcnt++;
454         return 0;
455 }
456
457 /* 
458  * Links a dentry into the directory tree.
459  *
460  * @dentry: The dentry to link.
461  * @parent: The dentry that will be the parent of @dentry.
462  */
463 void link_dentry(struct dentry *dentry, struct dentry *parent)
464 {
465         dentry->parent = parent;
466         if (parent->children) {
467                 /* Not an only child; link to siblings. */
468                 dentry->next = parent->children;
469                 dentry->prev = parent->children->prev;
470                 dentry->next->prev = dentry;
471                 dentry->prev->next = dentry;
472         } else {
473                 /* Only child; link to parent. */
474                 parent->children = dentry;
475                 dentry->next = dentry;
476                 dentry->prev = dentry;
477         }
478 }
479
480 /* Unlink a dentry from the directory tree. */
481 void unlink_dentry(struct dentry *dentry)
482 {
483         if (dentry_is_root(dentry))
484                 return;
485         if (dentry_is_only_child(dentry)) {
486                 dentry->parent->children = NULL;
487         } else {
488                 if (dentry_is_first_sibling(dentry))
489                         dentry->parent->children = dentry->next;
490                 dentry->next->prev = dentry->prev;
491                 dentry->prev->next = dentry->next;
492         }
493 }
494
495
496 /* Recalculates the length of @dentry based on its file name length and short
497  * name length.  */
498 static inline void recalculate_dentry_size(struct dentry *dentry)
499 {
500         dentry->length = WIM_DENTRY_DISK_SIZE + dentry->file_name_len + 
501                          2 + dentry->short_name_len;
502         /* Must be multiple of 8. */
503         dentry->length += (8 - dentry->length % 8) % 8;
504 }
505
506 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
507  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
508  * full_path_utf8 fields.  Also recalculates its length. */
509 int change_dentry_name(struct dentry *dentry, const char *new_name)
510 {
511         size_t utf8_len;
512         size_t utf16_len;
513
514         FREE(dentry->file_name);
515
516         utf8_len = strlen(new_name);
517
518         dentry->file_name = utf8_to_utf16(new_name, utf8_len, &utf16_len);
519
520         if (!dentry->file_name)
521                 return WIMLIB_ERR_NOMEM;
522
523         FREE(dentry->file_name_utf8);
524         dentry->file_name_utf8 = MALLOC(utf8_len + 1);
525         if (!dentry->file_name_utf8) {
526                 FREE(dentry->file_name);
527                 dentry->file_name = NULL;
528                 return WIMLIB_ERR_NOMEM;
529         }
530
531         dentry->file_name_len = utf16_len;
532         dentry->file_name_utf8_len = utf8_len;
533         memcpy(dentry->file_name_utf8, new_name, utf8_len + 1);
534         recalculate_dentry_size(dentry);
535         return 0;
536 }
537
538 /* Parameters for calculate_dentry_statistics(). */
539 struct image_statistics {
540         struct lookup_table *lookup_table;
541         u64 *dir_count;
542         u64 *file_count;
543         u64 *total_bytes;
544         u64 *hard_link_bytes;
545 };
546
547 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
548 {
549         struct image_statistics *stats;
550         struct lookup_table_entry *lte; 
551         
552         stats = arg;
553         lte = lookup_resource(stats->lookup_table, dentry->hash);
554
555         if (dentry_is_directory(dentry) && !dentry_is_root(dentry))
556                 ++*stats->dir_count;
557         else
558                 ++*stats->file_count;
559
560         if (lte) {
561                 u64 size = lte->resource_entry.original_size;
562                 *stats->total_bytes += size;
563                 if (++lte->out_refcnt == 1)
564                         *stats->hard_link_bytes += size;
565         }
566         return 0;
567 }
568
569 void calculate_dir_tree_statistics(struct dentry *root, struct lookup_table *table, 
570                                    u64 *dir_count_ret, u64 *file_count_ret, 
571                                    u64 *total_bytes_ret, 
572                                    u64 *hard_link_bytes_ret)
573 {
574         struct image_statistics stats;
575         *dir_count_ret         = 0;
576         *file_count_ret        = 0;
577         *total_bytes_ret       = 0;
578         *hard_link_bytes_ret   = 0;
579         stats.lookup_table     = table;
580         stats.dir_count       = dir_count_ret;
581         stats.file_count      = file_count_ret;
582         stats.total_bytes     = total_bytes_ret;
583         stats.hard_link_bytes = hard_link_bytes_ret;
584         for_lookup_table_entry(table, zero_out_refcnts, NULL);
585         for_dentry_in_tree(root, calculate_dentry_statistics, &stats);
586 }
587
588 /* 
589  * Reads a directory entry from the metadata resource.
590  */
591 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len, 
592                                         u64 offset, struct dentry *dentry)
593 {
594         const u8 *p;
595         u64 calculated_size;
596         char *file_name;
597         char *file_name_utf8;
598         char *short_name;
599         u16 short_name_len;
600         u16 file_name_len;
601         size_t file_name_utf8_len;
602
603         dentry_common_init(dentry);
604
605         /*Make sure the dentry really fits into the metadata resource.*/
606         if (offset + 8 > metadata_resource_len) {
607                 ERROR("Directory entry starting at %"PRIu64" ends past the "
608                         "end of the metadata resource (size %"PRIu64")!\n",
609                         offset, metadata_resource_len);
610                 return WIMLIB_ERR_INVALID_DENTRY;
611         }
612
613         /* Before reading the whole entry, we need to read just the length.
614          * This is because an entry of length 8 (that is, just the length field)
615          * terminates the list of sibling directory entries. */
616
617         p = get_u64(&metadata_resource[offset], &dentry->length);
618
619         /* A zero length field (really a length of 8, since that's how big the
620          * directory entry is...) indicates that this is the end of directory
621          * dentry.  We do not read it into memory as an actual dentry, so just
622          * return true in that case. */
623         if (dentry->length == 0)
624                 return 0;
625
626         if (offset + dentry->length >= metadata_resource_len) {
627                 ERROR("Directory entry at offset %"PRIu64" and with size "
628                                 "%"PRIu64" ends past the end of the metadata resource "
629                                 "(size %"PRIu64")!\n", offset, dentry->length,
630                                 metadata_resource_len);
631                 return WIMLIB_ERR_INVALID_DENTRY;
632         }
633
634         /* If it is a recognized length, read the rest of the directory entry.
635          * Note: The root directory entry has no name, and its length does not
636          * include the short name length field.  */
637         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
638                 ERROR("Directory entry has invalid length of "
639                                 "%"PRIu64" bytes\n", dentry->length);
640                 return WIMLIB_ERR_INVALID_DENTRY;
641         }
642
643         p = get_u32(p, &dentry->attributes);
644 #ifdef ENABLE_SECURITY_DATA
645         p = get_u32(p, (u32*)&dentry->security_id);
646 #else
647         p += sizeof(u32);
648 #endif
649         p = get_u64(p, &dentry->subdir_offset);
650
651         /* 2 unused fields */
652         p += 2 * sizeof(u64);
653
654         p = get_u64(p, &dentry->creation_time);
655         p = get_u64(p, &dentry->last_access_time);
656         p = get_u64(p, &dentry->last_write_time);
657
658         p = get_bytes(p, WIM_HASH_SIZE, dentry->hash);
659         
660         /* Currently ignoring reparse_tag. */
661         p += sizeof(u32);
662
663         /* The reparse_reserved field does not actually exist. */
664
665         p = get_u64(p, &dentry->hard_link);
666         
667         /* Currently ignoring streams. */
668         p += sizeof(u16);
669
670         p = get_u16(p, &short_name_len);
671         p = get_u16(p, &file_name_len);
672
673         calculated_size = WIM_DENTRY_DISK_SIZE + file_name_len + 2 +
674                           short_name_len;
675
676         if (dentry->length < calculated_size) {
677                 ERROR("Unexpected end of directory entry! (Expected "
678                                 "%"PRIu64" bytes, got %"PRIu64" bytes. "
679                                 "short_name_len = %hu, file_name_len = %hu)\n", 
680                                 calculated_size, dentry->length,
681                                 short_name_len, file_name_len);
682                 return WIMLIB_ERR_INVALID_DENTRY;
683         }
684
685         /* Read the filename. */
686         file_name = MALLOC(file_name_len);
687         if (!file_name) {
688                 ERROR("Failed to allocate %hu bytes for dentry file name!\n",
689                                 file_name_len);
690                 return WIMLIB_ERR_NOMEM;
691         }
692         p = get_bytes(p, file_name_len, file_name);
693
694         /* Convert filename to UTF-8. */
695         file_name_utf8 = utf16_to_utf8(file_name, file_name_len, 
696                                        &file_name_utf8_len);
697
698         if (!file_name_utf8) {
699                 ERROR("Failed to allocate memory to convert UTF16 "
700                                 "filename (%hu bytes) to UTF8\n",
701                                 file_name_len);
702                 goto err_nomem2;
703         }
704
705         /* Undocumented padding between file name and short name.  This probably
706          * is supposed to be a terminating NULL character. */
707         p += 2;
708
709         /* Read the short filename. */
710         short_name = MALLOC(short_name_len);
711         if (!short_name) {
712                 ERROR("Failed to allocate %hu bytes for short filename\n",
713                                 short_name_len);
714                 goto err_nomem1;
715         }
716
717         get_bytes(p, short_name_len, short_name);
718
719         dentry->file_name          = file_name;
720         dentry->file_name_utf8     = file_name_utf8;
721         dentry->short_name         = short_name;
722         dentry->file_name_len      = file_name_len;
723         dentry->file_name_utf8_len = file_name_utf8_len;
724         dentry->short_name_len     = short_name_len;
725         return 0;
726 err_nomem1:
727         FREE(dentry->file_name_utf8);
728 err_nomem2:
729         FREE(dentry->file_name);
730         return WIMLIB_ERR_NOMEM;
731 }
732
733 /* 
734  * Writes a dentry to an output buffer.
735  *
736  * @dentry:  The dentry structure.
737  * @p:       The memory location to write the data to.
738  * @return:  True on success, false on failure.
739  */
740 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
741 {
742         u8 *orig_p = p;
743         memset(p, 0, dentry->length);
744         p = put_u64(p, dentry->length);
745         p = put_u32(p, dentry->attributes);
746 #ifdef ENABLE_SECURITY_DATA
747         p = put_u32(p, dentry->security_id);
748 #else
749         p = put_u32(p, (u32)(-1));
750 #endif
751         p = put_u64(p, dentry->subdir_offset);
752         p = put_u64(p, 0); /* unused1 */
753         p = put_u64(p, 0); /* unused2 */
754         p = put_u64(p, dentry->creation_time);
755         p = put_u64(p, dentry->last_access_time);
756         p = put_u64(p, dentry->last_write_time);
757         if (!is_empty_file_hash(dentry->hash))
758                 memcpy(p, dentry->hash, WIM_HASH_SIZE);
759         else
760                 DEBUG("zero hash for %s\n", dentry->file_name_utf8);
761         p += WIM_HASH_SIZE;
762         p = put_u32(p, 0); /* reparse_tag */
763         p = put_u64(p, dentry->hard_link);
764         p = put_u16(p, 0); /*streams */
765         p = put_u16(p, dentry->short_name_len);
766         p = put_u16(p, dentry->file_name_len);
767         p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
768         p = put_u16(p, 0); /* filename padding, 2 bytes. */
769         p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
770         return orig_p + dentry->length;
771 }
772
773 /* Recursive function that writes a dentry tree rooted at @tree, not including
774  * @tree itself, which has already been written, except in the case of the root
775  * dentry, which is written right away, along with an end-of-directory entry. */
776 u8 *write_dentry_tree(const struct dentry *tree, u8 *p)
777 {
778         const struct dentry *child;
779
780         if (dentry_is_root(tree)) {
781                 p = write_dentry(tree, p);
782
783                 /* write end of directory entry */
784                 p = put_u64(p, 0);
785         } else {
786                 /* Nothing to do for a regular file. */
787                 if (dentry_is_regular_file(tree))
788                         return p;
789         }
790
791         /* Write child dentries and end-of-directory entry. */
792         child = tree->children;
793         if (child) {
794                 do {
795                         p = write_dentry(child, p);
796                         child = child->next;
797                 } while (child != tree->children);
798         }
799
800         /* write end of directory entry */
801         p = put_u64(p, 0);
802
803         /* Recurse on children. */
804         if (child) {
805                 do {
806                         p = write_dentry_tree(child, p);
807                         child = child->next;
808                 } while (child != tree->children);
809         }
810         return p;
811 }
812
813 /* Reads the children of a dentry, and all their children, ..., etc. from the
814  * metadata resource and into the dentry tree.
815  *
816  * @metadata_resource:  An array that contains the uncompressed metadata
817  *                              resource for the WIM file.
818  * @metadata_resource_len:      The length of @metadata_resource.
819  * @dentry:     A pointer to a struct dentry that is the root of the directory tree
820  *              and has already been read from the metadata resource.  It does not 
821  *              need to be the real root, because this procedure is called 
822  *              recursively.
823  * @return:     True on success, false on failure. 
824  */
825 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
826                      struct dentry *dentry)
827 {
828         u64 cur_offset = dentry->subdir_offset;
829         struct dentry *prev_child = NULL;
830         struct dentry *first_child = NULL;
831         struct dentry *child;
832         struct dentry cur_child;
833         int ret;
834
835         /* If @dentry is a regular file, nothing more needs to be done for this
836          * branch. */
837         if (cur_offset == 0)
838                 return 0;
839
840         /* Find and read all the children of @dentry. */
841         while (1) {
842
843                 /* Read next child of @dentry into @cur_child. */
844                 ret = read_dentry(metadata_resource, metadata_resource_len, 
845                                   cur_offset, &cur_child);
846                 if (ret != 0)
847                         break;
848
849                 /* Check for end of directory. */
850                 if (cur_child.length == 0) {
851                         ret = 0;
852                         break;
853                 }
854
855                 /* Not end of directory.  Allocate this child permanently and
856                  * link it to the parent and previous child. */
857                 child = MALLOC(sizeof(struct dentry));
858                 if (!child) {
859                         ERROR("Failed to allocate %zu bytes for new dentry!\n",
860                                         sizeof(struct dentry));
861                         ret = WIMLIB_ERR_NOMEM;
862                         break;
863                 }
864                 memcpy(child, &cur_child, sizeof(struct dentry));
865
866                 if (prev_child) {
867                         prev_child->next = child;
868                         child->prev = prev_child;
869                 } else {
870                         first_child = child;
871                 }
872
873                 child->parent = dentry;
874                 prev_child = child;
875
876                 /* If there are children of this child, call this procedure
877                  * recursively. */
878                 if (child->subdir_offset != 0) {
879                         ret = read_dentry_tree(metadata_resource, 
880                                                metadata_resource_len, child);
881                         if (ret != 0)
882                                 break;
883                 }
884
885                 /* Advance to the offset of the next child. */
886                 cur_offset += child->length;
887         }
888
889         /* Link last child to first one, and set parent's
890          * children pointer to the first child.  */
891         if (prev_child) {
892                 prev_child->next = first_child;
893                 first_child->prev = prev_child;
894         }
895         dentry->children = first_child;
896         return ret;
897 }