]> wimlib.net Git - wimlib/blob - src/dentry.c
Some preparations for supporting NTFS capture and apply.
[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         char *full_path;
152         u32 full_path_len;
153         if (dentry_is_root(dentry)) {
154                 full_path = MALLOC(2);
155                 if (!full_path)
156                         goto oom;
157                 full_path[0] = '/';
158                 full_path[1] = '\0';
159                 full_path_len = 1;
160         } else {
161                 char *parent_full_path;
162                 u32 parent_full_path_len;
163                 const struct dentry *parent = dentry->parent;
164
165                 if (dentry_is_root(parent)) {
166                         parent_full_path = "";
167                         parent_full_path_len = 0;
168                 } else {
169                         parent_full_path = parent->full_path_utf8;
170                         parent_full_path_len = parent->full_path_utf8_len;
171                 }
172
173                 full_path_len = parent_full_path_len + 1 +
174                                 dentry->file_name_utf8_len;
175                 full_path = MALLOC(full_path_len + 1);
176                 if (!full_path)
177                         goto oom;
178
179                 memcpy(full_path, parent_full_path, parent_full_path_len);
180                 full_path[parent_full_path_len] = '/';
181                 memcpy(full_path + parent_full_path_len + 1,
182                        dentry->file_name_utf8,
183                        dentry->file_name_utf8_len);
184                 full_path[full_path_len] = '\0';
185         }
186         FREE(dentry->full_path_utf8);
187         dentry->full_path_utf8 = full_path;
188         dentry->full_path_utf8_len = full_path_len;
189         return 0;
190 oom:
191         ERROR("Out of memory while calculating dentry full path");
192         return WIMLIB_ERR_NOMEM;
193 }
194
195 /* 
196  * Recursively calculates the subdir offsets for a directory tree. 
197  *
198  * @dentry:  The root of the directory tree.
199  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
200  *      offset for @dentry. 
201  */
202 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
203 {
204         struct dentry *child;
205
206         child = dentry->children;
207         dentry->subdir_offset = *subdir_offset_p;
208         if (child) {
209
210                 /* Advance the subdir offset by the amount of space the children
211                  * of this dentry take up. */
212                 do {
213                         *subdir_offset_p += child->length;
214                         child = child->next;
215                 } while (child != dentry->children);
216
217                 /* End-of-directory dentry on disk. */
218                 *subdir_offset_p += 8;
219
220                 /* Recursively call calculate_subdir_offsets() on all the
221                  * children. */
222                 do {
223                         calculate_subdir_offsets(child, subdir_offset_p);
224                         child = child->next;
225                 } while (child != dentry->children);
226         } else {
227                 /* On disk, childless directories have a valid subdir_offset
228                  * that points to an 8-byte end-of-directory dentry.  Regular
229                  * files have a subdir_offset of 0. */
230                 if (dentry_is_directory(dentry))
231                         *subdir_offset_p += 8;
232                 else
233                         dentry->subdir_offset = 0;
234         }
235 }
236
237
238 /* Returns the child of @dentry that has the file name @name.  
239  * Returns NULL if no child has the name. */
240 struct dentry *get_dentry_child_with_name(const struct dentry *dentry, 
241                                                         const char *name)
242 {
243         struct dentry *child;
244         size_t name_len;
245         
246         child = dentry->children;
247         if (child) {
248                 name_len = strlen(name);
249                 do {
250                         if (dentry_has_name(child, name, name_len))
251                                 return child;
252                         child = child->next;
253                 } while (child != dentry->children);
254         }
255         return NULL;
256 }
257
258 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
259  * @cur_dir.  Returns NULL if no dentry having the path is found. */
260 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir, const char *path)
261 {
262         struct dentry *child;
263         size_t base_len;
264         const char *new_path;
265
266         if (*path == '\0')
267                 return cur_dir;
268
269         child = cur_dir->children;
270         if (child) {
271                 new_path = path_next_part(path, &base_len);
272                 do {
273                         if (dentry_has_name(child, path, base_len))
274                                 return get_dentry_relative_path(child, new_path);
275                         child = child->next;
276                 } while (child != cur_dir->children);
277         }
278         return NULL;
279 }
280
281 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
282  * such dentry. */
283 struct dentry *get_dentry(WIMStruct *w, const char *path)
284 {
285         struct dentry *root = wim_root_dentry(w);
286         while (*path == '/')
287                 path++;
288         return get_dentry_relative_path(root, path);
289 }
290
291 /* Returns the parent directory for the @path. */
292 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
293 {
294         size_t path_len = strlen(path);
295         char buf[path_len + 1];
296
297         memcpy(buf, path, path_len + 1);
298
299         to_parent_name(buf, path_len);
300
301         return get_dentry(w, buf);
302 }
303
304 /* Prints the full path of a dentry. */
305 int print_dentry_full_path(struct dentry *dentry, void *ignore)
306 {
307         if (dentry->full_path_utf8)
308                 puts(dentry->full_path_utf8);
309         return 0;
310 }
311
312 struct file_attr_flag {
313         u32 flag;
314         const char *name;
315 };
316 struct file_attr_flag file_attr_flags[] = {
317         {WIM_FILE_ATTRIBUTE_READONLY,           "READONLY"},
318         {WIM_FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
319         {WIM_FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
320         {WIM_FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
321         {WIM_FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
322         {WIM_FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
323         {WIM_FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
324         {WIM_FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
325         {WIM_FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
326         {WIM_FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
327         {WIM_FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
328         {WIM_FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
329         {WIM_FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
330         {WIM_FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
331         {WIM_FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
332 };
333
334 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, or
335  * NULL if the resource entry for the dentry is not to be printed. */
336 int print_dentry(struct dentry *dentry, void *lookup_table)
337 {
338         struct lookup_table_entry *lte;
339         unsigned i;
340
341         printf("[DENTRY]\n");
342         printf("Length            = %"PRIu64"\n", dentry->length);
343         printf("Attributes        = 0x%x\n", dentry->attributes);
344         for (i = 0; i < ARRAY_LEN(file_attr_flags); i++)
345                 if (file_attr_flags[i].flag & dentry->attributes)
346                         printf("    WIM_FILE_ATTRIBUTE_%s is set\n",
347                                 file_attr_flags[i].name);
348         printf("Security ID       = %d\n", dentry->security_id);
349         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
350         /*printf("Unused1           = %"PRIu64"\n", dentry->unused1);*/
351         /*printf("Unused2           = %"PRIu64"\n", dentry->unused2);*/
352         printf("Creation Time     = %"PRIu64"\n", dentry->creation_time);
353         printf("Last Access Time  = %"PRIu64"\n", dentry->last_access_time);
354         printf("Last Write Time   = %"PRIu64"\n", dentry->last_write_time);
355         printf("Creation Time     = 0x%"PRIx64"\n", dentry->creation_time);
356         printf("Hash              = "); 
357         print_hash(dentry->hash); 
358         putchar('\n');
359         printf("Reparse Tag       = %u\n", dentry->reparse_tag);
360         printf("Hard Link Group   = %"PRIu64"\n", dentry->hard_link);
361         printf("Number of Alternate Data Streams = %hu\n", dentry->num_ads);
362         printf("Filename          = \"");
363         print_string(dentry->file_name, dentry->file_name_len);
364         puts("\"");
365         printf("Filename Length   = %hu\n", dentry->file_name_len);
366         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
367         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
368         printf("Short Name        = \"");
369         print_string(dentry->short_name, dentry->short_name_len);
370         puts("\"");
371         printf("Short Name Length = %hu\n", dentry->short_name_len);
372         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
373         if (lookup_table) {
374                 lte = lookup_resource(lookup_table, dentry->hash);
375                 if (lte)
376                         print_lookup_table_entry(lte, NULL);
377                 else
378                         putchar('\n');
379         } else {
380                 putchar('\n');
381         }
382         return 0;
383 }
384
385 static inline void dentry_common_init(struct dentry *dentry)
386 {
387         memset(dentry, 0, sizeof(struct dentry));
388         dentry->refcnt = 1;
389         dentry->security_id = -1;
390 }
391
392 /* 
393  * Creates an unlinked directory entry.
394  *
395  * @name:    The base name of the new dentry.
396  * @return:  A pointer to the new dentry, or NULL if out of memory.
397  */
398 struct dentry *new_dentry(const char *name)
399 {
400         struct dentry *dentry;
401         
402         dentry = MALLOC(sizeof(struct dentry));
403         if (!dentry)
404                 return NULL;
405
406         dentry_common_init(dentry);
407         if (change_dentry_name(dentry, name) != 0) {
408                 FREE(dentry);
409                 return NULL;
410         }
411
412         dentry_update_all_timestamps(dentry);
413         dentry->next   = dentry;
414         dentry->prev   = dentry;
415         dentry->parent = dentry;
416         return dentry;
417 }
418
419
420 void free_dentry(struct dentry *dentry)
421 {
422         FREE(dentry->file_name);
423         FREE(dentry->file_name_utf8);
424         FREE(dentry->short_name);
425         FREE(dentry->full_path_utf8);
426         FREE(dentry);
427 }
428
429 /* Arguments for do_free_dentry(). */
430 struct free_dentry_args {
431         struct lookup_table *lookup_table;
432         bool lt_decrement_refcnt;
433 };
434
435 /* 
436  * This function is passed as an argument to for_dentry_in_tree_depth() in order
437  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
438  */
439 static int do_free_dentry(struct dentry *dentry, void *__args)
440 {
441         struct free_dentry_args *args = (struct free_dentry_args*)__args;
442
443         if (args->lt_decrement_refcnt && !dentry_is_directory(dentry)) {
444                 lookup_table_decrement_refcnt(args->lookup_table, 
445                                               dentry->hash);
446         }
447
448         wimlib_assert(dentry->refcnt >= 1);
449         if (--dentry->refcnt == 0)
450                 free_dentry(dentry);
451         return 0;
452 }
453
454 /* 
455  * Unlinks and frees a dentry tree.
456  *
457  * @root:               The root of the tree.
458  * @lookup_table:       The lookup table for dentries.
459  * @decrement_refcnt:   True if the dentries in the tree are to have their 
460  *                      reference counts in the lookup table decremented.
461  */
462 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table, 
463                       bool lt_decrement_refcnt)
464 {
465         if (!root || !root->parent)
466                 return;
467
468         struct free_dentry_args args;
469         args.lookup_table        = lookup_table;
470         args.lt_decrement_refcnt = lt_decrement_refcnt;
471         for_dentry_in_tree_depth(root, do_free_dentry, &args);
472 }
473
474 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
475 {
476         dentry->refcnt++;
477         return 0;
478 }
479
480 /* 
481  * Links a dentry into the directory tree.
482  *
483  * @dentry: The dentry to link.
484  * @parent: The dentry that will be the parent of @dentry.
485  */
486 void link_dentry(struct dentry *dentry, struct dentry *parent)
487 {
488         dentry->parent = parent;
489         if (parent->children) {
490                 /* Not an only child; link to siblings. */
491                 dentry->next = parent->children;
492                 dentry->prev = parent->children->prev;
493                 dentry->next->prev = dentry;
494                 dentry->prev->next = dentry;
495         } else {
496                 /* Only child; link to parent. */
497                 parent->children = dentry;
498                 dentry->next = dentry;
499                 dentry->prev = dentry;
500         }
501 }
502
503 /* Unlink a dentry from the directory tree. */
504 void unlink_dentry(struct dentry *dentry)
505 {
506         if (dentry_is_root(dentry))
507                 return;
508         if (dentry_is_only_child(dentry)) {
509                 dentry->parent->children = NULL;
510         } else {
511                 if (dentry_is_first_sibling(dentry))
512                         dentry->parent->children = dentry->next;
513                 dentry->next->prev = dentry->prev;
514                 dentry->prev->next = dentry->next;
515         }
516 }
517
518
519 /* Recalculates the length of @dentry based on its file name length and short
520  * name length.  */
521 static inline void recalculate_dentry_size(struct dentry *dentry)
522 {
523         dentry->length = WIM_DENTRY_DISK_SIZE + dentry->file_name_len + 
524                          2 + dentry->short_name_len;
525         for (u16 i = 0; i < dentry->num_ads; i++)
526                 dentry->length += ads_entry_length(&dentry->ads_entries[i]);
527         /* Must be multiple of 8. */
528         dentry->length = (dentry->length + 7) & ~7;
529 }
530
531 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
532  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
533  * full_path_utf8 fields.  Also recalculates its length. */
534 int change_dentry_name(struct dentry *dentry, const char *new_name)
535 {
536         size_t utf8_len;
537         size_t utf16_len;
538
539         FREE(dentry->file_name);
540
541         utf8_len = strlen(new_name);
542
543         dentry->file_name = utf8_to_utf16(new_name, utf8_len, &utf16_len);
544
545         if (!dentry->file_name)
546                 return WIMLIB_ERR_NOMEM;
547
548         FREE(dentry->file_name_utf8);
549         dentry->file_name_utf8 = MALLOC(utf8_len + 1);
550         if (!dentry->file_name_utf8) {
551                 FREE(dentry->file_name);
552                 dentry->file_name = NULL;
553                 return WIMLIB_ERR_NOMEM;
554         }
555
556         dentry->file_name_len = utf16_len;
557         dentry->file_name_utf8_len = utf8_len;
558         memcpy(dentry->file_name_utf8, new_name, utf8_len + 1);
559         recalculate_dentry_size(dentry);
560         return 0;
561 }
562
563 /* Parameters for calculate_dentry_statistics(). */
564 struct image_statistics {
565         struct lookup_table *lookup_table;
566         u64 *dir_count;
567         u64 *file_count;
568         u64 *total_bytes;
569         u64 *hard_link_bytes;
570 };
571
572 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
573 {
574         struct image_statistics *stats;
575         struct lookup_table_entry *lte; 
576         
577         stats = arg;
578         lte = lookup_resource(stats->lookup_table, dentry->hash);
579
580         if (dentry_is_directory(dentry) && !dentry_is_root(dentry))
581                 ++*stats->dir_count;
582         else
583                 ++*stats->file_count;
584
585         if (lte) {
586                 u64 size = lte->resource_entry.original_size;
587                 *stats->total_bytes += size;
588                 if (++lte->out_refcnt == 1)
589                         *stats->hard_link_bytes += size;
590         }
591         return 0;
592 }
593
594 void calculate_dir_tree_statistics(struct dentry *root, struct lookup_table *table, 
595                                    u64 *dir_count_ret, u64 *file_count_ret, 
596                                    u64 *total_bytes_ret, 
597                                    u64 *hard_link_bytes_ret)
598 {
599         struct image_statistics stats;
600         *dir_count_ret         = 0;
601         *file_count_ret        = 0;
602         *total_bytes_ret       = 0;
603         *hard_link_bytes_ret   = 0;
604         stats.lookup_table     = table;
605         stats.dir_count       = dir_count_ret;
606         stats.file_count      = file_count_ret;
607         stats.total_bytes     = total_bytes_ret;
608         stats.hard_link_bytes = hard_link_bytes_ret;
609         for_lookup_table_entry(table, zero_out_refcnts, NULL);
610         for_dentry_in_tree(root, calculate_dentry_statistics, &stats);
611 }
612
613 static int read_ads_entries(const u8 *p, struct dentry *dentry,
614                             unsigned remaining_size)
615 {
616         u16 num_ads = dentry->num_ads;
617         struct ads_entry *ads_entries = CALLOC(num_ads, sizeof(struct ads_entry));
618         int ret;
619         if (!ads_entries) {
620                 ERROR("Could not allocate memory for %u alternate data stream "
621                       "entries", num_ads);
622                 return WIMLIB_ERR_NOMEM;
623         }
624         for (u16 i = 0; i < num_ads; i++) {
625                 struct ads_entry *cur_entry = &ads_entries[i];
626                 u64 length;
627                 size_t utf8_len;
628                 /* Read the base stream entry, excluding the stream name. */
629                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
630                         ERROR("Stream entries go past end of directory entry");
631                         ret = WIMLIB_ERR_INVALID_DENTRY;
632                         goto out_free_ads_entries;
633                 }
634                 remaining_size -= WIM_ADS_ENTRY_DISK_SIZE;
635
636                 p = get_u64(p, &length); /* ADS entry length */
637                 p += 8; /* Unused */
638                 p = get_bytes(p, WIM_HASH_SIZE, (u8*)cur_entry->hash);
639                 p = get_u16(p, &cur_entry->stream_name_len);
640                 cur_entry->stream_name = NULL;
641                 cur_entry->stream_name_utf8 = NULL;
642
643                 if (remaining_size < cur_entry->stream_name_len) {
644                         ERROR("Stream entries go past end of directory entry");
645                         ret = WIMLIB_ERR_INVALID_DENTRY;
646                         goto out_free_ads_entries;
647                 }
648
649                 cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
650                 if (!cur_entry->stream_name) {
651                         ret = WIMLIB_ERR_NOMEM;
652                         goto out_free_ads_entries;
653                 }
654                 p = get_bytes(p, cur_entry->stream_name_len,
655                               (u8*)cur_entry->stream_name);
656                 cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
657                                                             cur_entry->stream_name_len,
658                                                             &utf8_len);
659                 cur_entry->stream_name_len_utf8 = utf8_len;
660
661                 if (!cur_entry->stream_name_utf8) {
662                         ret = WIMLIB_ERR_NOMEM;
663                         goto out_free_ads_entries;
664                 }
665         }
666         dentry->ads_entries = ads_entries;
667         return 0;
668 out_free_ads_entries:
669         for (u16 i = 0; i < num_ads; i++) {
670                 FREE(ads_entries[i].stream_name);
671                 FREE(ads_entries[i].stream_name_utf8);
672         }
673         FREE(ads_entries);
674         return ret;
675 }
676
677 /* 
678  * Reads a directory entry from the metadata resource.
679  */
680 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len, 
681                 u64 offset, struct dentry *dentry)
682 {
683         const u8 *p;
684         u64 calculated_size;
685         char *file_name;
686         char *file_name_utf8;
687         char *short_name;
688         u16 short_name_len;
689         u16 file_name_len;
690         size_t file_name_utf8_len;
691         int ret;
692
693         dentry_common_init(dentry);
694
695         /*Make sure the dentry really fits into the metadata resource.*/
696         if (offset + 8 > metadata_resource_len) {
697                 ERROR("Directory entry starting at %"PRIu64" ends past the "
698                       "end of the metadata resource (size %"PRIu64")",
699                       offset, metadata_resource_len);
700                 return WIMLIB_ERR_INVALID_DENTRY;
701         }
702
703         /* Before reading the whole entry, we need to read just the length.
704          * This is because an entry of length 8 (that is, just the length field)
705          * terminates the list of sibling directory entries. */
706
707         p = get_u64(&metadata_resource[offset], &dentry->length);
708
709         /* A zero length field (really a length of 8, since that's how big the
710          * directory entry is...) indicates that this is the end of directory
711          * dentry.  We do not read it into memory as an actual dentry, so just
712          * return true in that case. */
713         if (dentry->length == 0)
714                 return 0;
715
716         if (offset + dentry->length >= metadata_resource_len) {
717                 ERROR("Directory entry at offset %"PRIu64" and with size "
718                       "%"PRIu64" ends past the end of the metadata resource "
719                       "(size %"PRIu64")",
720                       offset, dentry->length, metadata_resource_len);
721                 return WIMLIB_ERR_INVALID_DENTRY;
722         }
723
724         /* If it is a recognized length, read the rest of the directory entry.
725          * Note: The root directory entry has no name, and its length does not
726          * include the short name length field.  */
727         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
728                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
729                       dentry->length);
730                 return WIMLIB_ERR_INVALID_DENTRY;
731         }
732
733         p = get_u32(p, &dentry->attributes);
734         p = get_u32(p, (u32*)&dentry->security_id);
735         p = get_u64(p, &dentry->subdir_offset);
736
737         /* 2 unused fields */
738         p += 2 * sizeof(u64);
739
740         p = get_u64(p, &dentry->creation_time);
741         p = get_u64(p, &dentry->last_access_time);
742         p = get_u64(p, &dentry->last_write_time);
743
744         p = get_bytes(p, WIM_HASH_SIZE, dentry->hash);
745         
746         p = get_u32(p, &dentry->reparse_tag);
747
748         /* The reparse_reserved field does not actually exist. */
749
750         p = get_u64(p, &dentry->hard_link);
751         
752         p = get_u16(p, &dentry->num_ads);
753
754         p = get_u16(p, &short_name_len);
755         p = get_u16(p, &file_name_len);
756
757         calculated_size = WIM_DENTRY_DISK_SIZE + file_name_len + 2 +
758                           short_name_len;
759
760         if (dentry->length < calculated_size) {
761                 ERROR("Unexpected end of directory entry! (Expected "
762                       "%"PRIu64" bytes, got %"PRIu64" bytes. "
763                       "short_name_len = %hu, file_name_len = %hu)", 
764                       calculated_size, dentry->length,
765                       short_name_len, file_name_len);
766                 return WIMLIB_ERR_INVALID_DENTRY;
767         }
768
769         /* Read the filename. */
770         file_name = MALLOC(file_name_len);
771         if (!file_name) {
772                 ERROR("Failed to allocate %hu bytes for dentry file name",
773                       file_name_len);
774                 return WIMLIB_ERR_NOMEM;
775         }
776         p = get_bytes(p, file_name_len, file_name);
777
778         /* Convert filename to UTF-8. */
779         file_name_utf8 = utf16_to_utf8(file_name, file_name_len, 
780                                        &file_name_utf8_len);
781
782         if (!file_name_utf8) {
783                 ERROR("Failed to allocate memory to convert UTF-16 "
784                       "filename (%hu bytes) to UTF-8", file_name_len);
785                 ret = WIMLIB_ERR_NOMEM;
786                 goto out_free_file_name;
787         }
788
789         /* Undocumented padding between file name and short name.  This probably
790          * is supposed to be a terminating null character. */
791         p += 2;
792
793         /* Read the short filename. */
794         short_name = MALLOC(short_name_len);
795         if (!short_name) {
796                 ERROR("Failed to allocate %hu bytes for short filename",
797                       short_name_len);
798                 ret = WIMLIB_ERR_NOMEM;
799                 goto out_free_file_name_utf8;
800         }
801
802         get_bytes(p, short_name_len, short_name);
803
804         if (dentry->num_ads != 0) {
805                 ret = read_ads_entries(p, dentry,
806                                        dentry->length - calculated_size);
807                 if (ret != 0)
808                         goto out_free_short_name;
809         }
810
811         dentry->file_name          = file_name;
812         dentry->file_name_utf8     = file_name_utf8;
813         dentry->short_name         = short_name;
814         dentry->file_name_len      = file_name_len;
815         dentry->file_name_utf8_len = file_name_utf8_len;
816         dentry->short_name_len     = short_name_len;
817         return 0;
818 out_free_short_name:
819         FREE(short_name);
820 out_free_file_name_utf8:
821         FREE(file_name_utf8);
822 out_free_file_name:
823         FREE(file_name);
824         return ret;
825 }
826
827 /* 
828  * Writes a dentry to an output buffer.
829  *
830  * @dentry:  The dentry structure.
831  * @p:       The memory location to write the data to.
832  * @return:  Pointer to the byte after the last byte we wrote as part of the
833  *              dentry.
834  */
835 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
836 {
837         u8 *orig_p = p;
838         memset(p, 0, dentry->length);
839         p = put_u64(p, dentry->length);
840         p = put_u32(p, dentry->attributes);
841         p = put_u32(p, dentry->security_id);
842         p = put_u64(p, dentry->subdir_offset);
843         p = put_u64(p, 0); /* unused1 */
844         p = put_u64(p, 0); /* unused2 */
845         p = put_u64(p, dentry->creation_time);
846         p = put_u64(p, dentry->last_access_time);
847         p = put_u64(p, dentry->last_write_time);
848         if (!is_empty_file_hash(dentry->hash))
849                 memcpy(p, dentry->hash, WIM_HASH_SIZE);
850         else
851                 DEBUG("zero hash for %s\n", dentry->file_name_utf8);
852         p += WIM_HASH_SIZE;
853         p = put_u32(p, dentry->reparse_tag);
854         p = put_u64(p, dentry->hard_link);
855         p = put_u16(p, dentry->num_ads); /*streams */
856         p = put_u16(p, dentry->short_name_len);
857         p = put_u16(p, dentry->file_name_len);
858         p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
859         p = put_u16(p, 0); /* filename padding, 2 bytes. */
860         p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
861         for (u16 i = 0; i < dentry->num_ads; i++) {
862                 p = put_u64(p, ads_entry_length(&dentry->ads_entries[i]));
863                 p = put_u64(p, 0); /* Unused */
864                 p = put_bytes(p, WIM_HASH_SIZE, dentry->ads_entries[i].hash);
865                 p = put_u16(p, dentry->ads_entries[i].stream_name_len);
866                 p = put_bytes(p, dentry->ads_entries[i].stream_name_len,
867                                  (u8*)dentry->ads_entries[i].stream_name);
868         }
869         return orig_p + dentry->length;
870 }
871
872 /* Recursive function that writes a dentry tree rooted at @tree, not including
873  * @tree itself, which has already been written, except in the case of the root
874  * dentry, which is written right away, along with an end-of-directory entry. */
875 u8 *write_dentry_tree(const struct dentry *tree, u8 *p)
876 {
877         const struct dentry *child;
878
879         if (dentry_is_root(tree)) {
880                 p = write_dentry(tree, p);
881
882                 /* write end of directory entry */
883                 p = put_u64(p, 0);
884         } else {
885                 /* Nothing to do for a regular file. */
886                 if (dentry_is_regular_file(tree))
887                         return p;
888         }
889
890         /* Write child dentries and end-of-directory entry. */
891         child = tree->children;
892         if (child) {
893                 do {
894                         p = write_dentry(child, p);
895                         child = child->next;
896                 } while (child != tree->children);
897         }
898
899         /* write end of directory entry */
900         p = put_u64(p, 0);
901
902         /* Recurse on children. */
903         if (child) {
904                 do {
905                         p = write_dentry_tree(child, p);
906                         child = child->next;
907                 } while (child != tree->children);
908         }
909         return p;
910 }
911
912 /* Reads the children of a dentry, and all their children, ..., etc. from the
913  * metadata resource and into the dentry tree.
914  *
915  * @metadata_resource:  An array that contains the uncompressed metadata
916  *                      resource for the WIM file.
917  * @metadata_resource_len:      The length of @metadata_resource.
918  * @dentry:     A pointer to a struct dentry that is the root of the directory
919  *              tree and has already been read from the metadata resource.  It
920  *              does not need to be the real root because this procedure is
921  *              called recursively.
922  *
923  * @return:     Zero on success, nonzero on failure.
924  */
925 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
926                      struct dentry *dentry)
927 {
928         u64 cur_offset = dentry->subdir_offset;
929         struct dentry *prev_child = NULL;
930         struct dentry *first_child = NULL;
931         struct dentry *child;
932         struct dentry cur_child;
933         int ret;
934
935         /* If @dentry is a regular file, nothing more needs to be done for this
936          * branch. */
937         if (cur_offset == 0)
938                 return 0;
939
940         /* Find and read all the children of @dentry. */
941         while (1) {
942
943                 /* Read next child of @dentry into @cur_child. */
944                 ret = read_dentry(metadata_resource, metadata_resource_len, 
945                                   cur_offset, &cur_child);
946                 if (ret != 0)
947                         break;
948
949                 /* Check for end of directory. */
950                 if (cur_child.length == 0) {
951                         ret = 0;
952                         break;
953                 }
954
955                 /* Not end of directory.  Allocate this child permanently and
956                  * link it to the parent and previous child. */
957                 child = MALLOC(sizeof(struct dentry));
958                 if (!child) {
959                         ERROR("Failed to allocate %zu bytes for new dentry",
960                               sizeof(struct dentry));
961                         ret = WIMLIB_ERR_NOMEM;
962                         break;
963                 }
964                 memcpy(child, &cur_child, sizeof(struct dentry));
965
966                 if (prev_child) {
967                         prev_child->next = child;
968                         child->prev = prev_child;
969                 } else {
970                         first_child = child;
971                 }
972
973                 child->parent = dentry;
974                 prev_child = child;
975
976                 /* If there are children of this child, call this procedure
977                  * recursively. */
978                 if (child->subdir_offset != 0) {
979                         ret = read_dentry_tree(metadata_resource, 
980                                                metadata_resource_len, child);
981                         if (ret != 0)
982                                 break;
983                 }
984
985                 /* Advance to the offset of the next child. */
986                 cur_offset += child->length;
987         }
988
989         /* Link last child to first one, and set parent's
990          * children pointer to the first child.  */
991         if (prev_child) {
992                 prev_child->next = first_child;
993                 first_child->prev = prev_child;
994         }
995         dentry->children = first_child;
996         return ret;
997 }