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