Fix copyright notices
[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, 2013 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                 DEBUG("ReparseTag = %#x", *reparse_tag_ret);
226                 pos = 8;
227                 bytes_remaining -= 8;
228         }
229
230         sha1_init(&ctx);
231         while (bytes_remaining) {
232                 s64 to_read = min(bytes_remaining, sizeof(buf));
233                 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read)
234                         goto out_error;
235                 sha1_update(&ctx, buf, to_read);
236                 pos += to_read;
237                 bytes_remaining -= to_read;
238         }
239         sha1_final(md, &ctx);
240         ntfs_attr_close(na);
241         return 0;
242 out_error:
243         ERROR_WITH_ERRNO("Error reading NTFS attribute");
244         return WIMLIB_ERR_NTFS_3G;
245 }
246
247 /* Load the streams from a file or reparse point in the NTFS volume into the WIM
248  * lookup table */
249 static int capture_ntfs_streams(struct wim_dentry *dentry, ntfs_inode *ni,
250                                 char path[], size_t path_len,
251                                 struct wim_lookup_table *lookup_table,
252                                 ntfs_volume **ntfs_vol_p,
253                                 ATTR_TYPES type)
254 {
255         ntfs_attr_search_ctx *actx;
256         u8 attr_hash[SHA1_HASH_SIZE];
257         struct ntfs_location *ntfs_loc = NULL;
258         int ret = 0;
259         struct wim_lookup_table_entry *lte;
260
261         DEBUG2("Capturing NTFS data streams from `%s'", path);
262
263         /* Get context to search the streams of the NTFS file. */
264         actx = ntfs_attr_get_search_ctx(ni, NULL);
265         if (!actx) {
266                 ERROR_WITH_ERRNO("Cannot get NTFS attribute search "
267                                  "context");
268                 return WIMLIB_ERR_NTFS_3G;
269         }
270
271         /* Capture each data stream or reparse data stream. */
272         while (!ntfs_attr_lookup(type, NULL, 0,
273                                  CASE_SENSITIVE, 0, NULL, 0, actx))
274         {
275                 char *stream_name_utf8;
276                 u32 reparse_tag;
277                 u64 data_size = ntfs_get_attribute_value_length(actx->attr);
278                 u64 name_length = actx->attr->name_length;
279
280                 if (data_size == 0) {
281                         if (errno != 0) {
282                                 ERROR_WITH_ERRNO("Failed to get size of attribute of "
283                                                  "`%s'", path);
284                                 ret = WIMLIB_ERR_NTFS_3G;
285                                 goto out_put_actx;
286                         }
287                         /* Empty stream.  No lookup table entry is needed. */
288                         lte = NULL;
289                 } else {
290                         if (type == AT_REPARSE_POINT && data_size < 8) {
291                                 ERROR("`%s': reparse point buffer too small",
292                                       path);
293                                 ret = WIMLIB_ERR_NTFS_3G;
294                                 goto out_put_actx;
295                         }
296                         /* Checksum the stream. */
297                         ret = ntfs_attr_sha1sum(ni, actx->attr, attr_hash,
298                                                 type == AT_REPARSE_POINT, &reparse_tag);
299                         if (ret != 0)
300                                 goto out_put_actx;
301
302                         if (type == AT_REPARSE_POINT)
303                                 dentry->d_inode->i_reparse_tag = reparse_tag;
304
305                         /* Make a lookup table entry for the stream, or use an existing
306                          * one if there's already an identical stream. */
307                         lte = __lookup_resource(lookup_table, attr_hash);
308                         ret = WIMLIB_ERR_NOMEM;
309                         if (lte) {
310                                 lte->refcnt++;
311                         } else {
312                                 ntfs_loc = CALLOC(1, sizeof(*ntfs_loc));
313                                 if (!ntfs_loc)
314                                         goto out_put_actx;
315                                 ntfs_loc->ntfs_vol_p = ntfs_vol_p;
316                                 ntfs_loc->path_utf8 = MALLOC(path_len + 1);
317                                 if (!ntfs_loc->path_utf8)
318                                         goto out_free_ntfs_loc;
319                                 memcpy(ntfs_loc->path_utf8, path, path_len + 1);
320                                 if (name_length) {
321                                         ntfs_loc->stream_name_utf16 = MALLOC(name_length * 2);
322                                         if (!ntfs_loc->stream_name_utf16)
323                                                 goto out_free_ntfs_loc;
324                                         memcpy(ntfs_loc->stream_name_utf16,
325                                                attr_record_name(actx->attr),
326                                                actx->attr->name_length * 2);
327                                         ntfs_loc->stream_name_utf16_num_chars = name_length;
328                                 }
329
330                                 lte = new_lookup_table_entry();
331                                 if (!lte)
332                                         goto out_free_ntfs_loc;
333                                 lte->ntfs_loc = ntfs_loc;
334                                 lte->resource_location = RESOURCE_IN_NTFS_VOLUME;
335                                 if (type == AT_REPARSE_POINT) {
336                                         ntfs_loc->is_reparse_point = true;
337                                         lte->resource_entry.original_size = data_size - 8;
338                                         lte->resource_entry.size = data_size - 8;
339                                 } else {
340                                         ntfs_loc->is_reparse_point = false;
341                                         lte->resource_entry.original_size = data_size;
342                                         lte->resource_entry.size = data_size;
343                                 }
344                                 ntfs_loc = NULL;
345                                 DEBUG("Add resource for `%s' (size = %"PRIu64")",
346                                       dentry->file_name_utf8,
347                                       lte->resource_entry.original_size);
348                                 copy_hash(lte->hash, attr_hash);
349                                 lookup_table_insert(lookup_table, lte);
350                         }
351                 }
352                 if (name_length == 0) {
353                         /* Unnamed data stream.  Put the reference to it in the
354                          * dentry's inode. */
355                 #if 0
356                         if (dentry->d_inode->i_lte) {
357                                 ERROR("Found two un-named data streams for "
358                                       "`%s'", path);
359                                 ret = WIMLIB_ERR_NTFS_3G;
360                                 goto out_free_lte;
361                         }
362                         dentry->d_inode->i_lte = lte;
363                 #else
364                         if (dentry->d_inode->i_lte) {
365                                 WARNING("Found two un-named data streams for "
366                                         "`%s'", path);
367                                 free_lookup_table_entry(lte);
368                         } else {
369                                 dentry->d_inode->i_lte = lte;
370                         }
371                 #endif
372                 } else {
373                         /* Named data stream.  Put the reference to it in the
374                          * alternate data stream entries */
375                         struct wim_ads_entry *new_ads_entry;
376                         size_t stream_name_utf8_len;
377
378                         ret = utf16_to_utf8((const char*)attr_record_name(actx->attr),
379                                             name_length * 2,
380                                             &stream_name_utf8,
381                                             &stream_name_utf8_len);
382                         if (ret != 0)
383                                 goto out_free_lte;
384                         new_ads_entry = inode_add_ads(dentry->d_inode, stream_name_utf8);
385                         FREE(stream_name_utf8);
386                         if (!new_ads_entry)
387                                 goto out_free_lte;
388
389                         wimlib_assert(new_ads_entry->stream_name_len == name_length * 2);
390
391                         new_ads_entry->lte = lte;
392                 }
393         }
394         ret = 0;
395         goto out_put_actx;
396 out_free_lte:
397         free_lookup_table_entry(lte);
398 out_free_ntfs_loc:
399         if (ntfs_loc) {
400                 FREE(ntfs_loc->path_utf8);
401                 FREE(ntfs_loc->stream_name_utf16);
402                 FREE(ntfs_loc);
403         }
404 out_put_actx:
405         ntfs_attr_put_search_ctx(actx);
406         if (ret == 0)
407                 DEBUG2("Successfully captured NTFS streams from `%s'", path);
408         else
409                 ERROR("Failed to capture NTFS streams from `%s", path);
410         return ret;
411 }
412
413 /* Red-black tree that maps NTFS inode numbers to DOS names */
414 struct dos_name_map {
415         struct rb_root rb_root;
416 };
417
418 struct dos_name_node {
419         struct rb_node rb_node;
420         char dos_name[24];
421         int name_len_bytes;
422         u64 ntfs_ino;
423 };
424
425 /* Inserts a new DOS name into the map */
426 static int insert_dos_name(struct dos_name_map *map,
427                            const ntfschar *dos_name, int name_len,
428                            u64 ntfs_ino)
429 {
430         struct dos_name_node *new_node;
431         struct rb_node **p;
432         struct rb_root *root;
433         struct rb_node *rb_parent;
434
435         DEBUG("DOS name_len = %d", name_len);
436         new_node = MALLOC(sizeof(struct dos_name_node));
437         if (!new_node)
438                 return -1;
439
440         /* DOS names are supposed to be 12 characters max (that's 24 bytes,
441          * assuming 2-byte ntfs characters) */
442         wimlib_assert(name_len * sizeof(ntfschar) <= sizeof(new_node->dos_name));
443
444         /* Initialize the DOS name, DOS name length, and NTFS inode number of
445          * the red-black tree node */
446         memcpy(new_node->dos_name, dos_name, name_len * sizeof(ntfschar));
447         new_node->name_len_bytes = name_len * sizeof(ntfschar);
448         new_node->ntfs_ino = ntfs_ino;
449
450         /* Insert the red-black tree node */
451         root = &map->rb_root;
452         p = &root->rb_node;
453         rb_parent = NULL;
454         while (*p) {
455                 struct dos_name_node *this;
456
457                 this = container_of(*p, struct dos_name_node, rb_node);
458                 rb_parent = *p;
459                 if (new_node->ntfs_ino < this->ntfs_ino)
460                         p = &((*p)->rb_left);
461                 else if (new_node->ntfs_ino > this->ntfs_ino)
462                         p = &((*p)->rb_right);
463                 else {
464                         /* This should be impossible since a NTFS inode cannot
465                          * have multiple DOS names, and we only should get each
466                          * DOS name entry once from the ntfs_readdir() calls. */
467                         ERROR("NTFS inode %"PRIu64" has multiple DOS names",
468                               ntfs_ino);
469                         return -1;
470                 }
471         }
472         rb_link_node(&new_node->rb_node, rb_parent, p);
473         rb_insert_color(&new_node->rb_node, root);
474         DEBUG("Inserted DOS name for inode %"PRIu64, ntfs_ino);
475         return 0;
476 }
477
478 /* Returns a structure that contains the DOS name and its length for a NTFS
479  * inode, or NULL if the inode has no DOS name. */
480 static struct dos_name_node *
481 lookup_dos_name(const struct dos_name_map *map, u64 ntfs_ino)
482 {
483         struct rb_node *node = map->rb_root.rb_node;
484         while (node) {
485                 struct dos_name_node *this;
486                 this = container_of(node, struct dos_name_node, rb_node);
487                 if (ntfs_ino < this->ntfs_ino)
488                         node = node->rb_left;
489                 else if (ntfs_ino > this->ntfs_ino)
490                         node = node->rb_right;
491                 else
492                         return this;
493         }
494         return NULL;
495 }
496
497 static int set_dentry_dos_name(struct wim_dentry *dentry, void *arg)
498 {
499         const struct dos_name_map *map = arg;
500         const struct dos_name_node *node;
501
502         if (dentry->is_win32_name) {
503                 node = lookup_dos_name(map, dentry->d_inode->i_ino);
504                 if (node) {
505                         dentry->short_name = MALLOC(node->name_len_bytes);
506                         if (!dentry->short_name)
507                                 return WIMLIB_ERR_NOMEM;
508                         memcpy(dentry->short_name, node->dos_name,
509                                node->name_len_bytes);
510                         dentry->short_name_len = node->name_len_bytes;
511                         DEBUG("Assigned DOS name to ino %"PRIu64,
512                               dentry->d_inode->i_ino);
513                 } else {
514                         WARNING("NTFS inode %"PRIu64" has Win32 name with no "
515                                 "corresponding DOS name",
516                                 dentry->d_inode->i_ino);
517                 }
518         }
519         return 0;
520 }
521
522 static void free_dos_name_tree(struct rb_node *node) {
523         if (node) {
524                 free_dos_name_tree(node->rb_left);
525                 free_dos_name_tree(node->rb_right);
526                 FREE(container_of(node, struct dos_name_node, rb_node));
527         }
528 }
529
530 static void destroy_dos_name_map(struct dos_name_map *map)
531 {
532         free_dos_name_tree(map->rb_root.rb_node);
533 }
534
535 struct readdir_ctx {
536         struct wim_dentry *parent;
537         ntfs_inode *dir_ni;
538         char *path;
539         size_t path_len;
540         struct wim_lookup_table *lookup_table;
541         struct sd_set *sd_set;
542         struct dos_name_map *dos_name_map;
543         const struct capture_config *config;
544         ntfs_volume **ntfs_vol_p;
545         int add_image_flags;
546         wimlib_progress_func_t progress_func;
547 };
548
549 static int
550 build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p, ntfs_inode *dir_ni,
551                                  ntfs_inode *ni, char path[], size_t path_len,
552                                  int name_type,
553                                  struct wim_lookup_table *lookup_table,
554                                  struct sd_set *sd_set,
555                                  const struct capture_config *config,
556                                  ntfs_volume **ntfs_vol_p,
557                                  int add_image_flags,
558                                  wimlib_progress_func_t progress_func);
559
560 static int wim_ntfs_capture_filldir(void *dirent, const ntfschar *name,
561                                     const int name_len, const int name_type,
562                                     const s64 pos, const MFT_REF mref,
563                                     const unsigned dt_type)
564 {
565         struct readdir_ctx *ctx;
566         size_t utf8_name_len;
567         char *utf8_name;
568         struct wim_dentry *child;
569         int ret;
570         size_t path_len;
571
572         ctx = dirent;
573         if (name_type & FILE_NAME_DOS) {
574                 /* If this is the entry for a DOS name, store it for later. */
575                 ret = insert_dos_name(ctx->dos_name_map, name,
576                                       name_len, mref & MFT_REF_MASK_CPU);
577
578                 /* Return now if an error occurred or if this is just a DOS name
579                  * and not a Win32+DOS name. */
580                 if (ret != 0 || name_type == FILE_NAME_DOS)
581                         return ret;
582         }
583         ret = utf16_to_utf8((const char*)name, name_len * 2,
584                             &utf8_name, &utf8_name_len);
585         if (ret != 0)
586                 return -1;
587
588         if (utf8_name[0] == '.' &&
589              (utf8_name[1] == '\0' ||
590               (utf8_name[1] == '.' && utf8_name[2] == '\0'))) {
591                 /* . or .. entries
592                  *
593                  * note: name_type is POSIX for these, so DOS names will not
594                  * have been inserted for them.  */
595                 ret = 0;
596                 goto out_free_utf8_name;
597         }
598
599         /* Open the inode for this directory entry and recursively capture the
600          * directory tree rooted at it */
601         ntfs_inode *ni = ntfs_inode_open(ctx->dir_ni->vol, mref);
602         if (!ni) {
603                 ERROR_WITH_ERRNO("Failed to open NTFS inode");
604                 goto out_free_utf8_name;
605         }
606         path_len = ctx->path_len;
607         if (path_len != 1)
608                 ctx->path[path_len++] = '/';
609         memcpy(ctx->path + path_len, utf8_name, utf8_name_len + 1);
610         path_len += utf8_name_len;
611         child = NULL;
612         ret = build_dentry_tree_ntfs_recursive(&child, ctx->dir_ni,
613                                                ni, ctx->path, path_len, name_type,
614                                                ctx->lookup_table, ctx->sd_set,
615                                                ctx->config, ctx->ntfs_vol_p,
616                                                ctx->add_image_flags,
617                                                ctx->progress_func);
618         if (child)
619                 dentry_add_child(ctx->parent, child);
620         ntfs_inode_close(ni);
621 out_free_utf8_name:
622         FREE(utf8_name);
623         return ret;
624 }
625
626 /* Recursively build a WIM dentry tree corresponding to a NTFS volume.
627  * At the same time, update the WIM lookup table with lookup table entries for
628  * the NTFS streams, and build an array of security descriptors.
629  */
630 static int build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p,
631                                             ntfs_inode *dir_ni,
632                                             ntfs_inode *ni,
633                                             char path[],
634                                             size_t path_len,
635                                             int name_type,
636                                             struct wim_lookup_table *lookup_table,
637                                             struct sd_set *sd_set,
638                                             const struct capture_config *config,
639                                             ntfs_volume **ntfs_vol_p,
640                                             int add_image_flags,
641                                             wimlib_progress_func_t progress_func)
642 {
643         u32 attributes;
644         int ret;
645         struct wim_dentry *root;
646
647         if (exclude_path(path, config, false)) {
648                 /* Exclude a file or directory tree based on the capture
649                  * configuration file */
650                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
651                     && progress_func)
652                 {
653                         union wimlib_progress_info info;
654                         info.scan.cur_path = path;
655                         info.scan.excluded = true;
656                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
657                 }
658                 *root_p = NULL;
659                 return 0;
660         }
661
662         /* Get file attributes */
663         struct SECURITY_CONTEXT ctx;
664         memset(&ctx, 0, sizeof(ctx));
665         ctx.vol = ni->vol;
666         ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ATTRIB,
667                                          ni, dir_ni, (char *)&attributes,
668                                          sizeof(u32));
669         if (ret != 4) {
670                 ERROR_WITH_ERRNO("Failed to get NTFS attributes from `%s'",
671                                  path);
672                 return WIMLIB_ERR_NTFS_3G;
673         }
674
675         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
676             && progress_func)
677         {
678                 union wimlib_progress_info info;
679                 info.scan.cur_path = path;
680                 info.scan.excluded = false;
681                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
682         }
683
684         /* Create the new WIM dentry */
685         root = new_dentry_with_timeless_inode(path_basename(path));
686         if (!root) {
687                 if (errno == EILSEQ)
688                         return WIMLIB_ERR_INVALID_UTF8_STRING;
689                 else if (errno == ENOMEM)
690                         return WIMLIB_ERR_NOMEM;
691                 else
692                         return WIMLIB_ERR_ICONV_NOT_AVAILABLE;
693         }
694         *root_p = root;
695
696         if (name_type & FILE_NAME_WIN32) /* Win32 or Win32+DOS name */
697                 root->is_win32_name = 1;
698         root->d_inode->i_creation_time    = le64_to_cpu(ni->creation_time);
699         root->d_inode->i_last_write_time  = le64_to_cpu(ni->last_data_change_time);
700         root->d_inode->i_last_access_time = le64_to_cpu(ni->last_access_time);
701         root->d_inode->i_attributes       = le32_to_cpu(attributes);
702         root->d_inode->i_ino              = ni->mft_no;
703         root->d_inode->i_resolved         = 1;
704
705         if (attributes & FILE_ATTR_REPARSE_POINT) {
706                 /* Junction point, symbolic link, or other reparse point */
707                 ret = capture_ntfs_streams(root, ni, path, path_len,
708                                            lookup_table, ntfs_vol_p,
709                                            AT_REPARSE_POINT);
710         } else if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) {
711
712                 /* Normal directory */
713                 s64 pos = 0;
714                 struct dos_name_map dos_name_map = { .rb_root = {.rb_node = NULL} };
715                 struct readdir_ctx ctx = {
716                         .parent          = root,
717                         .dir_ni          = ni,
718                         .path            = path,
719                         .path_len        = path_len,
720                         .lookup_table    = lookup_table,
721                         .sd_set          = sd_set,
722                         .dos_name_map    = &dos_name_map,
723                         .config          = config,
724                         .ntfs_vol_p      = ntfs_vol_p,
725                         .add_image_flags = add_image_flags,
726                         .progress_func   = progress_func,
727                 };
728                 ret = ntfs_readdir(ni, &pos, &ctx, wim_ntfs_capture_filldir);
729                 if (ret) {
730                         ERROR_WITH_ERRNO("ntfs_readdir()");
731                         ret = WIMLIB_ERR_NTFS_3G;
732                 } else {
733                         ret = for_dentry_child(root, set_dentry_dos_name,
734                                                &dos_name_map);
735                 }
736                 destroy_dos_name_map(&dos_name_map);
737         } else {
738                 /* Normal file */
739                 ret = capture_ntfs_streams(root, ni, path, path_len,
740                                            lookup_table, ntfs_vol_p,
741                                            AT_DATA);
742         }
743         if (ret != 0)
744                 return ret;
745
746         /* Get security descriptor */
747         char _sd[1];
748         char *sd = _sd;
749         errno = 0;
750         ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
751                                          ni, dir_ni, sd,
752                                          sizeof(sd));
753         if (ret > sizeof(sd)) {
754                 sd = alloca(ret);
755                 ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
756                                                  ni, dir_ni, sd, ret);
757         }
758         if (ret > 0) {
759                 root->d_inode->i_security_id = sd_set_add_sd(sd_set, sd, ret);
760                 if (root->d_inode->i_security_id == -1) {
761                         ERROR("Out of memory");
762                         return WIMLIB_ERR_NOMEM;
763                 }
764                 DEBUG("Added security ID = %u for `%s'",
765                       root->d_inode->i_security_id, path);
766                 ret = 0;
767         } else if (ret < 0) {
768                 ERROR_WITH_ERRNO("Failed to get security information from "
769                                  "`%s'", path);
770                 ret = WIMLIB_ERR_NTFS_3G;
771         } else {
772                 root->d_inode->i_security_id = -1;
773                 DEBUG("No security ID for `%s'", path);
774         }
775         return ret;
776 }
777
778 int build_dentry_tree_ntfs(struct wim_dentry **root_p,
779                            const char *device,
780                            struct wim_lookup_table *lookup_table,
781                            struct wim_security_data *sd,
782                            const struct capture_config *config,
783                            int add_image_flags,
784                            wimlib_progress_func_t progress_func,
785                            void *extra_arg)
786 {
787         ntfs_volume *vol;
788         ntfs_inode *root_ni;
789         int ret;
790         struct sd_set sd_set = {
791                 .sd = sd,
792                 .rb_root = {NULL},
793         };
794         ntfs_volume **ntfs_vol_p = extra_arg;
795
796         DEBUG("Mounting NTFS volume `%s' read-only", device);
797
798 #ifdef HAVE_NTFS_MNT_RDONLY
799         /* NTFS-3g 2013 */
800         vol = ntfs_mount(device, NTFS_MNT_RDONLY);
801 #else
802         /* NTFS-3g 2011, 2012 */
803         vol = ntfs_mount(device, MS_RDONLY);
804 #endif
805         if (!vol) {
806                 ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s' read-only",
807                                  device);
808                 return WIMLIB_ERR_NTFS_3G;
809         }
810         ntfs_open_secure(vol);
811
812         /* We don't want to capture the special NTFS files such as $Bitmap.  Not
813          * to be confused with "hidden" or "system" files which are real files
814          * that we do need to capture.  */
815         NVolClearShowSysFiles(vol);
816
817         DEBUG("Opening root NTFS dentry");
818         root_ni = ntfs_inode_open(vol, FILE_root);
819         if (!root_ni) {
820                 ERROR_WITH_ERRNO("Failed to open root inode of NTFS volume "
821                                  "`%s'", device);
822                 ret = WIMLIB_ERR_NTFS_3G;
823                 goto out;
824         }
825
826         /* Currently we assume that all the UTF-8 paths fit into this length and
827          * there is no check for overflow. */
828         char *path = MALLOC(32768);
829         if (!path) {
830                 ERROR("Could not allocate memory for NTFS pathname");
831                 ret = WIMLIB_ERR_NOMEM;
832                 goto out_cleanup;
833         }
834
835         path[0] = '/';
836         path[1] = '\0';
837         ret = build_dentry_tree_ntfs_recursive(root_p, NULL, root_ni, path, 1,
838                                                FILE_NAME_POSIX, lookup_table,
839                                                &sd_set,
840                                                config, ntfs_vol_p,
841                                                add_image_flags,
842                                                progress_func);
843 out_cleanup:
844         FREE(path);
845         ntfs_inode_close(root_ni);
846         destroy_sd_set(&sd_set);
847 out:
848         ntfs_index_ctx_put(vol->secure_xsii);
849         ntfs_index_ctx_put(vol->secure_xsdh);
850         ntfs_inode_close(vol->secure_ni);
851
852         if (ret) {
853                 if (ntfs_umount(vol, FALSE) != 0) {
854                         ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'",
855                                          device);
856                         if (ret == 0)
857                                 ret = WIMLIB_ERR_NTFS_3G;
858                 }
859         } else {
860                 /* We need to leave the NTFS volume mounted so that we can read
861                  * the NTFS files again when we are actually writing the WIM */
862                 *ntfs_vol_p = vol;
863         }
864         return ret;
865 }