Run NTFS tests when --without-ntfs-3g
[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  * Copyright (C) 2012 Eric Biggers
14  *
15  * This file is part of wimlib, a library for working with WIM files.
16  *
17  * wimlib is free software; you can redistribute it and/or modify it under the
18  * terms of the GNU General Public License as published by the Free Software
19  * Foundation; either version 3 of the License, or (at your option) any later
20  * version.
21  *
22  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
23  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24  * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License along with
27  * wimlib; if not, see http://www.gnu.org/licenses/.
28  */
29
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <unistd.h>
34
35 #include "dentry.h"
36 #include "io.h"
37 #include "lookup_table.h"
38 #include "sha1.h"
39 #include "timestamp.h"
40 #include "wimlib_internal.h"
41
42
43 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
44  * a file name and short name that take the specified numbers of bytes.  This
45  * excludes any alternate data stream entries that may follow the dentry. */
46 static u64 __dentry_correct_length_unaligned(u16 file_name_len,
47                                              u16 short_name_len)
48 {
49         u64 length = WIM_DENTRY_DISK_SIZE;
50         if (file_name_len)
51                 length += file_name_len + 2;
52         if (short_name_len)
53                 length += short_name_len + 2;
54         return length;
55 }
56
57 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
58  * the file name length and short name length.  Note that dentry->length is
59  * ignored; also, this excludes any alternate data stream entries that may
60  * follow the dentry. */
61 static u64 dentry_correct_length_unaligned(const struct dentry *dentry)
62 {
63         return __dentry_correct_length_unaligned(dentry->file_name_len,
64                                                  dentry->short_name_len);
65 }
66
67 /* Return the "correct" value to write in the length field of a WIM dentry,
68  * based on the file name length and short name length. */
69 static u64 dentry_correct_length(const struct dentry *dentry)
70 {
71         return (dentry_correct_length_unaligned(dentry) + 7) & ~7;
72 }
73
74 /* Return %true iff @dentry has the UTF-8 file name @name that has length
75  * @name_len bytes. */
76 static bool dentry_has_name(const struct dentry *dentry, const char *name,
77                             size_t name_len)
78 {
79         if (dentry->file_name_utf8_len != name_len)
80                 return false;
81         return memcmp(dentry->file_name_utf8, name, name_len) == 0;
82 }
83
84 /* Return %true iff the alternate data stream entry @entry has the UTF-8 stream
85  * name @name that has length @name_len bytes. */
86 static inline bool ads_entry_has_name(const struct ads_entry *entry,
87                                       const char *name, size_t name_len)
88 {
89         if (entry->stream_name_utf8_len != name_len)
90                 return false;
91         return memcmp(entry->stream_name_utf8, name, name_len) == 0;
92 }
93
94 /* Duplicates a UTF-8 name into UTF-8 and UTF-16 strings and returns the strings
95  * and their lengths in the pointer arguments */
96 int get_names(char **name_utf16_ret, char **name_utf8_ret,
97               u16 *name_utf16_len_ret, u16 *name_utf8_len_ret,
98               const char *name)
99 {
100         size_t utf8_len;
101         size_t utf16_len;
102         char *name_utf16, *name_utf8;
103
104         utf8_len = strlen(name);
105
106         name_utf16 = utf8_to_utf16(name, utf8_len, &utf16_len);
107
108         if (!name_utf16)
109                 return WIMLIB_ERR_NOMEM;
110
111         name_utf8 = MALLOC(utf8_len + 1);
112         if (!name_utf8) {
113                 FREE(name_utf8);
114                 return WIMLIB_ERR_NOMEM;
115         }
116         memcpy(name_utf8, name, utf8_len + 1);
117         FREE(*name_utf8_ret);
118         FREE(*name_utf16_ret);
119         *name_utf8_ret      = name_utf8;
120         *name_utf16_ret     = name_utf16;
121         *name_utf8_len_ret  = utf8_len;
122         *name_utf16_len_ret = utf16_len;
123         return 0;
124 }
125
126 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
127  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
128  * full_path_utf8 fields.  Also recalculates its length. */
129 static int change_dentry_name(struct dentry *dentry, const char *new_name)
130 {
131         int ret;
132
133         ret = get_names(&dentry->file_name, &dentry->file_name_utf8,
134                         &dentry->file_name_len, &dentry->file_name_utf8_len,
135                          new_name);
136         FREE(dentry->short_name);
137         dentry->short_name_len = 0;
138         if (ret == 0)
139                 dentry->length = dentry_correct_length(dentry);
140         return ret;
141 }
142
143 /*
144  * Changes the name of an alternate data stream */
145 static int change_ads_name(struct ads_entry *entry, const char *new_name)
146 {
147         return get_names(&entry->stream_name, &entry->stream_name_utf8,
148                          &entry->stream_name_len,
149                          &entry->stream_name_utf8_len,
150                          new_name);
151 }
152
153 /* Returns the total length of a WIM alternate data stream entry on-disk,
154  * including the stream name, the null terminator, AND the padding after the
155  * entry to align the next one (or the next dentry) on an 8-byte boundary. */
156 static u64 ads_entry_total_length(const struct ads_entry *entry)
157 {
158         u64 len = WIM_ADS_ENTRY_DISK_SIZE;
159         if (entry->stream_name_len)
160                 len += entry->stream_name_len + 2;
161         return (len + 7) & ~7;
162 }
163
164
165 static u64 __dentry_total_length(const struct dentry *dentry, u64 length)
166 {
167         const struct inode *inode = dentry->d_inode;
168         for (u16 i = 0; i < inode->num_ads; i++)
169                 length += ads_entry_total_length(&inode->ads_entries[i]);
170         return (length + 7) & ~7;
171 }
172
173 /* Calculate the aligned *total* length of an on-disk WIM dentry.  This includes
174  * all alternate data streams. */
175 u64 dentry_correct_total_length(const struct dentry *dentry)
176 {
177         return __dentry_total_length(dentry,
178                                      dentry_correct_length_unaligned(dentry));
179 }
180
181 /* Like dentry_correct_total_length(), but use the existing dentry->length field
182  * instead of calculating its "correct" value. */
183 static u64 dentry_total_length(const struct dentry *dentry)
184 {
185         return __dentry_total_length(dentry, dentry->length);
186 }
187
188 /* Transfers file attributes from a `stat' buffer to a WIM "inode". */
189 void stbuf_to_inode(const struct stat *stbuf, struct inode *inode)
190 {
191         if (S_ISLNK(stbuf->st_mode)) {
192                 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
193                 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
194         } else if (S_ISDIR(stbuf->st_mode)) {
195                 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
196         } else {
197                 inode->attributes = FILE_ATTRIBUTE_NORMAL;
198         }
199         if (sizeof(ino_t) >= 8)
200                 inode->ino = (u64)stbuf->st_ino;
201         else
202                 inode->ino = (u64)stbuf->st_ino |
203                                    ((u64)stbuf->st_dev << ((sizeof(ino_t) * 8) & 63));
204         /* Set timestamps */
205         inode->creation_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
206         inode->last_write_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
207         inode->last_access_time = timespec_to_wim_timestamp(&stbuf->st_atim);
208 }
209
210 #ifdef WITH_FUSE
211 /* Transfers file attributes from a struct inode to a `stat' buffer.
212  *
213  * The lookup table entry tells us which stream in the inode we are statting.
214  * For a named data stream, everything returned is the same as the unnamed data
215  * stream except possibly the size and block count. */
216 int inode_to_stbuf(const struct inode *inode, struct lookup_table_entry *lte,
217                    struct stat *stbuf)
218 {
219         if (inode_is_symlink(inode))
220                 stbuf->st_mode = S_IFLNK | 0777;
221         else if (inode_is_directory(inode))
222                 stbuf->st_mode = S_IFDIR | 0755;
223         else
224                 stbuf->st_mode = S_IFREG | 0644;
225
226         stbuf->st_ino   = (ino_t)inode->ino;
227         stbuf->st_nlink = inode->link_count;
228         stbuf->st_uid   = getuid();
229         stbuf->st_gid   = getgid();
230
231         if (lte) {
232                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
233                         wimlib_assert(lte->staging_file_name);
234                         struct stat native_stat;
235                         if (stat(lte->staging_file_name, &native_stat) != 0) {
236                                 DEBUG("Failed to stat `%s': %m",
237                                       lte->staging_file_name);
238                                 return -errno;
239                         }
240                         stbuf->st_size = native_stat.st_size;
241                 } else {
242                         stbuf->st_size = wim_resource_size(lte);
243                 }
244         } else {
245                 stbuf->st_size = 0;
246         }
247
248         stbuf->st_atime   = wim_timestamp_to_unix(inode->last_access_time);
249         stbuf->st_mtime   = wim_timestamp_to_unix(inode->last_write_time);
250         stbuf->st_ctime   = wim_timestamp_to_unix(inode->creation_time);
251         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
252         return 0;
253 }
254 #endif
255
256 /*
257  * Calls a function on all directory entries in a directory tree.  It is called
258  * on a parent before its children.
259  */
260 int for_dentry_in_tree(struct dentry *root,
261                        int (*visitor)(struct dentry*, void*), void *arg)
262 {
263         int ret;
264         struct dentry *child;
265
266         ret = visitor(root, arg);
267
268         if (ret != 0)
269                 return ret;
270
271         child = root->d_inode->children;
272
273         if (!child)
274                 return 0;
275
276         do {
277                 ret = for_dentry_in_tree(child, visitor, arg);
278                 if (ret != 0)
279                         return ret;
280                 child = child->next;
281         } while (child != root->d_inode->children);
282         return 0;
283 }
284
285 /*
286  * Like for_dentry_in_tree(), but the visitor function is always called on a
287  * dentry's children before on itself.
288  */
289 int for_dentry_in_tree_depth(struct dentry *root,
290                              int (*visitor)(struct dentry*, void*), void *arg)
291 {
292         int ret;
293         struct dentry *child;
294         struct dentry *next;
295
296         child = root->d_inode->children;
297         if (child) {
298                 do {
299                         next = child->next;
300                         ret = for_dentry_in_tree_depth(child, visitor, arg);
301                         if (ret != 0)
302                                 return ret;
303                         child = next;
304                 } while (child != root->d_inode->children);
305         }
306         return visitor(root, arg);
307 }
308
309 /*
310  * Calculate the full path of @dentry, based on its parent's full path and on
311  * its UTF-8 file name.
312  */
313 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
314 {
315         char *full_path;
316         u32 full_path_len;
317         if (dentry_is_root(dentry)) {
318                 full_path = MALLOC(2);
319                 if (!full_path)
320                         goto oom;
321                 full_path[0] = '/';
322                 full_path[1] = '\0';
323                 full_path_len = 1;
324         } else {
325                 char *parent_full_path;
326                 u32 parent_full_path_len;
327                 const struct dentry *parent = dentry->parent;
328
329                 if (dentry_is_root(parent)) {
330                         parent_full_path = "";
331                         parent_full_path_len = 0;
332                 } else {
333                         parent_full_path = parent->full_path_utf8;
334                         parent_full_path_len = parent->full_path_utf8_len;
335                 }
336
337                 full_path_len = parent_full_path_len + 1 +
338                                 dentry->file_name_utf8_len;
339                 full_path = MALLOC(full_path_len + 1);
340                 if (!full_path)
341                         goto oom;
342
343                 memcpy(full_path, parent_full_path, parent_full_path_len);
344                 full_path[parent_full_path_len] = '/';
345                 memcpy(full_path + parent_full_path_len + 1,
346                        dentry->file_name_utf8,
347                        dentry->file_name_utf8_len);
348                 full_path[full_path_len] = '\0';
349         }
350         FREE(dentry->full_path_utf8);
351         dentry->full_path_utf8 = full_path;
352         dentry->full_path_utf8_len = full_path_len;
353         return 0;
354 oom:
355         ERROR("Out of memory while calculating dentry full path");
356         return WIMLIB_ERR_NOMEM;
357 }
358
359 /*
360  * Recursively calculates the subdir offsets for a directory tree.
361  *
362  * @dentry:  The root of the directory tree.
363  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
364  *                    offset for @dentry.
365  */
366 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
367 {
368         struct dentry *child, *children;
369
370         children = dentry->d_inode->children;
371         child = children;
372         dentry->subdir_offset = *subdir_offset_p;
373
374         if (child) {
375                 /* Advance the subdir offset by the amount of space the children
376                  * of this dentry take up. */
377                 do {
378                         *subdir_offset_p += dentry_correct_total_length(child);
379                         child = child->next;
380                 } while (child != children);
381
382                 /* End-of-directory dentry on disk. */
383                 *subdir_offset_p += 8;
384
385                 /* Recursively call calculate_subdir_offsets() on all the
386                  * children. */
387                 do {
388                         calculate_subdir_offsets(child, subdir_offset_p);
389                         child = child->next;
390                 } while (child != children);
391         } else {
392                 /* On disk, childless directories have a valid subdir_offset
393                  * that points to an 8-byte end-of-directory dentry.  Regular
394                  * files or reparse points have a subdir_offset of 0. */
395                 if (dentry_is_directory(dentry))
396                         *subdir_offset_p += 8;
397                 else
398                         dentry->subdir_offset = 0;
399         }
400 }
401
402 /* Returns the child of @dentry that has the file name @name.
403  * Returns NULL if no child has the name. */
404 struct dentry *get_dentry_child_with_name(const struct dentry *dentry,
405                                           const char *name)
406 {
407         struct dentry *child;
408         size_t name_len;
409
410         child = dentry->d_inode->children;
411         if (child) {
412                 name_len = strlen(name);
413                 do {
414                         if (dentry_has_name(child, name, name_len))
415                                 return child;
416                         child = child->next;
417                 } while (child != dentry->d_inode->children);
418         }
419         return NULL;
420 }
421
422 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
423  * @cur_dir.  Returns NULL if no dentry having the path is found. */
424 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir,
425                                                const char *path)
426 {
427         struct dentry *child, *children;
428         size_t base_len;
429         const char *new_path;
430
431         if (*path == '\0')
432                 return cur_dir;
433
434         children = cur_dir->d_inode->children;
435         if (children) {
436                 new_path = path_next_part(path, &base_len);
437                 child = children;
438                 do {
439                         if (dentry_has_name(child, path, base_len))
440                                 return get_dentry_relative_path(child, new_path);
441                         child = child->next;
442                 } while (child != children);
443         }
444         return NULL;
445 }
446
447 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
448  * such dentry. */
449 struct dentry *get_dentry(WIMStruct *w, const char *path)
450 {
451         struct dentry *root = wim_root_dentry(w);
452         while (*path == '/')
453                 path++;
454         return get_dentry_relative_path(root, path);
455 }
456
457 struct inode *wim_pathname_to_inode(WIMStruct *w, const char *path)
458 {
459         struct dentry *dentry;
460         dentry = get_dentry(w, path);
461         if (dentry)
462                 return dentry->d_inode;
463         else
464                 return NULL;
465 }
466
467 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
468  * if the dentry is not found. */
469 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
470 {
471         size_t path_len = strlen(path);
472         char buf[path_len + 1];
473
474         memcpy(buf, path, path_len + 1);
475
476         to_parent_name(buf, path_len);
477
478         return get_dentry(w, buf);
479 }
480
481 /* Prints the full path of a dentry. */
482 int print_dentry_full_path(struct dentry *dentry, void *ignore)
483 {
484         if (dentry->full_path_utf8)
485                 puts(dentry->full_path_utf8);
486         return 0;
487 }
488
489 /* We want to be able to show the names of the file attribute flags that are
490  * set. */
491 struct file_attr_flag {
492         u32 flag;
493         const char *name;
494 };
495 struct file_attr_flag file_attr_flags[] = {
496         {FILE_ATTRIBUTE_READONLY,           "READONLY"},
497         {FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
498         {FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
499         {FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
500         {FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
501         {FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
502         {FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
503         {FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
504         {FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
505         {FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
506         {FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
507         {FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
508         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
509         {FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
510         {FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
511 };
512
513 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
514  * available.  If the dentry is unresolved and the lookup table is NULL, the
515  * lookup table entries will not be printed.  Otherwise, they will be. */
516 int print_dentry(struct dentry *dentry, void *lookup_table)
517 {
518         const u8 *hash;
519         struct lookup_table_entry *lte;
520         const struct inode *inode = dentry->d_inode;
521         time_t time;
522         char *p;
523
524         printf("[DENTRY]\n");
525         printf("Length            = %"PRIu64"\n", dentry->length);
526         printf("Attributes        = 0x%x\n", inode->attributes);
527         for (unsigned i = 0; i < ARRAY_LEN(file_attr_flags); i++)
528                 if (file_attr_flags[i].flag & inode->attributes)
529                         printf("    FILE_ATTRIBUTE_%s is set\n",
530                                 file_attr_flags[i].name);
531         printf("Security ID       = %d\n", inode->security_id);
532         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
533
534         /* Translate the timestamps into something readable */
535         time = wim_timestamp_to_unix(inode->creation_time);
536         p = asctime(gmtime(&time));
537         *(strrchr(p, '\n')) = '\0';
538         printf("Creation Time     = %s UTC\n", p);
539
540         time = wim_timestamp_to_unix(inode->last_access_time);
541         p = asctime(gmtime(&time));
542         *(strrchr(p, '\n')) = '\0';
543         printf("Last Access Time  = %s UTC\n", p);
544
545         time = wim_timestamp_to_unix(inode->last_write_time);
546         p = asctime(gmtime(&time));
547         *(strrchr(p, '\n')) = '\0';
548         printf("Last Write Time   = %s UTC\n", p);
549
550         printf("Reparse Tag       = 0x%"PRIx32"\n", inode->reparse_tag);
551         printf("Hard Link Group   = 0x%"PRIx64"\n", inode->ino);
552         printf("Hard Link Group Size = %"PRIu32"\n", inode->link_count);
553         printf("Number of Alternate Data Streams = %hu\n", inode->num_ads);
554         printf("Filename          = \"");
555         print_string(dentry->file_name, dentry->file_name_len);
556         puts("\"");
557         printf("Filename Length   = %hu\n", dentry->file_name_len);
558         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
559         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
560         printf("Short Name        = \"");
561         print_string(dentry->short_name, dentry->short_name_len);
562         puts("\"");
563         printf("Short Name Length = %hu\n", dentry->short_name_len);
564         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
565         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
566         if (lte) {
567                 print_lookup_table_entry(lte);
568         } else {
569                 hash = inode_stream_hash(inode, 0);
570                 if (hash) {
571                         printf("Hash              = 0x");
572                         print_hash(hash);
573                         putchar('\n');
574                         putchar('\n');
575                 }
576         }
577         for (u16 i = 0; i < inode->num_ads; i++) {
578                 printf("[Alternate Stream Entry %u]\n", i);
579                 printf("Name = \"%s\"\n", inode->ads_entries[i].stream_name_utf8);
580                 printf("Name Length (UTF-16) = %u\n",
581                         inode->ads_entries[i].stream_name_len);
582                 hash = inode_stream_hash(inode, i + 1);
583                 if (hash) {
584                         printf("Hash              = 0x");
585                         print_hash(hash);
586                         putchar('\n');
587                 }
588                 print_lookup_table_entry(inode_stream_lte(inode, i + 1,
589                                                           lookup_table));
590         }
591         return 0;
592 }
593
594 /* Initializations done on every `struct dentry'. */
595 static void dentry_common_init(struct dentry *dentry)
596 {
597         memset(dentry, 0, sizeof(struct dentry));
598         dentry->refcnt = 1;
599 }
600
601 static struct inode *new_timeless_inode()
602 {
603         struct inode *inode = CALLOC(1, sizeof(struct inode));
604         if (inode) {
605                 inode->security_id = -1;
606                 inode->link_count = 1;
607         #ifdef WITH_FUSE
608                 inode->next_stream_id = 1;
609         #endif
610                 INIT_LIST_HEAD(&inode->dentry_list);
611         }
612         return inode;
613 }
614
615 static struct inode *new_inode()
616 {
617         struct inode *inode = new_timeless_inode();
618         if (inode) {
619                 u64 now = get_wim_timestamp();
620                 inode->creation_time = now;
621                 inode->last_access_time = now;
622                 inode->last_write_time = now;
623         }
624         return inode;
625 }
626
627 /*
628  * Creates an unlinked directory entry.
629  *
630  * @name:  The UTF-8 filename of the new dentry.
631  *
632  * Returns a pointer to the new dentry, or NULL if out of memory.
633  */
634 struct dentry *new_dentry(const char *name)
635 {
636         struct dentry *dentry;
637
638         dentry = MALLOC(sizeof(struct dentry));
639         if (!dentry)
640                 goto err;
641
642         dentry_common_init(dentry);
643         if (change_dentry_name(dentry, name) != 0)
644                 goto err;
645
646         dentry->next   = dentry;
647         dentry->prev   = dentry;
648         dentry->parent = dentry;
649
650         return dentry;
651 err:
652         FREE(dentry);
653         ERROR("Failed to allocate new dentry");
654         return NULL;
655 }
656
657
658 static struct dentry *__new_dentry_with_inode(const char *name, bool timeless)
659 {
660         struct dentry *dentry;
661         dentry = new_dentry(name);
662         if (dentry) {
663                 if (timeless)
664                         dentry->d_inode = new_timeless_inode();
665                 else
666                         dentry->d_inode = new_inode();
667                 if (dentry->d_inode) {
668                         inode_add_dentry(dentry, dentry->d_inode);
669                 } else {
670                         free_dentry(dentry);
671                         dentry = NULL;
672                 }
673         }
674         return dentry;
675 }
676
677 struct dentry *new_dentry_with_timeless_inode(const char *name)
678 {
679         return __new_dentry_with_inode(name, true);
680 }
681
682 struct dentry *new_dentry_with_inode(const char *name)
683 {
684         return __new_dentry_with_inode(name, false);
685 }
686
687
688 static int init_ads_entry(struct ads_entry *ads_entry, const char *name)
689 {
690         int ret = 0;
691         memset(ads_entry, 0, sizeof(*ads_entry));
692         if (name && *name)
693                 ret = change_ads_name(ads_entry, name);
694         return ret;
695 }
696
697 static void destroy_ads_entry(struct ads_entry *ads_entry)
698 {
699         FREE(ads_entry->stream_name);
700         FREE(ads_entry->stream_name_utf8);
701 }
702
703
704 /* Frees an inode. */
705 void free_inode(struct inode *inode)
706 {
707         if (inode) {
708                 if (inode->ads_entries) {
709                         for (u16 i = 0; i < inode->num_ads; i++)
710                                 destroy_ads_entry(&inode->ads_entries[i]);
711                         FREE(inode->ads_entries);
712                 }
713         #ifdef WITH_FUSE
714                 wimlib_assert(inode->num_opened_fds == 0);
715                 FREE(inode->fds);
716         #endif
717                 FREE(inode->extracted_file);
718                 FREE(inode);
719         }
720 }
721
722 /* Decrements link count on an inode and frees it if the link count reaches 0.
723  * */
724 static void put_inode(struct inode *inode)
725 {
726         wimlib_assert(inode);
727         wimlib_assert(inode->link_count);
728         if (--inode->link_count == 0) {
729         #ifdef WITH_FUSE
730                 if (inode->num_opened_fds == 0)
731         #endif
732                 {
733                         free_inode(inode);
734                 }
735         }
736 }
737
738 /* Frees a WIM dentry.
739  *
740  * The inode is freed only if its link count is decremented to 0.
741  */
742 void free_dentry(struct dentry *dentry)
743 {
744         wimlib_assert(dentry != NULL);
745         FREE(dentry->file_name);
746         FREE(dentry->file_name_utf8);
747         FREE(dentry->short_name);
748         FREE(dentry->full_path_utf8);
749         if (dentry->d_inode)
750                 put_inode(dentry->d_inode);
751         FREE(dentry);
752 }
753
754 void put_dentry(struct dentry *dentry)
755 {
756         wimlib_assert(dentry != NULL);
757         wimlib_assert(dentry->refcnt != 0);
758
759         if (--dentry->refcnt == 0)
760                 free_dentry(dentry);
761 }
762
763 /*
764  * This function is passed as an argument to for_dentry_in_tree_depth() in order
765  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
766  */
767 static int do_free_dentry(struct dentry *dentry, void *__lookup_table)
768 {
769         struct lookup_table *lookup_table = __lookup_table;
770         unsigned i;
771
772         if (lookup_table) {
773                 struct lookup_table_entry *lte;
774                 struct inode *inode = dentry->d_inode;
775                 wimlib_assert(inode->link_count);
776                 for (i = 0; i <= inode->num_ads; i++) {
777                         lte = inode_stream_lte(inode, i, lookup_table);
778                         if (lte)
779                                 lte_decrement_refcnt(lte, lookup_table);
780                 }
781         }
782
783         put_dentry(dentry);
784         return 0;
785 }
786
787 /*
788  * Unlinks and frees a dentry tree.
789  *
790  * @root:               The root of the tree.
791  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
792  *                      reference counts in the lookup table for the lookup
793  *                      table entries corresponding to the dentries will be
794  *                      decremented.
795  */
796 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table)
797 {
798         if (!root || !root->parent)
799                 return;
800         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
801 }
802
803 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
804 {
805         dentry->refcnt++;
806         return 0;
807 }
808
809 /*
810  * Links a dentry into the directory tree.
811  *
812  * @dentry: The dentry to link.
813  * @parent: The dentry that will be the parent of @dentry.
814  */
815 void link_dentry(struct dentry *dentry, struct dentry *parent)
816 {
817         wimlib_assert(dentry_is_directory(parent));
818         dentry->parent = parent;
819         if (parent->d_inode->children) {
820                 /* Not an only child; link to siblings. */
821                 dentry->next = parent->d_inode->children;
822                 dentry->prev = parent->d_inode->children->prev;
823                 dentry->next->prev = dentry;
824                 dentry->prev->next = dentry;
825         } else {
826                 /* Only child; link to parent. */
827                 parent->d_inode->children = dentry;
828                 dentry->next = dentry;
829                 dentry->prev = dentry;
830         }
831 }
832
833
834 #ifdef WITH_FUSE
835 /*
836  * Unlink a dentry from the directory tree.
837  *
838  * Note: This merely removes it from the in-memory tree structure.
839  */
840 void unlink_dentry(struct dentry *dentry)
841 {
842         if (dentry_is_root(dentry))
843                 return;
844         if (dentry_is_only_child(dentry)) {
845                 dentry->parent->d_inode->children = NULL;
846         } else {
847                 if (dentry_is_first_sibling(dentry))
848                         dentry->parent->d_inode->children = dentry->next;
849                 dentry->next->prev = dentry->prev;
850                 dentry->prev->next = dentry->next;
851         }
852 }
853 #endif
854
855 static inline struct dentry *inode_first_dentry(struct inode *inode)
856 {
857         wimlib_assert(inode->dentry_list.next != &inode->dentry_list);
858         return container_of(inode->dentry_list.next, struct dentry,
859                             inode_dentry_list);
860 }
861
862 static int verify_inode(struct inode *inode, const WIMStruct *w)
863 {
864         const struct lookup_table *table = w->lookup_table;
865         const struct wim_security_data *sd = wim_const_security_data(w);
866         const struct dentry *first_dentry = inode_first_dentry(inode);
867         int ret = WIMLIB_ERR_INVALID_DENTRY;
868
869         /* Check the security ID */
870         if (inode->security_id < -1) {
871                 ERROR("Dentry `%s' has an invalid security ID (%d)",
872                         first_dentry->full_path_utf8, inode->security_id);
873                 goto out;
874         }
875         if (inode->security_id >= sd->num_entries) {
876                 ERROR("Dentry `%s' has an invalid security ID (%d) "
877                       "(there are only %u entries in the security table)",
878                         first_dentry->full_path_utf8, inode->security_id,
879                         sd->num_entries);
880                 goto out;
881         }
882
883         /* Check that lookup table entries for all the resources exist, except
884          * if the SHA1 message digest is all 0's, which indicates there is
885          * intentionally no resource there.  */
886         if (w->hdr.total_parts == 1) {
887                 for (unsigned i = 0; i <= inode->num_ads; i++) {
888                         struct lookup_table_entry *lte;
889                         const u8 *hash;
890                         hash = inode_stream_hash_unresolved(inode, i);
891                         lte = __lookup_resource(table, hash);
892                         if (!lte && !is_zero_hash(hash)) {
893                                 ERROR("Could not find lookup table entry for stream "
894                                       "%u of dentry `%s'", i, first_dentry->full_path_utf8);
895                                 goto out;
896                         }
897                         if (lte && (lte->real_refcnt += inode->link_count) > lte->refcnt)
898                         {
899                         #ifdef ENABLE_ERROR_MESSAGES
900                                 WARNING("The following lookup table entry "
901                                         "has a reference count of %u, but",
902                                         lte->refcnt);
903                                 WARNING("We found %u references to it",
904                                         lte->real_refcnt);
905                                 WARNING("(One dentry referencing it is at `%s')",
906                                          first_dentry->full_path_utf8);
907
908                                 print_lookup_table_entry(lte);
909                         #endif
910                                 /* Guess what!  install.wim for Windows 8
911                                  * contains a stream with 2 dentries referencing
912                                  * it, but the lookup table entry has reference
913                                  * count of 1.  So we will need to handle this
914                                  * case and not just make it be an error...  I'm
915                                  * just setting the reference count to the
916                                  * number of references we found.
917                                  * (Unfortunately, even after doing this, the
918                                  * reference count could be too low if it's also
919                                  * referenced in other WIM images) */
920
921                         #if 1
922                                 lte->refcnt = lte->real_refcnt;
923                                 WARNING("Fixing reference count");
924                         #else
925                                 goto out;
926                         #endif
927                         }
928                 }
929         }
930
931         /* Make sure there is only one un-named stream. */
932         unsigned num_unnamed_streams = 0;
933         for (unsigned i = 0; i <= inode->num_ads; i++) {
934                 const u8 *hash;
935                 hash = inode_stream_hash_unresolved(inode, i);
936                 if (!inode_stream_name_len(inode, i) && !is_zero_hash(hash))
937                         num_unnamed_streams++;
938         }
939         if (num_unnamed_streams > 1) {
940                 ERROR("Dentry `%s' has multiple (%u) un-named streams",
941                       first_dentry->full_path_utf8, num_unnamed_streams);
942                 goto out;
943         }
944         inode->verified = true;
945         ret = 0;
946 out:
947         return ret;
948 }
949
950 /* Run some miscellaneous verifications on a WIM dentry */
951 int verify_dentry(struct dentry *dentry, void *wim)
952 {
953         int ret;
954
955         if (!dentry->d_inode->verified) {
956                 ret = verify_inode(dentry->d_inode, wim);
957                 if (ret != 0)
958                         return ret;
959         }
960
961         /* Cannot have a short name but no long name */
962         if (dentry->short_name_len && !dentry->file_name_len) {
963                 ERROR("Dentry `%s' has a short name but no long name",
964                       dentry->full_path_utf8);
965                 return WIMLIB_ERR_INVALID_DENTRY;
966         }
967
968         /* Make sure root dentry is unnamed */
969         if (dentry_is_root(dentry)) {
970                 if (dentry->file_name_len) {
971                         ERROR("The root dentry is named `%s', but it must "
972                               "be unnamed", dentry->file_name_utf8);
973                         return WIMLIB_ERR_INVALID_DENTRY;
974                 }
975         }
976
977 #if 0
978         /* Check timestamps */
979         if (inode->last_access_time < inode->creation_time ||
980             inode->last_write_time < inode->creation_time) {
981                 WARNING("Dentry `%s' was created after it was last accessed or "
982                       "written to", dentry->full_path_utf8);
983         }
984 #endif
985
986         return 0;
987 }
988
989
990 #ifdef WITH_FUSE
991 /* Returns the alternate data stream entry belonging to @inode that has the
992  * stream name @stream_name. */
993 struct ads_entry *inode_get_ads_entry(struct inode *inode,
994                                       const char *stream_name,
995                                       u16 *idx_ret)
996 {
997         size_t stream_name_len;
998         if (!stream_name)
999                 return NULL;
1000         if (inode->num_ads) {
1001                 u16 i = 0;
1002                 stream_name_len = strlen(stream_name);
1003                 do {
1004                         if (ads_entry_has_name(&inode->ads_entries[i],
1005                                                stream_name, stream_name_len))
1006                         {
1007                                 if (idx_ret)
1008                                         *idx_ret = i;
1009                                 return &inode->ads_entries[i];
1010                         }
1011                 } while (++i != inode->num_ads);
1012         }
1013         return NULL;
1014 }
1015 #endif
1016
1017 #if defined(WITH_FUSE) || defined(WITH_NTFS_3G)
1018 /*
1019  * Add an alternate stream entry to an inode and return a pointer to it, or NULL
1020  * if memory could not be allocated.
1021  */
1022 struct ads_entry *inode_add_ads(struct inode *inode, const char *stream_name)
1023 {
1024         u16 num_ads;
1025         struct ads_entry *ads_entries;
1026         struct ads_entry *new_entry;
1027
1028         DEBUG("Add alternate data stream \"%s\"", stream_name);
1029
1030         if (inode->num_ads >= 0xfffe) {
1031                 ERROR("Too many alternate data streams in one inode!");
1032                 return NULL;
1033         }
1034         num_ads = inode->num_ads + 1;
1035         ads_entries = REALLOC(inode->ads_entries,
1036                               num_ads * sizeof(inode->ads_entries[0]));
1037         if (!ads_entries) {
1038                 ERROR("Failed to allocate memory for new alternate data stream");
1039                 return NULL;
1040         }
1041         inode->ads_entries = ads_entries;
1042
1043         new_entry = &inode->ads_entries[num_ads - 1];
1044         if (init_ads_entry(new_entry, stream_name) != 0)
1045                 return NULL;
1046 #ifdef WITH_FUSE
1047         new_entry->stream_id = inode->next_stream_id++;
1048 #endif
1049         inode->num_ads = num_ads;
1050         return new_entry;
1051 }
1052 #endif
1053
1054 #ifdef WITH_FUSE
1055 /* Remove an alternate data stream from the inode  */
1056 void inode_remove_ads(struct inode *inode, u16 idx,
1057                       struct lookup_table *lookup_table)
1058 {
1059         struct ads_entry *ads_entry;
1060         struct lookup_table_entry *lte;
1061
1062         wimlib_assert(idx < inode->num_ads);
1063         wimlib_assert(inode->resolved);
1064
1065         ads_entry = &inode->ads_entries[idx];
1066
1067         DEBUG("Remove alternate data stream \"%s\"", ads_entry->stream_name_utf8);
1068
1069         lte = ads_entry->lte;
1070         if (lte)
1071                 lte_decrement_refcnt(lte, lookup_table);
1072
1073         destroy_ads_entry(ads_entry);
1074
1075         memcpy(&inode->ads_entries[idx],
1076                &inode->ads_entries[idx + 1],
1077                (inode->num_ads - idx - 1) * sizeof(inode->ads_entries[0]));
1078         inode->num_ads--;
1079 }
1080 #endif
1081
1082
1083
1084 /*
1085  * Reads the alternate data stream entries for a dentry.
1086  *
1087  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1088  *
1089  * @inode:      Inode to load the alternate data streams into.
1090  *                      @inode->num_ads must have been set to the number of
1091  *                      alternate data streams that are expected.
1092  *
1093  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1094  *                              to by @p.
1095  *
1096  * The format of the on-disk alternate stream entries is as follows:
1097  *
1098  * struct ads_entry_on_disk {
1099  *      u64  length;          // Length of the entry, in bytes.  This includes
1100  *                                  all fields (including the stream name and
1101  *                                  null terminator if present, AND the padding!).
1102  *      u64  reserved;        // Seems to be unused
1103  *      u8   hash[20];        // SHA1 message digest of the uncompressed stream
1104  *      u16  stream_name_len; // Length of the stream name, in bytes
1105  *      char stream_name[];   // Stream name in UTF-16LE, @stream_name_len bytes long,
1106  *                                  not including null terminator
1107  *      u16  zero;            // UTF-16 null terminator for the stream name, NOT
1108  *                                  included in @stream_name_len.  Based on what
1109  *                                  I've observed from filenames in dentries,
1110  *                                  this field should not exist when
1111  *                                  (@stream_name_len == 0), but you can't
1112  *                                  actually tell because of the padding anyway
1113  *                                  (provided that the padding is zeroed, which
1114  *                                  it always seems to be).
1115  *      char padding[];       // Padding to make the size a multiple of 8 bytes.
1116  * };
1117  *
1118  * In addition, the entries are 8-byte aligned.
1119  *
1120  * Return 0 on success or nonzero on failure.  On success, inode->ads_entries
1121  * is set to an array of `struct ads_entry's of length inode->num_ads.  On
1122  * failure, @inode is not modified.
1123  */
1124 static int read_ads_entries(const u8 *p, struct inode *inode,
1125                             u64 remaining_size)
1126 {
1127         u16 num_ads;
1128         struct ads_entry *ads_entries;
1129         int ret;
1130
1131         num_ads = inode->num_ads;
1132         ads_entries = CALLOC(num_ads, sizeof(inode->ads_entries[0]));
1133         if (!ads_entries) {
1134                 ERROR("Could not allocate memory for %"PRIu16" "
1135                       "alternate data stream entries", num_ads);
1136                 return WIMLIB_ERR_NOMEM;
1137         }
1138
1139         for (u16 i = 0; i < num_ads; i++) {
1140                 struct ads_entry *cur_entry;
1141                 u64 length;
1142                 u64 length_no_padding;
1143                 u64 total_length;
1144                 size_t utf8_len;
1145                 const u8 *p_save = p;
1146
1147                 cur_entry = &ads_entries[i];
1148
1149         #ifdef WITH_FUSE
1150                 ads_entries[i].stream_id = i + 1;
1151         #endif
1152
1153                 /* Read the base stream entry, excluding the stream name. */
1154                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
1155                         ERROR("Stream entries go past end of metadata resource");
1156                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
1157                         ret = WIMLIB_ERR_INVALID_DENTRY;
1158                         goto out_free_ads_entries;
1159                 }
1160
1161                 p = get_u64(p, &length);
1162                 p += 8; /* Skip the reserved field */
1163                 p = get_bytes(p, SHA1_HASH_SIZE, (u8*)cur_entry->hash);
1164                 p = get_u16(p, &cur_entry->stream_name_len);
1165
1166                 cur_entry->stream_name = NULL;
1167                 cur_entry->stream_name_utf8 = NULL;
1168
1169                 /* Length including neither the null terminator nor the padding
1170                  * */
1171                 length_no_padding = WIM_ADS_ENTRY_DISK_SIZE +
1172                                     cur_entry->stream_name_len;
1173
1174                 /* Length including the null terminator and the padding */
1175                 total_length = ((length_no_padding + 2) + 7) & ~7;
1176
1177                 wimlib_assert(total_length == ads_entry_total_length(cur_entry));
1178
1179                 if (remaining_size < length_no_padding) {
1180                         ERROR("Stream entries go past end of metadata resource");
1181                         ERROR("(remaining_size = %"PRIu64" bytes, "
1182                               "length_no_padding = %"PRIu64" bytes)",
1183                               remaining_size, length_no_padding);
1184                         ret = WIMLIB_ERR_INVALID_DENTRY;
1185                         goto out_free_ads_entries;
1186                 }
1187
1188                 /* The @length field in the on-disk ADS entry is expected to be
1189                  * equal to @total_length, which includes all of the entry and
1190                  * the padding that follows it to align the next ADS entry to an
1191                  * 8-byte boundary.  However, to be safe, we'll accept the
1192                  * length field as long as it's not less than the un-padded
1193                  * total length and not more than the padded total length. */
1194                 if (length < length_no_padding || length > total_length) {
1195                         ERROR("Stream entry has unexpected length "
1196                               "field (length field = %"PRIu64", "
1197                               "unpadded total length = %"PRIu64", "
1198                               "padded total length = %"PRIu64")",
1199                               length, length_no_padding, total_length);
1200                         ret = WIMLIB_ERR_INVALID_DENTRY;
1201                         goto out_free_ads_entries;
1202                 }
1203
1204                 if (cur_entry->stream_name_len) {
1205                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
1206                         if (!cur_entry->stream_name) {
1207                                 ret = WIMLIB_ERR_NOMEM;
1208                                 goto out_free_ads_entries;
1209                         }
1210                         get_bytes(p, cur_entry->stream_name_len,
1211                                   (u8*)cur_entry->stream_name);
1212                         cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
1213                                                                     cur_entry->stream_name_len,
1214                                                                     &utf8_len);
1215                         cur_entry->stream_name_utf8_len = utf8_len;
1216
1217                         if (!cur_entry->stream_name_utf8) {
1218                                 ret = WIMLIB_ERR_NOMEM;
1219                                 goto out_free_ads_entries;
1220                         }
1221                 }
1222                 /* It's expected that the size of every ADS entry is a multiple
1223                  * of 8.  However, to be safe, I'm allowing the possibility of
1224                  * an ADS entry at the very end of the metadata resource ending
1225                  * un-aligned.  So although we still need to increment the input
1226                  * pointer by @total_length to reach the next ADS entry, it's
1227                  * possible that less than @total_length is actually remaining
1228                  * in the metadata resource. We should set the remaining size to
1229                  * 0 bytes if this happens. */
1230                 p = p_save + total_length;
1231                 if (remaining_size < total_length)
1232                         remaining_size = 0;
1233                 else
1234                         remaining_size -= total_length;
1235         }
1236         inode->ads_entries = ads_entries;
1237 #ifdef WITH_FUSE
1238         inode->next_stream_id = inode->num_ads + 1;
1239 #endif
1240         return 0;
1241 out_free_ads_entries:
1242         for (u16 i = 0; i < num_ads; i++)
1243                 destroy_ads_entry(&ads_entries[i]);
1244         FREE(ads_entries);
1245         return ret;
1246 }
1247
1248 /*
1249  * Reads a directory entry, including all alternate data stream entries that
1250  * follow it, from the WIM image's metadata resource.
1251  *
1252  * @metadata_resource:  Buffer containing the uncompressed metadata resource.
1253  * @metadata_resource_len:   Length of the metadata resource.
1254  * @offset:     Offset of this directory entry in the metadata resource.
1255  * @dentry:     A `struct dentry' that will be filled in by this function.
1256  *
1257  * Return 0 on success or nonzero on failure.  On failure, @dentry have been
1258  * modified, bu it will be left with no pointers to any allocated buffers.
1259  * On success, the dentry->length field must be examined.  If zero, this was a
1260  * special "end of directory" dentry and not a real dentry.  If nonzero, this
1261  * was a real dentry.
1262  */
1263 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len,
1264                 u64 offset, struct dentry *dentry)
1265 {
1266         const u8 *p;
1267         u64 calculated_size;
1268         char *file_name = NULL;
1269         char *file_name_utf8 = NULL;
1270         char *short_name = NULL;
1271         u16 short_name_len;
1272         u16 file_name_len;
1273         size_t file_name_utf8_len = 0;
1274         int ret;
1275         struct inode *inode = NULL;
1276
1277         dentry_common_init(dentry);
1278
1279         /*Make sure the dentry really fits into the metadata resource.*/
1280         if (offset + 8 > metadata_resource_len || offset + 8 < offset) {
1281                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1282                       "end of the metadata resource (size %"PRIu64")",
1283                       offset, metadata_resource_len);
1284                 return WIMLIB_ERR_INVALID_DENTRY;
1285         }
1286
1287         /* Before reading the whole dentry, we need to read just the length.
1288          * This is because a dentry of length 8 (that is, just the length field)
1289          * terminates the list of sibling directory entries. */
1290
1291         p = get_u64(&metadata_resource[offset], &dentry->length);
1292
1293         /* A zero length field (really a length of 8, since that's how big the
1294          * directory entry is...) indicates that this is the end of directory
1295          * dentry.  We do not read it into memory as an actual dentry, so just
1296          * return successfully in that case. */
1297         if (dentry->length == 0)
1298                 return 0;
1299
1300         /* If the dentry does not overflow the metadata resource buffer and is
1301          * not too short, read the rest of it (excluding the alternate data
1302          * streams, but including the file name and short name variable-length
1303          * fields) into memory. */
1304         if (offset + dentry->length >= metadata_resource_len
1305             || offset + dentry->length < offset)
1306         {
1307                 ERROR("Directory entry at offset %"PRIu64" and with size "
1308                       "%"PRIu64" ends past the end of the metadata resource "
1309                       "(size %"PRIu64")",
1310                       offset, dentry->length, metadata_resource_len);
1311                 return WIMLIB_ERR_INVALID_DENTRY;
1312         }
1313
1314         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
1315                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1316                       dentry->length);
1317                 return WIMLIB_ERR_INVALID_DENTRY;
1318         }
1319
1320         inode = new_timeless_inode();
1321         if (!inode)
1322                 return WIMLIB_ERR_NOMEM;
1323
1324         p = get_u32(p, &inode->attributes);
1325         p = get_u32(p, (u32*)&inode->security_id);
1326         p = get_u64(p, &dentry->subdir_offset);
1327
1328         /* 2 unused fields */
1329         p += 2 * sizeof(u64);
1330         /*p = get_u64(p, &dentry->unused1);*/
1331         /*p = get_u64(p, &dentry->unused2);*/
1332
1333         p = get_u64(p, &inode->creation_time);
1334         p = get_u64(p, &inode->last_access_time);
1335         p = get_u64(p, &inode->last_write_time);
1336
1337         p = get_bytes(p, SHA1_HASH_SIZE, inode->hash);
1338
1339         /*
1340          * I don't know what's going on here.  It seems like M$ screwed up the
1341          * reparse points, then put the fields in the same place and didn't
1342          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1343          * have something to do with this, but it's not documented.
1344          */
1345         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1346                 /* ??? */
1347                 p += 4;
1348                 p = get_u32(p, &inode->reparse_tag);
1349                 p += 4;
1350         } else {
1351                 p = get_u32(p, &inode->reparse_tag);
1352                 p = get_u64(p, &inode->ino);
1353         }
1354
1355         /* By the way, the reparse_reserved field does not actually exist (at
1356          * least when the file is not a reparse point) */
1357
1358         p = get_u16(p, &inode->num_ads);
1359
1360         p = get_u16(p, &short_name_len);
1361         p = get_u16(p, &file_name_len);
1362
1363         /* We now know the length of the file name and short name.  Make sure
1364          * the length of the dentry is large enough to actually hold them.
1365          *
1366          * The calculated length here is unaligned to allow for the possibility
1367          * that the dentry->length names an unaligned length, although this
1368          * would be unexpected. */
1369         calculated_size = __dentry_correct_length_unaligned(file_name_len,
1370                                                             short_name_len);
1371
1372         if (dentry->length < calculated_size) {
1373                 ERROR("Unexpected end of directory entry! (Expected "
1374                       "at least %"PRIu64" bytes, got %"PRIu64" bytes. "
1375                       "short_name_len = %hu, file_name_len = %hu)",
1376                       calculated_size, dentry->length,
1377                       short_name_len, file_name_len);
1378                 ret = WIMLIB_ERR_INVALID_DENTRY;
1379                 goto out_free_inode;
1380         }
1381
1382         /* Read the filename if present.  Note: if the filename is empty, there
1383          * is no null terminator following it. */
1384         if (file_name_len) {
1385                 file_name = MALLOC(file_name_len);
1386                 if (!file_name) {
1387                         ERROR("Failed to allocate %hu bytes for dentry file name",
1388                               file_name_len);
1389                         ret = WIMLIB_ERR_NOMEM;
1390                         goto out_free_inode;
1391                 }
1392                 p = get_bytes(p, file_name_len, file_name);
1393
1394                 /* Convert filename to UTF-8. */
1395                 file_name_utf8 = utf16_to_utf8(file_name, file_name_len,
1396                                                &file_name_utf8_len);
1397
1398                 if (!file_name_utf8) {
1399                         ERROR("Failed to allocate memory to convert UTF-16 "
1400                               "filename (%hu bytes) to UTF-8", file_name_len);
1401                         ret = WIMLIB_ERR_NOMEM;
1402                         goto out_free_file_name;
1403                 }
1404                 if (*(u16*)p)
1405                         WARNING("Expected two zero bytes following the file name "
1406                                 "`%s', but found non-zero bytes", file_name_utf8);
1407                 p += 2;
1408         }
1409
1410         /* Align the calculated size */
1411         calculated_size = (calculated_size + 7) & ~7;
1412
1413         if (dentry->length > calculated_size) {
1414                 /* Weird; the dentry says it's longer than it should be.  Note
1415                  * that the length field does NOT include the size of the
1416                  * alternate stream entries. */
1417
1418                 /* Strangely, some directory entries inexplicably have a little
1419                  * over 70 bytes of extra data.  The exact amount of data seems
1420                  * to be 72 bytes, but it is aligned on the next 8-byte
1421                  * boundary.  It does NOT seem to be alternate data stream
1422                  * entries.  Here's an example of the aligned data:
1423                  *
1424                  * 01000000 40000000 6c786bba c58ede11 b0bb0026 1870892a b6adb76f
1425                  * e63a3e46 8fca8653 0d2effa1 6c786bba c58ede11 b0bb0026 1870892a
1426                  * 00000000 00000000 00000000 00000000
1427                  *
1428                  * Here's one interpretation of how the data is laid out.
1429                  *
1430                  * struct unknown {
1431                  *      u32 field1; (always 0x00000001)
1432                  *      u32 field2; (always 0x40000000)
1433                  *      u8  data[48]; (???)
1434                  *      u64 reserved1; (always 0)
1435                  *      u64 reserved2; (always 0)
1436                  * };*/
1437                 DEBUG("Dentry for file or directory `%s' has %zu extra "
1438                       "bytes of data",
1439                       file_name_utf8, dentry->length - calculated_size);
1440         }
1441
1442         /* Read the short filename if present.  Note: if there is no short
1443          * filename, there is no null terminator following it. */
1444         if (short_name_len) {
1445                 short_name = MALLOC(short_name_len);
1446                 if (!short_name) {
1447                         ERROR("Failed to allocate %hu bytes for short filename",
1448                               short_name_len);
1449                         ret = WIMLIB_ERR_NOMEM;
1450                         goto out_free_file_name_utf8;
1451                 }
1452
1453                 p = get_bytes(p, short_name_len, short_name);
1454                 if (*(u16*)p)
1455                         WARNING("Expected two zero bytes following the short name of "
1456                                 "`%s', but found non-zero bytes", file_name_utf8);
1457                 p += 2;
1458         }
1459
1460         /*
1461          * Read the alternate data streams, if present.  dentry->num_ads tells
1462          * us how many they are, and they will directly follow the dentry
1463          * on-disk.
1464          *
1465          * Note that each alternate data stream entry begins on an 8-byte
1466          * aligned boundary, and the alternate data stream entries are NOT
1467          * included in the dentry->length field for some reason.
1468          */
1469         if (inode->num_ads != 0) {
1470
1471                 /* Trying different lengths is just a hack to make sure we have
1472                  * a chance of reading the ADS entries correctly despite the
1473                  * poor documentation. */
1474
1475                 if (calculated_size != dentry->length) {
1476                         WARNING("Trying calculated dentry length (%"PRIu64") "
1477                                 "instead of dentry->length field (%"PRIu64") "
1478                                 "to read ADS entries",
1479                                 calculated_size, dentry->length);
1480                 }
1481                 u64 lengths_to_try[3] = {calculated_size,
1482                                          (dentry->length + 7) & ~7,
1483                                          dentry->length};
1484                 ret = WIMLIB_ERR_INVALID_DENTRY;
1485                 for (size_t i = 0; i < ARRAY_LEN(lengths_to_try); i++) {
1486                         if (lengths_to_try[i] > metadata_resource_len - offset)
1487                                 continue;
1488                         ret = read_ads_entries(&metadata_resource[offset + lengths_to_try[i]],
1489                                                inode,
1490                                                metadata_resource_len - offset - lengths_to_try[i]);
1491                         if (ret == 0)
1492                                 goto out;
1493                 }
1494                 ERROR("Failed to read alternate data stream "
1495                       "entries of `%s'", dentry->file_name_utf8);
1496                 goto out_free_short_name;
1497         }
1498 out:
1499
1500         /* We've read all the data for this dentry.  Set the names and their
1501          * lengths, and we've done. */
1502         dentry->d_inode              = inode;
1503         dentry->file_name          = file_name;
1504         dentry->file_name_utf8     = file_name_utf8;
1505         dentry->short_name         = short_name;
1506         dentry->file_name_len      = file_name_len;
1507         dentry->file_name_utf8_len = file_name_utf8_len;
1508         dentry->short_name_len     = short_name_len;
1509         return 0;
1510 out_free_short_name:
1511         FREE(short_name);
1512 out_free_file_name_utf8:
1513         FREE(file_name_utf8);
1514 out_free_file_name:
1515         FREE(file_name);
1516 out_free_inode:
1517         free_inode(inode);
1518         return ret;
1519 }
1520
1521 /* Reads the children of a dentry, and all their children, ..., etc. from the
1522  * metadata resource and into the dentry tree.
1523  *
1524  * @metadata_resource:  An array that contains the uncompressed metadata
1525  *                      resource for the WIM file.
1526  *
1527  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1528  *                          bytes.
1529  *
1530  * @dentry:     A pointer to a `struct dentry' that is the root of the directory
1531  *              tree and has already been read from the metadata resource.  It
1532  *              does not need to be the real root because this procedure is
1533  *              called recursively.
1534  *
1535  * @return:     Zero on success, nonzero on failure.
1536  */
1537 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1538                      struct dentry *dentry)
1539 {
1540         u64 cur_offset = dentry->subdir_offset;
1541         struct dentry *prev_child = NULL;
1542         struct dentry *first_child = NULL;
1543         struct dentry *child;
1544         struct dentry cur_child;
1545         int ret;
1546
1547         /*
1548          * If @dentry has no child dentries, nothing more needs to be done for
1549          * this branch.  This is the case for regular files, symbolic links, and
1550          * *possibly* empty directories (although an empty directory may also
1551          * have one child dentry that is the special end-of-directory dentry)
1552          */
1553         if (cur_offset == 0)
1554                 return 0;
1555
1556         /* Find and read all the children of @dentry. */
1557         while (1) {
1558
1559                 /* Read next child of @dentry into @cur_child. */
1560                 ret = read_dentry(metadata_resource, metadata_resource_len,
1561                                   cur_offset, &cur_child);
1562                 if (ret != 0)
1563                         break;
1564
1565                 /* Check for end of directory. */
1566                 if (cur_child.length == 0)
1567                         break;
1568
1569                 /* Not end of directory.  Allocate this child permanently and
1570                  * link it to the parent and previous child. */
1571                 child = MALLOC(sizeof(struct dentry));
1572                 if (!child) {
1573                         ERROR("Failed to allocate %zu bytes for new dentry",
1574                               sizeof(struct dentry));
1575                         ret = WIMLIB_ERR_NOMEM;
1576                         break;
1577                 }
1578                 memcpy(child, &cur_child, sizeof(struct dentry));
1579
1580                 if (prev_child) {
1581                         prev_child->next = child;
1582                         child->prev = prev_child;
1583                 } else {
1584                         first_child = child;
1585                 }
1586
1587                 child->parent = dentry;
1588                 prev_child = child;
1589                 inode_add_dentry(child, child->d_inode);
1590
1591                 /* If there are children of this child, call this procedure
1592                  * recursively. */
1593                 if (child->subdir_offset != 0) {
1594                         ret = read_dentry_tree(metadata_resource,
1595                                                metadata_resource_len, child);
1596                         if (ret != 0)
1597                                 break;
1598                 }
1599
1600                 /* Advance to the offset of the next child.  Note: We need to
1601                  * advance by the TOTAL length of the dentry, not by the length
1602                  * child->length, which although it does take into account the
1603                  * padding, it DOES NOT take into account alternate stream
1604                  * entries. */
1605                 cur_offset += dentry_total_length(child);
1606         }
1607
1608         /* Link last child to first one, and set parent's children pointer to
1609          * the first child.  */
1610         if (prev_child) {
1611                 prev_child->next = first_child;
1612                 first_child->prev = prev_child;
1613         }
1614         dentry->d_inode->children = first_child;
1615         return ret;
1616 }
1617
1618 /*
1619  * Writes a WIM dentry to an output buffer.
1620  *
1621  * @dentry:  The dentry structure.
1622  * @p:       The memory location to write the data to.
1623  * @return:  Pointer to the byte after the last byte we wrote as part of the
1624  *              dentry.
1625  */
1626 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
1627 {
1628         u8 *orig_p = p;
1629         const u8 *hash;
1630         const struct inode *inode = dentry->d_inode;
1631
1632         /* We calculate the correct length of the dentry ourselves because the
1633          * dentry->length field may been set to an unexpected value from when we
1634          * read the dentry in (for example, there may have been unknown data
1635          * appended to the end of the dentry...) */
1636         u64 length = dentry_correct_length(dentry);
1637
1638         p = put_u64(p, length);
1639         p = put_u32(p, inode->attributes);
1640         p = put_u32(p, inode->security_id);
1641         p = put_u64(p, dentry->subdir_offset);
1642         p = put_u64(p, 0); /* unused1 */
1643         p = put_u64(p, 0); /* unused2 */
1644         p = put_u64(p, inode->creation_time);
1645         p = put_u64(p, inode->last_access_time);
1646         p = put_u64(p, inode->last_write_time);
1647         hash = inode_stream_hash(inode, 0);
1648         p = put_bytes(p, SHA1_HASH_SIZE, hash);
1649         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1650                 p = put_zeroes(p, 4);
1651                 p = put_u32(p, inode->reparse_tag);
1652                 p = put_zeroes(p, 4);
1653         } else {
1654                 u64 link_group_id;
1655                 p = put_u32(p, 0);
1656                 if (inode->link_count == 1)
1657                         link_group_id = 0;
1658                 else
1659                         link_group_id = inode->ino;
1660                 p = put_u64(p, link_group_id);
1661         }
1662         p = put_u16(p, inode->num_ads);
1663         p = put_u16(p, dentry->short_name_len);
1664         p = put_u16(p, dentry->file_name_len);
1665         if (dentry->file_name_len) {
1666                 p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
1667                 p = put_u16(p, 0); /* filename padding, 2 bytes. */
1668         }
1669         if (dentry->short_name) {
1670                 p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
1671                 p = put_u16(p, 0); /* short name padding, 2 bytes */
1672         }
1673
1674         /* Align to 8-byte boundary */
1675         wimlib_assert(length >= (p - orig_p) && length - (p - orig_p) <= 7);
1676         p = put_zeroes(p, length - (p - orig_p));
1677
1678         /* Write the alternate data streams, if there are any.  Please see
1679          * read_ads_entries() for comments about the format of the on-disk
1680          * alternate data stream entries. */
1681         for (u16 i = 0; i < inode->num_ads; i++) {
1682                 p = put_u64(p, ads_entry_total_length(&inode->ads_entries[i]));
1683                 p = put_u64(p, 0); /* Unused */
1684                 hash = inode_stream_hash(inode, i + 1);
1685                 p = put_bytes(p, SHA1_HASH_SIZE, hash);
1686                 p = put_u16(p, inode->ads_entries[i].stream_name_len);
1687                 if (inode->ads_entries[i].stream_name_len) {
1688                         p = put_bytes(p, inode->ads_entries[i].stream_name_len,
1689                                          (u8*)inode->ads_entries[i].stream_name);
1690                         p = put_u16(p, 0);
1691                 }
1692                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1693         }
1694         wimlib_assert(p - orig_p == __dentry_total_length(dentry, length));
1695         return p;
1696 }
1697
1698 /* Recursive function that writes a dentry tree rooted at @parent, not including
1699  * @parent itself, which has already been written. */
1700 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p)
1701 {
1702         const struct dentry *child, *children;
1703
1704         /* Nothing to do if this dentry has no children. */
1705         if (parent->subdir_offset == 0)
1706                 return p;
1707
1708         /* Write child dentries and end-of-directory entry.
1709          *
1710          * Note: we need to write all of this dentry's children before
1711          * recursively writing the directory trees rooted at each of the child
1712          * dentries, since the on-disk dentries for a dentry's children are
1713          * always located at consecutive positions in the metadata resource! */
1714         children = parent->d_inode->children;
1715         child = children;
1716         if (child) {
1717                 do {
1718                         p = write_dentry(child, p);
1719                         child = child->next;
1720                 } while (child != children);
1721         }
1722
1723         /* write end of directory entry */
1724         p = put_u64(p, 0);
1725
1726         /* Recurse on children. */
1727         if (child) {
1728                 do {
1729                         p = write_dentry_tree_recursive(child, p);
1730                         child = child->next;
1731                 } while (child != children);
1732         }
1733         return p;
1734 }
1735
1736 /* Writes a directory tree to the metadata resource.
1737  *
1738  * @root:       Root of the dentry tree.
1739  * @p:          Pointer to a buffer with enough space for the dentry tree.
1740  *
1741  * Returns pointer to the byte after the last byte we wrote.
1742  */
1743 u8 *write_dentry_tree(const struct dentry *root, u8 *p)
1744 {
1745         DEBUG("Writing dentry tree.");
1746         wimlib_assert(dentry_is_root(root));
1747
1748         /* If we're the root dentry, we have no parent that already
1749          * wrote us, so we need to write ourselves. */
1750         p = write_dentry(root, p);
1751
1752         /* Write end of directory entry after the root dentry just to be safe;
1753          * however the root dentry obviously cannot have any siblings. */
1754         p = put_u64(p, 0);
1755
1756         /* Recursively write the rest of the dentry tree. */
1757         return write_dentry_tree_recursive(root, p);
1758 }
1759