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