]> wimlib.net Git - wimlib/blob - src/dentry.c
inode: move 'i_extra_size' to 'i_extra' buffer
[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         if (inode->i_extra)
362                 len += ALIGN(inode->i_extra->size, 8);
363
364         if (!(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
365                 /*
366                  * Extra stream entries:
367                  *
368                  * - Use one extra stream entry for each named data stream
369                  * - Use one extra stream entry for the unnamed data stream when there is either:
370                  *      - a reparse point stream
371                  *      - at least one named data stream (for Windows PE bug workaround)
372                  * - Use one extra stream entry for the reparse point stream if there is one
373                  */
374                 bool have_named_data_stream = false;
375                 bool have_reparse_point_stream = false;
376                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
377                         const struct wim_inode_stream *strm = &inode->i_streams[i];
378                         if (stream_is_named_data_stream(strm)) {
379                                 len += stream_out_total_length(strm);
380                                 have_named_data_stream = true;
381                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
382                                 wimlib_assert(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT);
383                                 have_reparse_point_stream = true;
384                         }
385                 }
386
387                 if (have_named_data_stream || have_reparse_point_stream) {
388                         if (have_reparse_point_stream)
389                                 len += ALIGN(sizeof(struct wim_extra_stream_entry_on_disk), 8);
390                         len += ALIGN(sizeof(struct wim_extra_stream_entry_on_disk), 8);
391                 }
392         }
393
394         return len;
395 }
396
397 /* Internal version of for_dentry_in_tree() that omits the NULL check  */
398 static int
399 do_for_dentry_in_tree(struct wim_dentry *dentry,
400                       int (*visitor)(struct wim_dentry *, void *), void *arg)
401 {
402         int ret;
403         struct wim_dentry *child;
404
405         ret = (*visitor)(dentry, arg);
406         if (unlikely(ret))
407                 return ret;
408
409         for_dentry_child(child, dentry) {
410                 ret = do_for_dentry_in_tree(child, visitor, arg);
411                 if (unlikely(ret))
412                         return ret;
413         }
414         return 0;
415 }
416
417 /* Internal version of for_dentry_in_tree_depth() that omits the NULL check  */
418 static int
419 do_for_dentry_in_tree_depth(struct wim_dentry *dentry,
420                             int (*visitor)(struct wim_dentry *, void *), void *arg)
421 {
422         int ret;
423         struct wim_dentry *child;
424
425         for_dentry_child_postorder(child, dentry) {
426                 ret = do_for_dentry_in_tree_depth(child, visitor, arg);
427                 if (unlikely(ret))
428                         return ret;
429         }
430         return unlikely((*visitor)(dentry, arg));
431 }
432
433 /*
434  * Call a function on all dentries in a tree.
435  *
436  * @arg will be passed as the second argument to each invocation of @visitor.
437  *
438  * This function does a pre-order traversal --- that is, a parent will be
439  * visited before its children.  It also will visit siblings in order of
440  * case-sensitive filename.  Equivalently, this function visits the entire tree
441  * in the case-sensitive lexicographic order of the full paths.
442  *
443  * It is safe to pass NULL for @root, which means that the dentry tree is empty.
444  * In this case, this function does nothing.
445  *
446  * @visitor must not modify the structure of the dentry tree during the
447  * traversal.
448  *
449  * The return value will be 0 if all calls to @visitor returned 0.  Otherwise,
450  * the return value will be the first nonzero value returned by @visitor.
451  */
452 int
453 for_dentry_in_tree(struct wim_dentry *root,
454                    int (*visitor)(struct wim_dentry *, void *), void *arg)
455 {
456         if (unlikely(!root))
457                 return 0;
458         return do_for_dentry_in_tree(root, visitor, arg);
459 }
460
461 /* Like for_dentry_in_tree(), but do a depth-first traversal of the dentry tree.
462  * That is, the visitor function will be called on a dentry's children before
463  * itself.  It will be safe to free a dentry when visiting it.  */
464 static int
465 for_dentry_in_tree_depth(struct wim_dentry *root,
466                          int (*visitor)(struct wim_dentry *, void *), void *arg)
467 {
468         if (unlikely(!root))
469                 return 0;
470         return do_for_dentry_in_tree_depth(root, visitor, arg);
471 }
472
473 /*
474  * Calculate the full path to @dentry within the WIM image, if not already done.
475  *
476  * The full name will be saved in the cached value 'dentry->d_full_path'.
477  *
478  * Whenever possible, use dentry_full_path() instead of calling this and
479  * accessing d_full_path directly.
480  *
481  * Returns 0 or an error code resulting from a failed string conversion.
482  */
483 int
484 calculate_dentry_full_path(struct wim_dentry *dentry)
485 {
486         size_t ulen;
487         size_t dummy;
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                 memcpy(p, d->d_name, d->d_name_nbytes);
508                 *--p = cpu_to_le16(WIM_PATH_SEPARATOR);
509                 d = d->d_parent;  /* assumes d == d->d_parent for root  */
510         } while (!dentry_is_root(d));
511
512         wimlib_assert(p == ubuf);
513
514         return utf16le_to_tstr(ubuf, ulen * sizeof(utf16lechar),
515                                &dentry->d_full_path, &dummy);
516 }
517
518 /*
519  * Return the full path to the @dentry within the WIM image, or NULL if the full
520  * path could not be determined due to a string conversion error.
521  *
522  * The returned memory will be cached in the dentry, so the caller is not
523  * responsible for freeing it.
524  */
525 tchar *
526 dentry_full_path(struct wim_dentry *dentry)
527 {
528         calculate_dentry_full_path(dentry);
529         return dentry->d_full_path;
530 }
531
532 static int
533 dentry_calculate_subdir_offset(struct wim_dentry *dentry, void *_subdir_offset_p)
534 {
535         if (dentry_is_directory(dentry)) {
536                 u64 *subdir_offset_p = _subdir_offset_p;
537                 struct wim_dentry *child;
538
539                 /* Set offset of directory's child dentries  */
540                 dentry->d_subdir_offset = *subdir_offset_p;
541
542                 /* Account for child dentries  */
543                 for_dentry_child(child, dentry)
544                         *subdir_offset_p += dentry_out_total_length(child);
545
546                 /* Account for end-of-directory entry  */
547                 *subdir_offset_p += 8;
548         } else {
549                 /* Not a directory; set the subdir offset to 0  */
550                 dentry->d_subdir_offset = 0;
551         }
552         return 0;
553 }
554
555 /*
556  * Calculate the subdir offsets for a dentry tree, in preparation of writing
557  * that dentry tree to a metadata resource.
558  *
559  * The subdir offset of each dentry is the offset in the uncompressed metadata
560  * resource at which its child dentries begin, or 0 if that dentry has no
561  * children.
562  *
563  * The caller must initialize *subdir_offset_p to the first subdir offset that
564  * is available to use after the root dentry is written.
565  *
566  * When this function returns, *subdir_offset_p will have been advanced past the
567  * size needed for the dentry tree within the uncompressed metadata resource.
568  */
569 void
570 calculate_subdir_offsets(struct wim_dentry *root, u64 *subdir_offset_p)
571 {
572         for_dentry_in_tree(root, dentry_calculate_subdir_offset, subdir_offset_p);
573 }
574
575 /* Compare the UTF-16LE long filenames of two dentries case insensitively.  */
576 static int
577 dentry_compare_names_case_insensitive(const struct wim_dentry *d1,
578                                       const struct wim_dentry *d2)
579 {
580         return cmp_utf16le_strings(d1->d_name,
581                                    d1->d_name_nbytes / 2,
582                                    d2->d_name,
583                                    d2->d_name_nbytes / 2,
584                                    true);
585 }
586
587 /* Compare the UTF-16LE long filenames of two dentries case sensitively.  */
588 static int
589 dentry_compare_names_case_sensitive(const struct wim_dentry *d1,
590                                     const struct wim_dentry *d2)
591 {
592         return cmp_utf16le_strings(d1->d_name,
593                                    d1->d_name_nbytes / 2,
594                                    d2->d_name,
595                                    d2->d_name_nbytes / 2,
596                                    false);
597 }
598
599 static int
600 _avl_dentry_compare_names_ci(const struct avl_tree_node *n1,
601                              const struct avl_tree_node *n2)
602 {
603         const struct wim_dentry *d1, *d2;
604
605         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node_ci);
606         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node_ci);
607         return dentry_compare_names_case_insensitive(d1, d2);
608 }
609
610 static int
611 _avl_dentry_compare_names(const struct avl_tree_node *n1,
612                           const struct avl_tree_node *n2)
613 {
614         const struct wim_dentry *d1, *d2;
615
616         d1 = avl_tree_entry(n1, struct wim_dentry, d_index_node);
617         d2 = avl_tree_entry(n2, struct wim_dentry, d_index_node);
618         return dentry_compare_names_case_sensitive(d1, d2);
619 }
620
621 /* Default case sensitivity behavior for searches with
622  * WIMLIB_CASE_PLATFORM_DEFAULT specified.  This can be modified by passing
623  * WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE or
624  * WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE to wimlib_global_init().  */
625 bool default_ignore_case =
626 #ifdef __WIN32__
627         true
628 #else
629         false
630 #endif
631 ;
632
633 /* Case-sensitive dentry lookup.  Only @d_name and @d_name_nbytes of @dummy must
634  * be valid.  */
635 static struct wim_dentry *
636 dir_lookup(const struct wim_inode *dir, const struct wim_dentry *dummy)
637 {
638         struct avl_tree_node *node;
639
640         node = avl_tree_lookup_node(dir->i_children,
641                                     &dummy->d_index_node,
642                                     _avl_dentry_compare_names);
643         if (!node)
644                 return NULL;
645         return avl_tree_entry(node, struct wim_dentry, d_index_node);
646 }
647
648 /* Case-insensitive dentry lookup.  Only @d_name and @d_name_nbytes of @dummy
649  * must be valid.  */
650 static struct wim_dentry *
651 dir_lookup_ci(const struct wim_inode *dir, const struct wim_dentry *dummy)
652 {
653         struct avl_tree_node *node;
654
655         node = avl_tree_lookup_node(dir->i_children_ci,
656                                     &dummy->d_index_node_ci,
657                                     _avl_dentry_compare_names_ci);
658         if (!node)
659                 return NULL;
660         return avl_tree_entry(node, struct wim_dentry, d_index_node_ci);
661 }
662
663 /* Given a UTF-16LE filename and a directory, look up the dentry for the file.
664  * Return it if found, otherwise NULL.  This has configurable case sensitivity,
665  * and @name need not be null-terminated.  */
666 struct wim_dentry *
667 get_dentry_child_with_utf16le_name(const struct wim_dentry *dentry,
668                                    const utf16lechar *name,
669                                    size_t name_nbytes,
670                                    CASE_SENSITIVITY_TYPE case_type)
671 {
672         const struct wim_inode *dir = dentry->d_inode;
673         bool ignore_case = will_ignore_case(case_type);
674         struct wim_dentry dummy;
675         struct wim_dentry *child;
676
677         dummy.d_name = (utf16lechar*)name;
678         dummy.d_name_nbytes = name_nbytes;
679
680         if (!ignore_case)
681                 /* Case-sensitive lookup.  */
682                 return dir_lookup(dir, &dummy);
683
684         /* Case-insensitive lookup.  */
685
686         child = dir_lookup_ci(dir, &dummy);
687         if (!child)
688                 return NULL;
689
690         if (likely(list_empty(&child->d_ci_conflict_list)))
691                 /* Only one dentry has this case-insensitive name; return it */
692                 return child;
693
694         /* Multiple dentries have the same case-insensitive name.  Choose the
695          * dentry with the same case-sensitive name, if one exists; otherwise
696          * print a warning and choose one of the possible dentries arbitrarily.
697          */
698         struct wim_dentry *alt = child;
699         size_t num_alts = 0;
700
701         do {
702                 num_alts++;
703                 if (!dentry_compare_names_case_sensitive(&dummy, alt))
704                         return alt;
705                 alt = list_entry(alt->d_ci_conflict_list.next,
706                                  struct wim_dentry, d_ci_conflict_list);
707         } while (alt != child);
708
709         WARNING("Result of case-insensitive lookup is ambiguous\n"
710                 "          (returning \"%"TS"\" of %zu "
711                 "possible files, including \"%"TS"\")",
712                 dentry_full_path(child),
713                 num_alts,
714                 dentry_full_path(list_entry(child->d_ci_conflict_list.next,
715                                             struct wim_dentry,
716                                             d_ci_conflict_list)));
717         return child;
718 }
719
720 /* Given a 'tchar' filename and a directory, look up the dentry for the file.
721  * If the filename was successfully converted to UTF-16LE and the dentry was
722  * found, return it; otherwise return NULL.  This has configurable case
723  * sensitivity.  */
724 struct wim_dentry *
725 get_dentry_child_with_name(const struct wim_dentry *dentry, const tchar *name,
726                            CASE_SENSITIVITY_TYPE case_type)
727 {
728         int ret;
729         const utf16lechar *name_utf16le;
730         size_t name_utf16le_nbytes;
731         struct wim_dentry *child;
732
733         ret = tstr_get_utf16le_and_len(name, &name_utf16le,
734                                        &name_utf16le_nbytes);
735         if (ret)
736                 return NULL;
737
738         child = get_dentry_child_with_utf16le_name(dentry,
739                                                    name_utf16le,
740                                                    name_utf16le_nbytes,
741                                                    case_type);
742         tstr_put_utf16le(name_utf16le);
743         return child;
744 }
745
746 /* This is the UTF-16LE version of get_dentry(), currently private to this file
747  * because no one needs it besides get_dentry().  */
748 static struct wim_dentry *
749 get_dentry_utf16le(WIMStruct *wim, const utf16lechar *path,
750                    CASE_SENSITIVITY_TYPE case_type)
751 {
752         struct wim_dentry *cur_dentry;
753         const utf16lechar *name_start, *name_end;
754
755         /* Start with the root directory of the image.  Note: this will be NULL
756          * if an image has been added directly with wimlib_add_empty_image() but
757          * no files have been added yet; in that case we fail with ENOENT.  */
758         cur_dentry = wim_get_current_root_dentry(wim);
759
760         name_start = path;
761         for (;;) {
762                 if (cur_dentry == NULL) {
763                         errno = ENOENT;
764                         return NULL;
765                 }
766
767                 if (*name_start && !dentry_is_directory(cur_dentry)) {
768                         errno = ENOTDIR;
769                         return NULL;
770                 }
771
772                 while (*name_start == cpu_to_le16(WIM_PATH_SEPARATOR))
773                         name_start++;
774
775                 if (!*name_start)
776                         return cur_dentry;
777
778                 name_end = name_start;
779                 do {
780                         ++name_end;
781                 } while (*name_end != cpu_to_le16(WIM_PATH_SEPARATOR) && *name_end);
782
783                 cur_dentry = get_dentry_child_with_utf16le_name(cur_dentry,
784                                                                 name_start,
785                                                                 (u8*)name_end - (u8*)name_start,
786                                                                 case_type);
787                 name_start = name_end;
788         }
789 }
790
791 /*
792  * WIM path lookup: translate a path in the currently selected WIM image to the
793  * corresponding dentry, if it exists.
794  *
795  * @wim
796  *      The WIMStruct for the WIM.  The search takes place in the currently
797  *      selected image.
798  *
799  * @path
800  *      The path to look up, given relative to the root of the WIM image.
801  *      Characters with value WIM_PATH_SEPARATOR are taken to be path
802  *      separators.  Leading path separators are ignored, whereas one or more
803  *      trailing path separators cause the path to only match a directory.
804  *
805  * @case_type
806  *      The case-sensitivity behavior of this function, as one of the following
807  *      constants:
808  *
809  *    - WIMLIB_CASE_SENSITIVE:  Perform the search case sensitively.  This means
810  *      that names must match exactly.
811  *
812  *    - WIMLIB_CASE_INSENSITIVE:  Perform the search case insensitively.  This
813  *      means that names are considered to match if they are equal when
814  *      transformed to upper case.  If a path component matches multiple names
815  *      case-insensitively, the name that matches the path component
816  *      case-sensitively is chosen, if existent; otherwise one
817  *      case-insensitively matching name is chosen arbitrarily.
818  *
819  *    - WIMLIB_CASE_PLATFORM_DEFAULT:  Perform either case-sensitive or
820  *      case-insensitive search, depending on the value of the global variable
821  *      default_ignore_case.
822  *
823  *    In any case, no Unicode normalization is done before comparing strings.
824  *
825  * Returns a pointer to the dentry that is the result of the lookup, or NULL if
826  * no such dentry exists.  If NULL is returned, errno is set to one of the
827  * following values:
828  *
829  *      ENOTDIR if one of the path components used as a directory existed but
830  *      was not, in fact, a directory.
831  *
832  *      ENOENT otherwise.
833  *
834  * Additional notes:
835  *
836  *    - This function does not consider a reparse point to be a directory, even
837  *      if it has FILE_ATTRIBUTE_DIRECTORY set.
838  *
839  *    - This function does not dereference symbolic links or junction points
840  *      when performing the search.
841  *
842  *    - Since this function ignores leading slashes, the empty path is valid and
843  *      names the root directory of the WIM image.
844  *
845  *    - An image added with wimlib_add_empty_image() does not have a root
846  *      directory yet, and this function will fail with ENOENT for any path on
847  *      such an image.
848  */
849 struct wim_dentry *
850 get_dentry(WIMStruct *wim, const tchar *path, CASE_SENSITIVITY_TYPE case_type)
851 {
852         int ret;
853         const utf16lechar *path_utf16le;
854         struct wim_dentry *dentry;
855
856         ret = tstr_get_utf16le(path, &path_utf16le);
857         if (ret)
858                 return NULL;
859         dentry = get_dentry_utf16le(wim, path_utf16le, case_type);
860         tstr_put_utf16le(path_utf16le);
861         return dentry;
862 }
863
864 /* Modify @path, which is a null-terminated string @len 'tchars' in length,
865  * in-place to produce the path to its parent directory.  */
866 static void
867 to_parent_name(tchar *path, size_t len)
868 {
869         ssize_t i = (ssize_t)len - 1;
870         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
871                 i--;
872         while (i >= 0 && path[i] != WIM_PATH_SEPARATOR)
873                 i--;
874         while (i >= 0 && path[i] == WIM_PATH_SEPARATOR)
875                 i--;
876         path[i + 1] = T('\0');
877 }
878
879 /* Similar to get_dentry(), but returns the dentry named by @path with the last
880  * component stripped off.
881  *
882  * Note: The returned dentry is NOT guaranteed to be a directory.  */
883 struct wim_dentry *
884 get_parent_dentry(WIMStruct *wim, const tchar *path,
885                   CASE_SENSITIVITY_TYPE case_type)
886 {
887         size_t path_len = tstrlen(path);
888         tchar buf[path_len + 1];
889
890         tmemcpy(buf, path, path_len + 1);
891         to_parent_name(buf, path_len);
892         return get_dentry(wim, buf, case_type);
893 }
894
895 /*
896  * Create an unlinked dentry.
897  *
898  * @name specifies the long name to give the new dentry.  If NULL or empty, the
899  * new dentry will be given no long name.
900  *
901  * The new dentry will have no short name and no associated inode.
902  *
903  * On success, returns 0 and a pointer to the new, allocated dentry is stored in
904  * *dentry_ret.  On failure, returns WIMLIB_ERR_NOMEM or an error code resulting
905  * from a failed string conversion.
906  */
907 static int
908 new_dentry(const tchar *name, struct wim_dentry **dentry_ret)
909 {
910         struct wim_dentry *dentry;
911         int ret;
912
913         dentry = CALLOC(1, sizeof(struct wim_dentry));
914         if (!dentry)
915                 return WIMLIB_ERR_NOMEM;
916
917         if (name && *name) {
918                 ret = dentry_set_name(dentry, name);
919                 if (ret) {
920                         FREE(dentry);
921                         return ret;
922                 }
923         }
924         dentry->d_parent = dentry;
925         *dentry_ret = dentry;
926         return 0;
927 }
928
929 /* Like new_dentry(), but also allocate an inode and associate it with the
930  * dentry.  If set_timestamps=true, the timestamps for the inode will be set to
931  * the current time; otherwise, they will be left 0.  */
932 int
933 new_dentry_with_new_inode(const tchar *name, bool set_timestamps,
934                           struct wim_dentry **dentry_ret)
935 {
936         struct wim_dentry *dentry;
937         struct wim_inode *inode;
938         int ret;
939
940         ret = new_dentry(name, &dentry);
941         if (ret)
942                 return ret;
943
944         inode = new_inode(dentry, set_timestamps);
945         if (!inode) {
946                 free_dentry(dentry);
947                 return WIMLIB_ERR_NOMEM;
948         }
949
950         *dentry_ret = dentry;
951         return 0;
952 }
953
954 /* Like new_dentry(), but also associate the new dentry with the specified inode
955  * and acquire a reference to each of the inode's blobs.  */
956 int
957 new_dentry_with_existing_inode(const tchar *name, struct wim_inode *inode,
958                                struct wim_dentry **dentry_ret)
959 {
960         int ret = new_dentry(name, dentry_ret);
961         if (ret)
962                 return ret;
963         d_associate(*dentry_ret, inode);
964         inode_ref_blobs(inode);
965         return 0;
966 }
967
968 /* Create an unnamed dentry with a new inode for a directory with the default
969  * metadata.  */
970 int
971 new_filler_directory(struct wim_dentry **dentry_ret)
972 {
973         int ret;
974         struct wim_dentry *dentry;
975
976         ret = new_dentry_with_new_inode(NULL, true, &dentry);
977         if (ret)
978                 return ret;
979         /* Leave the inode number as 0; this is allowed for non
980          * hard-linked files. */
981         dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
982         *dentry_ret = dentry;
983         return 0;
984 }
985
986 /*
987  * Free a WIM dentry.
988  *
989  * In addition to freeing the dentry itself, this disassociates the dentry from
990  * its inode.  If the inode is no longer in use, it will be freed as well.
991  */
992 void
993 free_dentry(struct wim_dentry *dentry)
994 {
995         if (dentry) {
996                 d_disassociate(dentry);
997                 FREE(dentry->d_name);
998                 FREE(dentry->d_short_name);
999                 FREE(dentry->d_full_path);
1000                 FREE(dentry);
1001         }
1002 }
1003
1004 static int
1005 do_free_dentry(struct wim_dentry *dentry, void *_ignore)
1006 {
1007         free_dentry(dentry);
1008         return 0;
1009 }
1010
1011 static int
1012 do_free_dentry_and_unref_blobs(struct wim_dentry *dentry, void *blob_table)
1013 {
1014         inode_unref_blobs(dentry->d_inode, blob_table);
1015         free_dentry(dentry);
1016         return 0;
1017 }
1018
1019 /*
1020  * Free all dentries in a tree.
1021  *
1022  * @root:
1023  *      The root of the dentry tree to free.  If NULL, this function has no
1024  *      effect.
1025  *
1026  * @blob_table:
1027  *      A pointer to the blob table for the WIM, or NULL if not specified.  If
1028  *      specified, this function will decrement the reference counts of the
1029  *      blobs referenced by the dentries.
1030  *
1031  * This function also releases references to the corresponding inodes.
1032  *
1033  * This function does *not* unlink @root from its parent directory, if it has
1034  * one.  If @root has a parent, the caller must unlink @root before calling this
1035  * function.
1036  */
1037 void
1038 free_dentry_tree(struct wim_dentry *root, struct blob_table *blob_table)
1039 {
1040         int (*f)(struct wim_dentry *, void *);
1041
1042         if (blob_table)
1043                 f = do_free_dentry_and_unref_blobs;
1044         else
1045                 f = do_free_dentry;
1046
1047         for_dentry_in_tree_depth(root, f, blob_table);
1048 }
1049
1050 /* Insert the @child dentry into the case sensitive index of the @dir directory.
1051  * Return NULL if successfully inserted, otherwise a pointer to the
1052  * already-inserted duplicate.  */
1053 static struct wim_dentry *
1054 dir_index_child(struct wim_inode *dir, struct wim_dentry *child)
1055 {
1056         struct avl_tree_node *duplicate;
1057
1058         duplicate = avl_tree_insert(&dir->i_children,
1059                                     &child->d_index_node,
1060                                     _avl_dentry_compare_names);
1061         if (!duplicate)
1062                 return NULL;
1063         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node);
1064 }
1065
1066 /* Insert the @child dentry into the case insensitive index of the @dir
1067  * directory.  Return NULL if successfully inserted, otherwise a pointer to the
1068  * already-inserted duplicate.  */
1069 static struct wim_dentry *
1070 dir_index_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1071 {
1072         struct avl_tree_node *duplicate;
1073
1074         duplicate = avl_tree_insert(&dir->i_children_ci,
1075                                     &child->d_index_node_ci,
1076                                     _avl_dentry_compare_names_ci);
1077         if (!duplicate)
1078                 return NULL;
1079         return avl_tree_entry(duplicate, struct wim_dentry, d_index_node_ci);
1080 }
1081
1082 /* Remove the specified dentry from its directory's case-sensitive index.  */
1083 static void
1084 dir_unindex_child(struct wim_inode *dir, struct wim_dentry *child)
1085 {
1086         avl_tree_remove(&dir->i_children, &child->d_index_node);
1087 }
1088
1089 /* Remove the specified dentry from its directory's case-insensitive index.  */
1090 static void
1091 dir_unindex_child_ci(struct wim_inode *dir, struct wim_dentry *child)
1092 {
1093         avl_tree_remove(&dir->i_children_ci, &child->d_index_node_ci);
1094 }
1095
1096 /* Return true iff the specified dentry is in its parent directory's
1097  * case-insensitive index.  */
1098 static bool
1099 dentry_in_ci_index(const struct wim_dentry *dentry)
1100 {
1101         return !avl_tree_node_is_unlinked(&dentry->d_index_node_ci);
1102 }
1103
1104 /*
1105  * Link a dentry into the tree.
1106  *
1107  * @parent:
1108  *      The dentry that will be the parent of @child.  It must name a directory.
1109  *
1110  * @child:
1111  *      The dentry to link.  It must be currently unlinked.
1112  *
1113  * Returns NULL if successful.  If @parent already contains a dentry with the
1114  * same case-sensitive name as @child, returns a pointer to this duplicate
1115  * dentry.
1116  */
1117 struct wim_dentry *
1118 dentry_add_child(struct wim_dentry *parent, struct wim_dentry *child)
1119 {
1120         struct wim_dentry *duplicate;
1121         struct wim_inode *dir;
1122
1123         wimlib_assert(parent != child);
1124
1125         dir = parent->d_inode;
1126
1127         wimlib_assert(inode_is_directory(dir));
1128
1129         duplicate = dir_index_child(dir, child);
1130         if (duplicate)
1131                 return duplicate;
1132
1133         duplicate = dir_index_child_ci(dir, child);
1134         if (duplicate) {
1135                 list_add(&child->d_ci_conflict_list, &duplicate->d_ci_conflict_list);
1136                 avl_tree_node_set_unlinked(&child->d_index_node_ci);
1137         } else {
1138                 INIT_LIST_HEAD(&child->d_ci_conflict_list);
1139         }
1140         child->d_parent = parent;
1141         return NULL;
1142 }
1143
1144 /* Unlink a dentry from the tree.  */
1145 void
1146 unlink_dentry(struct wim_dentry *dentry)
1147 {
1148         struct wim_inode *dir;
1149
1150         /* Do nothing if the dentry is root or it's already unlinked.  Not
1151          * actually necessary based on the current callers, but we do the check
1152          * here to be safe.  */
1153         if (unlikely(dentry->d_parent == dentry))
1154                 return;
1155
1156         dir = dentry->d_parent->d_inode;
1157
1158         dir_unindex_child(dir, dentry);
1159
1160         if (dentry_in_ci_index(dentry)) {
1161
1162                 dir_unindex_child_ci(dir, dentry);
1163
1164                 if (!list_empty(&dentry->d_ci_conflict_list)) {
1165                         /* Make a different case-insensitively-the-same dentry
1166                          * be the "representative" in the search index.  */
1167                         struct list_head *next;
1168                         struct wim_dentry *other;
1169                         struct wim_dentry *existing;
1170
1171                         next = dentry->d_ci_conflict_list.next;
1172                         other = list_entry(next, struct wim_dentry, d_ci_conflict_list);
1173                         existing = dir_index_child_ci(dir, other);
1174                         wimlib_assert(existing == NULL);
1175                 }
1176         }
1177         list_del(&dentry->d_ci_conflict_list);
1178
1179         /* Not actually necessary, but to be safe don't retain the now-obsolete
1180          * parent pointer.  */
1181         dentry->d_parent = dentry;
1182 }
1183
1184 static int
1185 read_extra_data(const u8 *p, const u8 *end, struct wim_inode *inode)
1186 {
1187         while (((uintptr_t)p & 7) && p < end)
1188                 p++;
1189
1190         if (unlikely(p < end)) {
1191                 inode->i_extra = MALLOC(sizeof(struct wim_inode_extra) +
1192                                         end - p);
1193                 if (!inode->i_extra)
1194                         return WIMLIB_ERR_NOMEM;
1195                 inode->i_extra->size = end - p;
1196                 memcpy(inode->i_extra->data, p, end - p);
1197         }
1198         return 0;
1199 }
1200
1201 /*
1202  * Set the type of each stream for an encrypted file.
1203  *
1204  * All data streams of the encrypted file should have been packed into a single
1205  * stream in the format provided by ReadEncryptedFileRaw() on Windows.  We
1206  * assign this stream type STREAM_TYPE_EFSRPC_RAW_DATA.
1207  *
1208  * Encrypted files can't have a reparse point stream.  In the on-disk NTFS
1209  * format they can, but as far as I know the reparse point stream of an
1210  * encrypted file can't be stored in the WIM format in a way that's compatible
1211  * with WIMGAPI, nor is there even any way for it to be read or written on
1212  * Windows when the process does not have access to the file encryption key.
1213  */
1214 static void
1215 assign_stream_types_encrypted(struct wim_inode *inode)
1216 {
1217         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1218                 struct wim_inode_stream *strm = &inode->i_streams[i];
1219                 if (!stream_is_named(strm) && !is_zero_hash(strm->_stream_hash))
1220                 {
1221                         strm->stream_type = STREAM_TYPE_EFSRPC_RAW_DATA;
1222                         return;
1223                 }
1224         }
1225 }
1226
1227 /*
1228  * Set the type of each stream for an unencrypted file.
1229  *
1230  * There will be an unnamed data stream, a reparse point stream, or both an
1231  * unnamed data stream and a reparse point stream.  In addition, there may be
1232  * named data streams.
1233  *
1234  * NOTE: if the file has a reparse point stream or at least one named data
1235  * stream, then WIMGAPI puts *all* streams in the extra stream entries and
1236  * leaves the default stream hash zeroed.  wimlib now does the same.  However,
1237  * for input we still support the default hash field being used, since wimlib
1238  * used to use it and MS software is somewhat accepting of it as well.
1239  */
1240 static void
1241 assign_stream_types_unencrypted(struct wim_inode *inode)
1242 {
1243         bool found_reparse_point_stream = false;
1244         bool found_unnamed_data_stream = false;
1245         struct wim_inode_stream *unnamed_stream_with_zero_hash = NULL;
1246
1247         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1248                 struct wim_inode_stream *strm = &inode->i_streams[i];
1249
1250                 if (stream_is_named(strm)) {
1251                         /* Named data stream  */
1252                         strm->stream_type = STREAM_TYPE_DATA;
1253                 } else if (i != 0 || !is_zero_hash(strm->_stream_hash)) {
1254                         /* Unnamed stream in the extra stream entries, OR the
1255                          * default stream in the dentry provided that it has a
1256                          * nonzero hash.  */
1257                         if ((inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1258                             !found_reparse_point_stream) {
1259                                 found_reparse_point_stream = true;
1260                                 strm->stream_type = STREAM_TYPE_REPARSE_POINT;
1261                         } else if (!found_unnamed_data_stream) {
1262                                 found_unnamed_data_stream = true;
1263                                 strm->stream_type = STREAM_TYPE_DATA;
1264                         }
1265                 } else if (!unnamed_stream_with_zero_hash) {
1266                         unnamed_stream_with_zero_hash = strm;
1267                 }
1268         }
1269
1270         if (unnamed_stream_with_zero_hash) {
1271                 int type = STREAM_TYPE_UNKNOWN;
1272                 if ((inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1273                     !found_reparse_point_stream) {
1274                         type = STREAM_TYPE_REPARSE_POINT;
1275                 } else if (!found_unnamed_data_stream) {
1276                         type = STREAM_TYPE_DATA;
1277                 }
1278                 unnamed_stream_with_zero_hash->stream_type = type;
1279         }
1280 }
1281
1282 /*
1283  * Read and interpret the collection of streams for the specified inode.
1284  */
1285 static int
1286 setup_inode_streams(const u8 *p, const u8 *end, struct wim_inode *inode,
1287                     unsigned num_extra_streams, const u8 *default_hash,
1288                     u64 *offset_p)
1289 {
1290         const u8 *orig_p = p;
1291
1292         inode->i_num_streams = 1 + num_extra_streams;
1293
1294         if (unlikely(inode->i_num_streams > ARRAY_LEN(inode->i_embedded_streams))) {
1295                 inode->i_streams = CALLOC(inode->i_num_streams,
1296                                           sizeof(inode->i_streams[0]));
1297                 if (!inode->i_streams)
1298                         return WIMLIB_ERR_NOMEM;
1299         }
1300
1301         /* Use the default hash field for the first stream  */
1302         inode->i_streams[0].stream_name = (utf16lechar *)NO_STREAM_NAME;
1303         copy_hash(inode->i_streams[0]._stream_hash, default_hash);
1304         inode->i_streams[0].stream_type = STREAM_TYPE_UNKNOWN;
1305         inode->i_streams[0].stream_id = 0;
1306
1307         /* Read the extra stream entries  */
1308         for (unsigned i = 1; i < inode->i_num_streams; i++) {
1309                 struct wim_inode_stream *strm;
1310                 const struct wim_extra_stream_entry_on_disk *disk_strm;
1311                 u64 length;
1312                 u16 name_nbytes;
1313
1314                 strm = &inode->i_streams[i];
1315
1316                 strm->stream_id = i;
1317
1318                 /* Do we have at least the size of the fixed-length data we know
1319                  * need?  */
1320                 if ((end - p) < sizeof(struct wim_extra_stream_entry_on_disk))
1321                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1322
1323                 disk_strm = (const struct wim_extra_stream_entry_on_disk *)p;
1324
1325                 /* Read the length field  */
1326                 length = ALIGN(le64_to_cpu(disk_strm->length), 8);
1327
1328                 /* Make sure the length field is neither so small it doesn't
1329                  * include all the fixed-length data nor so large it overflows
1330                  * the metadata resource buffer. */
1331                 if (length < sizeof(struct wim_extra_stream_entry_on_disk) ||
1332                     length > (end - p))
1333                         return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1334
1335                 /* Read the rest of the fixed-length data. */
1336
1337                 copy_hash(strm->_stream_hash, disk_strm->hash);
1338                 name_nbytes = le16_to_cpu(disk_strm->name_nbytes);
1339
1340                 /* If stream_name_nbytes != 0, the stream is named.  */
1341                 if (name_nbytes != 0) {
1342                         /* The name is encoded in UTF16-LE, which uses 2-byte
1343                          * coding units, so the length of the name had better be
1344                          * an even number of bytes.  */
1345                         if (name_nbytes & 1)
1346                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1347
1348                         /* Add the length of the stream name to get the length
1349                          * we actually need to read.  Make sure this isn't more
1350                          * than the specified length of the entry.  */
1351                         if (sizeof(struct wim_extra_stream_entry_on_disk) +
1352                             name_nbytes > length)
1353                                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1354
1355                         strm->stream_name = utf16le_dupz(disk_strm->name,
1356                                                          name_nbytes);
1357                         if (!strm->stream_name)
1358                                 return WIMLIB_ERR_NOMEM;
1359                 } else {
1360                         strm->stream_name = (utf16lechar *)NO_STREAM_NAME;
1361                 }
1362
1363                 strm->stream_type = STREAM_TYPE_UNKNOWN;
1364
1365                 p += length;
1366         }
1367
1368         inode->i_next_stream_id = inode->i_num_streams;
1369
1370         /* Now, assign a type to each stream.  Unfortunately this requires
1371          * various hacks because stream types aren't explicitly provided in the
1372          * WIM on-disk format.  */
1373
1374         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED))
1375                 assign_stream_types_encrypted(inode);
1376         else
1377                 assign_stream_types_unencrypted(inode);
1378
1379         *offset_p += p - orig_p;
1380         return 0;
1381 }
1382
1383 /* Read a dentry, including all extra stream entries that follow it, from an
1384  * uncompressed metadata resource buffer.  */
1385 static int
1386 read_dentry(const u8 * restrict buf, size_t buf_len,
1387             u64 *offset_p, struct wim_dentry **dentry_ret)
1388 {
1389         u64 offset = *offset_p;
1390         u64 length;
1391         const u8 *p;
1392         const struct wim_dentry_on_disk *disk_dentry;
1393         struct wim_dentry *dentry;
1394         struct wim_inode *inode;
1395         u16 short_name_nbytes;
1396         u16 name_nbytes;
1397         u64 calculated_size;
1398         int ret;
1399
1400         STATIC_ASSERT(sizeof(struct wim_dentry_on_disk) == WIM_DENTRY_DISK_SIZE);
1401
1402         /* Before reading the whole dentry, we need to read just the length.
1403          * This is because a dentry of length 8 (that is, just the length field)
1404          * terminates the list of sibling directory entries. */
1405
1406         /* Check for buffer overrun.  */
1407         if (unlikely(offset + sizeof(u64) > buf_len ||
1408                      offset + sizeof(u64) < offset))
1409                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1410
1411         /* Get pointer to the dentry data.  */
1412         p = &buf[offset];
1413         disk_dentry = (const struct wim_dentry_on_disk*)p;
1414
1415         /* Get dentry length.  */
1416         length = ALIGN(le64_to_cpu(disk_dentry->length), 8);
1417
1418         /* Check for end-of-directory.  */
1419         if (length <= 8) {
1420                 *dentry_ret = NULL;
1421                 return 0;
1422         }
1423
1424         /* Validate dentry length.  */
1425         if (unlikely(length < sizeof(struct wim_dentry_on_disk)))
1426                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1427
1428         /* Check for buffer overrun.  */
1429         if (unlikely(offset + length > buf_len ||
1430                      offset + length < offset))
1431                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1432
1433         /* Allocate new dentry structure, along with a preliminary inode.  */
1434         ret = new_dentry_with_new_inode(NULL, false, &dentry);
1435         if (ret)
1436                 return ret;
1437
1438         inode = dentry->d_inode;
1439
1440         /* Read more fields: some into the dentry, and some into the inode.  */
1441         inode->i_attributes = le32_to_cpu(disk_dentry->attributes);
1442         inode->i_security_id = le32_to_cpu(disk_dentry->security_id);
1443         dentry->d_subdir_offset = le64_to_cpu(disk_dentry->subdir_offset);
1444         inode->i_creation_time = le64_to_cpu(disk_dentry->creation_time);
1445         inode->i_last_access_time = le64_to_cpu(disk_dentry->last_access_time);
1446         inode->i_last_write_time = le64_to_cpu(disk_dentry->last_write_time);
1447         inode->i_unknown_0x54 = le32_to_cpu(disk_dentry->unknown_0x54);
1448
1449         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1450                 inode->i_reparse_tag = le32_to_cpu(disk_dentry->reparse.reparse_tag);
1451                 inode->i_rp_reserved = le16_to_cpu(disk_dentry->reparse.rp_reserved);
1452                 inode->i_rp_flags = le16_to_cpu(disk_dentry->reparse.rp_flags);
1453                 /* Leave inode->i_ino at 0.  Note: this means that WIM cannot
1454                  * represent multiple hard links to a reparse point file.  */
1455         } else {
1456                 inode->i_ino = le64_to_cpu(disk_dentry->nonreparse.hard_link_group_id);
1457         }
1458
1459         /* Now onto reading the names.  There are two of them: the (long) file
1460          * name, and the short name.  */
1461
1462         short_name_nbytes = le16_to_cpu(disk_dentry->short_name_nbytes);
1463         name_nbytes = le16_to_cpu(disk_dentry->name_nbytes);
1464
1465         if (unlikely((short_name_nbytes & 1) | (name_nbytes & 1))) {
1466                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1467                 goto err_free_dentry;
1468         }
1469
1470         /* We now know the length of the file name and short name.  Make sure
1471          * the length of the dentry is large enough to actually hold them.  */
1472         calculated_size = dentry_min_len_with_names(name_nbytes,
1473                                                     short_name_nbytes);
1474
1475         if (unlikely(length < calculated_size)) {
1476                 ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1477                 goto err_free_dentry;
1478         }
1479
1480         /* Advance p to point past the base dentry, to the first name.  */
1481         p += sizeof(struct wim_dentry_on_disk);
1482
1483         /* Read the filename if present.  Note: if the filename is empty, there
1484          * is no null terminator following it.  */
1485         if (name_nbytes) {
1486                 dentry->d_name = utf16le_dupz(p, name_nbytes);
1487                 if (unlikely(!dentry->d_name)) {
1488                         ret = WIMLIB_ERR_NOMEM;
1489                         goto err_free_dentry;
1490                 }
1491                 dentry->d_name_nbytes = name_nbytes;
1492                 p += (u32)name_nbytes + 2;
1493         }
1494
1495         /* Read the short filename if present.  Note: if there is no short
1496          * filename, there is no null terminator following it. */
1497         if (short_name_nbytes) {
1498                 dentry->d_short_name = utf16le_dupz(p, short_name_nbytes);
1499                 if (unlikely(!dentry->d_short_name)) {
1500                         ret = WIMLIB_ERR_NOMEM;
1501                         goto err_free_dentry;
1502                 }
1503                 dentry->d_short_name_nbytes = short_name_nbytes;
1504                 p += (u32)short_name_nbytes + 2;
1505         }
1506
1507         /* Read extra data at end of dentry (but before extra stream entries).
1508          * This may contain tagged metadata items.  */
1509         ret = read_extra_data(p, &buf[offset + length], inode);
1510         if (ret)
1511                 goto err_free_dentry;
1512
1513         offset += length;
1514
1515         /* Set up the inode's collection of streams.  */
1516         ret = setup_inode_streams(&buf[offset],
1517                                   &buf[buf_len],
1518                                   inode,
1519                                   le16_to_cpu(disk_dentry->num_extra_streams),
1520                                   disk_dentry->default_hash,
1521                                   &offset);
1522         if (ret)
1523                 goto err_free_dentry;
1524
1525         *offset_p = offset;  /* Sets offset of next dentry in directory  */
1526         *dentry_ret = dentry;
1527         return 0;
1528
1529 err_free_dentry:
1530         free_dentry(dentry);
1531         return ret;
1532 }
1533
1534 /* Is the dentry named "." or ".." ?  */
1535 static bool
1536 dentry_is_dot_or_dotdot(const struct wim_dentry *dentry)
1537 {
1538         if (dentry->d_name_nbytes <= 4) {
1539                 if (dentry->d_name_nbytes == 4) {
1540                         if (dentry->d_name[0] == cpu_to_le16('.') &&
1541                             dentry->d_name[1] == cpu_to_le16('.'))
1542                                 return true;
1543                 } else if (dentry->d_name_nbytes == 2) {
1544                         if (dentry->d_name[0] == cpu_to_le16('.'))
1545                                 return true;
1546                 }
1547         }
1548         return false;
1549 }
1550
1551 static int
1552 read_dentry_tree_recursive(const u8 * restrict buf, size_t buf_len,
1553                            struct wim_dentry * restrict dir, unsigned depth)
1554 {
1555         u64 cur_offset = dir->d_subdir_offset;
1556
1557         /* Disallow extremely deep or cyclic directory structures  */
1558         if (unlikely(depth >= 16384)) {
1559                 ERROR("Directory structure too deep!");
1560                 return WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1561         }
1562
1563         for (;;) {
1564                 struct wim_dentry *child;
1565                 struct wim_dentry *duplicate;
1566                 int ret;
1567
1568                 /* Read next child of @dir.  */
1569                 ret = read_dentry(buf, buf_len, &cur_offset, &child);
1570                 if (ret)
1571                         return ret;
1572
1573                 /* Check for end of directory.  */
1574                 if (child == NULL)
1575                         return 0;
1576
1577                 /* All dentries except the root should be named.  */
1578                 if (unlikely(!dentry_has_long_name(child))) {
1579                         WARNING("Ignoring unnamed dentry in "
1580                                 "directory \"%"TS"\"", dentry_full_path(dir));
1581                         free_dentry(child);
1582                         continue;
1583                 }
1584
1585                 /* Don't allow files named "." or "..".  */
1586                 if (unlikely(dentry_is_dot_or_dotdot(child))) {
1587                         WARNING("Ignoring file named \".\" or \"..\"; "
1588                                 "potentially malicious archive!!!");
1589                         free_dentry(child);
1590                         continue;
1591                 }
1592
1593                 /* Link the child into the directory.  */
1594                 duplicate = dentry_add_child(dir, child);
1595                 if (unlikely(duplicate)) {
1596                         /* We already found a dentry with this same
1597                          * case-sensitive long name.  Only keep the first one.
1598                          */
1599                         WARNING("Ignoring duplicate file \"%"TS"\" "
1600                                 "(the WIM image already contains a file "
1601                                 "at that path with the exact same name)",
1602                                 dentry_full_path(duplicate));
1603                         free_dentry(child);
1604                         continue;
1605                 }
1606
1607                 /* If this child is a directory that itself has children, call
1608                  * this procedure recursively.  */
1609                 if (child->d_subdir_offset != 0) {
1610                         if (likely(dentry_is_directory(child))) {
1611                                 ret = read_dentry_tree_recursive(buf,
1612                                                                  buf_len,
1613                                                                  child,
1614                                                                  depth + 1);
1615                                 if (ret)
1616                                         return ret;
1617                         } else {
1618                                 WARNING("Ignoring children of "
1619                                         "non-directory file \"%"TS"\"",
1620                                         dentry_full_path(child));
1621                         }
1622                 }
1623         }
1624 }
1625
1626 /*
1627  * Read a tree of dentries from a WIM metadata resource.
1628  *
1629  * @buf:
1630  *      Buffer containing an uncompressed WIM metadata resource.
1631  *
1632  * @buf_len:
1633  *      Length of the uncompressed metadata resource, in bytes.
1634  *
1635  * @root_offset
1636  *      Offset in the metadata resource of the root of the dentry tree.
1637  *
1638  * @root_ret:
1639  *      On success, either NULL or a pointer to the root dentry is written to
1640  *      this location.  The former case only occurs in the unexpected case that
1641  *      the tree began with an end-of-directory entry.
1642  *
1643  * Return values:
1644  *      WIMLIB_ERR_SUCCESS (0)
1645  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
1646  *      WIMLIB_ERR_NOMEM
1647  */
1648 int
1649 read_dentry_tree(const u8 *buf, size_t buf_len,
1650                  u64 root_offset, struct wim_dentry **root_ret)
1651 {
1652         int ret;
1653         struct wim_dentry *root;
1654
1655         ret = read_dentry(buf, buf_len, &root_offset, &root);
1656         if (ret)
1657                 return ret;
1658
1659         if (likely(root != NULL)) {
1660                 if (unlikely(dentry_has_long_name(root) ||
1661                              dentry_has_short_name(root)))
1662                 {
1663                         WARNING("The root directory has a nonempty name; "
1664                                 "removing it.");
1665                         dentry_set_name(root, NULL);
1666                 }
1667
1668                 if (unlikely(!dentry_is_directory(root))) {
1669                         ERROR("The root of the WIM image is not a directory!");
1670                         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
1671                         goto err_free_dentry_tree;
1672                 }
1673
1674                 if (likely(root->d_subdir_offset != 0)) {
1675                         ret = read_dentry_tree_recursive(buf, buf_len, root, 0);
1676                         if (ret)
1677                                 goto err_free_dentry_tree;
1678                 }
1679         } else {
1680                 WARNING("The metadata resource has no directory entries; "
1681                         "treating as an empty image.");
1682         }
1683         *root_ret = root;
1684         return 0;
1685
1686 err_free_dentry_tree:
1687         free_dentry_tree(root, NULL);
1688         return ret;
1689 }
1690
1691 static u8 *
1692 write_extra_stream_entry(u8 * restrict p, const utf16lechar * restrict name,
1693                          const u8 * restrict hash)
1694 {
1695         struct wim_extra_stream_entry_on_disk *disk_strm =
1696                         (struct wim_extra_stream_entry_on_disk *)p;
1697         u8 *orig_p = p;
1698         size_t name_nbytes;
1699
1700         if (name == NO_STREAM_NAME)
1701                 name_nbytes = 0;
1702         else
1703                 name_nbytes = utf16le_len_bytes(name);
1704
1705         disk_strm->reserved = 0;
1706         copy_hash(disk_strm->hash, hash);
1707         disk_strm->name_nbytes = cpu_to_le16(name_nbytes);
1708         p += sizeof(struct wim_extra_stream_entry_on_disk);
1709         if (name_nbytes != 0)
1710                 p = mempcpy(p, name, name_nbytes + 2);
1711         /* Align to 8-byte boundary */
1712         while ((uintptr_t)p & 7)
1713                 *p++ = 0;
1714         disk_strm->length = cpu_to_le64(p - orig_p);
1715         return p;
1716 }
1717
1718 /*
1719  * Write a WIM dentry to an output buffer.
1720  *
1721  * This includes any extra stream entries that may follow the dentry itself.
1722  *
1723  * @dentry:
1724  *      The dentry to write.
1725  *
1726  * @p:
1727  *      The memory location to which to write the data.
1728  *
1729  * Returns a pointer to the byte following the last written.
1730  */
1731 static u8 *
1732 write_dentry(const struct wim_dentry * restrict dentry, u8 * restrict p)
1733 {
1734         const struct wim_inode *inode;
1735         struct wim_dentry_on_disk *disk_dentry;
1736         const u8 *orig_p;
1737
1738         wimlib_assert(((uintptr_t)p & 7) == 0); /* 8 byte aligned */
1739         orig_p = p;
1740
1741         inode = dentry->d_inode;
1742         disk_dentry = (struct wim_dentry_on_disk*)p;
1743
1744         disk_dentry->attributes = cpu_to_le32(inode->i_attributes);
1745         disk_dentry->security_id = cpu_to_le32(inode->i_security_id);
1746         disk_dentry->subdir_offset = cpu_to_le64(dentry->d_subdir_offset);
1747
1748         disk_dentry->unused_1 = cpu_to_le64(0);
1749         disk_dentry->unused_2 = cpu_to_le64(0);
1750
1751         disk_dentry->creation_time = cpu_to_le64(inode->i_creation_time);
1752         disk_dentry->last_access_time = cpu_to_le64(inode->i_last_access_time);
1753         disk_dentry->last_write_time = cpu_to_le64(inode->i_last_write_time);
1754         disk_dentry->unknown_0x54 = cpu_to_le32(inode->i_unknown_0x54);
1755         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1756                 disk_dentry->reparse.reparse_tag = cpu_to_le32(inode->i_reparse_tag);
1757                 disk_dentry->reparse.rp_reserved = cpu_to_le16(inode->i_rp_reserved);
1758                 disk_dentry->reparse.rp_flags = cpu_to_le16(inode->i_rp_flags);
1759         } else {
1760                 disk_dentry->nonreparse.hard_link_group_id =
1761                         cpu_to_le64((inode->i_nlink == 1) ? 0 : inode->i_ino);
1762         }
1763
1764         disk_dentry->short_name_nbytes = cpu_to_le16(dentry->d_short_name_nbytes);
1765         disk_dentry->name_nbytes = cpu_to_le16(dentry->d_name_nbytes);
1766         p += sizeof(struct wim_dentry_on_disk);
1767
1768         wimlib_assert(dentry_is_root(dentry) != dentry_has_long_name(dentry));
1769
1770         if (dentry_has_long_name(dentry))
1771                 p = mempcpy(p, dentry->d_name, (u32)dentry->d_name_nbytes + 2);
1772
1773         if (dentry_has_short_name(dentry))
1774                 p = mempcpy(p, dentry->d_short_name, (u32)dentry->d_short_name_nbytes + 2);
1775
1776         /* Align to 8-byte boundary */
1777         while ((uintptr_t)p & 7)
1778                 *p++ = 0;
1779
1780         if (inode->i_extra) {
1781                 /* Extra tagged items --- not usually present.  */
1782                 p = mempcpy(p, inode->i_extra->data, inode->i_extra->size);
1783
1784                 /* Align to 8-byte boundary */
1785                 while ((uintptr_t)p & 7)
1786                         *p++ = 0;
1787         }
1788
1789         disk_dentry->length = cpu_to_le64(p - orig_p);
1790
1791         /* Streams  */
1792
1793         if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1794                 const struct wim_inode_stream *efs_strm;
1795                 const u8 *efs_hash;
1796
1797                 efs_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_EFSRPC_RAW_DATA);
1798                 efs_hash = efs_strm ? stream_hash(efs_strm) : zero_hash;
1799                 copy_hash(disk_dentry->default_hash, efs_hash);
1800                 disk_dentry->num_extra_streams = cpu_to_le16(0);
1801         } else {
1802                 /*
1803                  * Extra stream entries:
1804                  *
1805                  * - Use one extra stream entry for each named data stream
1806                  * - Use one extra stream entry for the unnamed data stream when there is either:
1807                  *      - a reparse point stream
1808                  *      - at least one named data stream (for Windows PE bug workaround)
1809                  * - Use one extra stream entry for the reparse point stream if there is one
1810                  */
1811                 bool have_named_data_stream = false;
1812                 bool have_reparse_point_stream = false;
1813                 const u8 *unnamed_data_stream_hash = zero_hash;
1814                 const u8 *reparse_point_hash;
1815                 for (unsigned i = 0; i < inode->i_num_streams; i++) {
1816                         const struct wim_inode_stream *strm = &inode->i_streams[i];
1817                         if (strm->stream_type == STREAM_TYPE_DATA) {
1818                                 if (stream_is_named(strm))
1819                                         have_named_data_stream = true;
1820                                 else
1821                                         unnamed_data_stream_hash = stream_hash(strm);
1822                         } else if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
1823                                 have_reparse_point_stream = true;
1824                                 reparse_point_hash = stream_hash(strm);
1825                         }
1826                 }
1827
1828                 if (unlikely(have_reparse_point_stream || have_named_data_stream)) {
1829
1830                         unsigned num_extra_streams = 0;
1831
1832                         copy_hash(disk_dentry->default_hash, zero_hash);
1833
1834                         if (have_reparse_point_stream) {
1835                                 p = write_extra_stream_entry(p, NO_STREAM_NAME,
1836                                                              reparse_point_hash);
1837                                 num_extra_streams++;
1838                         }
1839
1840                         p = write_extra_stream_entry(p, NO_STREAM_NAME,
1841                                                      unnamed_data_stream_hash);
1842                         num_extra_streams++;
1843
1844                         for (unsigned i = 0; i < inode->i_num_streams; i++) {
1845                                 const struct wim_inode_stream *strm = &inode->i_streams[i];
1846                                 if (stream_is_named_data_stream(strm)) {
1847                                         p = write_extra_stream_entry(p, strm->stream_name,
1848                                                                      stream_hash(strm));
1849                                         num_extra_streams++;
1850                                 }
1851                         }
1852                         wimlib_assert(num_extra_streams <= 0xFFFF);
1853
1854                         disk_dentry->num_extra_streams = cpu_to_le16(num_extra_streams);
1855                 } else {
1856                         copy_hash(disk_dentry->default_hash, unnamed_data_stream_hash);
1857                         disk_dentry->num_extra_streams = cpu_to_le16(0);
1858                 }
1859         }
1860
1861         return p;
1862 }
1863
1864 static int
1865 write_dir_dentries(struct wim_dentry *dir, void *_pp)
1866 {
1867         if (dir->d_subdir_offset != 0) {
1868                 u8 **pp = _pp;
1869                 u8 *p = *pp;
1870                 struct wim_dentry *child;
1871
1872                 /* write child dentries */
1873                 for_dentry_child(child, dir)
1874                         p = write_dentry(child, p);
1875
1876                 /* write end of directory entry */
1877                 *(u64*)p = 0;
1878                 p += 8;
1879                 *pp = p;
1880         }
1881         return 0;
1882 }
1883
1884 /*
1885  * Write a directory tree to the metadata resource.
1886  *
1887  * @root:
1888  *      The root of a dentry tree on which calculate_subdir_offsets() has been
1889  *      called.  This cannot be NULL; if the dentry tree is empty, the caller is
1890  *      expected to first generate a dummy root directory.
1891  *
1892  * @p:
1893  *      Pointer to a buffer with enough space for the dentry tree.  This size
1894  *      must have been obtained by calculate_subdir_offsets().
1895  *
1896  * Returns a pointer to the byte following the last written.
1897  */
1898 u8 *
1899 write_dentry_tree(struct wim_dentry *root, u8 *p)
1900 {
1901         /* write root dentry and end-of-directory entry following it */
1902         p = write_dentry(root, p);
1903         *(u64*)p = 0;
1904         p += 8;
1905
1906         /* write the rest of the dentry tree */
1907         for_dentry_in_tree(root, write_dir_dentries, &p);
1908
1909         return p;
1910 }