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