]> wimlib.net Git - wimlib/blob - src/ntfs-3g_apply.c
59edc3631fa7a42e4654d0c57babbd412c9b2f58
[wimlib] / src / ntfs-3g_apply.c
1 /*
2  * ntfs-3g_apply.c
3  *
4  * Apply a WIM image directly to an NTFS volume using libntfs-3g.  Restore as
5  * much information as possible, including security data, file attributes, DOS
6  * names, and alternate data streams.
7  *
8  * Note: because NTFS-3g offers inode-based interfaces, we actually don't need
9  * to deal with paths at all!  (Other than for error messages.)
10  */
11
12 /*
13  * Copyright (C) 2012, 2013, 2014 Eric Biggers
14  *
15  * This file is part of wimlib, a library for working with WIM files.
16  *
17  * wimlib is free software; you can redistribute it and/or modify it under the
18  * terms of the GNU General Public License as published by the Free
19  * Software Foundation; either version 3 of the License, or (at your option)
20  * any later version.
21  *
22  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
23  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24  * A PARTICULAR PURPOSE. See the GNU General Public License for more
25  * details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with wimlib; if not, see http://www.gnu.org/licenses/.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #  include "config.h"
33 #endif
34
35 #include <locale.h>
36 #include <string.h>
37
38 #include <ntfs-3g/attrib.h>
39 #include <ntfs-3g/reparse.h>
40 #include <ntfs-3g/security.h>
41
42 #include "wimlib/assert.h"
43 #include "wimlib/apply.h"
44 #include "wimlib/dentry.h"
45 #include "wimlib/encoding.h"
46 #include "wimlib/error.h"
47 #include "wimlib/metadata.h"
48 #include "wimlib/ntfs_3g.h"
49 #include "wimlib/reparse.h"
50 #include "wimlib/security.h"
51 #include "wimlib/security_descriptor.h"
52
53 static int
54 ntfs_3g_get_supported_features(const char *target,
55                                struct wim_features *supported_features)
56 {
57         supported_features->archive_files             = 1;
58         supported_features->hidden_files              = 1;
59         supported_features->system_files              = 1;
60         supported_features->compressed_files          = 1;
61         supported_features->encrypted_directories     = 1;
62         supported_features->not_context_indexed_files = 1;
63         supported_features->named_data_streams        = 1;
64         supported_features->hard_links                = 1;
65         supported_features->reparse_points            = 1;
66         supported_features->security_descriptors      = 1;
67         supported_features->short_names               = 1;
68         supported_features->timestamps                = 1;
69         supported_features->case_sensitive_filenames  = 1;
70         return 0;
71 }
72
73 #define MAX_OPEN_ATTRS 1024
74
75 struct ntfs_3g_apply_ctx {
76         /* Extract flags, the pointer to the WIMStruct, etc.  */
77         struct apply_ctx common;
78
79         /* Pointer to the open NTFS volume  */
80         ntfs_volume *vol;
81
82         ntfs_attr *open_attrs[MAX_OPEN_ATTRS];
83         unsigned num_open_attrs;
84         ntfs_inode *open_inodes[MAX_OPEN_ATTRS];
85         unsigned num_open_inodes;
86
87         struct reparse_buffer_disk rpbuf;
88         u8 *reparse_ptr;
89
90         /* Offset in the stream currently being read  */
91         u64 offset;
92
93         unsigned num_reparse_inodes;
94         ntfs_inode *ntfs_reparse_inodes[MAX_OPEN_ATTRS];
95         struct wim_inode *wim_reparse_inodes[MAX_OPEN_ATTRS];
96 };
97
98 static size_t
99 sid_size(const wimlib_SID *sid)
100 {
101         return offsetof(wimlib_SID, sub_authority) +
102                 sizeof(le32) * sid->sub_authority_count;
103 }
104
105 /*
106  * sd_fixup - Fix up a Windows NT security descriptor for libntfs-3g.
107  *
108  * libntfs-3g validates security descriptors before setting them, but old
109  * versions contain bugs causing it to reject unusual but valid security
110  * descriptors:
111  *
112  * - Versions before 2013.1.13 reject security descriptors ending with an empty
113  *   SACL (System Access Control List).  This bug can be worked around either by
114  *   moving the empty SACL earlier in the security descriptor or by removing the
115  *   SACL entirely.  The latter work-around is valid because an empty SACL is
116  *   equivalent to a "null", or non-existent, SACL.
117  * - Versions up to and including 2013.1.13 reject security descriptors ending
118  *   with an empty DACL (Discretionary Access Control List).  This is very
119  *   similar to the SACL bug and should be fixed in the next release after
120  *   2013.1.13.  However, removing the DACL is not a valid workaround because
121  *   this changes the meaning of the security descriptor--- an empty DACL allows
122  *   no access, whereas a "null" DACL allows all access.
123  *
124  * If the security descriptor was fixed, this function returns an allocated
125  * buffer containing the fixed security descriptor, and its size is updated.
126  * Otherwise (or if no memory is available) the original descriptor is returned.
127  */
128 static u8 *
129 sd_fixup(const u8 *_desc, size_t *size_p)
130 {
131         u32 owner_offset, group_offset, dacl_offset, sacl_offset;
132         bool owner_valid, group_valid;
133         size_t size = *size_p;
134         const wimlib_SECURITY_DESCRIPTOR_RELATIVE *desc =
135                         (const wimlib_SECURITY_DESCRIPTOR_RELATIVE*)_desc;
136         wimlib_SECURITY_DESCRIPTOR_RELATIVE *desc_new;
137         const wimlib_SID *owner, *group, *sid;
138
139         /* Don't attempt to fix clearly invalid security descriptors.  */
140         if (size < sizeof(wimlib_SECURITY_DESCRIPTOR_RELATIVE))
141                 return (u8*)_desc;
142
143         if (le16_to_cpu(desc->control) & wimlib_SE_DACL_PRESENT)
144                 dacl_offset = le32_to_cpu(desc->dacl_offset);
145         else
146                 dacl_offset = 0;
147
148         if (le16_to_cpu(desc->control) & wimlib_SE_SACL_PRESENT)
149                 sacl_offset = le32_to_cpu(desc->sacl_offset);
150         else
151                 sacl_offset = 0;
152
153         /* Check if the security descriptor will be affected by one of the bugs.
154          * If not, do nothing and return.
155          *
156          * Note: HAVE_NTFS_MNT_RDONLY is defined if libntfs-3g is
157          * version 2013.1.13 or later.  */
158         if (!(
159         #if !defined(HAVE_NTFS_MNT_RDONLY)
160             (sacl_offset != 0 && sacl_offset == size - sizeof(wimlib_ACL)) ||
161         #endif
162             (dacl_offset != 0 && dacl_offset == size - sizeof(wimlib_ACL))))
163                 return (u8*)_desc;
164
165         owner_offset = le32_to_cpu(desc->owner_offset);
166         group_offset = le32_to_cpu(desc->group_offset);
167         owner = (const wimlib_SID*)((const u8*)desc + owner_offset);
168         group = (const wimlib_SID*)((const u8*)desc + group_offset);
169
170         /* We'll try to move the owner or group SID to the end of the security
171          * descriptor to avoid the bug.  This is only possible if at least one
172          * is valid.  */
173         owner_valid = (owner_offset != 0) &&
174                         (owner_offset % 4 == 0) &&
175                         (owner_offset <= size - sizeof(SID)) &&
176                         (owner_offset + sid_size(owner) <= size) &&
177                         (owner_offset >= sizeof(wimlib_SECURITY_DESCRIPTOR_RELATIVE));
178         group_valid = (group_offset != 0) &&
179                         (group_offset % 4 == 0) &&
180                         (group_offset <= size - sizeof(SID)) &&
181                         (group_offset + sid_size(group) <= size) &&
182                         (group_offset >= sizeof(wimlib_SECURITY_DESCRIPTOR_RELATIVE));
183         if (owner_valid) {
184                 sid = owner;
185         } else if (group_valid) {
186                 sid = group;
187         } else {
188                 return (u8*)_desc;
189         }
190
191         desc_new = MALLOC(size + sid_size(sid));
192         if (!desc_new)
193                 return (u8*)_desc;
194
195         memcpy(desc_new, desc, size);
196         if (owner_valid)
197                 desc_new->owner_offset = cpu_to_le32(size);
198         else if (group_valid)
199                 desc_new->group_offset = cpu_to_le32(size);
200         memcpy((u8*)desc_new + size, sid, sid_size(sid));
201         *size_p = size + sid_size(sid);
202         return (u8*)desc_new;
203 }
204
205 /* Set the security descriptor @desc of size @desc_size on the NTFS inode @ni.
206   */
207 static int
208 ntfs_3g_set_security_descriptor(ntfs_inode *ni, const void *desc, size_t desc_size)
209 {
210         struct SECURITY_CONTEXT sec_ctx;
211         u8 *desc_fixed;
212         int ret = 0;
213
214         memset(&sec_ctx, 0, sizeof(sec_ctx));
215         sec_ctx.vol = ni->vol;
216
217         desc_fixed = sd_fixup(desc, &desc_size);
218
219         if (ntfs_set_ntfs_acl(&sec_ctx, ni, desc_fixed, desc_size, 0))
220                 ret = WIMLIB_ERR_SET_SECURITY;
221
222         if (desc_fixed != desc)
223                 FREE(desc_fixed);
224
225         return ret;
226 }
227
228 static int
229 ntfs_3g_set_timestamps(ntfs_inode *ni, const struct wim_inode *inode)
230 {
231         u64 times[3] = {
232                 inode->i_creation_time,
233                 inode->i_last_write_time,
234                 inode->i_last_access_time,
235         };
236
237         if (ntfs_inode_set_times(ni, (const char *)times, sizeof(times), 0))
238                 return WIMLIB_ERR_SET_TIMESTAMPS;
239         return 0;
240 }
241
242 /* Restore the timestamps on the NTFS inode corresponding to @inode.  */
243 static int
244 ntfs_3g_restore_timestamps(ntfs_volume *vol, const struct wim_inode *inode)
245 {
246         ntfs_inode *ni;
247         int res;
248
249         ni = ntfs_inode_open(vol, inode->i_mft_no);
250         if (!ni)
251                 goto fail;
252
253         res = ntfs_3g_set_timestamps(ni, inode);
254
255         if (ntfs_inode_close(ni) || res)
256                 goto fail;
257
258         return 0;
259
260 fail:
261         ERROR_WITH_ERRNO("Failed to update timestamps of \"%s\" in NTFS volume",
262                          dentry_full_path(inode_first_extraction_dentry(inode)));
263         return WIMLIB_ERR_SET_TIMESTAMPS;
264 }
265
266 /* Restore the DOS name of the @dentry.
267  * This closes both @ni and @dir_ni.
268  * If either is NULL, then they are opened temporarily.  */
269 static int
270 ntfs_3g_restore_dos_name(ntfs_inode *ni, ntfs_inode *dir_ni,
271                          struct wim_dentry *dentry, ntfs_volume *vol)
272 {
273         int ret;
274         const char *dos_name;
275         size_t dos_name_nbytes;
276
277         /* Note: ntfs_set_ntfs_dos_name() closes both inodes (even if it fails).
278          * And it takes in a multibyte string, even though it translates it to
279          * UTF-16LE internally... which is annoying because we currently have
280          * the UTF-16LE string but not the multibyte string.  */
281
282         ret = utf16le_get_tstr(dentry->short_name, dentry->short_name_nbytes,
283                                &dos_name, &dos_name_nbytes);
284         if (ret)
285                 goto out_close;
286
287         if (!dir_ni)
288                 dir_ni = ntfs_inode_open(vol, dentry->d_parent->d_inode->i_mft_no);
289         if (!ni)
290                 ni = ntfs_inode_open(vol, dentry->d_inode->i_mft_no);
291         if (dir_ni && ni) {
292                 ret = ntfs_set_ntfs_dos_name(ni, dir_ni,
293                                              dos_name, dos_name_nbytes, 0);
294                 dir_ni = NULL;
295                 ni = NULL;
296         } else {
297                 ret = -1;
298         }
299         utf16le_put_tstr(dos_name);
300         if (ret) {
301                 ERROR_WITH_ERRNO("Failed to set DOS name of \"%s\" in NTFS "
302                                  "volume", dentry_full_path(dentry));
303                 ret = WIMLIB_ERR_SET_SHORT_NAME;
304                 goto out_close;
305         }
306
307         /* Unlike most other NTFS-3g functions, ntfs_set_ntfs_dos_name()
308          * changes the directory's last modification timestamp...
309          * Change it back.  */
310         return ntfs_3g_restore_timestamps(vol, dentry->d_parent->d_inode);
311
312 out_close:
313         /* ntfs_inode_close() can take a NULL argument, but it's probably best
314          * not to rely on this behavior.  */
315         if (ni)
316                 ntfs_inode_close(ni);
317         if (dir_ni)
318                 ntfs_inode_close(dir_ni);
319         return ret;
320 }
321
322 /* Create empty named data streams.
323  *
324  * Since these won't have 'struct wim_lookup_table_entry's, they won't show up
325  * in the call to extract_stream_list().  Hence the need for the special case.
326  */
327 static int
328 ntfs_3g_create_any_empty_ads(ntfs_inode *ni, const struct wim_inode *inode,
329                              const struct ntfs_3g_apply_ctx *ctx)
330 {
331         for (u16 i = 0; i < inode->i_num_ads; i++) {
332                 const struct wim_ads_entry *entry;
333
334                 entry = &inode->i_ads_entries[i];
335
336                 /* Not named?  */
337                 if (!entry->stream_name_nbytes)
338                         continue;
339
340                 /* Not empty?  */
341                 if (entry->lte)
342                         continue;
343
344                 if (ntfs_attr_add(ni, AT_DATA, entry->stream_name,
345                                   entry->stream_name_nbytes /
346                                         sizeof(utf16lechar),
347                                   NULL, 0))
348                 {
349                         ERROR_WITH_ERRNO("Failed to create named data stream "
350                                          "of \"%s\"", dentry_full_path(
351                                                 inode_first_extraction_dentry(inode)));
352                         return WIMLIB_ERR_NTFS_3G;
353                 }
354         }
355         return 0;
356 }
357
358 /* Set attributes, security descriptor, and timestamps on the NTFS inode @ni.
359  */
360 static int
361 ntfs_3g_set_metadata(ntfs_inode *ni, const struct wim_inode *inode,
362                      const struct ntfs_3g_apply_ctx *ctx)
363 {
364         int extract_flags;
365         const struct wim_security_data *sd;
366         struct wim_dentry *one_dentry;
367         int ret;
368
369         extract_flags = ctx->common.extract_flags;
370         sd = wim_get_current_security_data(ctx->common.wim);
371         one_dentry = inode_first_extraction_dentry(inode);
372
373         /* Attributes  */
374         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
375                 u32 attrib = inode->i_attributes;
376
377                 attrib &= ~(FILE_ATTRIBUTE_SPARSE_FILE |
378                             FILE_ATTRIBUTE_ENCRYPTED);
379
380                 if (ntfs_set_ntfs_attrib(ni, (const char *)&attrib,
381                                          sizeof(attrib), 0))
382                 {
383                         ERROR_WITH_ERRNO("Failed to set attributes on \"%s\" "
384                                          "in NTFS volume",
385                                          dentry_full_path(one_dentry));
386                         return WIMLIB_ERR_SET_ATTRIBUTES;
387                 }
388         }
389
390         /* Security descriptor  */
391         if ((inode->i_security_id >= 0)
392             && !(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
393         {
394                 const void *desc;
395                 size_t desc_size;
396
397                 desc = sd->descriptors[inode->i_security_id];
398                 desc_size = sd->sizes[inode->i_security_id];
399
400                 ret = ntfs_3g_set_security_descriptor(ni, desc, desc_size);
401                 if (ret) {
402                         if (wimlib_print_errors) {
403                                 ERROR_WITH_ERRNO("Failed to set security descriptor "
404                                                  "on \"%s\" in NTFS volume",
405                                                  dentry_full_path(one_dentry));
406                                 fprintf(stderr, "The security descriptor is: ");
407                                 print_byte_field(desc, desc_size, stderr);
408                                 fprintf(stderr, "\n");
409                         }
410                         return ret;
411                 }
412         }
413
414         /* Timestamps  */
415         ret = ntfs_3g_set_timestamps(ni, inode);
416         if (ret) {
417                 ERROR_WITH_ERRNO("Failed to set timestamps on \"%s\" "
418                                  "in NTFS volume",
419                                  dentry_full_path(one_dentry));
420                 return ret;
421         }
422         return 0;
423 }
424
425 /* Recursively creates all the subdirectories of @dir, which has been created as
426  * the NTFS inode @dir_ni.  */
427 static int
428 ntfs_3g_create_dirs_recursive(ntfs_inode *dir_ni, struct wim_dentry *dir,
429                               const struct ntfs_3g_apply_ctx *ctx)
430 {
431         struct wim_dentry *child;
432
433         for_dentry_child(child, dir) {
434                 ntfs_inode *ni;
435                 int ret;
436
437                 if (!(child->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
438                         continue;
439                 if (!will_extract_dentry(child))
440                         continue;
441
442                 ni = ntfs_create(dir_ni, 0, child->d_extraction_name,
443                                  child->d_extraction_name_nchars, S_IFDIR);
444                 if (!ni) {
445                         ERROR_WITH_ERRNO("Error creating \"%s\" in NTFS volume",
446                                          dentry_full_path(child));
447                         return WIMLIB_ERR_NTFS_3G;
448                 }
449
450                 child->d_inode->i_mft_no = ni->mft_no;
451
452                 ret = ntfs_3g_set_metadata(ni, child->d_inode, ctx);
453                 if (!ret)
454                         ret = ntfs_3g_create_any_empty_ads(ni, child->d_inode, ctx);
455                 if (!ret)
456                         ret = ntfs_3g_create_dirs_recursive(ni, child, ctx);
457
458                 if (ntfs_inode_close_in_dir(ni, dir_ni) && !ret) {
459                         ERROR_WITH_ERRNO("Error closing \"%s\" in NTFS volume",
460                                          dentry_full_path(child));
461                         ret = WIMLIB_ERR_NTFS_3G;
462                 }
463                 if (ret)
464                         return ret;
465         }
466         return 0;
467 }
468
469 /* For each WIM dentry in the @root tree that represents a directory, create the
470  * corresponding directory in the NTFS volume @ctx->vol.  */
471 static int
472 ntfs_3g_create_directories(struct wim_dentry *root,
473                            struct list_head *dentry_list,
474                            const struct ntfs_3g_apply_ctx *ctx)
475 {
476         ntfs_inode *root_ni;
477         int ret;
478         struct wim_dentry *dentry;
479
480         /* Create the directories using POSIX names.  */
481
482         root_ni = ntfs_inode_open(ctx->vol, FILE_root);
483         if (!root_ni) {
484                 ERROR_WITH_ERRNO("Can't open root of NTFS volume");
485                 return WIMLIB_ERR_NTFS_3G;
486         }
487
488         root->d_inode->i_mft_no = FILE_root;
489
490         ret = ntfs_3g_create_dirs_recursive(root_ni, root, ctx);
491
492         if (ntfs_inode_close(root_ni) && !ret) {
493                 ERROR_WITH_ERRNO("Error closing root of NTFS volume");
494                 ret = WIMLIB_ERR_NTFS_3G;
495         }
496         if (ret)
497                 return ret;
498
499         /* Set the DOS name of any directory that has one.  */
500         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
501                 if (!(dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
502                         continue;
503                 if (!dentry_has_short_name(dentry))
504                         continue;
505                 ret = ntfs_3g_restore_dos_name(NULL, NULL, dentry, ctx->vol);
506                 if (ret)
507                         return ret;
508         }
509         return 0;
510 }
511
512 /* When creating an inode that will have a short (DOS) name, we create it using
513  * the long name associated with the short name.  This ensures that the short
514  * name gets associated with the correct long name.  */
515 static struct wim_dentry *
516 ntfs_3g_first_extraction_alias(struct wim_inode *inode)
517 {
518         struct list_head *next = inode->i_extraction_aliases.next;
519         struct wim_dentry *dentry;
520
521         do {
522                 dentry = list_entry(next, struct wim_dentry,
523                                     d_extraction_alias_node);
524                 if (dentry_has_short_name(dentry))
525                         break;
526                 next = next->next;
527         } while (next != &inode->i_extraction_aliases);
528         return dentry;
529 }
530
531 /*
532  * Add a hard link for the NTFS inode @ni at the location corresponding to the
533  * WIM dentry @dentry.
534  *
535  * The parent directory must have already been created on the NTFS volume.
536  *
537  * Returns 0 on success; returns WIMLIB_ERR_NTFS_3G and sets errno on failure.
538  */
539 static int
540 ntfs_3g_add_link(ntfs_inode *ni, struct wim_dentry *dentry)
541 {
542         ntfs_inode *dir_ni;
543         int res;
544
545         /* Open the inode of the parent directory.  */
546         dir_ni = ntfs_inode_open(ni->vol, dentry->d_parent->d_inode->i_mft_no);
547         if (!dir_ni)
548                 goto fail;
549
550         /* Create the link.  */
551         res = ntfs_link(ni, dir_ni, dentry->d_extraction_name,
552                         dentry->d_extraction_name_nchars);
553
554         /* Close the parent directory.  */
555         if (ntfs_inode_close(dir_ni) || res)
556                 goto fail;
557
558         return 0;
559
560 fail:
561         ERROR_WITH_ERRNO("Can't create link \"%s\" in NTFS volume",
562                          dentry_full_path(dentry));
563         return WIMLIB_ERR_NTFS_3G;
564 }
565
566 static int
567 ntfs_3g_create_nondirectory(struct wim_inode *inode,
568                             const struct ntfs_3g_apply_ctx *ctx)
569 {
570         struct wim_dentry *first_dentry;
571         ntfs_inode *dir_ni;
572         ntfs_inode *ni;
573         struct list_head *next;
574         struct wim_dentry *dentry;
575         int ret;
576
577         first_dentry = ntfs_3g_first_extraction_alias(inode);
578
579         /* Create first link.  */
580
581         dir_ni = ntfs_inode_open(ctx->vol, first_dentry->d_parent->d_inode->i_mft_no);
582         if (!dir_ni) {
583                 ERROR_WITH_ERRNO("Can't open \"%s\" in NTFS volume",
584                                  dentry_full_path(first_dentry->d_parent));
585                 return WIMLIB_ERR_NTFS_3G;
586         }
587
588         ni = ntfs_create(dir_ni, 0, first_dentry->d_extraction_name,
589                          first_dentry->d_extraction_name_nchars, S_IFREG);
590
591         if (!ni) {
592                 ERROR_WITH_ERRNO("Can't create \"%s\" in NTFS volume",
593                                  dentry_full_path(first_dentry));
594                 ntfs_inode_close(dir_ni);
595                 return WIMLIB_ERR_NTFS_3G;
596         }
597
598         inode->i_mft_no = ni->mft_no;
599
600         /* Set short name if present.  */
601         if (dentry_has_short_name(first_dentry)) {
602
603                 ret = ntfs_3g_restore_dos_name(ni, dir_ni, first_dentry, ctx->vol);
604
605                 /* ntfs_3g_restore_dos_name() closed both 'ni' and 'dir_ni'.  */
606
607                 if (ret)
608                         return ret;
609
610                 /* Reopen the inode.  */
611                 ni = ntfs_inode_open(ctx->vol, inode->i_mft_no);
612                 if (!ni) {
613                         ERROR_WITH_ERRNO("Failed to reopen \"%s\" "
614                                          "in NTFS volume",
615                                          dentry_full_path(first_dentry));
616                         return WIMLIB_ERR_NTFS_3G;
617                 }
618         } else {
619                 /* Close the directory in which the first link was created.  */
620                 if (ntfs_inode_close(dir_ni)) {
621                         ERROR_WITH_ERRNO("Failed to close \"%s\" in NTFS volume",
622                                          dentry_full_path(first_dentry->d_parent));
623                         ret = WIMLIB_ERR_NTFS_3G;
624                         goto out_close_ni;
625                 }
626         }
627
628         /* Create additional links if present.  */
629         next = inode->i_extraction_aliases.next;
630         do {
631                 dentry = list_entry(next, struct wim_dentry,
632                                     d_extraction_alias_node);
633                 if (dentry != first_dentry) {
634                         ret = ntfs_3g_add_link(ni, dentry);
635                         if (ret)
636                                 goto out_close_ni;
637                 }
638                 next = next->next;
639         } while (next != &inode->i_extraction_aliases);
640
641         /* Set metadata.  */
642         ret = ntfs_3g_set_metadata(ni, inode, ctx);
643         if (ret)
644                 goto out_close_ni;
645
646         ret = ntfs_3g_create_any_empty_ads(ni, inode, ctx);
647
648 out_close_ni:
649         /* Close the inode.  */
650         if (ntfs_inode_close(ni) && !ret) {
651                 ERROR_WITH_ERRNO("Error closing \"%s\" in NTFS volume",
652                                  dentry_full_path(first_dentry));
653                 ret = WIMLIB_ERR_NTFS_3G;
654         }
655         return ret;
656 }
657
658 /* For each WIM dentry in the @dentry_list that represents a nondirectory file,
659  * create the corresponding nondirectory file in the NTFS volume.
660  *
661  * Directories must have already been created.  */
662 static int
663 ntfs_3g_create_nondirectories(struct list_head *dentry_list,
664                               const struct ntfs_3g_apply_ctx *ctx)
665 {
666         struct wim_dentry *dentry;
667         struct wim_inode *inode;
668         int ret;
669
670         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
671                 inode = dentry->d_inode;
672                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
673                         continue;
674                 if (dentry != inode_first_extraction_dentry(inode))
675                         continue;
676                 ret = ntfs_3g_create_nondirectory(inode, ctx);
677                 if (ret)
678                         return ret;
679         }
680         return 0;
681 }
682
683 static int
684 ntfs_3g_begin_extract_stream_to_attr(struct wim_lookup_table_entry *stream,
685                                      ntfs_inode *ni,
686                                      struct wim_inode *inode,
687                                      ntfschar *stream_name,
688                                      struct ntfs_3g_apply_ctx *ctx)
689 {
690         struct wim_dentry *one_dentry = inode_first_extraction_dentry(inode);
691         size_t stream_name_nchars = 0;
692         ntfs_attr *attr;
693
694         if (stream_name)
695                 for (const ntfschar *p = stream_name; *p; p++)
696                         stream_name_nchars++;
697
698         if (stream_name_nchars == 0)
699                 stream_name = AT_UNNAMED;
700         if ((inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
701             && (stream_name_nchars == 0))
702         {
703                 if (stream->size > REPARSE_DATA_MAX_SIZE) {
704                         ERROR("Reparse data of \"%s\" has size "
705                               "%"PRIu64" bytes (exceeds %u bytes)",
706                               dentry_full_path(one_dentry),
707                               stream->size, REPARSE_DATA_MAX_SIZE);
708                         return WIMLIB_ERR_INVALID_REPARSE_DATA;
709                 }
710                 ctx->reparse_ptr = ctx->rpbuf.rpdata;
711                 ctx->rpbuf.rpdatalen = cpu_to_le16(stream->size);
712                 ctx->rpbuf.rpreserved = cpu_to_le16(0);
713                 ctx->ntfs_reparse_inodes[ctx->num_reparse_inodes] = ni;
714                 ctx->wim_reparse_inodes[ctx->num_reparse_inodes] = inode;
715                 ctx->num_reparse_inodes++;
716                 return 0;
717         }
718
719         if (stream_name_nchars &&
720             (ntfs_attr_add(ni, AT_DATA, stream_name,
721                            stream_name_nchars, NULL, 0)))
722         {
723                 ERROR_WITH_ERRNO("Failed to create named data stream of \"%s\"",
724                                  dentry_full_path(one_dentry));
725                 return WIMLIB_ERR_NTFS_3G;
726         }
727
728         if (ctx->num_open_attrs == MAX_OPEN_ATTRS) {
729                 ERROR("Can't extract data: too many open files!");
730                 return WIMLIB_ERR_UNSUPPORTED;
731         }
732
733         attr = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_nchars);
734         if (!attr) {
735                 ERROR_WITH_ERRNO("Failed to open data stream of \"%s\"",
736                                  dentry_full_path(one_dentry));
737                 return WIMLIB_ERR_NTFS_3G;
738         }
739         ctx->open_attrs[ctx->num_open_attrs++] = attr;
740         ntfs_attr_truncate_solid(attr, stream->size);
741         return 0;
742 }
743
744 static int
745 ntfs_3g_cleanup_stream_extract(struct ntfs_3g_apply_ctx *ctx)
746 {
747         int ret = 0;
748
749         for (unsigned i = 0; i < ctx->num_open_attrs; i++) {
750                 if (ntfs_attr_pclose(ctx->open_attrs[i]))
751                         ret = -1;
752                 ntfs_attr_close(ctx->open_attrs[i]);
753         }
754
755         ctx->num_open_attrs = 0;
756
757         for (unsigned i = 0; i < ctx->num_open_inodes; i++) {
758                 if (ntfs_inode_close(ctx->open_inodes[i]))
759                         ret = -1;
760         }
761         ctx->num_open_inodes = 0;
762
763         ctx->offset = 0;
764         ctx->reparse_ptr = NULL;
765         ctx->num_reparse_inodes = 0;
766         return ret;
767 }
768
769 static ntfs_inode *
770 ntfs_3g_open_inode(struct wim_inode *inode, struct ntfs_3g_apply_ctx *ctx)
771 {
772         ntfs_inode *ni = NULL;
773
774         if (inode->i_visited) {
775                 for (u32 i = 0; i < ctx->num_open_inodes; i++) {
776                         if (ctx->open_inodes[i]->mft_no == inode->i_mft_no) {
777                                 ni = ctx->open_inodes[i];
778                                 break;
779                         }
780                 }
781         }
782         if (!ni) {
783                 ni = ntfs_inode_open(ctx->vol, inode->i_mft_no);
784                 ctx->open_inodes[ctx->num_open_inodes++] = ni;
785                 inode->i_visited = 1;
786         }
787
788         if (!ni) {
789                 ERROR_WITH_ERRNO("Can't open \"%s\" in NTFS volume",
790                                  dentry_full_path(
791                                         inode_first_extraction_dentry(inode)));
792                 return NULL;
793         }
794         return ni;
795 }
796
797 static int
798 ntfs_3g_begin_extract_stream(struct wim_lookup_table_entry *stream,
799                              u32 flags, void *_ctx)
800 {
801         struct ntfs_3g_apply_ctx *ctx = _ctx;
802         const struct stream_owner *owners = stream_owners(stream);
803         int ret;
804
805         for (u32 i = 0; i < stream->out_refcnt; i++) {
806                 struct wim_inode *inode = owners[i].inode;
807                 ntfschar *stream_name = (ntfschar *)owners[i].stream_name;
808                 ntfs_inode *ni;
809
810                 ret = WIMLIB_ERR_NTFS_3G;
811                 ni = ntfs_3g_open_inode(inode, ctx);
812                 if (!ni)
813                         goto out_cleanup;
814
815                 ret = ntfs_3g_begin_extract_stream_to_attr(stream, ni, inode,
816                                                            stream_name, ctx);
817                 if (ret)
818                         goto out_cleanup;
819         }
820         ret = 0;
821         goto out;
822
823 out_cleanup:
824         ntfs_3g_cleanup_stream_extract(ctx);
825 out:
826         for (u32 i = 0; i < stream->out_refcnt; i++)
827                 owners[i].inode->i_visited = 0;
828         return ret;
829 }
830
831 static int
832 ntfs_3g_extract_chunk(const void *chunk, size_t size, void *_ctx)
833 {
834         struct ntfs_3g_apply_ctx *ctx = _ctx;
835         s64 res;
836
837         for (unsigned i = 0; i < ctx->num_open_attrs; i++) {
838                 res = ntfs_attr_pwrite(ctx->open_attrs[i],
839                                        ctx->offset, size, chunk);
840                 if (res != size) {
841                         ERROR_WITH_ERRNO("Error writing data to NTFS volume");
842                         return WIMLIB_ERR_NTFS_3G;
843                 }
844         }
845         if (ctx->reparse_ptr)
846                 ctx->reparse_ptr = mempcpy(ctx->reparse_ptr, chunk, size);
847         ctx->offset += size;
848         return 0;
849 }
850
851 static int
852 ntfs_3g_end_extract_stream(struct wim_lookup_table_entry *stream,
853                            int status, void *_ctx)
854 {
855         struct ntfs_3g_apply_ctx *ctx = _ctx;
856         int ret;
857
858         if (status) {
859                 ret = status;
860                 goto out;
861         }
862
863         for (u32 i = 0; i < ctx->num_reparse_inodes; i++) {
864                 struct wim_inode *inode = ctx->wim_reparse_inodes[i];
865
866                 ctx->rpbuf.rptag = cpu_to_le32(inode->i_reparse_tag);
867
868                 if (ntfs_set_ntfs_reparse_data(ctx->ntfs_reparse_inodes[i],
869                                                (const char *)&ctx->rpbuf,
870                                                stream->size + REPARSE_DATA_OFFSET,
871                                                0))
872                 {
873                         ERROR_WITH_ERRNO("Failed to set reparse "
874                                          "data on \"%s\"",
875                                          dentry_full_path(
876                                                 inode_first_extraction_dentry(inode)));
877                         ret = WIMLIB_ERR_NTFS_3G;
878                         goto out;
879                 }
880         }
881         ret = 0;
882 out:
883         if (ntfs_3g_cleanup_stream_extract(ctx) && !ret) {
884                 ERROR_WITH_ERRNO("Error writing data to NTFS volume");
885                 ret = WIMLIB_ERR_NTFS_3G;
886         }
887         return ret;
888 }
889
890 static int
891 ntfs_3g_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
892 {
893         struct ntfs_3g_apply_ctx *ctx = (struct ntfs_3g_apply_ctx *)_ctx;
894         ntfs_volume *vol;
895         struct wim_dentry *root;
896         int ret;
897
898         /* For NTFS-3g extraction mode we require that the dentries to extract
899          * form a single tree.  */
900         root = list_first_entry(dentry_list, struct wim_dentry,
901                                 d_extraction_list_node);
902
903         /* Mount the NTFS volume.  */
904         vol = ntfs_mount(ctx->common.target, 0);
905         if (!vol) {
906                 ERROR_WITH_ERRNO("Failed to mount \"%s\" with NTFS-3g",
907                                  ctx->common.target);
908                 return WIMLIB_ERR_NTFS_3G;
909         }
910         ctx->vol = vol;
911
912         /* Create all inodes and aliases, including short names, and set
913          * metadata (attributes, security descriptors, and timestamps).  */
914
915         ret = ntfs_3g_create_directories(root, dentry_list, ctx);
916         if (ret)
917                 goto out_unmount;
918
919         ret = ntfs_3g_create_nondirectories(dentry_list, ctx);
920         if (ret)
921                 goto out_unmount;
922
923         /* Extract streams.  */
924         struct read_stream_list_callbacks cbs = {
925                 .begin_stream      = ntfs_3g_begin_extract_stream,
926                 .begin_stream_ctx  = ctx,
927                 .consume_chunk     = ntfs_3g_extract_chunk,
928                 .consume_chunk_ctx = ctx,
929                 .end_stream        = ntfs_3g_end_extract_stream,
930                 .end_stream_ctx    = ctx,
931         };
932         ret = extract_stream_list(&ctx->common, &cbs);
933
934         /* We do not need a final pass to set timestamps because libntfs-3g does
935          * not update timestamps automatically (exception:
936          * ntfs_set_ntfs_dos_name() does, but we handle this elsewhere).  */
937
938 out_unmount:
939         if (ntfs_umount(ctx->vol, FALSE) && !ret) {
940                 ERROR_WITH_ERRNO("Failed to unmount \"%s\" with NTFS-3g",
941                                  ctx->common.target);
942                 ret = WIMLIB_ERR_NTFS_3G;
943         }
944         return ret;
945 }
946
947 const struct apply_operations ntfs_3g_apply_ops = {
948         .name                   = "NTFS-3g",
949         .get_supported_features = ntfs_3g_get_supported_features,
950         .extract                = ntfs_3g_extract,
951         .context_size           = sizeof(struct ntfs_3g_apply_ctx),
952         .single_tree_only       = true,
953 };
954
955 void
956 libntfs3g_global_init(void)
957 {
958        ntfs_set_char_encoding(setlocale(LC_ALL, ""));
959 }