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