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