]> wimlib.net Git - wimlib/blob - src/ntfs-capture.c
capture_ntfs_streams(): Warn, not error, if multiple unnamed streams
[wimlib] / src / ntfs-capture.c
1 /*
2  * ntfs-capture.c
3  *
4  * Capture a WIM image from a NTFS volume.  We capture everything we can,
5  * including security data and alternate data streams.
6  */
7
8 /*
9  * Copyright (C) 2012 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27
28 #include "config.h"
29
30 #include <ntfs-3g/endians.h>
31 #include <ntfs-3g/types.h>
32
33 #include "wimlib_internal.h"
34
35
36 #include "dentry.h"
37 #include "lookup_table.h"
38 #include "buffer_io.h"
39 #include <ntfs-3g/layout.h>
40 #include <ntfs-3g/acls.h>
41 #include <ntfs-3g/attrib.h>
42 #include <ntfs-3g/misc.h>
43 #include <ntfs-3g/reparse.h>
44 #include <ntfs-3g/security.h> /* security.h before xattrs.h */
45 #include <ntfs-3g/xattrs.h>
46 #include <ntfs-3g/volume.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <errno.h>
50 #include "rbtree.h"
51
52 /* Red-black tree that maps SHA1 message digests of security descriptors to
53  * security IDs, which are themselves indices into the table of security
54  * descriptors in the 'struct wim_security_data'. */
55 struct sd_set {
56         struct wim_security_data *sd;
57         struct rb_root rb_root;
58 };
59
60 struct sd_node {
61         int security_id;
62         u8 hash[SHA1_HASH_SIZE];
63         struct rb_node rb_node;
64 };
65
66 static void free_sd_tree(struct rb_node *node)
67 {
68         if (node) {
69                 free_sd_tree(node->rb_left);
70                 free_sd_tree(node->rb_right);
71                 FREE(container_of(node, struct sd_node, rb_node));
72         }
73 }
74 /* Frees a security descriptor index set. */
75 static void destroy_sd_set(struct sd_set *sd_set)
76 {
77         free_sd_tree(sd_set->rb_root.rb_node);
78 }
79
80 /* Inserts a a new node into the security descriptor index tree. */
81 static void insert_sd_node(struct sd_set *set, struct sd_node *new)
82 {
83         struct rb_root *root = &set->rb_root;
84         struct rb_node **p = &(root->rb_node);
85         struct rb_node *rb_parent = NULL;
86
87         while (*p) {
88                 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
89                 int cmp = hashes_cmp(new->hash, this->hash);
90
91                 rb_parent = *p;
92                 if (cmp < 0)
93                         p = &((*p)->rb_left);
94                 else if (cmp > 0)
95                         p = &((*p)->rb_right);
96                 else
97                         wimlib_assert(0); /* Duplicate SHA1 message digest */
98         }
99         rb_link_node(&new->rb_node, rb_parent, p);
100         rb_insert_color(&new->rb_node, root);
101 }
102
103 /* Returns the index of the security descriptor having a SHA1 message digest of
104  * @hash.  If not found, return -1. */
105 static int lookup_sd(struct sd_set *set, const u8 hash[SHA1_HASH_SIZE])
106 {
107         struct rb_node *node = set->rb_root.rb_node;
108
109         while (node) {
110                 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
111                 int cmp = hashes_cmp(hash, sd_node->hash);
112                 if (cmp < 0)
113                         node = node->rb_left;
114                 else if (cmp > 0)
115                         node = node->rb_right;
116                 else
117                         return sd_node->security_id;
118         }
119         return -1;
120 }
121
122 /*
123  * Adds a security descriptor to the indexed security descriptor set as well as
124  * the corresponding `struct wim_security_data', and returns the new security
125  * ID; or, if there is an existing security descriptor that is the same, return
126  * the security ID for it.  If a new security descriptor cannot be allocated,
127  * return -1.
128  */
129 static int sd_set_add_sd(struct sd_set *sd_set, const char descriptor[],
130                          size_t size)
131 {
132         u8 hash[SHA1_HASH_SIZE];
133         int security_id;
134         struct sd_node *new;
135         u8 **descriptors;
136         u64 *sizes;
137         u8 *descr_copy;
138         struct wim_security_data *sd;
139
140         sha1_buffer((const u8*)descriptor, size, hash);
141
142         security_id = lookup_sd(sd_set, hash);
143         if (security_id >= 0) /* Identical descriptor already exists */
144                 return security_id;
145
146         /* Need to add a new security descriptor */
147         new = MALLOC(sizeof(*new));
148         if (!new)
149                 goto out;
150         descr_copy = MALLOC(size);
151         if (!descr_copy)
152                 goto out_free_node;
153
154         sd = sd_set->sd;
155
156         memcpy(descr_copy, descriptor, size);
157         new->security_id = sd->num_entries;
158         copy_hash(new->hash, hash);
159
160         descriptors = REALLOC(sd->descriptors,
161                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
162         if (!descriptors)
163                 goto out_free_descr;
164         sd->descriptors = descriptors;
165         sizes = REALLOC(sd->sizes,
166                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
167         if (!sizes)
168                 goto out_free_descr;
169         sd->sizes = sizes;
170         sd->descriptors[sd->num_entries] = descr_copy;
171         sd->sizes[sd->num_entries] = size;
172         sd->num_entries++;
173         DEBUG("There are now %d security descriptors", sd->num_entries);
174         sd->total_length += size + sizeof(sd->sizes[0]);
175         insert_sd_node(sd_set, new);
176         return new->security_id;
177 out_free_descr:
178         FREE(descr_copy);
179 out_free_node:
180         FREE(new);
181 out:
182         return -1;
183 }
184
185 static inline ntfschar *attr_record_name(ATTR_RECORD *ar)
186 {
187         return (ntfschar*)((u8*)ar + le16_to_cpu(ar->name_offset));
188 }
189
190 /* Calculates the SHA1 message digest of a NTFS attribute.
191  *
192  * @ni:  The NTFS inode containing the attribute.
193  * @ar:  The ATTR_RECORD describing the attribute.
194  * @md:  If successful, the returned SHA1 message digest.
195  * @reparse_tag_ret:    Optional pointer into which the first 4 bytes of the
196  *                              attribute will be written (to get the reparse
197  *                              point ID)
198  *
199  * Return 0 on success or nonzero on error.
200  */
201 static int ntfs_attr_sha1sum(ntfs_inode *ni, ATTR_RECORD *ar,
202                              u8 md[SHA1_HASH_SIZE],
203                              bool is_reparse_point,
204                              u32 *reparse_tag_ret)
205 {
206         s64 pos = 0;
207         s64 bytes_remaining;
208         char buf[BUFFER_SIZE];
209         ntfs_attr *na;
210         SHA_CTX ctx;
211
212         na = ntfs_attr_open(ni, ar->type, attr_record_name(ar),
213                             ar->name_length);
214         if (!na) {
215                 ERROR_WITH_ERRNO("Failed to open NTFS attribute");
216                 return WIMLIB_ERR_NTFS_3G;
217         }
218
219         bytes_remaining = na->data_size;
220
221         if (is_reparse_point) {
222                 if (ntfs_attr_pread(na, 0, 8, buf) != 8)
223                         goto out_error;
224                 *reparse_tag_ret = le32_to_cpu(*(u32*)buf);
225                 pos = 8;
226                 bytes_remaining -= 8;
227         }
228
229         sha1_init(&ctx);
230         while (bytes_remaining) {
231                 s64 to_read = min(bytes_remaining, sizeof(buf));
232                 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read)
233                         goto out_error;
234                 sha1_update(&ctx, buf, to_read);
235                 pos += to_read;
236                 bytes_remaining -= to_read;
237         }
238         sha1_final(md, &ctx);
239         ntfs_attr_close(na);
240         return 0;
241 out_error:
242         ERROR_WITH_ERRNO("Error reading NTFS attribute");
243         return WIMLIB_ERR_NTFS_3G;
244 }
245
246 /* Load the streams from a file or reparse point in the NTFS volume into the WIM
247  * lookup table */
248 static int capture_ntfs_streams(struct wim_dentry *dentry, ntfs_inode *ni,
249                                 char path[], size_t path_len,
250                                 struct wim_lookup_table *lookup_table,
251                                 ntfs_volume **ntfs_vol_p,
252                                 ATTR_TYPES type)
253 {
254         ntfs_attr_search_ctx *actx;
255         u8 attr_hash[SHA1_HASH_SIZE];
256         struct ntfs_location *ntfs_loc = NULL;
257         int ret = 0;
258         struct wim_lookup_table_entry *lte;
259
260         DEBUG2("Capturing NTFS data streams from `%s'", path);
261
262         /* Get context to search the streams of the NTFS file. */
263         actx = ntfs_attr_get_search_ctx(ni, NULL);
264         if (!actx) {
265                 ERROR_WITH_ERRNO("Cannot get NTFS attribute search "
266                                  "context");
267                 return WIMLIB_ERR_NTFS_3G;
268         }
269
270         /* Capture each data stream or reparse data stream. */
271         while (!ntfs_attr_lookup(type, NULL, 0,
272                                  CASE_SENSITIVE, 0, NULL, 0, actx))
273         {
274                 char *stream_name_utf8;
275                 u32 reparse_tag;
276                 u64 data_size = ntfs_get_attribute_value_length(actx->attr);
277                 u64 name_length = actx->attr->name_length;
278
279                 if (data_size == 0) {
280                         if (errno != 0) {
281                                 ERROR_WITH_ERRNO("Failed to get size of attribute of "
282                                                  "`%s'", path);
283                                 ret = WIMLIB_ERR_NTFS_3G;
284                                 goto out_put_actx;
285                         }
286                         /* Empty stream.  No lookup table entry is needed. */
287                         lte = NULL;
288                 } else {
289                         if (type == AT_REPARSE_POINT && data_size < 8) {
290                                 ERROR("`%s': reparse point buffer too small",
291                                       path);
292                                 ret = WIMLIB_ERR_NTFS_3G;
293                                 goto out_put_actx;
294                         }
295                         /* Checksum the stream. */
296                         ret = ntfs_attr_sha1sum(ni, actx->attr, attr_hash,
297                                                 type == AT_REPARSE_POINT, &reparse_tag);
298                         if (ret != 0)
299                                 goto out_put_actx;
300
301                         /* Make a lookup table entry for the stream, or use an existing
302                          * one if there's already an identical stream. */
303                         lte = __lookup_resource(lookup_table, attr_hash);
304                         ret = WIMLIB_ERR_NOMEM;
305                         if (lte) {
306                                 lte->refcnt++;
307                         } else {
308                                 ntfs_loc = CALLOC(1, sizeof(*ntfs_loc));
309                                 if (!ntfs_loc)
310                                         goto out_put_actx;
311                                 ntfs_loc->ntfs_vol_p = ntfs_vol_p;
312                                 ntfs_loc->path_utf8 = MALLOC(path_len + 1);
313                                 if (!ntfs_loc->path_utf8)
314                                         goto out_free_ntfs_loc;
315                                 memcpy(ntfs_loc->path_utf8, path, path_len + 1);
316                                 if (name_length) {
317                                         ntfs_loc->stream_name_utf16 = MALLOC(name_length * 2);
318                                         if (!ntfs_loc->stream_name_utf16)
319                                                 goto out_free_ntfs_loc;
320                                         memcpy(ntfs_loc->stream_name_utf16,
321                                                attr_record_name(actx->attr),
322                                                actx->attr->name_length * 2);
323                                         ntfs_loc->stream_name_utf16_num_chars = name_length;
324                                 }
325
326                                 lte = new_lookup_table_entry();
327                                 if (!lte)
328                                         goto out_free_ntfs_loc;
329                                 lte->ntfs_loc = ntfs_loc;
330                                 lte->resource_location = RESOURCE_IN_NTFS_VOLUME;
331                                 if (type == AT_REPARSE_POINT) {
332                                         dentry->d_inode->i_reparse_tag = reparse_tag;
333                                         ntfs_loc->is_reparse_point = true;
334                                         lte->resource_entry.original_size = data_size - 8;
335                                         lte->resource_entry.size = data_size - 8;
336                                 } else {
337                                         ntfs_loc->is_reparse_point = false;
338                                         lte->resource_entry.original_size = data_size;
339                                         lte->resource_entry.size = data_size;
340                                 }
341                                 ntfs_loc = NULL;
342                                 DEBUG("Add resource for `%s' (size = %"PRIu64")",
343                                       dentry->file_name_utf8,
344                                       lte->resource_entry.original_size);
345                                 copy_hash(lte->hash, attr_hash);
346                                 lookup_table_insert(lookup_table, lte);
347                         }
348                 }
349                 if (name_length == 0) {
350                         /* Unnamed data stream.  Put the reference to it in the
351                          * dentry's inode. */
352                 #if 0
353                         if (dentry->d_inode->i_lte) {
354                                 ERROR("Found two un-named data streams for "
355                                       "`%s'", path);
356                                 ret = WIMLIB_ERR_NTFS_3G;
357                                 goto out_free_lte;
358                         }
359                         dentry->d_inode->i_lte = lte;
360                 #else
361                         if (dentry->d_inode->i_lte) {
362                                 WARNING("Found two un-named data streams for "
363                                         "`%s'", path);
364                                 free_lookup_table_entry(lte);
365                         } else {
366                                 dentry->d_inode->i_lte = lte;
367                         }
368                 #endif
369                 } else {
370                         /* Named data stream.  Put the reference to it in the
371                          * alternate data stream entries */
372                         struct wim_ads_entry *new_ads_entry;
373                         size_t stream_name_utf8_len;
374
375                         ret = utf16_to_utf8((const char*)attr_record_name(actx->attr),
376                                             name_length * 2,
377                                             &stream_name_utf8,
378                                             &stream_name_utf8_len);
379                         if (ret != 0)
380                                 goto out_free_lte;
381                         new_ads_entry = inode_add_ads(dentry->d_inode, stream_name_utf8);
382                         FREE(stream_name_utf8);
383                         if (!new_ads_entry)
384                                 goto out_free_lte;
385
386                         wimlib_assert(new_ads_entry->stream_name_len == name_length * 2);
387
388                         new_ads_entry->lte = lte;
389                 }
390         }
391         ret = 0;
392         goto out_put_actx;
393 out_free_lte:
394         free_lookup_table_entry(lte);
395 out_free_ntfs_loc:
396         if (ntfs_loc) {
397                 FREE(ntfs_loc->path_utf8);
398                 FREE(ntfs_loc->stream_name_utf16);
399                 FREE(ntfs_loc);
400         }
401 out_put_actx:
402         ntfs_attr_put_search_ctx(actx);
403         if (ret == 0)
404                 DEBUG2("Successfully captured NTFS streams from `%s'", path);
405         else
406                 ERROR("Failed to capture NTFS streams from `%s", path);
407         return ret;
408 }
409
410 /* Red-black tree that maps NTFS inode numbers to DOS names */
411 struct dos_name_map {
412         struct rb_root rb_root;
413 };
414
415 struct dos_name_node {
416         struct rb_node rb_node;
417         char dos_name[24];
418         int name_len_bytes;
419         u64 ntfs_ino;
420 };
421
422 /* Inserts a new DOS name into the map */
423 static int insert_dos_name(struct dos_name_map *map,
424                            const ntfschar *dos_name, int name_len,
425                            u64 ntfs_ino)
426 {
427         struct dos_name_node *new_node;
428         struct rb_node **p;
429         struct rb_root *root;
430         struct rb_node *rb_parent;
431
432         DEBUG("DOS name_len = %d", name_len);
433         new_node = MALLOC(sizeof(struct dos_name_node));
434         if (!new_node)
435                 return -1;
436
437         /* DOS names are supposed to be 12 characters max (that's 24 bytes,
438          * assuming 2-byte ntfs characters) */
439         wimlib_assert(name_len * sizeof(ntfschar) <= sizeof(new_node->dos_name));
440
441         /* Initialize the DOS name, DOS name length, and NTFS inode number of
442          * the red-black tree node */
443         memcpy(new_node->dos_name, dos_name, name_len * sizeof(ntfschar));
444         new_node->name_len_bytes = name_len * sizeof(ntfschar);
445         new_node->ntfs_ino = ntfs_ino;
446
447         /* Insert the red-black tree node */
448         root = &map->rb_root;
449         p = &root->rb_node;
450         rb_parent = NULL;
451         while (*p) {
452                 struct dos_name_node *this;
453
454                 this = container_of(*p, struct dos_name_node, rb_node);
455                 rb_parent = *p;
456                 if (new_node->ntfs_ino < this->ntfs_ino)
457                         p = &((*p)->rb_left);
458                 else if (new_node->ntfs_ino > this->ntfs_ino)
459                         p = &((*p)->rb_right);
460                 else {
461                         /* This should be impossible since a NTFS inode cannot
462                          * have multiple DOS names, and we only should get each
463                          * DOS name entry once from the ntfs_readdir() calls. */
464                         ERROR("NTFS inode %"PRIu64" has multiple DOS names",
465                               ntfs_ino);
466                         return -1;
467                 }
468         }
469         rb_link_node(&new_node->rb_node, rb_parent, p);
470         rb_insert_color(&new_node->rb_node, root);
471         DEBUG("Inserted DOS name for inode %"PRIu64, ntfs_ino);
472         return 0;
473 }
474
475 /* Returns a structure that contains the DOS name and its length for a NTFS
476  * inode, or NULL if the inode has no DOS name. */
477 static struct dos_name_node *
478 lookup_dos_name(const struct dos_name_map *map, u64 ntfs_ino)
479 {
480         struct rb_node *node = map->rb_root.rb_node;
481         while (node) {
482                 struct dos_name_node *this;
483                 this = container_of(node, struct dos_name_node, rb_node);
484                 if (ntfs_ino < this->ntfs_ino)
485                         node = node->rb_left;
486                 else if (ntfs_ino > this->ntfs_ino)
487                         node = node->rb_right;
488                 else
489                         return this;
490         }
491         return NULL;
492 }
493
494 static int set_dentry_dos_name(struct wim_dentry *dentry, void *arg)
495 {
496         const struct dos_name_map *map = arg;
497         const struct dos_name_node *node;
498
499         if (dentry->is_win32_name) {
500                 node = lookup_dos_name(map, dentry->d_inode->i_ino);
501                 if (node) {
502                         dentry->short_name = MALLOC(node->name_len_bytes);
503                         if (!dentry->short_name)
504                                 return WIMLIB_ERR_NOMEM;
505                         memcpy(dentry->short_name, node->dos_name,
506                                node->name_len_bytes);
507                         dentry->short_name_len = node->name_len_bytes;
508                         DEBUG("Assigned DOS name to ino %"PRIu64,
509                               dentry->d_inode->i_ino);
510                 } else {
511                         WARNING("NTFS inode %"PRIu64" has Win32 name with no "
512                                 "corresponding DOS name",
513                                 dentry->d_inode->i_ino);
514                 }
515         }
516         return 0;
517 }
518
519 static void free_dos_name_tree(struct rb_node *node) {
520         if (node) {
521                 free_dos_name_tree(node->rb_left);
522                 free_dos_name_tree(node->rb_right);
523                 FREE(container_of(node, struct dos_name_node, rb_node));
524         }
525 }
526
527 static void destroy_dos_name_map(struct dos_name_map *map)
528 {
529         free_dos_name_tree(map->rb_root.rb_node);
530 }
531
532 struct readdir_ctx {
533         struct wim_dentry *parent;
534         ntfs_inode *dir_ni;
535         char *path;
536         size_t path_len;
537         struct wim_lookup_table *lookup_table;
538         struct sd_set *sd_set;
539         struct dos_name_map *dos_name_map;
540         const struct capture_config *config;
541         ntfs_volume **ntfs_vol_p;
542         int add_image_flags;
543         wimlib_progress_func_t progress_func;
544 };
545
546 static int
547 build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p, ntfs_inode *dir_ni,
548                                  ntfs_inode *ni, char path[], size_t path_len,
549                                  int name_type,
550                                  struct wim_lookup_table *lookup_table,
551                                  struct sd_set *sd_set,
552                                  const struct capture_config *config,
553                                  ntfs_volume **ntfs_vol_p,
554                                  int add_image_flags,
555                                  wimlib_progress_func_t progress_func);
556
557 static int wim_ntfs_capture_filldir(void *dirent, const ntfschar *name,
558                                     const int name_len, const int name_type,
559                                     const s64 pos, const MFT_REF mref,
560                                     const unsigned dt_type)
561 {
562         struct readdir_ctx *ctx;
563         size_t utf8_name_len;
564         char *utf8_name;
565         struct wim_dentry *child;
566         int ret;
567         size_t path_len;
568
569         ctx = dirent;
570         if (name_type & FILE_NAME_DOS) {
571                 /* If this is the entry for a DOS name, store it for later. */
572                 ret = insert_dos_name(ctx->dos_name_map, name,
573                                       name_len, mref & MFT_REF_MASK_CPU);
574
575                 /* Return now if an error occurred or if this is just a DOS name
576                  * and not a Win32+DOS name. */
577                 if (ret != 0 || name_type == FILE_NAME_DOS)
578                         return ret;
579         }
580         ret = utf16_to_utf8((const char*)name, name_len * 2,
581                             &utf8_name, &utf8_name_len);
582         if (ret != 0)
583                 return -1;
584
585         if (utf8_name[0] == '.' &&
586              (utf8_name[1] == '\0' ||
587               (utf8_name[1] == '.' && utf8_name[2] == '\0'))) {
588                 /* . or .. entries
589                  *
590                  * note: name_type is POSIX for these, so DOS names will not
591                  * have been inserted for them.  */
592                 ret = 0;
593                 goto out_free_utf8_name;
594         }
595
596         /* Open the inode for this directory entry and recursively capture the
597          * directory tree rooted at it */
598         ntfs_inode *ni = ntfs_inode_open(ctx->dir_ni->vol, mref);
599         if (!ni) {
600                 ERROR_WITH_ERRNO("Failed to open NTFS inode");
601                 goto out_free_utf8_name;
602         }
603         path_len = ctx->path_len;
604         if (path_len != 1)
605                 ctx->path[path_len++] = '/';
606         memcpy(ctx->path + path_len, utf8_name, utf8_name_len + 1);
607         path_len += utf8_name_len;
608         child = NULL;
609         ret = build_dentry_tree_ntfs_recursive(&child, ctx->dir_ni,
610                                                ni, ctx->path, path_len, name_type,
611                                                ctx->lookup_table, ctx->sd_set,
612                                                ctx->config, ctx->ntfs_vol_p,
613                                                ctx->add_image_flags,
614                                                ctx->progress_func);
615         if (child)
616                 dentry_add_child(ctx->parent, child);
617         ntfs_inode_close(ni);
618 out_free_utf8_name:
619         FREE(utf8_name);
620         return ret;
621 }
622
623 /* Recursively build a WIM dentry tree corresponding to a NTFS volume.
624  * At the same time, update the WIM lookup table with lookup table entries for
625  * the NTFS streams, and build an array of security descriptors.
626  */
627 static int build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p,
628                                             ntfs_inode *dir_ni,
629                                             ntfs_inode *ni,
630                                             char path[],
631                                             size_t path_len,
632                                             int name_type,
633                                             struct wim_lookup_table *lookup_table,
634                                             struct sd_set *sd_set,
635                                             const struct capture_config *config,
636                                             ntfs_volume **ntfs_vol_p,
637                                             int add_image_flags,
638                                             wimlib_progress_func_t progress_func)
639 {
640         u32 attributes;
641         int ret;
642         struct wim_dentry *root;
643
644         if (exclude_path(path, config, false)) {
645                 /* Exclude a file or directory tree based on the capture
646                  * configuration file */
647                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
648                     && progress_func)
649                 {
650                         union wimlib_progress_info info;
651                         info.scan.cur_path = path;
652                         info.scan.excluded = true;
653                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
654                 }
655                 *root_p = NULL;
656                 return 0;
657         }
658
659         /* Get file attributes */
660         struct SECURITY_CONTEXT ctx;
661         memset(&ctx, 0, sizeof(ctx));
662         ctx.vol = ni->vol;
663         ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ATTRIB,
664                                          ni, dir_ni, (char *)&attributes,
665                                          sizeof(u32));
666         if (ret != 4) {
667                 ERROR_WITH_ERRNO("Failed to get NTFS attributes from `%s'",
668                                  path);
669                 return WIMLIB_ERR_NTFS_3G;
670         }
671
672         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
673             && progress_func)
674         {
675                 union wimlib_progress_info info;
676                 info.scan.cur_path = path;
677                 info.scan.excluded = false;
678                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
679         }
680
681         /* Create the new WIM dentry */
682         root = new_dentry_with_timeless_inode(path_basename(path));
683         if (!root) {
684                 if (errno == EILSEQ)
685                         return WIMLIB_ERR_INVALID_UTF8_STRING;
686                 else if (errno == ENOMEM)
687                         return WIMLIB_ERR_NOMEM;
688                 else
689                         return WIMLIB_ERR_ICONV_NOT_AVAILABLE;
690         }
691         *root_p = root;
692
693         if (name_type & FILE_NAME_WIN32) /* Win32 or Win32+DOS name */
694                 root->is_win32_name = 1;
695         root->d_inode->i_creation_time    = le64_to_cpu(ni->creation_time);
696         root->d_inode->i_last_write_time  = le64_to_cpu(ni->last_data_change_time);
697         root->d_inode->i_last_access_time = le64_to_cpu(ni->last_access_time);
698         root->d_inode->i_attributes       = le32_to_cpu(attributes);
699         root->d_inode->i_ino              = ni->mft_no;
700         root->d_inode->i_resolved         = 1;
701
702         if (attributes & FILE_ATTR_REPARSE_POINT) {
703                 /* Junction point, symbolic link, or other reparse point */
704                 ret = capture_ntfs_streams(root, ni, path, path_len,
705                                            lookup_table, ntfs_vol_p,
706                                            AT_REPARSE_POINT);
707         } else if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) {
708
709                 /* Normal directory */
710                 s64 pos = 0;
711                 struct dos_name_map dos_name_map = { .rb_root = {.rb_node = NULL} };
712                 struct readdir_ctx ctx = {
713                         .parent          = root,
714                         .dir_ni          = ni,
715                         .path            = path,
716                         .path_len        = path_len,
717                         .lookup_table    = lookup_table,
718                         .sd_set          = sd_set,
719                         .dos_name_map    = &dos_name_map,
720                         .config          = config,
721                         .ntfs_vol_p      = ntfs_vol_p,
722                         .add_image_flags = add_image_flags,
723                         .progress_func   = progress_func,
724                 };
725                 ret = ntfs_readdir(ni, &pos, &ctx, wim_ntfs_capture_filldir);
726                 if (ret) {
727                         ERROR_WITH_ERRNO("ntfs_readdir()");
728                         ret = WIMLIB_ERR_NTFS_3G;
729                 } else {
730                         ret = for_dentry_child(root, set_dentry_dos_name,
731                                                &dos_name_map);
732                 }
733                 destroy_dos_name_map(&dos_name_map);
734         } else {
735                 /* Normal file */
736                 ret = capture_ntfs_streams(root, ni, path, path_len,
737                                            lookup_table, ntfs_vol_p,
738                                            AT_DATA);
739         }
740         if (ret != 0)
741                 return ret;
742
743         /* Get security descriptor */
744         char _sd[1];
745         char *sd = _sd;
746         errno = 0;
747         ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
748                                          ni, dir_ni, sd,
749                                          sizeof(sd));
750         if (ret > sizeof(sd)) {
751                 sd = alloca(ret);
752                 ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
753                                                  ni, dir_ni, sd, ret);
754         }
755         if (ret > 0) {
756                 root->d_inode->i_security_id = sd_set_add_sd(sd_set, sd, ret);
757                 if (root->d_inode->i_security_id == -1) {
758                         ERROR("Out of memory");
759                         return WIMLIB_ERR_NOMEM;
760                 }
761                 DEBUG("Added security ID = %u for `%s'",
762                       root->d_inode->i_security_id, path);
763                 ret = 0;
764         } else if (ret < 0) {
765                 ERROR_WITH_ERRNO("Failed to get security information from "
766                                  "`%s'", path);
767                 ret = WIMLIB_ERR_NTFS_3G;
768         } else {
769                 root->d_inode->i_security_id = -1;
770                 DEBUG("No security ID for `%s'", path);
771         }
772         return ret;
773 }
774
775 int build_dentry_tree_ntfs(struct wim_dentry **root_p,
776                            const char *device,
777                            struct wim_lookup_table *lookup_table,
778                            struct wim_security_data *sd,
779                            const struct capture_config *config,
780                            int add_image_flags,
781                            wimlib_progress_func_t progress_func,
782                            void *extra_arg)
783 {
784         ntfs_volume *vol;
785         ntfs_inode *root_ni;
786         int ret;
787         struct sd_set sd_set = {
788                 .sd = sd,
789                 .rb_root = {NULL},
790         };
791         ntfs_volume **ntfs_vol_p = extra_arg;
792
793         DEBUG("Mounting NTFS volume `%s' read-only", device);
794
795 #ifdef HAVE_NTFS_MNT_RDONLY
796         /* NTFS-3g 2013 */
797         vol = ntfs_mount(device, NTFS_MNT_RDONLY);
798 #else
799         /* NTFS-3g 2011, 2012 */
800         vol = ntfs_mount(device, MS_RDONLY);
801 #endif
802         if (!vol) {
803                 ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s' read-only",
804                                  device);
805                 return WIMLIB_ERR_NTFS_3G;
806         }
807         ntfs_open_secure(vol);
808
809         /* We don't want to capture the special NTFS files such as $Bitmap.  Not
810          * to be confused with "hidden" or "system" files which are real files
811          * that we do need to capture.  */
812         NVolClearShowSysFiles(vol);
813
814         DEBUG("Opening root NTFS dentry");
815         root_ni = ntfs_inode_open(vol, FILE_root);
816         if (!root_ni) {
817                 ERROR_WITH_ERRNO("Failed to open root inode of NTFS volume "
818                                  "`%s'", device);
819                 ret = WIMLIB_ERR_NTFS_3G;
820                 goto out;
821         }
822
823         /* Currently we assume that all the UTF-8 paths fit into this length and
824          * there is no check for overflow. */
825         char *path = MALLOC(32768);
826         if (!path) {
827                 ERROR("Could not allocate memory for NTFS pathname");
828                 ret = WIMLIB_ERR_NOMEM;
829                 goto out_cleanup;
830         }
831
832         path[0] = '/';
833         path[1] = '\0';
834         ret = build_dentry_tree_ntfs_recursive(root_p, NULL, root_ni, path, 1,
835                                                FILE_NAME_POSIX, lookup_table,
836                                                &sd_set,
837                                                config, ntfs_vol_p,
838                                                add_image_flags,
839                                                progress_func);
840 out_cleanup:
841         FREE(path);
842         ntfs_inode_close(root_ni);
843         destroy_sd_set(&sd_set);
844 out:
845         ntfs_index_ctx_put(vol->secure_xsii);
846         ntfs_index_ctx_put(vol->secure_xsdh);
847         ntfs_inode_close(vol->secure_ni);
848
849         if (ret) {
850                 if (ntfs_umount(vol, FALSE) != 0) {
851                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'",
852                                          device);
853                         if (ret == 0)
854                                 ret = WIMLIB_ERR_NTFS_3G;
855                 }
856         } else {
857                 /* We need to leave the NTFS volume mounted so that we can read
858                  * the NTFS files again when we are actually writing the WIM */
859                 *ntfs_vol_p = vol;
860         }
861         return ret;
862 }