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