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