]> wimlib.net Git - wimlib/blob - src/ntfs-3g_capture.c
ca8d1b2ffe4a335002569c0a6de780a52d13e9f2
[wimlib] / src / ntfs-3g_capture.c
1 /*
2  * ntfs-3g_capture.c
3  *
4  * Capture a WIM image directly from an NTFS volume using libntfs-3g.  We capture
5  * everything we can, including security data and alternate data streams.
6  */
7
8 /*
9  * Copyright (C) 2012-2016 Eric Biggers
10  *
11  * This file is free software; you can redistribute it and/or modify it under
12  * the terms of the GNU Lesser General Public License as published by the Free
13  * Software Foundation; either version 3 of the License, or (at your option) any
14  * later version.
15  *
16  * This file is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this file; if not, see http://www.gnu.org/licenses/.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #ifdef WITH_NTFS_3G
30
31 #include <errno.h>
32
33 #include <ntfs-3g/attrib.h>
34 #include <ntfs-3g/compat.h> /* for ENODATA, if needed */
35 #include <ntfs-3g/object_id.h>
36 #include <ntfs-3g/reparse.h>
37 #include <ntfs-3g/security.h>
38 #include <ntfs-3g/volume.h>
39
40 #include "wimlib/alloca.h"
41 #include "wimlib/assert.h"
42 #include "wimlib/blob_table.h"
43 #include "wimlib/dentry.h"
44 #include "wimlib/encoding.h"
45 #include "wimlib/endianness.h"
46 #include "wimlib/error.h"
47 #include "wimlib/ntfs_3g.h"
48 #include "wimlib/object_id.h"
49 #include "wimlib/paths.h"
50 #include "wimlib/reparse.h"
51 #include "wimlib/scan.h"
52 #include "wimlib/security.h"
53
54 /* NTFS-3G 2013 renamed MS_RDONLY to NTFS_MNT_RDONLY.  We can't check for the
55  * existence of NTFS_MNT_RDONLY at compilation time because it's an enum.  We
56  * also can't check for MS_RDONLY being missing because it's also a system
57  * constant.  So check if the NTFS-3G specific MS_IGNORE_HIBERFILE is defined;
58  * if yes, then we need to use the old MS_RDONLY.  */
59 #ifdef MS_IGNORE_HIBERFILE
60 #  define NTFS_MNT_RDONLY MS_RDONLY
61 #endif
62
63 /* A reference-counted NTFS volume than is automatically unmounted when the
64  * reference count reaches 0  */
65 struct ntfs_volume_wrapper {
66         ntfs_volume *vol;
67         size_t refcnt;
68         bool dedup_warned;
69 };
70
71 /* Description of where data is located in an NTFS volume  */
72 struct ntfs_location {
73         struct ntfs_volume_wrapper *volume;
74         u64 mft_no;
75         ATTR_TYPES attr_type;
76         u32 attr_name_nchars;
77         ntfschar *attr_name;
78         u64 sort_key;
79 };
80
81 static struct ntfs_volume_wrapper *
82 get_ntfs_volume(struct ntfs_volume_wrapper *volume)
83 {
84         volume->refcnt++;
85         return volume;
86 }
87
88 static void
89 put_ntfs_volume(struct ntfs_volume_wrapper *volume)
90 {
91         if (--volume->refcnt == 0) {
92                 ntfs_umount(volume->vol, FALSE);
93                 FREE(volume);
94         }
95 }
96
97 static inline const ntfschar *
98 attr_record_name(const ATTR_RECORD *record)
99 {
100         return (const ntfschar *)
101                 ((const u8 *)record + le16_to_cpu(record->name_offset));
102 }
103
104 static ntfs_attr *
105 open_ntfs_attr(ntfs_inode *ni, const struct ntfs_location *loc)
106 {
107         ntfs_attr *na;
108
109         na = ntfs_attr_open(ni, loc->attr_type, loc->attr_name,
110                             loc->attr_name_nchars);
111         if (!na) {
112                 ERROR_WITH_ERRNO("Failed to open attribute of NTFS inode %"PRIu64,
113                                  loc->mft_no);
114         }
115         return na;
116 }
117
118 int
119 read_ntfs_attribute_prefix(const struct blob_descriptor *blob, u64 size,
120                            const struct consume_chunk_callback *cb)
121 {
122         const struct ntfs_location *loc = blob->ntfs_loc;
123         ntfs_volume *vol = loc->volume->vol;
124         ntfs_inode *ni;
125         ntfs_attr *na;
126         s64 pos;
127         s64 bytes_remaining;
128         int ret;
129         u8 buf[BUFFER_SIZE];
130
131         ni = ntfs_inode_open(vol, loc->mft_no);
132         if (!ni) {
133                 ERROR_WITH_ERRNO("Failed to open NTFS inode %"PRIu64,
134                                  loc->mft_no);
135                 ret = WIMLIB_ERR_NTFS_3G;
136                 goto out;
137         }
138
139         na = open_ntfs_attr(ni, loc);
140         if (!na) {
141                 ret = WIMLIB_ERR_NTFS_3G;
142                 goto out_close_ntfs_inode;
143         }
144
145         pos = (loc->attr_type == AT_REPARSE_POINT) ? REPARSE_DATA_OFFSET : 0;
146         bytes_remaining = size;
147         while (bytes_remaining) {
148                 s64 to_read = min(bytes_remaining, sizeof(buf));
149                 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read) {
150                         ERROR_WITH_ERRNO("Error reading data from NTFS inode "
151                                          "%"PRIu64, loc->mft_no);
152                         ret = WIMLIB_ERR_NTFS_3G;
153                         goto out_close_ntfs_attr;
154                 }
155                 pos += to_read;
156                 bytes_remaining -= to_read;
157                 ret = consume_chunk(cb, buf, to_read);
158                 if (ret)
159                         goto out_close_ntfs_attr;
160         }
161         ret = 0;
162 out_close_ntfs_attr:
163         ntfs_attr_close(na);
164 out_close_ntfs_inode:
165         ntfs_inode_close(ni);
166 out:
167         return ret;
168 }
169
170 void
171 free_ntfs_location(struct ntfs_location *loc)
172 {
173         put_ntfs_volume(loc->volume);
174         if (loc->attr_name != AT_UNNAMED)
175                 FREE(loc->attr_name);
176         FREE(loc);
177 }
178
179 struct ntfs_location *
180 clone_ntfs_location(const struct ntfs_location *loc)
181 {
182         struct ntfs_location *new = memdup(loc, sizeof(*loc));
183         if (!new)
184                 goto err0;
185         if (loc->attr_name != AT_UNNAMED) {
186                 new->attr_name = utf16le_dup(loc->attr_name);
187                 if (!new->attr_name)
188                         goto err1;
189         }
190         new->volume = get_ntfs_volume(loc->volume);
191         return new;
192
193 err1:
194         FREE(new);
195 err0:
196         return NULL;
197 }
198
199 int
200 cmp_ntfs_locations(const struct ntfs_location *loc1,
201                    const struct ntfs_location *loc2)
202 {
203         return cmp_u64(loc1->sort_key, loc2->sort_key);
204 }
205
206 /* Read rptag and rpreserved from the NTFS inode and save them in the WIM inode.
207  */
208 static int
209 read_reparse_header(ntfs_inode *ni, struct wim_inode *inode)
210 {
211         struct {
212                 le32 rptag;
213                 le16 rpdatalen;
214                 le16 rpreserved;
215         } hdr;
216         s64 res;
217         ntfs_attr *na;
218
219         na = ntfs_attr_open(ni, AT_REPARSE_POINT, AT_UNNAMED, 0);
220         if (!na)
221                 return WIMLIB_ERR_NTFS_3G;
222
223         res = ntfs_attr_pread(na, 0, sizeof(hdr), &hdr);
224
225         ntfs_attr_close(na);
226
227         if (res != sizeof(hdr))
228                 return WIMLIB_ERR_NTFS_3G;
229
230         inode->i_reparse_tag = le32_to_cpu(hdr.rptag);
231         inode->i_rp_reserved = le16_to_cpu(hdr.rpreserved);
232         return 0;
233 }
234
235
236 static void
237 warn_special_reparse_points(const struct wim_inode *inode,
238                             const struct scan_params *params,
239                             struct ntfs_volume_wrapper *volume)
240 {
241         if (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_DEDUP &&
242             (params->add_flags & WIMLIB_ADD_FLAG_WINCONFIG) &&
243             !volume->dedup_warned)
244         {
245                 WARNING(
246           "Filesystem includes files deduplicated with Windows'\n"
247 "          Data Deduplication feature, which to properly restore\n"
248 "          would require that the chunk store in \"System Volume Information\"\n"
249 "          be included in the WIM image. By default \"System Volume Information\"\n"
250 "          is excluded, so you may want to use a custom capture configuration\n"
251 "          file which includes it.");
252                 volume->dedup_warned = true;
253         }
254 }
255
256 static int
257 attr_type_to_wimlib_stream_type(ATTR_TYPES type)
258 {
259         switch (type) {
260         case AT_DATA:
261                 return STREAM_TYPE_DATA;
262         case AT_REPARSE_POINT:
263                 return STREAM_TYPE_REPARSE_POINT;
264         default:
265                 wimlib_assert(0);
266                 return STREAM_TYPE_UNKNOWN;
267         }
268 }
269
270 /* When sorting blobs located in NTFS volumes for sequential reading, we sort
271  * first by starting LCN of the attribute if available, otherwise no sort order
272  * is defined.  This usually results in better sequential access to the volume.
273  */
274 static int
275 set_attr_sort_key(ntfs_inode *ni, struct ntfs_location *loc)
276 {
277         ntfs_attr *na;
278         runlist_element *rl;
279
280         na = open_ntfs_attr(ni, loc);
281         if (!na)
282                 return WIMLIB_ERR_NTFS_3G;
283
284         rl = ntfs_attr_find_vcn(na, 0);
285         if (rl && rl->lcn != LCN_HOLE)
286                 loc->sort_key = rl->lcn;
287         else
288                 loc->sort_key = 0;
289
290         ntfs_attr_close(na);
291         return 0;
292 }
293
294 /*
295  * Add a new stream to the specified inode, with duplicate checking.
296  *
297  * This works around a problem where NTFS-3G can list multiple unnamed data
298  * streams for a single file.  In this case we can only keep one.  We'll prefer
299  * one that is nonempty.
300  */
301 static int
302 add_stream(struct wim_inode *inode, const char *path, int stream_type,
303            const utf16lechar *stream_name, struct blob_descriptor **blob_p,
304            struct list_head *unhashed_blobs)
305 {
306         struct blob_descriptor *blob = *blob_p;
307         struct wim_inode_stream *strm;
308
309         strm = inode_get_stream(inode, stream_type, stream_name);
310         if (unlikely(strm)) {
311                 /* Stream already existed.  */
312                 if (!blob)
313                         return 0;
314                 if (stream_blob_resolved(strm)) {
315                         WARNING("\"%s\" has multiple nonempty streams "
316                                 "with the same type and name!  Only the first "
317                                 "will be saved.", path);
318                         return 0;
319                 }
320                 inode_replace_stream_blob(inode, strm, blob, NULL);
321         } else {
322                 strm = inode_add_stream(inode, stream_type, stream_name, blob);
323                 if (unlikely(!strm))
324                         return WIMLIB_ERR_NOMEM;
325         }
326         prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
327         *blob_p = NULL;
328         return 0;
329
330 }
331
332 /* Save information about an NTFS attribute (stream) to a WIM inode.  */
333 static int
334 scan_ntfs_attr(struct wim_inode *inode,
335                ntfs_inode *ni,
336                const char *path,
337                struct list_head *unhashed_blobs,
338                struct ntfs_volume_wrapper *volume,
339                ATTR_TYPES type,
340                const ATTR_RECORD *record)
341 {
342         u64 data_size = ntfs_get_attribute_value_length(record);
343         const u32 name_nchars = record->name_length;
344         struct blob_descriptor *blob = NULL;
345         utf16lechar *stream_name = (utf16lechar *)NO_STREAM_NAME;
346         int ret;
347
348         if (unlikely(name_nchars)) {
349                 /* Named stream  */
350                 stream_name = utf16le_dupz(attr_record_name(record),
351                                            name_nchars * sizeof(ntfschar));
352                 if (!stream_name) {
353                         ret = WIMLIB_ERR_NOMEM;
354                         goto out_cleanup;
355                 }
356         }
357
358         if (unlikely(type == AT_REPARSE_POINT)) {
359                 if (data_size < REPARSE_DATA_OFFSET) {
360                         ERROR("Reparse point attribute of \"%s\" "
361                               "is too short!", path);
362                         ret = WIMLIB_ERR_INVALID_REPARSE_DATA;
363                         goto out_cleanup;
364                 }
365                 data_size -= REPARSE_DATA_OFFSET;
366
367                 ret = read_reparse_header(ni, inode);
368                 if (ret) {
369                         ERROR_WITH_ERRNO("Error reading reparse point header "
370                                          "of \"%s\"", path);
371                         goto out_cleanup;
372                 }
373         }
374
375         /* If the stream is non-empty, set up a blob descriptor for it.  */
376         if (data_size != 0) {
377                 blob = new_blob_descriptor();
378                 if (unlikely(!blob)) {
379                         ret = WIMLIB_ERR_NOMEM;
380                         goto out_cleanup;
381                 }
382
383                 blob->ntfs_loc = MALLOC(sizeof(struct ntfs_location));
384                 if (unlikely(!blob->ntfs_loc)) {
385                         ret = WIMLIB_ERR_NOMEM;
386                         goto out_cleanup;
387                 }
388
389                 blob->blob_location = BLOB_IN_NTFS_VOLUME;
390                 blob->size = data_size;
391                 blob->ntfs_loc->volume = get_ntfs_volume(volume);
392                 blob->ntfs_loc->mft_no = ni->mft_no;
393                 blob->ntfs_loc->attr_type = type;
394
395                 if (unlikely(name_nchars)) {
396                         blob->ntfs_loc->attr_name_nchars = name_nchars;
397                         blob->ntfs_loc->attr_name = utf16le_dup(stream_name);
398                         if (!blob->ntfs_loc->attr_name) {
399                                 ret = WIMLIB_ERR_NOMEM;
400                                 goto out_cleanup;
401                         }
402                 } else {
403                         blob->ntfs_loc->attr_name_nchars = 0;
404                         blob->ntfs_loc->attr_name = AT_UNNAMED;
405                 }
406
407                 ret = set_attr_sort_key(ni, blob->ntfs_loc);
408                 if (ret)
409                         goto out_cleanup;
410         }
411
412         ret = add_stream(inode, path, attr_type_to_wimlib_stream_type(type),
413                          stream_name, &blob, unhashed_blobs);
414 out_cleanup:
415         free_blob_descriptor(blob);
416         if (stream_name != NO_STREAM_NAME)
417                 FREE(stream_name);
418         return ret;
419 }
420
421 /* Scan attributes of the specified type from a file in the NTFS volume  */
422 static int
423 scan_ntfs_attrs_with_type(struct wim_inode *inode,
424                           ntfs_inode *ni,
425                           const char *path,
426                           struct list_head *unhashed_blobs,
427                           struct ntfs_volume_wrapper *volume,
428                           ATTR_TYPES type)
429 {
430         ntfs_attr_search_ctx *actx;
431         int ret;
432
433         actx = ntfs_attr_get_search_ctx(ni, NULL);
434         if (!actx) {
435                 ERROR_WITH_ERRNO("Failed to get NTFS attribute search "
436                                  "context for \"%s\"", path);
437                 return WIMLIB_ERR_NTFS_3G;
438         }
439
440         while (!ntfs_attr_lookup(type, NULL, 0,
441                                  CASE_SENSITIVE, 0, NULL, 0, actx))
442         {
443                 ret = scan_ntfs_attr(inode,
444                                      ni,
445                                      path,
446                                      unhashed_blobs,
447                                      volume,
448                                      type,
449                                      actx->attr);
450                 if (ret)
451                         goto out_put_actx;
452         }
453         if (errno != ENOENT) {
454                 ERROR_WITH_ERRNO("Error listing NTFS attributes of \"%s\"", path);
455                 ret = WIMLIB_ERR_NTFS_3G;
456                 goto out_put_actx;
457         }
458         ret = 0;
459 out_put_actx:
460         ntfs_attr_put_search_ctx(actx);
461         return ret;
462 }
463
464 static noinline_for_stack int
465 load_object_id(ntfs_inode *ni, struct wim_inode *inode)
466 {
467         OBJECT_ID_ATTR attr;
468         int len;
469
470         len = ntfs_get_ntfs_object_id(ni, (char *)&attr, sizeof(attr));
471         if (likely(len == -ENODATA || len == 0))
472                 return 0;
473         if (len < 0)
474                 return WIMLIB_ERR_NTFS_3G;
475         if (!inode_set_object_id(inode, &attr, len))
476                 return WIMLIB_ERR_NOMEM;
477         return 0;
478 }
479
480 /* Load the security descriptor of an NTFS inode into the corresponding WIM
481  * inode and the WIM image's security descriptor set.  */
482 static noinline_for_stack int
483 get_security_descriptor(ntfs_inode *ni, struct wim_inode *inode,
484                         ntfs_volume *vol, struct wim_sd_set *sd_set)
485 {
486         struct SECURITY_CONTEXT scx = {.vol = vol};
487         char _buf[4096];
488         char *buf = _buf;
489         size_t avail_size = sizeof(_buf);
490         int ret;
491
492 retry:
493         ret = ntfs_get_ntfs_acl(&scx, ni, buf, avail_size);
494         if (unlikely(ret < 0)) {
495                 ret = WIMLIB_ERR_NTFS_3G;
496                 goto out;
497         }
498
499         if (unlikely(ret > avail_size)) {
500                 if (unlikely(buf != _buf))
501                         FREE(buf);
502                 buf = MALLOC(ret);
503                 if (!buf) {
504                         ret = WIMLIB_ERR_NOMEM;
505                         goto out;
506                 }
507                 avail_size = ret;
508                 goto retry;
509         }
510
511         if (likely(ret > 0)) {
512                 inode->i_security_id = sd_set_add_sd(sd_set, buf, ret);
513                 if (unlikely(inode->i_security_id < 0)) {
514                         ret = WIMLIB_ERR_NOMEM;
515                         goto out;
516                 }
517         }
518
519         ret = 0;
520 out:
521         if (unlikely(buf != _buf))
522                 FREE(buf);
523         return ret;
524 }
525
526 /* Binary tree that maps NTFS inode numbers to DOS names */
527 struct dos_name_map {
528         struct avl_tree_node *root;
529 };
530
531 struct dos_name_node {
532         struct avl_tree_node index_node;
533         char dos_name[24];
534         int name_nbytes;
535         u64 ntfs_ino;
536 };
537
538 #define DOS_NAME_NODE(avl_node) \
539         avl_tree_entry(avl_node, struct dos_name_node, index_node)
540
541 static int
542 _avl_cmp_by_ntfs_ino(const struct avl_tree_node *n1,
543                      const struct avl_tree_node *n2)
544 {
545         return cmp_u64(DOS_NAME_NODE(n1)->ntfs_ino,
546                        DOS_NAME_NODE(n2)->ntfs_ino);
547 }
548
549 /* Inserts a new DOS name into the map */
550 static int
551 insert_dos_name(struct dos_name_map *map, const ntfschar *dos_name,
552                 size_t name_nbytes, u64 ntfs_ino)
553 {
554         struct dos_name_node *new_node;
555
556         new_node = MALLOC(sizeof(struct dos_name_node));
557         if (!new_node)
558                 return WIMLIB_ERR_NOMEM;
559
560         /* DOS names are supposed to be 12 characters max (that's 24 bytes,
561          * assuming 2-byte ntfs characters) */
562         wimlib_assert(name_nbytes <= sizeof(new_node->dos_name));
563
564         /* Initialize the DOS name, DOS name length, and NTFS inode number of
565          * the search tree node */
566         memcpy(new_node->dos_name, dos_name, name_nbytes);
567         new_node->name_nbytes = name_nbytes;
568         new_node->ntfs_ino = ntfs_ino;
569
570         /* Insert the search tree node */
571         if (avl_tree_insert(&map->root, &new_node->index_node,
572                             _avl_cmp_by_ntfs_ino))
573         {
574                 /* This should be impossible since an NTFS inode cannot have
575                  * multiple DOS names, and we only should get each DOS name
576                  * entry once from the ntfs_readdir() calls. */
577                 WARNING("NTFS inode %"PRIu64" has multiple DOS names", ntfs_ino);
578                 FREE(new_node);
579         }
580         return 0;
581 }
582
583 /* Returns a structure that contains the DOS name and its length for an NTFS
584  * inode, or NULL if the inode has no DOS name. */
585 static struct dos_name_node *
586 lookup_dos_name(const struct dos_name_map *map, u64 ntfs_ino)
587 {
588         struct dos_name_node dummy;
589         struct avl_tree_node *res;
590
591         dummy.ntfs_ino = ntfs_ino;
592
593         res = avl_tree_lookup_node(map->root, &dummy.index_node,
594                                    _avl_cmp_by_ntfs_ino);
595         if (!res)
596                 return NULL;
597         return DOS_NAME_NODE(res);
598 }
599
600 static int
601 set_dentry_dos_name(struct wim_dentry *dentry, const struct dos_name_map *map)
602 {
603         const struct dos_name_node *node;
604
605         if (dentry->d_is_win32_name) {
606                 node = lookup_dos_name(map, dentry->d_inode->i_ino);
607                 if (node) {
608                         dentry->d_short_name = utf16le_dupz(node->dos_name,
609                                                             node->name_nbytes);
610                         if (!dentry->d_short_name)
611                                 return WIMLIB_ERR_NOMEM;
612                         dentry->d_short_name_nbytes = node->name_nbytes;
613                 } else {
614                         WARNING("NTFS inode %"PRIu64" has Win32 name with no "
615                                 "corresponding DOS name",
616                                 dentry->d_inode->i_ino);
617                 }
618         }
619         return 0;
620 }
621
622 static void
623 destroy_dos_name_map(struct dos_name_map *map)
624 {
625         struct dos_name_node *node;
626         avl_tree_for_each_in_postorder(node, map->root,
627                                        struct dos_name_node, index_node)
628                 FREE(node);
629 }
630
631 struct readdir_ctx {
632         struct wim_dentry *parent;
633         char *path;
634         size_t path_len;
635         struct dos_name_map dos_name_map;
636         struct ntfs_volume_wrapper *volume;
637         struct scan_params *params;
638         int ret;
639 };
640
641 static int
642 ntfs_3g_build_dentry_tree_recursive(struct wim_dentry **root_p,
643                                     const MFT_REF mref,
644                                     char *path,
645                                     size_t path_len,
646                                     int name_type,
647                                     struct ntfs_volume_wrapper *volume,
648                                     struct scan_params *params);
649
650 static int
651 filldir(void *_ctx, const ntfschar *name, const int name_nchars,
652         const int name_type, const s64 pos, const MFT_REF mref,
653         const unsigned dt_type)
654 {
655         struct readdir_ctx *ctx = _ctx;
656         const size_t name_nbytes = name_nchars * sizeof(ntfschar);
657         char *mbs_name;
658         size_t mbs_name_nbytes;
659         size_t path_len;
660         struct wim_dentry *child;
661         int ret;
662
663         if (name_type & FILE_NAME_DOS) {
664                 /* If this is the entry for a DOS name, store it for later. */
665                 ret = insert_dos_name(&ctx->dos_name_map, name,
666                                       name_nbytes, MREF(mref));
667
668                 /* Return now if an error occurred or if this is just a DOS name
669                  * and not a Win32+DOS name. */
670                 if (ret != 0 || name_type == FILE_NAME_DOS)
671                         goto out;
672         }
673
674         ret = utf16le_to_tstr(name, name_nbytes, &mbs_name, &mbs_name_nbytes);
675         if (ret)
676                 goto out;
677
678         if (should_ignore_filename(mbs_name, mbs_name_nbytes))
679                 goto out_free_mbs_name;
680
681         path_len = ctx->path_len;
682         if (path_len != 1)
683                 ctx->path[path_len++] = '/';
684         memcpy(ctx->path + path_len, mbs_name, mbs_name_nbytes + 1);
685         path_len += mbs_name_nbytes;
686         child = NULL;
687         ret = ntfs_3g_build_dentry_tree_recursive(&child, mref, ctx->path,
688                                                   path_len, name_type,
689                                                   ctx->volume, ctx->params);
690         attach_scanned_tree(ctx->parent, child, ctx->params->blob_table);
691 out_free_mbs_name:
692         FREE(mbs_name);
693 out:
694         ctx->ret = ret;
695         return ret;
696 }
697
698 static int
699 ntfs_3g_recurse_directory(ntfs_inode *ni, char *path, size_t path_len,
700                           struct wim_dentry *parent,
701                           struct ntfs_volume_wrapper *volume,
702                           struct scan_params *params)
703 {
704         int ret;
705         s64 pos = 0;
706         struct readdir_ctx ctx = {
707                 .parent          = parent,
708                 .path            = path,
709                 .path_len        = path_len,
710                 .dos_name_map    = { .root = NULL },
711                 .volume          = volume,
712                 .params          = params,
713                 .ret             = 0,
714         };
715         ret = ntfs_readdir(ni, &pos, &ctx, filldir);
716         path[path_len] = '\0';
717         if (unlikely(ret)) {
718                 if (ctx.ret) {
719                         /* wimlib error  */
720                         ret = ctx.ret;
721                 } else {
722                         /* error from ntfs_readdir() itself  */
723                         ERROR_WITH_ERRNO("Error reading directory \"%s\"", path);
724                         ret = WIMLIB_ERR_NTFS_3G;
725                 }
726         } else {
727                 struct wim_dentry *child;
728
729                 ret = 0;
730                 for_dentry_child(child, parent) {
731                         ret = set_dentry_dos_name(child, &ctx.dos_name_map);
732                         if (ret)
733                                 break;
734                 }
735         }
736         destroy_dos_name_map(&ctx.dos_name_map);
737         return ret;
738 }
739
740 static int
741 ntfs_3g_build_dentry_tree_recursive(struct wim_dentry **root_ret,
742                                     const MFT_REF mref,
743                                     char *path,
744                                     size_t path_len,
745                                     int name_type,
746                                     struct ntfs_volume_wrapper *volume,
747                                     struct scan_params *params)
748 {
749         u32 attributes;
750         int ret;
751         struct wim_dentry *root = NULL;
752         struct wim_inode *inode = NULL;
753         ntfs_inode *ni = NULL;
754
755         ret = try_exclude(path, params);
756         if (unlikely(ret < 0)) /* Excluded? */
757                 goto out_progress;
758         if (unlikely(ret > 0)) /* Error? */
759                 goto out;
760
761         ni = ntfs_inode_open(volume->vol, mref);
762         if (!ni) {
763                 ERROR_WITH_ERRNO("Failed to open NTFS file \"%s\"", path);
764                 ret = WIMLIB_ERR_NTFS_3G;
765                 goto out;
766         }
767
768         /* Get file attributes */
769         ret = ntfs_get_ntfs_attrib(ni, (char*)&attributes, sizeof(attributes));
770         if (ret != sizeof(attributes)) {
771                 ERROR_WITH_ERRNO("Failed to get NTFS attributes from \"%s\"", path);
772                 ret = WIMLIB_ERR_NTFS_3G;
773                 goto out;
774         }
775
776         if (unlikely(attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
777                 if (params->add_flags & WIMLIB_ADD_FLAG_NO_UNSUPPORTED_EXCLUDE)
778                 {
779                         ERROR("Can't archive \"%s\" because NTFS-3G capture mode "
780                               "does not support encrypted files and directories", path);
781                         ret = WIMLIB_ERR_UNSUPPORTED_FILE;
782                         goto out;
783                 }
784                 params->progress.scan.cur_path = path;
785                 ret = do_scan_progress(params, WIMLIB_SCAN_DENTRY_UNSUPPORTED, NULL);
786                 goto out;
787         }
788
789         /* Create a WIM dentry with an associated inode, which may be shared */
790         ret = inode_table_new_dentry(params->inode_table,
791                                      path_basename_with_len(path, path_len),
792                                      ni->mft_no, 0, false, &root);
793         if (ret)
794                 goto out;
795
796         if (name_type & FILE_NAME_WIN32) /* Win32 or Win32+DOS name (rather than POSIX) */
797                 root->d_is_win32_name = 1;
798
799         inode = root->d_inode;
800
801         if (inode->i_nlink > 1) {
802                 /* Shared inode; nothing more to do */
803                 goto out_progress;
804         }
805
806         inode->i_creation_time    = le64_to_cpu(ni->creation_time);
807         inode->i_last_write_time  = le64_to_cpu(ni->last_data_change_time);
808         inode->i_last_access_time = le64_to_cpu(ni->last_access_time);
809         inode->i_attributes       = attributes;
810
811         if (attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
812                 /* Scan the reparse point stream.  */
813                 ret = scan_ntfs_attrs_with_type(inode, ni, path,
814                                                 params->unhashed_blobs,
815                                                 volume, AT_REPARSE_POINT);
816                 if (ret)
817                         goto out;
818
819                 warn_special_reparse_points(inode, params, volume);
820         }
821
822         /* Load the object ID.  */
823         ret = load_object_id(ni, inode);
824         if (ret) {
825                 ERROR_WITH_ERRNO("Error reading object ID of \"%s\"", path);
826                 goto out;
827         }
828
829         /* Scan the data streams.
830          *
831          * Note: directories should not have an unnamed data stream, but they
832          * may have named data streams.  Nondirectories (including reparse
833          * points) can have an unnamed data stream as well as named data
834          * streams.  */
835         ret = scan_ntfs_attrs_with_type(inode, ni, path, params->unhashed_blobs,
836                                         volume, AT_DATA);
837         if (ret)
838                 goto out;
839
840         /* Reparse-point fixups are a no-op because in NTFS-3G capture mode we
841          * only allow capturing an entire volume. */
842         if (params->add_flags & WIMLIB_ADD_FLAG_RPFIX &&
843             inode_is_symlink(inode))
844                 inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
845
846         if (!(params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
847                 ret = get_security_descriptor(ni, inode, volume->vol,
848                                               params->sd_set);
849                 if (ret) {
850                         ERROR_WITH_ERRNO("Error reading security descriptor "
851                                          "of \"%s\"", path);
852                         goto out;
853                 }
854         }
855
856         if (inode_is_directory(inode)) {
857                 ret = ntfs_3g_recurse_directory(ni, path, path_len, root,
858                                                 volume, params);
859                 if (ret)
860                         goto out;
861         }
862
863 out_progress:
864         params->progress.scan.cur_path = path;
865         if (root == NULL)
866                 ret = do_scan_progress(params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
867         else
868                 ret = do_scan_progress(params, WIMLIB_SCAN_DENTRY_OK, inode);
869 out:
870         if (ni)
871                 ntfs_inode_close(ni);
872         if (unlikely(ret)) {
873                 free_dentry_tree(root, params->blob_table);
874                 root = NULL;
875                 ret = report_scan_error(params, ret, path);
876         }
877         *root_ret = root;
878         return ret;
879 }
880
881 int
882 ntfs_3g_build_dentry_tree(struct wim_dentry **root_ret,
883                           const char *device, struct scan_params *params)
884 {
885         struct ntfs_volume_wrapper *volume;
886         ntfs_volume *vol;
887         char *path;
888         int ret;
889
890         volume = CALLOC(1, sizeof(struct ntfs_volume_wrapper));
891         if (!volume)
892                 return WIMLIB_ERR_NOMEM;
893
894         vol = ntfs_mount(device, NTFS_MNT_RDONLY);
895         if (!vol) {
896                 ERROR_WITH_ERRNO("Failed to mount NTFS volume \"%s\" read-only",
897                                  device);
898                 FREE(volume);
899                 return WIMLIB_ERR_NTFS_3G;
900         }
901
902         volume->vol = vol;
903         volume->refcnt = 1;
904
905         /* Currently, libntfs-3g users that need to read security descriptors
906          * are required to call ntfs_open_secure() to open the volume's security
907          * descriptor index, "$Secure".  This is only required to work on NTFS
908          * v3.0+, as older versions did not have a security descriptor index. */
909         if (ntfs_open_secure(vol) && vol->major_ver >= 3) {
910                 ERROR_WITH_ERRNO("Unable to open security descriptor index of "
911                                  "NTFS volume \"%s\"", device);
912                 ret = WIMLIB_ERR_NTFS_3G;
913                 goto out_put_ntfs_volume;
914         }
915
916         /* We don't want to capture the special NTFS files such as $Bitmap.  Not
917          * to be confused with "hidden" or "system" files which are real files
918          * that we do need to capture.  */
919         NVolClearShowSysFiles(vol);
920
921         /* Currently we assume that all the paths fit into this length and there
922          * is no check for overflow.  */
923         path = MALLOC(32768);
924         if (!path) {
925                 ret = WIMLIB_ERR_NOMEM;
926                 goto out_close_secure;
927         }
928
929         path[0] = '/';
930         path[1] = '\0';
931         ret = ntfs_3g_build_dentry_tree_recursive(root_ret, FILE_root, path, 1,
932                                                   FILE_NAME_POSIX, volume,
933                                                   params);
934         FREE(path);
935 out_close_secure:
936         /* Undo the effects of ntfs_open_secure().  This is not yet done
937          * automatically by ntfs_umount().  But NULL out the inode to
938          * potentially be robust against future versions doing so. */
939         if (vol->secure_ni) {
940                 ntfs_index_ctx_put(vol->secure_xsii);
941                 ntfs_index_ctx_put(vol->secure_xsdh);
942                 ntfs_inode_close(vol->secure_ni);
943                 vol->secure_ni = NULL;
944         }
945 out_put_ntfs_volume:
946         put_ntfs_volume(volume);
947         return ret;
948 }
949 #endif /* WITH_NTFS_3G */