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