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