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