]> wimlib.net Git - wimlib/blob - src/dentry.c
Remove remaining DEBUG() messages
[wimlib] / src / dentry.c
1 /*
2  * dentry.c - see description below
3  */
4
5 /*
6  * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 /*
23  * This file contains logic to deal with WIM directory entries, or "dentries":
24  *
25  *  - Reading a dentry tree from a metadata resource in a WIM file
26  *  - Writing a dentry tree to a metadata resource in a WIM file
27  *  - Iterating through a tree of WIM dentries
28  *  - Path lookup: translating a path into a WIM dentry or inode
29  *  - Creating, modifying, and deleting WIM dentries
30  *
31  * Notes:
32  *
33  *  - A WIM file can contain multiple images, each of which has an independent
34  *    tree of dentries.  "On disk", the dentry tree for an image is stored in
35  *    the "metadata resource" for that image.
36  *
37  *  - Multiple dentries in an image may correspond to the same inode, or "file".
38  *    When this occurs, it means that the file has multiple names, or "hard
39  *    links".  A dentry is not a file, but rather the name of a file!
40  *
41  *  - Inodes are not represented explicitly in the WIM file format.  Instead,
42  *    the metadata resource provides a "hard link group ID" for each dentry.
43  *    wimlib handles pulling out actual inodes from this information, but this
44  *    occurs in inode_fixup.c and not in this file.
45  *
46  *  - wimlib does not allow *directory* hard links, so a WIM image really does
47  *    have a *tree* of dentries (and not an arbitrary graph of dentries).
48  *
49  *  - wimlib indexes dentries both case-insensitively and case-sensitively,
50  *    allowing either behavior to be used for path lookup.
51  *
52  *  - Multiple dentries in a directory might have the same case-insensitive
53  *    name.  But wimlib enforces that at most one dentry in a directory can have
54  *    a given case-sensitive name.
55  */
56
57 #ifdef HAVE_CONFIG_H
58 #  include "config.h"
59 #endif
60
61 #include <errno.h>
62
63 #include "wimlib/assert.h"
64 #include "wimlib/dentry.h"
65 #include "wimlib/inode.h"
66 #include "wimlib/encoding.h"
67 #include "wimlib/endianness.h"
68 #include "wimlib/metadata.h"
69 #include "wimlib/paths.h"
70
71 /* On-disk format of a WIM dentry (directory entry), located in the metadata
72  * resource for a WIM image.  */
73 struct wim_dentry_on_disk {
74
75         /* Length of this directory entry in bytes, not including any extra
76          * stream entries.  Should be a multiple of 8 so that the following
77          * dentry or extra stream entry is aligned on an 8-byte boundary.  (If
78          * not, wimlib will round it up.)  It must be at least as long as the
79          * fixed-length fields of the dentry (WIM_DENTRY_DISK_SIZE), plus the
80          * lengths of the file name and/or short name if present, plus the size
81          * of any "extra" data.
82          *
83          * It is also possible for this field to be 0.  This case indicates the
84          * end of a list of sibling entries in a directory.  It also means the
85          * real length is 8, because the dentry included only the length field,
86          * but that takes up 8 bytes.  */
87         le64 length;
88
89         /* File attributes for the file or directory.  This is a bitwise OR of
90          * the FILE_ATTRIBUTE_* constants and should correspond to the value
91          * retrieved by GetFileAttributes() on Windows. */
92         le32 attributes;
93
94         /* A value that specifies the security descriptor for this file or
95          * directory.  If -1, the file or directory has no security descriptor.
96          * Otherwise, it is a 0-based index into the WIM image's table of
97          * security descriptors (see: `struct wim_security_data') */
98         sle32 security_id;
99
100         /* Offset, in bytes, from the start of the uncompressed metadata
101          * resource of this directory's child directory entries, or 0 if this
102          * directory entry does not correspond to a directory or otherwise does
103          * not have any children. */
104         le64 subdir_offset;
105
106         /* Reserved fields */
107         le64 unused_1;
108         le64 unused_2;
109
110         /* Creation time, last access time, and last write time, in
111          * 100-nanosecond intervals since 12:00 a.m UTC January 1, 1601.  They
112          * should correspond to the times gotten by calling GetFileTime() on
113          * Windows. */
114         le64 creation_time;
115         le64 last_access_time;
116         le64 last_write_time;
117
118         /*
119          * Usually this is the SHA-1 message digest of the file's "contents"
120          * (the unnamed data stream).
121          *
122          * If the file has FILE_ATTRIBUTE_REPARSE_POINT set, then this is
123          * instead usually the SHA-1 message digest of the uncompressed reparse
124          * point data.
125          *
126          * However, there are some special rules that need to be applied to
127          * interpret this field correctly when extra stream entries are present.
128          * See the code for details.
129          */
130         u8 default_hash[SHA1_HASH_SIZE];
131
132         /* Unknown field (maybe accidental padding)  */
133         le32 unknown_0x54;
134
135         /*
136          * The following 8-byte union contains either information about the
137          * reparse point (for files with FILE_ATTRIBUTE_REPARSE_POINT set), or
138          * the "hard link group ID" (for other files).
139          *
140          * The reparse point information contains ReparseTag and ReparseReserved
141          * from the header of the reparse point buffer.  It also contains a flag
142          * that indicates whether a reparse point fixup (for the target of an
143          * absolute symbolic link or junction) was done or not.
144          *
145          * The "hard link group ID" is like an inode number; all dentries for
146          * the same inode share the same value.  See inode_fixup.c for more
147          * information.
148          *
149          * Note that this union creates the limitation that reparse point files
150          * cannot have multiple names (hard links).
151          */
152         union {
153                 struct {
154                         le32 reparse_tag;
155                         le16 rp_reserved;
156                         le16 rp_flags;
157                 } _packed_attribute reparse;
158                 struct {
159                         le64 hard_link_group_id;
160                 } _packed_attribute nonreparse;
161         };
162
163         /* Number of extra stream entries that directly follow this dentry
164          * on-disk.  */
165         le16 num_extra_streams;
166
167         /* If nonzero, this is the length, in bytes, of this dentry's UTF-16LE
168          * encoded short name (8.3 DOS-compatible name), excluding the null
169          * terminator.  If zero, then the long name of this dentry does not have
170          * a corresponding short name (but this does not exclude the possibility
171          * that another dentry for the same file has a short name).  */
172         le16 short_name_nbytes;
173
174         /* If nonzero, this is the length, in bytes, of this dentry's UTF-16LE
175          * encoded "long" name, excluding the null terminator.  If zero, then
176          * this file has no long name.  The root dentry should not have a long
177          * name, but all other dentries in the image should have long names.  */
178         le16 name_nbytes;
179
180         /* Beginning of optional, variable-length fields  */
181
182         /* If name_nbytes != 0, the next field will be the UTF-16LE encoded long
183          * name.  This will be null-terminated, so the size of this field will
184          * really be name_nbytes + 2.  */
185         /*utf16lechar name[];*/
186
187         /* If short_name_nbytes != 0, the next field will be the UTF-16LE
188          * encoded short name.  This will be null-terminated, so the size of
189          * this field will really be short_name_nbytes + 2.  */
190         /*utf16lechar short_name[];*/
191
192         /* If there is still space in the dentry (according to the 'length'
193          * field) after 8-byte alignment, then the remaining space will be a
194          * variable-length list of tagged metadata items.  See tagged_items.c
195          * for more information.  */
196         /* u8 tagged_items[] _aligned_attribute(8); */
197
198 } _packed_attribute;
199         /* If num_extra_streams != 0, then there are that many extra stream
200          * entries following the dentry, starting on the next 8-byte aligned
201          * boundary.  They are not counted in the 'length' field of the dentry.
202          */
203
204 /* On-disk format of an extra stream entry.  This represents an extra NTFS-style
205  * "stream" associated with the file, such as a named data stream.  */
206 struct wim_extra_stream_entry_on_disk {
207
208         /* Length of this extra stream entry, in bytes.  This includes all
209          * fixed-length fields, plus the name and null terminator if present,
210          * and any needed padding such that the length is a multiple of 8.  */
211         le64 length;
212
213         /* Reserved field  */
214         le64 reserved;
215
216         /* SHA-1 message digest of this stream's uncompressed data, or all
217          * zeroes if this stream's data is of zero length.  */
218         u8 hash[SHA1_HASH_SIZE];
219
220         /* Length of this stream's name, in bytes and excluding the null
221          * terminator; or 0 if this stream is unnamed.  */
222         le16 name_nbytes;
223
224         /* Stream name in UTF-16LE.  It is @name_nbytes bytes long, excluding
225          * the null terminator.  There is a null terminator character if
226          * @name_nbytes != 0; i.e., if this stream is named.  */
227         utf16lechar name[];
228 } _packed_attribute;
229
230 static void
231 do_dentry_set_name(struct wim_dentry *dentry, utf16lechar *name,
232                    size_t name_nbytes)
233 {
234         FREE(dentry->d_name);
235         dentry->d_name = name;
236         dentry->d_name_nbytes = name_nbytes;
237
238         if (dentry_has_short_name(dentry)) {
239                 FREE(dentry->d_short_name);
240                 dentry->d_short_name = NULL;
241                 dentry->d_short_name_nbytes = 0;
242         }
243 }
244
245 /*
246  * Set the name of a WIM dentry from a UTF-16LE string.
247  *
248  * This sets the long name of the dentry.  The short name will automatically be
249  * removed, since it may not be appropriate for the new long name.
250  *
251  * The @name string need not be null-terminated, since its length is specified
252  * in @name_nbytes.
253  *
254  * If @name_nbytes is 0, both the long and short names of the dentry will be
255  * removed.
256  *
257  * Only use this function on unlinked dentries, since it doesn't update the name
258  * indices.  For dentries that are currently linked into the tree, use
259  * rename_wim_path().
260  *
261  * Returns 0 or WIMLIB_ERR_NOMEM.
262  */
263 int
264 dentry_set_name_utf16le(struct wim_dentry *dentry, const utf16lechar *name,
265                         size_t name_nbytes)
266 {
267         utf16lechar *dup = NULL;
268
269         if (name_nbytes) {
270                 dup = utf16le_dupz(name, name_nbytes);
271                 if (!dup)
272                         return WIMLIB_ERR_NOMEM;
273         }
274         do_dentry_set_name(dentry, dup, name_nbytes);
275         return 0;
276 }
277
278
279 /*
280  * Set the name of a WIM dentry from a 'tchar' string.
281  *
282  * This sets the long name of the dentry.  The short name will automatically be
283  * removed, since it may not be appropriate for the new long name.
284  *
285  * If @name is NULL or empty, both the long and short names of the dentry will
286  * be removed.
287  *
288  * Only use this function on unlinked dentries, since it doesn't update the name
289  * indices.  For dentries that are currently linked into the tree, use
290  * rename_wim_path().
291  *
292  * Returns 0 or an error code resulting from a failed string conversion.
293  */
294 int
295 dentry_set_name(struct wim_dentry *dentry, const tchar *name)
296 {
297         utf16lechar *name_utf16le = NULL;
298         size_t name_utf16le_nbytes = 0;
299         int ret;
300
301         if (name && *name) {
302                 ret = tstr_to_utf16le(name, tstrlen(name) * sizeof(tchar),
303                                       &name_utf16le, &name_utf16le_nbytes);
304                 if (ret)
305                         return ret;
306         }
307
308         do_dentry_set_name(dentry, name_utf16le, name_utf16le_nbytes);
309         return 0;
310 }
311
312 /* Calculate the minimum unaligned length, in bytes, of an on-disk WIM dentry
313  * that has names of the specified lengths.  (Zero length means the
314  * corresponding name actually does not exist.)  The returned value excludes
315  * tagged metadata items as well as any extra stream entries that may need to
316  * follow the dentry.  */
317 static size_t
318 dentry_min_len_with_names(u16 name_nbytes, u16 short_name_nbytes)
319 {
320         size_t length = sizeof(struct wim_dentry_on_disk);
321         if (name_nbytes)
322                 length += (u32)name_nbytes + 2;
323         if (short_name_nbytes)
324                 length += (u32)short_name_nbytes + 2;
325         return length;
326 }
327
328
329 /* Return the length, in bytes, required for the specified stream on-disk, when
330  * represented as an extra stream entry.  */
331 static size_t
332 stream_out_total_length(const struct wim_inode_stream *strm)
333 {
334         /* Account for the fixed length portion  */
335         size_t len = sizeof(struct wim_extra_stream_entry_on_disk);
336
337         /* For named streams, account for the variable-length name.  */
338         if (stream_is_named(strm))
339                 len += utf16le_len_bytes(strm->stream_name) + 2;
340
341         /* Account for any necessary padding to the next 8-byte boundary.  */
342         return ALIGN(len, 8);
343 }
344
345 /*
346  * Calculate the total number of bytes that will be consumed when a dentry is
347  * written.  This includes the fixed-length portion of the dentry, the name
348  * fields, any tagged metadata items, and any extra stream entries.  This also
349  * includes all alignment bytes.
350  */
351 size_t
352 dentry_out_total_length(const struct wim_dentry *dentry)
353 {
354         const struct wim_inode *inode = dentry->d_inode;
355         size_t len;
356
357         len = dentry_min_len_with_names(dentry->d_name_nbytes,
358                                         dentry->d_short_name_nbytes);
359         len = ALIGN(len, 8);
360
361         len += ALIGN(inode->i_extra_size, 8);
362
363         if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
364                 /*
365                  * Extra stream entries:
366                  *
367                  * - Use one extra stream entry for each named data stream
368                  * - Use one extra stream entry for the unnamed data stream when there is either:
369                  *      - a reparse point stream
370                  *      - at least one named data stream (for Windows PE bug workaround)
371                  * - Use one extra stream entry for the reparse point stream if there is one
372                  */
373                 bool have_named_data_stream = false;
374                 bool have_reparse_point_stream = false;
375                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
376                         const struct wim_inode_stream *strm = &inode->i_streams[i];
377                         if (stream_is_named_data_stream(strm)) {
378                                 len += stream_out_total_length(strm);
379                                 have_named_data_stream = true;
380                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
381                                 wimlib_assert(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT);
382                                 have_reparse_point_stream = true;
383                         }
384                 }
385
386                 if (have_named_data_stream || have_reparse_point_stream) {
387                         if (have_reparse_point_stream)
388                                 len += ALIGN(sizeof(struct wim_extra_stream_entry_on_disk), 8);
389                         len += ALIGN(sizeof(struct wim_extra_stream_entry_on_disk), 8);
390                 }
391         }
392
393         return len;
394 }
395
396 /* Internal version of for_dentry_in_tree() that omits the NULL check  */
397 static int
398 do_for_dentry_in_tree(struct wim_dentry *dentry,
399                       int (*visitor)(struct wim_dentry *, void *), void *arg)
400 {
401         int ret;
402         struct wim_dentry *child;
403
404         ret = (*visitor)(dentry, arg);
405         if (unlikely(ret))
406                 return ret;
407
408         for_dentry_child(child, dentry) {
409                 ret = do_for_dentry_in_tree(child, visitor, arg);
410                 if (unlikely(ret))
411                         return ret;
412         }
413         return 0;
414 }
415
416 /* Internal version of for_dentry_in_tree_depth() that omits the NULL check  */
417 static int
418 do_for_dentry_in_tree_depth(struct wim_dentry *dentry,
419                             int (*visitor)(struct wim_dentry *, void *), void *arg)
420 {
421         int ret;
422         struct wim_dentry *child;
423
424         for_dentry_child_postorder(child, dentry) {
425                 ret = do_for_dentry_in_tree_depth(child, visitor, arg);
426                 if (unlikely(ret))
427                         return ret;
428         }
429         return unlikely((*visitor)(dentry, arg));
430 }
431
432 /*
433  * Call a function on all dentries in a tree.
434  *
435  * @arg will be passed as the second argument to each invocation of @visitor.
436  *
437  * This function does a pre-order traversal --- that is, a parent will be
438  * visited before its children.  It also will visit siblings in order of
439  * case-sensitive filename.  Equivalently, this function visits the entire tree
440  * in the case-sensitive lexicographic order of the full paths.
441  *
442  * It is safe to pass NULL for @root, which means that the dentry tree is empty.
443  * In this case, this function does nothing.
444  *
445  * @visitor must not modify the structure of the dentry tree during the
446  * traversal.
447  *
448  * The return value will be 0 if all calls to @visitor returned 0.  Otherwise,
449  * the return value will be the first nonzero value returned by @visitor.
450  */
451 int
452 for_dentry_in_tree(struct wim_dentry *root,
453                    int (*visitor)(struct wim_dentry *, void *), void *arg)
454 {
455         if (unlikely(!root))
456                 return 0;
457         return do_for_dentry_in_tree(root, visitor, arg);
458 }
459
460 /* Like for_dentry_in_tree(), but do a depth-first traversal of the dentry tree.
461  * That is, the visitor function will be called on a dentry's children before
462  * itself.  It will be safe to free a dentry when visiting it.  */
463 static int
464 for_dentry_in_tree_depth(struct wim_dentry *root,
465                          int (*visitor)(struct wim_dentry *, void *), void *arg)
466 {
467         if (unlikely(!root))
468                 return 0;
469         return do_for_dentry_in_tree_depth(root, visitor, arg);
470 }
471
472 /*
473  * Calculate the full path to @dentry within the WIM image, if not already done.
474  *
475  * The full name will be saved in the cached value 'dentry->d_full_path'.
476  *
477  * Whenever possible, use dentry_full_path() instead of calling this and
478  * accessing d_full_path directly.
479  *
480  * Returns 0 or an error code resulting from a failed string conversion.
481  */
482 int
483 calculate_dentry_full_path(struct wim_dentry *dentry)
484 {
485         size_t ulen;
486         size_t dummy;
487         const struct wim_dentry *d;
488
489         if (dentry->d_full_path)
490                 return 0;
491
492         ulen = 0;
493         d = dentry;
494         do {
495                 ulen += d->d_name_nbytes / sizeof(utf16lechar);
496                 ulen++;
497                 d = d->d_parent;  /* assumes d == d->d_parent for root  */
498         } while (!dentry_is_root(d));
499
500         utf16lechar ubuf[ulen];
501         utf16lechar *p = &ubuf[ulen];
502
503         d = dentry;
504         do {
505                 p -= d->d_name_nbytes / sizeof(utf16lechar);
506                 memcpy(p, d->d_name, d->d_name_nbytes);
507                 *--p = cpu_to_le16(WIM_PATH_SEPARATOR);
508                 d = d->d_parent;  /* assumes d == d->d_parent for root  */
509         } while (!dentry_is_root(d));
510
511         wimlib_assert(p == ubuf);
512
513         return utf16le_to_tstr(ubuf, ulen * sizeof(utf16lechar),
514                                &dentry->d_full_path, &dummy);
515 }
516
517 /*
518  * Return the full path to the @dentry within the WIM image, or NULL if the full
519  * path could not be determined due to a string conversion error.
520  *
521  * The returned memory will be cached in the dentry, so the caller is not
522  * responsible for freeing it.
523  */
524 tchar *
525 dentry_full_path(struct wim_dentry *dentry)
526 {
527         calculate_dentry_full_path(dentry);
528         return dentry->d_full_path;
529 }
530
531 static int
532 dentry_calculate_subdir_offset(struct wim_dentry *dentry, void *_subdir_offset_p)
533 {
534         if (dentry_is_directory(dentry)) {
535                 u64 *subdir_offset_p = _subdir_offset_p;
536                 struct wim_dentry *child;
537
538                 /* Set offset of directory's child dentries  */
539                 dentry->d_subdir_offset = *subdir_offset_p;
540
541                 /* Account for child dentries  */
542                 for_dentry_child(child, dentry)
543                         *subdir_offset_p += dentry_out_total_length(child);
544
545                 /* Account for end-of-directory entry  */
546                 *subdir_offset_p += 8;
547         } else {
548                 /* Not a directory; set the subdir offset to 0  */
549                 dentry->d_subdir_offset = 0;
550         }
551         return 0;
552 }
553
554 /*
555  * Calculate the subdir offsets for a dentry tree, in preparation of writing
556  * that dentry tree to a metadata resource.
557  *
558  * The subdir offset of each dentry is the offset in the uncompressed metadata
559  * resource at which its child dentries begin, or 0 if that dentry has no
560  * children.
561  *
562  * The caller must initialize *subdir_offset_p to the first subdir offset that
563  * is available to use after the root dentry is written.
564  *
565  * When this function returns, *subdir_offset_p will have been advanced past the
566  * size needed for the dentry tree within the uncompressed metadata resource.
567  */
568 void
569 calculate_subdir_offsets(struct wim_dentry *root, u64 *subdir_offset_p)
570 {
571         for_dentry_in_tree(root, dentry_calculate_subdir_offset, subdir_offset_p);
572 }
573
574 /* Compare the UTF-16LE long filenames of two dentries case insensitively.  */
575 static int
576 dentry_compare_names_case_insensitive(const struct wim_dentry *d1,
577                                       const struct wim_dentry *d2)
578 {
579         return cmp_utf16le_strings(d1->d_name,
580                                    d1->d_name_nbytes / 2,
581                                    d2->d_name,
582                                    d2->d_name_nbytes / 2,
583                                    true);
584 }
585
586 /* Compare the UTF-16LE long filenames of two dentries case sensitively.  */
587 static int
588 dentry_compare_names_case_sensitive(const struct wim_dentry *d1,
589                                     const struct wim_dentry *d2)
590 {
591         return cmp_utf16le_strings(d1->d_name,
592                                    d1->d_name_nbytes / 2,
593                                    d2->d_name,
594                                    d2->d_name_nbytes / 2,
595                                    false);
596 }
597
598 static int
599 _avl_dentry_compare_names_ci(const struct avl_tree_node *n1,
600                              const struct avl_tree_node *n2)
601 {
602         const struct wim_dentry *d1, *d2;
603
604         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node_ci);
605         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node_ci);
606         return dentry_compare_names_case_insensitive(d1, d2);
607 }
608
609 static int
610 _avl_dentry_compare_names(const struct avl_tree_node *n1,
611                           const struct avl_tree_node *n2)
612 {
613         const struct wim_dentry *d1, *d2;
614
615         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node);
616         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node);
617         return dentry_compare_names_case_sensitive(d1, d2);
618 }
619
620 /* Default case sensitivity behavior for searches with
621  * WIMLIB_CASE_PLATFORM_DEFAULT specified.  This can be modified by passing
622  * WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE or
623  * WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE to wimlib_global_init().  */
624 bool default_ignore_case =
625 #ifdef __WIN32__
626         true
627 #else
628         false
629 #endif
630 ;
631
632 /* Case-sensitive dentry lookup.  Only @d_name and @d_name_nbytes of @dummy must
633  * be valid.  */
634 static struct wim_dentry *
635 dir_lookup(const struct wim_inode *dir, const struct wim_dentry *dummy)
636 {
637         struct avl_tree_node *node;
638
639         node = avl_tree_lookup_node(dir->i_children,
640                                     &dummy->d_index_node,
641                                     _avl_dentry_compare_names);
642         if (!node)
643                 return NULL;
644         return avl_tree_entry(node, struct wim_dentry, d_index_node);
645 }
646
647 /* Case-insensitive dentry lookup.  Only @d_name and @d_name_nbytes of @dummy
648  * must be valid.  */
649 static struct wim_dentry *
650 dir_lookup_ci(const struct wim_inode *dir, const struct wim_dentry *dummy)
651 {
652         struct avl_tree_node *node;
653
654         node = avl_tree_lookup_node(dir->i_children_ci,
655                                     &dummy->d_index_node_ci,
656                                     _avl_dentry_compare_names_ci);
657         if (!node)
658                 return NULL;
659         return avl_tree_entry(node, struct wim_dentry, d_index_node_ci);
660 }
661
662 /* Given a UTF-16LE filename and a directory, look up the dentry for the file.
663  * Return it if found, otherwise NULL.  This has configurable case sensitivity,
664  * and @name need not be null-terminated.  */
665 struct wim_dentry *
666 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
667                                    const utf16lechar *name,
668                                    size_t name_nbytes,
669                                    CASE_SENSITIVITY_TYPE case_type)
670 {
671         const struct wim_inode *dir = dentry->d_inode;
672         bool ignore_case = will_ignore_case(case_type);
673         struct wim_dentry dummy;
674         struct wim_dentry *child;
675
676         dummy.d_name = (utf16lechar*)name;
677         dummy.d_name_nbytes = name_nbytes;
678
679         if (!ignore_case)
680                 /* Case-sensitive lookup.  */
681                 return dir_lookup(dir, &dummy);
682
683         /* Case-insensitive lookup.  */
684
685         child = dir_lookup_ci(dir, &dummy);
686         if (!child)
687                 return NULL;
688
689         if (likely(list_empty(&child->d_ci_conflict_list)))
690                 /* Only one dentry has this case-insensitive name; return it */
691                 return child;
692
693         /* Multiple dentries have the same case-insensitive name.  Choose the
694          * dentry with the same case-sensitive name, if one exists; otherwise
695          * print a warning and choose one of the possible dentries arbitrarily.
696          */
697         struct wim_dentry *alt = child;
698         size_t num_alts = 0;
699
700         do {
701                 num_alts++;
702                 if (!dentry_compare_names_case_sensitive(&dummy, alt))
703                         return alt;
704                 alt = list_entry(alt->d_ci_conflict_list.next,
705                                  struct wim_dentry, d_ci_conflict_list);
706         } while (alt != child);
707
708         WARNING("Result of case-insensitive lookup is ambiguous\n"
709                 "          (returning \"%"TS"\" of %zu "
710                 "possible files, including \"%"TS"\")",
711                 dentry_full_path(child),
712                 num_alts,
713                 dentry_full_path(list_entry(child->d_ci_conflict_list.next,
714                                             struct wim_dentry,
715                                             d_ci_conflict_list)));
716         return child;
717 }
718
719 /* Given a 'tchar' filename and a directory, look up the dentry for the file.
720  * If the filename was successfully converted to UTF-16LE and the dentry was
721  * found, return it; otherwise return NULL.  This has configurable case
722  * sensitivity.  */
723 struct wim_dentry *
724 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name,
725                            CASE_SENSITIVITY_TYPE case_type)
726 {
727         int ret;
728         const utf16lechar *name_utf16le;
729         size_t name_utf16le_nbytes;
730         struct wim_dentry *child;
731
732         ret = tstr_get_utf16le_and_len(name, &name_utf16le,
733                                        &name_utf16le_nbytes);
734         if (ret)
735                 return NULL;
736
737         child = get_dentry_child_with_utf16le_name(dentry,
738                                                    name_utf16le,
739                                                    name_utf16le_nbytes,
740                                                    case_type);
741         tstr_put_utf16le(name_utf16le);
742         return child;
743 }
744
745 /* This is the UTF-16LE version of get_dentry(), currently private to this file
746  * because no one needs it besides get_dentry().  */
747 static struct wim_dentry *
748 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path,
749                    CASE_SENSITIVITY_TYPE case_type)
750 {
751         struct wim_dentry *cur_dentry;
752         const utf16lechar *name_start, *name_end;
753
754         /* Start with the root directory of the image.  Note: this will be NULL
755          * if an image has been added directly with wimlib_add_empty_image() but
756          * no files have been added yet; in that case we fail with ENOENT.  */
757         cur_dentry = wim_get_current_root_dentry(wim);
758
759         name_start = path;
760         for (;;) {
761                 if (cur_dentry == NULL) {
762                         errno = ENOENT;
763                         return NULL;
764                 }
765
766                 if (*name_start && !dentry_is_directory(cur_dentry)) {
767                         errno = ENOTDIR;
768                         return NULL;
769                 }
770
771                 while (*name_start == cpu_to_le16(WIM_PATH_SEPARATOR))
772                         name_start++;
773
774                 if (!*name_start)
775                         return cur_dentry;
776
777                 name_end = name_start;
778                 do {
779                         ++name_end;
780                 } while (*name_end != cpu_to_le16(WIM_PATH_SEPARATOR) && *name_end);
781
782                 cur_dentry = get_dentry_child_with_utf16le_name(cur_dentry,
783                                                                 name_start,
784                                                                 (u8*)name_end - (u8*)name_start,
785                                                                 case_type);
786                 name_start = name_end;
787         }
788 }
789
790 /*
791  * WIM path lookup: translate a path in the currently selected WIM image to the
792  * corresponding dentry, if it exists.
793  *
794  * @wim
795  *      The WIMStruct for the WIM.  The search takes place in the currently
796  *      selected image.
797  *
798  * @path
799  *      The path to look up, given relative to the root of the WIM image.
800  *      Characters with value WIM_PATH_SEPARATOR are taken to be path
801  *      separators.  Leading path separators are ignored, whereas one or more
802  *      trailing path separators cause the path to only match a directory.
803  *
804  * @case_type
805  *      The case-sensitivity behavior of this function, as one of the following
806  *      constants:
807  *
808  *    - WIMLIB_CASE_SENSITIVE:  Perform the search case sensitively.  This means
809  *      that names must match exactly.
810  *
811  *    - WIMLIB_CASE_INSENSITIVE:  Perform the search case insensitively.  This
812  *      means that names are considered to match if they are equal when
813  *      transformed to upper case.  If a path component matches multiple names
814  *      case-insensitively, the name that matches the path component
815  *      case-sensitively is chosen, if existent; otherwise one
816  *      case-insensitively matching name is chosen arbitrarily.
817  *
818  *    - WIMLIB_CASE_PLATFORM_DEFAULT:  Perform either case-sensitive or
819  *      case-insensitive search, depending on the value of the global variable
820  *      default_ignore_case.
821  *
822  *    In any case, no Unicode normalization is done before comparing strings.
823  *
824  * Returns a pointer to the dentry that is the result of the lookup, or NULL if
825  * no such dentry exists.  If NULL is returned, errno is set to one of the
826  * following values:
827  *
828  *      ENOTDIR if one of the path components used as a directory existed but
829  *      was not, in fact, a directory.
830  *
831  *      ENOENT otherwise.
832  *
833  * Additional notes:
834  *
835  *    - This function does not consider a reparse point to be a directory, even
836  *      if it has FILE_ATTRIBUTE_DIRECTORY set.
837  *
838  *    - This function does not dereference symbolic links or junction points
839  *      when performing the search.
840  *
841  *    - Since this function ignores leading slashes, the empty path is valid and
842  *      names the root directory of the WIM image.
843  *
844  *    - An image added with wimlib_add_empty_image() does not have a root
845  *      directory yet, and this function will fail with ENOENT for any path on
846  *      such an image.
847  */
848 struct wim_dentry *
849 get_dentry(WIMStruct *wim, const tchar *path, CASE_SENSITIVITY_TYPE case_type)
850 {
851         int ret;
852         const utf16lechar *path_utf16le;
853         struct wim_dentry *dentry;
854
855         ret = tstr_get_utf16le(path, &path_utf16le);
856         if (ret)
857                 return NULL;
858         dentry = get_dentry_utf16le(wim, path_utf16le, case_type);
859         tstr_put_utf16le(path_utf16le);
860         return dentry;
861 }
862
863 /* Modify @path, which is a null-terminated string @len 'tchars' in length,
864  * in-place to produce the path to its parent directory.  */
865 static void
866 to_parent_name(tchar *path, size_t len)
867 {
868         ssize_t i = (ssize_t)len - 1;
869         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
870                 i--;
871         while (i >= 0 && path[i] != WIM_PATH_SEPARATOR)
872                 i--;
873         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
874                 i--;
875         path[i + 1] = T('\0');
876 }
877
878 /* Similar to get_dentry(), but returns the dentry named by @path with the last
879  * component stripped off.
880  *
881  * Note: The returned dentry is NOT guaranteed to be a directory.  */
882 struct wim_dentry *
883 get_parent_dentry(WIMStruct *wim, const tchar *path,
884                   CASE_SENSITIVITY_TYPE case_type)
885 {
886         size_t path_len = tstrlen(path);
887         tchar buf[path_len + 1];
888
889         tmemcpy(buf, path, path_len + 1);
890         to_parent_name(buf, path_len);
891         return get_dentry(wim, buf, case_type);
892 }
893
894 /*
895  * Create an unlinked dentry.
896  *
897  * @name specifies the long name to give the new dentry.  If NULL or empty, the
898  * new dentry will be given no long name.
899  *
900  * The new dentry will have no short name and no associated inode.
901  *
902  * On success, returns 0 and a pointer to the new, allocated dentry is stored in
903  * *dentry_ret.  On failure, returns WIMLIB_ERR_NOMEM or an error code resulting
904  * from a failed string conversion.
905  */
906 static int
907 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
908 {
909         struct wim_dentry *dentry;
910         int ret;
911
912         dentry = CALLOC(1, sizeof(struct wim_dentry));
913         if (!dentry)
914                 return WIMLIB_ERR_NOMEM;
915
916         if (name && *name) {
917                 ret = dentry_set_name(dentry, name);
918                 if (ret) {
919                         FREE(dentry);
920                         return ret;
921                 }
922         }
923         dentry->d_parent = dentry;
924         *dentry_ret = dentry;
925         return 0;
926 }
927
928 /* Like new_dentry(), but also allocate an inode and associate it with the
929  * dentry.  If set_timestamps=true, the timestamps for the inode will be set to
930  * the current time; otherwise, they will be left 0.  */
931 int
932 new_dentry_with_new_inode(const tchar *name, bool set_timestamps,
933                           struct wim_dentry **dentry_ret)
934 {
935         struct wim_dentry *dentry;
936         struct wim_inode *inode;
937         int ret;
938
939         ret = new_dentry(name, &dentry);
940         if (ret)
941                 return ret;
942
943         inode = new_inode(dentry, set_timestamps);
944         if (!inode) {
945                 free_dentry(dentry);
946                 return WIMLIB_ERR_NOMEM;
947         }
948
949         *dentry_ret = dentry;
950         return 0;
951 }
952
953 /* Like new_dentry(), but also associate the new dentry with the specified inode
954  * and acquire a reference to each of the inode's blobs.  */
955 int
956 new_dentry_with_existing_inode(const tchar *name, struct wim_inode *inode,
957                                struct wim_dentry **dentry_ret)
958 {
959         int ret = new_dentry(name, dentry_ret);
960         if (ret)
961                 return ret;
962         d_associate(*dentry_ret, inode);
963         inode_ref_blobs(inode);
964         return 0;
965 }
966
967 /* Create an unnamed dentry with a new inode for a directory with the default
968  * metadata.  */
969 int
970 new_filler_directory(struct wim_dentry **dentry_ret)
971 {
972         int ret;
973         struct wim_dentry *dentry;
974
975         ret = new_dentry_with_new_inode(NULL, true, &dentry);
976         if (ret)
977                 return ret;
978         /* Leave the inode number as 0; this is allowed for non
979          * hard-linked files. */
980         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
981         *dentry_ret = dentry;
982         return 0;
983 }
984
985 /*
986  * Free a WIM dentry.
987  *
988  * In addition to freeing the dentry itself, this disassociates the dentry from
989  * its inode.  If the inode is no longer in use, it will be freed as well.
990  */
991 void
992 free_dentry(struct wim_dentry *dentry)
993 {
994         if (dentry) {
995                 d_disassociate(dentry);
996                 FREE(dentry->d_name);
997                 FREE(dentry->d_short_name);
998                 FREE(dentry->d_full_path);
999                 FREE(dentry);
1000         }
1001 }
1002
1003 static int
1004 do_free_dentry(struct wim_dentry *dentry, void *_ignore)
1005 {
1006         free_dentry(dentry);
1007         return 0;
1008 }
1009
1010 static int
1011 do_free_dentry_and_unref_blobs(struct wim_dentry *dentry, void *blob_table)
1012 {
1013         inode_unref_blobs(dentry->d_inode, blob_table);
1014         free_dentry(dentry);
1015         return 0;
1016 }
1017
1018 /*
1019  * Free all dentries in a tree.
1020  *
1021  * @root:
1022  *      The root of the dentry tree to free.  If NULL, this function has no
1023  *      effect.
1024  *
1025  * @blob_table:
1026  *      A pointer to the blob table for the WIM, or NULL if not specified.  If
1027  *      specified, this function will decrement the reference counts of the
1028  *      blobs referenced by the dentries.
1029  *
1030  * This function also releases references to the corresponding inodes.
1031  *
1032  * This function does *not* unlink @root from its parent directory, if it has
1033  * one.  If @root has a parent, the caller must unlink @root before calling this
1034  * function.
1035  */
1036 void
1037 free_dentry_tree(struct wim_dentry *root, struct blob_table *blob_table)
1038 {
1039         int (*f)(struct wim_dentry *, void *);
1040
1041         if (blob_table)
1042                 f = do_free_dentry_and_unref_blobs;
1043         else
1044                 f = do_free_dentry;
1045
1046         for_dentry_in_tree_depth(root, f, blob_table);
1047 }
1048
1049 /* Insert the @child dentry into the case sensitive index of the @dir directory.
1050  * Return NULL if successfully inserted, otherwise a pointer to the
1051  * already-inserted duplicate.  */
1052 static struct wim_dentry *
1053 dir_index_child(struct wim_inode *dir, struct wim_dentry *child)
1054 {
1055         struct avl_tree_node *duplicate;
1056
1057         duplicate = avl_tree_insert(&dir->i_children,
1058                                     &child->d_index_node,
1059                                     _avl_dentry_compare_names);
1060         if (!duplicate)
1061                 return NULL;
1062         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node);
1063 }
1064
1065 /* Insert the @child dentry into the case insensitive index of the @dir
1066  * directory.  Return NULL if successfully inserted, otherwise a pointer to the
1067  * already-inserted duplicate.  */
1068 static struct wim_dentry *
1069 dir_index_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1070 {
1071         struct avl_tree_node *duplicate;
1072
1073         duplicate = avl_tree_insert(&dir->i_children_ci,
1074                                     &child->d_index_node_ci,
1075                                     _avl_dentry_compare_names_ci);
1076         if (!duplicate)
1077                 return NULL;
1078         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node_ci);
1079 }
1080
1081 /* Remove the specified dentry from its directory's case-sensitive index.  */
1082 static void
1083 dir_unindex_child(struct wim_inode *dir, struct wim_dentry *child)
1084 {
1085         avl_tree_remove(&dir->i_children, &child->d_index_node);
1086 }
1087
1088 /* Remove the specified dentry from its directory's case-insensitive index.  */
1089 static void
1090 dir_unindex_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1091 {
1092         avl_tree_remove(&dir->i_children_ci, &child->d_index_node_ci);
1093 }
1094
1095 /* Return true iff the specified dentry is in its parent directory's
1096  * case-insensitive index.  */
1097 static bool
1098 dentry_in_ci_index(const struct wim_dentry *dentry)
1099 {
1100         return !avl_tree_node_is_unlinked(&dentry->d_index_node_ci);
1101 }
1102
1103 /*
1104  * Link a dentry into the tree.
1105  *
1106  * @parent:
1107  *      The dentry that will be the parent of @child.  It must name a directory.
1108  *
1109  * @child:
1110  *      The dentry to link.  It must be currently unlinked.
1111  *
1112  * Returns NULL if successful.  If @parent already contains a dentry with the
1113  * same case-sensitive name as @child, returns a pointer to this duplicate
1114  * dentry.
1115  */
1116 struct wim_dentry *
1117 dentry_add_child(struct wim_dentry *parent, struct wim_dentry *child)
1118 {
1119         struct wim_dentry *duplicate;
1120         struct wim_inode *dir;
1121
1122         wimlib_assert(parent != child);
1123
1124         dir = parent->d_inode;
1125
1126         wimlib_assert(inode_is_directory(dir));
1127
1128         duplicate = dir_index_child(dir, child);
1129         if (duplicate)
1130                 return duplicate;
1131
1132         duplicate = dir_index_child_ci(dir, child);
1133         if (duplicate) {
1134                 list_add(&child->d_ci_conflict_list, &duplicate->d_ci_conflict_list);
1135                 avl_tree_node_set_unlinked(&child->d_index_node_ci);
1136         } else {
1137                 INIT_LIST_HEAD(&child->d_ci_conflict_list);
1138         }
1139         child->d_parent = parent;
1140         return NULL;
1141 }
1142
1143 /* Unlink a dentry from the tree.  */
1144 void
1145 unlink_dentry(struct wim_dentry *dentry)
1146 {
1147         struct wim_inode *dir;
1148
1149         /* Do nothing if the dentry is root or it's already unlinked.  Not
1150          * actually necessary based on the current callers, but we do the check
1151          * here to be safe.  */
1152         if (unlikely(dentry->d_parent == dentry))
1153                 return;
1154
1155         dir = dentry->d_parent->d_inode;
1156
1157         dir_unindex_child(dir, dentry);
1158
1159         if (dentry_in_ci_index(dentry)) {
1160
1161                 dir_unindex_child_ci(dir, dentry);
1162
1163                 if (!list_empty(&dentry->d_ci_conflict_list)) {
1164                         /* Make a different case-insensitively-the-same dentry
1165                          * be the "representative" in the search index.  */
1166                         struct list_head *next;
1167                         struct wim_dentry *other;
1168                         struct wim_dentry *existing;
1169
1170                         next = dentry->d_ci_conflict_list.next;
1171                         other = list_entry(next, struct wim_dentry, d_ci_conflict_list);
1172                         existing = dir_index_child_ci(dir, other);
1173                         wimlib_assert(existing == NULL);
1174                 }
1175         }
1176         list_del(&dentry->d_ci_conflict_list);
1177
1178         /* Not actually necessary, but to be safe don't retain the now-obsolete
1179          * parent pointer.  */
1180         dentry->d_parent = dentry;
1181 }
1182
1183 static int
1184 read_extra_data(const u8 *p, const u8 *end, struct wim_inode *inode)
1185 {
1186         while (((uintptr_t)p & 7) && p < end)
1187                 p++;
1188
1189         if (unlikely(p < end)) {
1190                 inode->i_extra = memdup(p, end - p);
1191                 if (!inode->i_extra)
1192                         return WIMLIB_ERR_NOMEM;
1193                 inode->i_extra_size = end - p;
1194         }
1195         return 0;
1196 }
1197
1198 /*
1199  * Set the type of each stream for an encrypted file.
1200  *
1201  * All data streams of the encrypted file should have been packed into a single
1202  * stream in the format provided by ReadEncryptedFileRaw() on Windows.  We
1203  * assign this stream type STREAM_TYPE_EFSRPC_RAW_DATA.
1204  *
1205  * Encrypted files can't have a reparse point stream.  In the on-disk NTFS
1206  * format they can, but as far as I know the reparse point stream of an
1207  * encrypted file can't be stored in the WIM format in a way that's compatible
1208  * with WIMGAPI, nor is there even any way for it to be read or written on
1209  * Windows when the process does not have access to the file encryption key.
1210  */
1211 static void
1212 assign_stream_types_encrypted(struct wim_inode *inode)
1213 {
1214         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1215                 struct wim_inode_stream *strm = &inode->i_streams[i];
1216                 if (!stream_is_named(strm) && !is_zero_hash(strm->_stream_hash))
1217                 {
1218                         strm->stream_type = STREAM_TYPE_EFSRPC_RAW_DATA;
1219                         return;
1220                 }
1221         }
1222 }
1223
1224 /*
1225  * Set the type of each stream for an unencrypted file.
1226  *
1227  * There will be an unnamed data stream, a reparse point stream, or both an
1228  * unnamed data stream and a reparse point stream.  In addition, there may be
1229  * named data streams.
1230  */
1231 static void
1232 assign_stream_types_unencrypted(struct wim_inode *inode)
1233 {
1234         bool found_reparse_point_stream = false;
1235         bool found_unnamed_data_stream = false;
1236         struct wim_inode_stream *unnamed_stream_with_zero_hash = NULL;
1237
1238         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1239                 struct wim_inode_stream *strm = &inode->i_streams[i];
1240
1241                 if (stream_is_named(strm)) {
1242                         /* Named data stream  */
1243                         strm->stream_type = STREAM_TYPE_DATA;
1244                 } else if (!is_zero_hash(strm->_stream_hash)) {
1245                         if ((inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1246                             !found_reparse_point_stream) {
1247                                 found_reparse_point_stream = true;
1248                                 strm->stream_type = STREAM_TYPE_REPARSE_POINT;
1249                         } else if (!found_unnamed_data_stream) {
1250                                 found_unnamed_data_stream = true;
1251                                 strm->stream_type = STREAM_TYPE_DATA;
1252                         }
1253                 } else {
1254                         /* If no stream name is specified and the hash is zero,
1255                          * then remember this stream for later so that we can
1256                          * assign it to the unnamed data stream if we don't find
1257                          * a better candidate.  */
1258                         unnamed_stream_with_zero_hash = strm;
1259                 }
1260         }
1261
1262         if (!found_unnamed_data_stream && unnamed_stream_with_zero_hash != NULL)
1263                 unnamed_stream_with_zero_hash->stream_type = STREAM_TYPE_DATA;
1264 }
1265
1266 /*
1267  * Read and interpret the collection of streams for the specified inode.
1268  */
1269 static int
1270 setup_inode_streams(const u8 *p, const u8 *end, struct wim_inode *inode,
1271                     unsigned num_extra_streams, const u8 *default_hash,
1272                     u64 *offset_p)
1273 {
1274         const u8 *orig_p = p;
1275
1276         inode->i_num_streams = 1 + num_extra_streams;
1277
1278         if (unlikely(inode->i_num_streams > ARRAY_LEN(inode->i_embedded_streams))) {
1279                 inode->i_streams = CALLOC(inode->i_num_streams,
1280                                           sizeof(inode->i_streams[0]));
1281                 if (!inode->i_streams)
1282                         return WIMLIB_ERR_NOMEM;
1283         }
1284
1285         /* Use the default hash field for the first stream  */
1286         inode->i_streams[0].stream_name = (utf16lechar *)NO_STREAM_NAME;
1287         copy_hash(inode->i_streams[0]._stream_hash, default_hash);
1288         inode->i_streams[0].stream_type = STREAM_TYPE_UNKNOWN;
1289         inode->i_streams[0].stream_id = 0;
1290
1291         /* Read the extra stream entries  */
1292         for (unsigned i = 1; i < inode->i_num_streams; i++) {
1293                 struct wim_inode_stream *strm;
1294                 const struct wim_extra_stream_entry_on_disk *disk_strm;
1295                 u64 length;
1296                 u16 name_nbytes;
1297
1298                 strm = &inode->i_streams[i];
1299
1300                 strm->stream_id = i;
1301
1302                 /* Do we have at least the size of the fixed-length data we know
1303                  * need?  */
1304                 if ((end - p) < sizeof(struct wim_extra_stream_entry_on_disk))
1305                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1306
1307                 disk_strm = (const struct wim_extra_stream_entry_on_disk *)p;
1308
1309                 /* Read the length field  */
1310                 length = ALIGN(le64_to_cpu(disk_strm->length), 8);
1311
1312                 /* Make sure the length field is neither so small it doesn't
1313                  * include all the fixed-length data nor so large it overflows
1314                  * the metadata resource buffer. */
1315                 if (length < sizeof(struct wim_extra_stream_entry_on_disk) ||
1316                     length > (end - p))
1317                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1318
1319                 /* Read the rest of the fixed-length data. */
1320
1321                 copy_hash(strm->_stream_hash, disk_strm->hash);
1322                 name_nbytes = le16_to_cpu(disk_strm->name_nbytes);
1323
1324                 /* If stream_name_nbytes != 0, the stream is named.  */
1325                 if (name_nbytes != 0) {
1326                         /* The name is encoded in UTF16-LE, which uses 2-byte
1327                          * coding units, so the length of the name had better be
1328                          * an even number of bytes.  */
1329                         if (name_nbytes & 1)
1330                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1331
1332                         /* Add the length of the stream name to get the length
1333                          * we actually need to read.  Make sure this isn't more
1334                          * than the specified length of the entry.  */
1335                         if (sizeof(struct wim_extra_stream_entry_on_disk) +
1336                             name_nbytes > length)
1337                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1338
1339                         strm->stream_name = utf16le_dupz(disk_strm->name,
1340                                                          name_nbytes);
1341                         if (!strm->stream_name)
1342                                 return WIMLIB_ERR_NOMEM;
1343                 } else {
1344                         strm->stream_name = (utf16lechar *)NO_STREAM_NAME;
1345                 }
1346
1347                 strm->stream_type = STREAM_TYPE_UNKNOWN;
1348
1349                 p += length;
1350         }
1351
1352         inode->i_next_stream_id = inode->i_num_streams;
1353
1354         /* Now, assign a type to each stream.  Unfortunately this requires
1355          * various hacks because stream types aren't explicitly provided in the
1356          * WIM on-disk format.  */
1357
1358         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
1359                 assign_stream_types_encrypted(inode);
1360         else
1361                 assign_stream_types_unencrypted(inode);
1362
1363         *offset_p += p - orig_p;
1364         return 0;
1365 }
1366
1367 /* Read a dentry, including all extra stream entries that follow it, from an
1368  * uncompressed metadata resource buffer.  */
1369 static int
1370 read_dentry(const u8 * restrict buf, size_t buf_len,
1371             u64 *offset_p, struct wim_dentry **dentry_ret)
1372 {
1373         u64 offset = *offset_p;
1374         u64 length;
1375         const u8 *p;
1376         const struct wim_dentry_on_disk *disk_dentry;
1377         struct wim_dentry *dentry;
1378         struct wim_inode *inode;
1379         u16 short_name_nbytes;
1380         u16 name_nbytes;
1381         u64 calculated_size;
1382         int ret;
1383
1384         BUILD_BUG_ON(sizeof(struct wim_dentry_on_disk) != WIM_DENTRY_DISK_SIZE);
1385
1386         /* Before reading the whole dentry, we need to read just the length.
1387          * This is because a dentry of length 8 (that is, just the length field)
1388          * terminates the list of sibling directory entries. */
1389
1390         /* Check for buffer overrun.  */
1391         if (unlikely(offset + sizeof(u64) > buf_len ||
1392                      offset + sizeof(u64) < offset))
1393                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1394
1395         /* Get pointer to the dentry data.  */
1396         p = &buf[offset];
1397         disk_dentry = (const struct wim_dentry_on_disk*)p;
1398
1399         /* Get dentry length.  */
1400         length = ALIGN(le64_to_cpu(disk_dentry->length), 8);
1401
1402         /* Check for end-of-directory.  */
1403         if (length <= 8) {
1404                 *dentry_ret = NULL;
1405                 return 0;
1406         }
1407
1408         /* Validate dentry length.  */
1409         if (unlikely(length < sizeof(struct wim_dentry_on_disk)))
1410                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1411
1412         /* Check for buffer overrun.  */
1413         if (unlikely(offset + length > buf_len ||
1414                      offset + length < offset))
1415                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1416
1417         /* Allocate new dentry structure, along with a preliminary inode.  */
1418         ret = new_dentry_with_new_inode(NULL, false, &dentry);
1419         if (ret)
1420                 return ret;
1421
1422         inode = dentry->d_inode;
1423
1424         /* Read more fields: some into the dentry, and some into the inode.  */
1425         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1426         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1427         dentry->d_subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1428         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1429         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1430         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1431         inode->i_unknown_0x54 = le32_to_cpu(disk_dentry->unknown_0x54);
1432
1433         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1434                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
1435                 inode->i_rp_reserved = le16_to_cpu(disk_dentry->reparse.rp_reserved);
1436                 inode->i_rp_flags = le16_to_cpu(disk_dentry->reparse.rp_flags);
1437                 /* Leave inode->i_ino at 0.  Note: this means that WIM cannot
1438                  * represent multiple hard links to a reparse point file.  */
1439         } else {
1440                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
1441         }
1442
1443         /* Now onto reading the names.  There are two of them: the (long) file
1444          * name, and the short name.  */
1445
1446         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
1447         name_nbytes = le16_to_cpu(disk_dentry->name_nbytes);
1448
1449         if (unlikely((short_name_nbytes & 1) | (name_nbytes & 1))) {
1450                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1451                 goto err_free_dentry;
1452         }
1453
1454         /* We now know the length of the file name and short name.  Make sure
1455          * the length of the dentry is large enough to actually hold them.  */
1456         calculated_size = dentry_min_len_with_names(name_nbytes,
1457                                                     short_name_nbytes);
1458
1459         if (unlikely(length < calculated_size)) {
1460                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1461                 goto err_free_dentry;
1462         }
1463
1464         /* Advance p to point past the base dentry, to the first name.  */
1465         p += sizeof(struct wim_dentry_on_disk);
1466
1467         /* Read the filename if present.  Note: if the filename is empty, there
1468          * is no null terminator following it.  */
1469         if (name_nbytes) {
1470                 dentry->d_name = utf16le_dupz(p, name_nbytes);
1471                 if (unlikely(!dentry->d_name)) {
1472                         ret = WIMLIB_ERR_NOMEM;
1473                         goto err_free_dentry;
1474                 }
1475                 dentry->d_name_nbytes = name_nbytes;
1476                 p += (u32)name_nbytes + 2;
1477         }
1478
1479         /* Read the short filename if present.  Note: if there is no short
1480          * filename, there is no null terminator following it. */
1481         if (short_name_nbytes) {
1482                 dentry->d_short_name = utf16le_dupz(p, short_name_nbytes);
1483                 if (unlikely(!dentry->d_short_name)) {
1484                         ret = WIMLIB_ERR_NOMEM;
1485                         goto err_free_dentry;
1486                 }
1487                 dentry->d_short_name_nbytes = short_name_nbytes;
1488                 p += (u32)short_name_nbytes + 2;
1489         }
1490
1491         /* Read extra data at end of dentry (but before extra stream entries).
1492          * This may contain tagged metadata items.  */
1493         ret = read_extra_data(p, &buf[offset + length], inode);
1494         if (ret)
1495                 goto err_free_dentry;
1496
1497         offset += length;
1498
1499         /* Set up the inode's collection of streams.  */
1500         ret = setup_inode_streams(&buf[offset],
1501                                   &buf[buf_len],
1502                                   inode,
1503                                   le16_to_cpu(disk_dentry->num_extra_streams),
1504                                   disk_dentry->default_hash,
1505                                   &offset);
1506         if (ret)
1507                 goto err_free_dentry;
1508
1509         *offset_p = offset;  /* Sets offset of next dentry in directory  */
1510         *dentry_ret = dentry;
1511         return 0;
1512
1513 err_free_dentry:
1514         free_dentry(dentry);
1515         return ret;
1516 }
1517
1518 /* Is the dentry named "." or ".." ?  */
1519 static bool
1520 dentry_is_dot_or_dotdot(const struct wim_dentry *dentry)
1521 {
1522         if (dentry->d_name_nbytes <= 4) {
1523                 if (dentry->d_name_nbytes == 4) {
1524                         if (dentry->d_name[0] == cpu_to_le16('.') &&
1525                             dentry->d_name[1] == cpu_to_le16('.'))
1526                                 return true;
1527                 } else if (dentry->d_name_nbytes == 2) {
1528                         if (dentry->d_name[0] == cpu_to_le16('.'))
1529                                 return true;
1530                 }
1531         }
1532         return false;
1533 }
1534
1535 static int
1536 read_dentry_tree_recursive(const u8 * restrict buf, size_t buf_len,
1537                            struct wim_dentry * restrict dir)
1538 {
1539         u64 cur_offset = dir->d_subdir_offset;
1540
1541         /* Check for cyclic directory structure, which would cause infinite
1542          * recursion if not handled.  */
1543         for (struct wim_dentry *d = dir->d_parent;
1544              !dentry_is_root(d); d = d->d_parent)
1545         {
1546                 if (unlikely(d->d_subdir_offset == cur_offset)) {
1547                         ERROR("Cyclic directory structure detected: children "
1548                               "of \"%"TS"\" coincide with children of \"%"TS"\"",
1549                               dentry_full_path(dir), dentry_full_path(d));
1550                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1551                 }
1552         }
1553
1554         for (;;) {
1555                 struct wim_dentry *child;
1556                 struct wim_dentry *duplicate;
1557                 int ret;
1558
1559                 /* Read next child of @dir.  */
1560                 ret = read_dentry(buf, buf_len, &cur_offset, &child);
1561                 if (ret)
1562                         return ret;
1563
1564                 /* Check for end of directory.  */
1565                 if (child == NULL)
1566                         return 0;
1567
1568                 /* All dentries except the root should be named.  */
1569                 if (unlikely(!dentry_has_long_name(child))) {
1570                         WARNING("Ignoring unnamed dentry in "
1571                                 "directory \"%"TS"\"", dentry_full_path(dir));
1572                         free_dentry(child);
1573                         continue;
1574                 }
1575
1576                 /* Don't allow files named "." or "..".  */
1577                 if (unlikely(dentry_is_dot_or_dotdot(child))) {
1578                         WARNING("Ignoring file named \".\" or \"..\"; "
1579                                 "potentially malicious archive!!!");
1580                         free_dentry(child);
1581                         continue;
1582                 }
1583
1584                 /* Link the child into the directory.  */
1585                 duplicate = dentry_add_child(dir, child);
1586                 if (unlikely(duplicate)) {
1587                         /* We already found a dentry with this same
1588                          * case-sensitive long name.  Only keep the first one.
1589                          */
1590                         WARNING("Ignoring duplicate file \"%"TS"\" "
1591                                 "(the WIM image already contains a file "
1592                                 "at that path with the exact same name)",
1593                                 dentry_full_path(duplicate));
1594                         free_dentry(child);
1595                         continue;
1596                 }
1597
1598                 /* If this child is a directory that itself has children, call
1599                  * this procedure recursively.  */
1600                 if (child->d_subdir_offset != 0) {
1601                         if (likely(dentry_is_directory(child))) {
1602                                 ret = read_dentry_tree_recursive(buf,
1603                                                                  buf_len,
1604                                                                  child);
1605                                 if (ret)
1606                                         return ret;
1607                         } else {
1608                                 WARNING("Ignoring children of "
1609                                         "non-directory file \"%"TS"\"",
1610                                         dentry_full_path(child));
1611                         }
1612                 }
1613         }
1614 }
1615
1616 /*
1617  * Read a tree of dentries from a WIM metadata resource.
1618  *
1619  * @buf:
1620  *      Buffer containing an uncompressed WIM metadata resource.
1621  *
1622  * @buf_len:
1623  *      Length of the uncompressed metadata resource, in bytes.
1624  *
1625  * @root_offset
1626  *      Offset in the metadata resource of the root of the dentry tree.
1627  *
1628  * @root_ret:
1629  *      On success, either NULL or a pointer to the root dentry is written to
1630  *      this location.  The former case only occurs in the unexpected case that
1631  *      the tree began with an end-of-directory entry.
1632  *
1633  * Return values:
1634  *      WIMLIB_ERR_SUCCESS (0)
1635  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1636  *      WIMLIB_ERR_NOMEM
1637  */
1638 int
1639 read_dentry_tree(const u8 *buf, size_t buf_len,
1640                  u64 root_offset, struct wim_dentry **root_ret)
1641 {
1642         int ret;
1643         struct wim_dentry *root;
1644
1645         ret = read_dentry(buf, buf_len, &root_offset, &root);
1646         if (ret)
1647                 return ret;
1648
1649         if (likely(root != NULL)) {
1650                 if (unlikely(dentry_has_long_name(root) ||
1651                              dentry_has_short_name(root)))
1652                 {
1653                         WARNING("The root directory has a nonempty name; "
1654                                 "removing it.");
1655                         dentry_set_name(root, NULL);
1656                 }
1657
1658                 if (unlikely(!dentry_is_directory(root))) {
1659                         ERROR("The root of the WIM image is not a directory!");
1660                         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1661                         goto err_free_dentry_tree;
1662                 }
1663
1664                 if (likely(root->d_subdir_offset != 0)) {
1665                         ret = read_dentry_tree_recursive(buf, buf_len, root);
1666                         if (ret)
1667                                 goto err_free_dentry_tree;
1668                 }
1669         } else {
1670                 WARNING("The metadata resource has no directory entries; "
1671                         "treating as an empty image.");
1672         }
1673         *root_ret = root;
1674         return 0;
1675
1676 err_free_dentry_tree:
1677         free_dentry_tree(root, NULL);
1678         return ret;
1679 }
1680
1681 static u8 *
1682 write_extra_stream_entry(u8 * restrict p, const utf16lechar * restrict name,
1683                          const u8 * restrict hash)
1684 {
1685         struct wim_extra_stream_entry_on_disk *disk_strm =
1686                         (struct wim_extra_stream_entry_on_disk *)p;
1687         u8 *orig_p = p;
1688         size_t name_nbytes;
1689
1690         if (name == NO_STREAM_NAME)
1691                 name_nbytes = 0;
1692         else
1693                 name_nbytes = utf16le_len_bytes(name);
1694
1695         disk_strm->reserved = 0;
1696         copy_hash(disk_strm->hash, hash);
1697         disk_strm->name_nbytes = cpu_to_le16(name_nbytes);
1698         p += sizeof(struct wim_extra_stream_entry_on_disk);
1699         if (name_nbytes != 0)
1700                 p = mempcpy(p, name, name_nbytes + 2);
1701         /* Align to 8-byte boundary */
1702         while ((uintptr_t)p & 7)
1703                 *p++ = 0;
1704         disk_strm->length = cpu_to_le64(p - orig_p);
1705         return p;
1706 }
1707
1708 /*
1709  * Write a WIM dentry to an output buffer.
1710  *
1711  * This includes any extra stream entries that may follow the dentry itself.
1712  *
1713  * @dentry:
1714  *      The dentry to write.
1715  *
1716  * @p:
1717  *      The memory location to which to write the data.
1718  *
1719  * Returns a pointer to the byte following the last written.
1720  */
1721 static u8 *
1722 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
1723 {
1724         const struct wim_inode *inode;
1725         struct wim_dentry_on_disk *disk_dentry;
1726         const u8 *orig_p;
1727
1728         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
1729         orig_p = p;
1730
1731         inode = dentry->d_inode;
1732         disk_dentry = (struct wim_dentry_on_disk*)p;
1733
1734         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
1735         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
1736         disk_dentry->subdir_offset = cpu_to_le64(dentry->d_subdir_offset);
1737
1738         disk_dentry->unused_1 = cpu_to_le64(0);
1739         disk_dentry->unused_2 = cpu_to_le64(0);
1740
1741         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
1742         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
1743         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
1744         disk_dentry->unknown_0x54 = cpu_to_le32(inode->i_unknown_0x54);
1745         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1746                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
1747                 disk_dentry->reparse.rp_reserved = cpu_to_le16(inode->i_rp_reserved);
1748                 disk_dentry->reparse.rp_flags = cpu_to_le16(inode->i_rp_flags);
1749         } else {
1750                 disk_dentry->nonreparse.hard_link_group_id =
1751                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
1752         }
1753
1754         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->d_short_name_nbytes);
1755         disk_dentry->name_nbytes = cpu_to_le16(dentry->d_name_nbytes);
1756         p += sizeof(struct wim_dentry_on_disk);
1757
1758         wimlib_assert(dentry_is_root(dentry) != dentry_has_long_name(dentry));
1759
1760         if (dentry_has_long_name(dentry))
1761                 p = mempcpy(p, dentry->d_name, (u32)dentry->d_name_nbytes + 2);
1762
1763         if (dentry_has_short_name(dentry))
1764                 p = mempcpy(p, dentry->d_short_name, (u32)dentry->d_short_name_nbytes + 2);
1765
1766         /* Align to 8-byte boundary */
1767         while ((uintptr_t)p & 7)
1768                 *p++ = 0;
1769
1770         if (inode->i_extra_size) {
1771                 /* Extra tagged items --- not usually present.  */
1772                 p = mempcpy(p, inode->i_extra, inode->i_extra_size);
1773
1774                 /* Align to 8-byte boundary */
1775                 while ((uintptr_t)p & 7)
1776                         *p++ = 0;
1777         }
1778
1779         disk_dentry->length = cpu_to_le64(p - orig_p);
1780
1781         /* Streams  */
1782
1783         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1784                 const struct wim_inode_stream *efs_strm;
1785                 const u8 *efs_hash;
1786
1787                 efs_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA);
1788                 efs_hash = efs_strm ? stream_hash(efs_strm) : zero_hash;
1789                 copy_hash(disk_dentry->default_hash, efs_hash);
1790                 disk_dentry->num_extra_streams = cpu_to_le16(0);
1791         } else {
1792                 /*
1793                  * Extra stream entries:
1794                  *
1795                  * - Use one extra stream entry for each named data stream
1796                  * - Use one extra stream entry for the unnamed data stream when there is either:
1797                  *      - a reparse point stream
1798                  *      - at least one named data stream (for Windows PE bug workaround)
1799                  * - Use one extra stream entry for the reparse point stream if there is one
1800                  */
1801                 bool have_named_data_stream = false;
1802                 bool have_reparse_point_stream = false;
1803                 const u8 *unnamed_data_stream_hash = zero_hash;
1804                 const u8 *reparse_point_hash;
1805                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1806                         const struct wim_inode_stream *strm = &inode->i_streams[i];
1807                         if (strm->stream_type == STREAM_TYPE_DATA) {
1808                                 if (stream_is_named(strm))
1809                                         have_named_data_stream = true;
1810                                 else
1811                                         unnamed_data_stream_hash = stream_hash(strm);
1812                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
1813                                 have_reparse_point_stream = true;
1814                                 reparse_point_hash = stream_hash(strm);
1815                         }
1816                 }
1817
1818                 if (unlikely(have_reparse_point_stream || have_named_data_stream)) {
1819
1820                         unsigned num_extra_streams = 0;
1821
1822                         copy_hash(disk_dentry->default_hash, zero_hash);
1823
1824                         if (have_reparse_point_stream) {
1825                                 p = write_extra_stream_entry(p, NO_STREAM_NAME,
1826                                                              reparse_point_hash);
1827                                 num_extra_streams++;
1828                         }
1829
1830                         p = write_extra_stream_entry(p, NO_STREAM_NAME,
1831                                                      unnamed_data_stream_hash);
1832                         num_extra_streams++;
1833
1834                         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1835                                 const struct wim_inode_stream *strm = &inode->i_streams[i];
1836                                 if (stream_is_named_data_stream(strm)) {
1837                                         p = write_extra_stream_entry(p, strm->stream_name,
1838                                                                      stream_hash(strm));
1839                                         num_extra_streams++;
1840                                 }
1841                         }
1842                         wimlib_assert(num_extra_streams <= 0xFFFF);
1843
1844                         disk_dentry->num_extra_streams = cpu_to_le16(num_extra_streams);
1845                 } else {
1846                         copy_hash(disk_dentry->default_hash, unnamed_data_stream_hash);
1847                         disk_dentry->num_extra_streams = cpu_to_le16(0);
1848                 }
1849         }
1850
1851         return p;
1852 }
1853
1854 static int
1855 write_dir_dentries(struct wim_dentry *dir, void *_pp)
1856 {
1857         if (dir->d_subdir_offset != 0) {
1858                 u8 **pp = _pp;
1859                 u8 *p = *pp;
1860                 struct wim_dentry *child;
1861
1862                 /* write child dentries */
1863                 for_dentry_child(child, dir)
1864                         p = write_dentry(child, p);
1865
1866                 /* write end of directory entry */
1867                 *(u64*)p = 0;
1868                 p += 8;
1869                 *pp = p;
1870         }
1871         return 0;
1872 }
1873
1874 /*
1875  * Write a directory tree to the metadata resource.
1876  *
1877  * @root:
1878  *      The root of a dentry tree on which calculate_subdir_offsets() has been
1879  *      called.  This cannot be NULL; if the dentry tree is empty, the caller is
1880  *      expected to first generate a dummy root directory.
1881  *
1882  * @p:
1883  *      Pointer to a buffer with enough space for the dentry tree.  This size
1884  *      must have been obtained by calculate_subdir_offsets().
1885  *
1886  * Returns a pointer to the byte following the last written.
1887  */
1888 u8 *
1889 write_dentry_tree(struct wim_dentry *root, u8 *p)
1890 {
1891         /* write root dentry and end-of-directory entry following it */
1892         p = write_dentry(root, p);
1893         *(u64*)p = 0;
1894         p += 8;
1895
1896         /* write the rest of the dentry tree */
1897         for_dentry_in_tree(root, write_dir_dentries, &p);
1898
1899         return p;
1900 }