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