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