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