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