]> wimlib.net Git - wimlib/blob - src/ntfs-3g_apply.c
ntfs_3g_apply.c: work around EOPNOTSUPP when setting short name of reparse point...
[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                 ERROR_WITH_ERRNO("Failed to set reparse data on \"%s\"",
326                                  dentry_full_path(
327                                         inode_first_extraction_dentry(inode)));
328                 return WIMLIB_ERR_SET_REPARSE_DATA;
329         }
330
331         return 0;
332 }
333
334 static bool
335 ntfs_3g_has_empty_attributes(const struct wim_inode *inode)
336 {
337         for (unsigned i = 0; i < inode->i_num_streams; i++) {
338                 const struct wim_inode_stream *strm = &inode->i_streams[i];
339
340                 if (stream_blob_resolved(strm) == NULL &&
341                     (strm->stream_type == STREAM_TYPE_REPARSE_POINT ||
342                      stream_is_named_data_stream(strm)))
343                         return true;
344         }
345         return false;
346 }
347
348 /*
349  * Create empty attributes (named data streams and potentially a reparse point)
350  * for the specified file, if there are any.
351  *
352  * Since these won't have blob descriptors, they won't show up in the call to
353  * extract_blob_list().  Hence the need for the special case.
354  *
355  * Keep this in sync with ntfs_3g_has_empty_attributes()!
356  */
357 static int
358 ntfs_3g_create_empty_attributes(ntfs_inode *ni,
359                                 const struct wim_inode *inode,
360                                 struct ntfs_3g_apply_ctx *ctx)
361 {
362         for (unsigned i = 0; i < inode->i_num_streams; i++) {
363
364                 const struct wim_inode_stream *strm = &inode->i_streams[i];
365                 int ret;
366
367                 if (stream_blob_resolved(strm) != NULL)
368                         continue;
369
370                 if (strm->stream_type == STREAM_TYPE_REPARSE_POINT) {
371                         ret = ntfs_3g_restore_reparse_point(ni, inode, 0, ctx);
372                         if (ret)
373                                 return ret;
374                 } else if (stream_is_named_data_stream(strm)) {
375                         if (ntfs_attr_add(ni, AT_DATA, strm->stream_name,
376                                           utf16le_len_chars(strm->stream_name),
377                                           NULL, 0))
378                         {
379                                 ERROR_WITH_ERRNO("Failed to create named data "
380                                                  "stream of \"%s\"",
381                                                  dentry_full_path(
382                                         inode_first_extraction_dentry(inode)));
383                                 return WIMLIB_ERR_NTFS_3G;
384                         }
385                 }
386         }
387         return 0;
388 }
389
390 /* Set attributes, security descriptor, and timestamps on the NTFS inode @ni.
391  */
392 static int
393 ntfs_3g_set_metadata(ntfs_inode *ni, const struct wim_inode *inode,
394                      const struct ntfs_3g_apply_ctx *ctx)
395 {
396         int extract_flags;
397         const struct wim_security_data *sd;
398         struct wim_dentry *one_dentry;
399         int ret;
400
401         extract_flags = ctx->common.extract_flags;
402         sd = wim_get_current_security_data(ctx->common.wim);
403         one_dentry = inode_first_extraction_dentry(inode);
404
405         /* Attributes  */
406         if (!(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ATTRIBUTES)) {
407                 u32 attrib = inode->i_attributes;
408
409                 attrib &= ~(FILE_ATTRIBUTE_SPARSE_FILE |
410                             FILE_ATTRIBUTE_ENCRYPTED);
411
412                 if (ntfs_set_ntfs_attrib(ni, (const char *)&attrib,
413                                          sizeof(attrib), 0))
414                 {
415                         ERROR_WITH_ERRNO("Failed to set attributes on \"%s\" "
416                                          "in NTFS volume",
417                                          dentry_full_path(one_dentry));
418                         return WIMLIB_ERR_SET_ATTRIBUTES;
419                 }
420         }
421
422         /* Security descriptor  */
423         if (inode_has_security_descriptor(inode)
424             && !(extract_flags & WIMLIB_EXTRACT_FLAG_NO_ACLS))
425         {
426                 const void *desc;
427                 size_t desc_size;
428
429                 desc = sd->descriptors[inode->i_security_id];
430                 desc_size = sd->sizes[inode->i_security_id];
431
432                 ret = ntfs_3g_set_security_descriptor(ni, desc, desc_size);
433
434                 if (unlikely(ret)) {
435                         int err = errno;
436                         ERROR_WITH_ERRNO("Failed to set security descriptor on "
437                                          "\"%s\" in NTFS volume",
438                                          dentry_full_path(one_dentry));
439                         if (err == EINVAL && wimlib_print_errors) {
440                                 fprintf(wimlib_error_file,
441                                         "The security descriptor is: ");
442                                 print_byte_field(desc, desc_size, wimlib_error_file);
443                                 fprintf(wimlib_error_file, "\n");
444                                 fprintf(wimlib_error_file,
445                                         "\nThis error occurred because libntfs-3g thinks "
446                                         "the security descriptor is invalid.  If you "
447                                         "are extracting a Windows 10 image, this may be "
448                                         "caused by a known bug in libntfs-3g.  See: "
449                                         "http://wimlib.net/forums/viewtopic.php?f=1&t=4 "
450                                         "for more information.\n\n");
451                         }
452                         return ret;
453                 }
454         }
455
456         /* Timestamps  */
457         ret = ntfs_3g_set_timestamps(ni, inode);
458         if (ret) {
459                 ERROR_WITH_ERRNO("Failed to set timestamps on \"%s\" "
460                                  "in NTFS volume",
461                                  dentry_full_path(one_dentry));
462                 return ret;
463         }
464         return 0;
465 }
466
467 /* Recursively creates all the subdirectories of @dir, which has been created as
468  * the NTFS inode @dir_ni.  */
469 static int
470 ntfs_3g_create_dirs_recursive(ntfs_inode *dir_ni, struct wim_dentry *dir,
471                               struct ntfs_3g_apply_ctx *ctx)
472 {
473         struct wim_dentry *child;
474
475         for_dentry_child(child, dir) {
476                 ntfs_inode *ni;
477                 int ret;
478
479                 if (!(child->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
480                         continue;
481                 if (!will_extract_dentry(child))
482                         continue;
483
484                 ni = ntfs_create(dir_ni, 0, child->d_extraction_name,
485                                  child->d_extraction_name_nchars, S_IFDIR);
486                 if (!ni) {
487                         ERROR_WITH_ERRNO("Error creating \"%s\" in NTFS volume",
488                                          dentry_full_path(child));
489                         return WIMLIB_ERR_NTFS_3G;
490                 }
491
492                 child->d_inode->i_mft_no = ni->mft_no;
493
494                 ret = report_file_created(&ctx->common);
495                 if (!ret)
496                         ret = ntfs_3g_set_metadata(ni, child->d_inode, ctx);
497                 if (!ret)
498                         ret = ntfs_3g_create_dirs_recursive(ni, child, ctx);
499
500                 if (ntfs_inode_close_in_dir(ni, dir_ni) && !ret) {
501                         ERROR_WITH_ERRNO("Error closing \"%s\" in NTFS volume",
502                                          dentry_full_path(child));
503                         ret = WIMLIB_ERR_NTFS_3G;
504                 }
505                 if (ret)
506                         return ret;
507         }
508         return 0;
509 }
510
511 /* For each WIM dentry in the @root tree that represents a directory, create the
512  * corresponding directory in the NTFS volume @ctx->vol.  */
513 static int
514 ntfs_3g_create_directories(struct wim_dentry *root,
515                            struct list_head *dentry_list,
516                            struct ntfs_3g_apply_ctx *ctx)
517 {
518         ntfs_inode *root_ni;
519         int ret;
520         struct wim_dentry *dentry;
521
522         /* Create the directories using POSIX names.  */
523
524         root_ni = ntfs_inode_open(ctx->vol, FILE_root);
525         if (!root_ni) {
526                 ERROR_WITH_ERRNO("Can't open root of NTFS volume");
527                 return WIMLIB_ERR_NTFS_3G;
528         }
529
530         root->d_inode->i_mft_no = FILE_root;
531
532         ret = ntfs_3g_set_metadata(root_ni, root->d_inode, ctx);
533         if (!ret)
534                 ret = ntfs_3g_create_dirs_recursive(root_ni, root, ctx);
535
536         if (ntfs_inode_close(root_ni) && !ret) {
537                 ERROR_WITH_ERRNO("Error closing root of NTFS volume");
538                 ret = WIMLIB_ERR_NTFS_3G;
539         }
540         if (ret)
541                 return ret;
542
543         /* Set the DOS name of any directory that has one.  In addition, create
544          * empty attributes for directories that have them.  Note that creating
545          * an empty reparse point attribute must happen *after* setting the
546          * DOS name in order to work around a case where
547          * ntfs_set_ntfs_dos_name() fails with EOPNOTSUPP.  */
548         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
549                 const struct wim_inode *inode = dentry->d_inode;
550
551                 if (!(inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY))
552                         continue;
553                 if (dentry_has_short_name(dentry)) {
554                         ret = ntfs_3g_restore_dos_name(NULL, NULL, dentry,
555                                                        ctx->vol);
556                         if (ret)
557                                 return ret;
558                         ret = report_file_created(&ctx->common);
559                         if (ret)
560                                 return ret;
561                 }
562                 if (ntfs_3g_has_empty_attributes(inode)) {
563                         ntfs_inode *ni;
564
565                         ret = WIMLIB_ERR_NTFS_3G;
566                         ni = ntfs_inode_open(ctx->vol, inode->i_mft_no);
567                         if (ni) {
568                                 ret = ntfs_3g_create_empty_attributes(ni, inode,
569                                                                       ctx);
570                                 if (ntfs_inode_close(ni) && !ret)
571                                         ret = WIMLIB_ERR_NTFS_3G;
572                         }
573                         if (ret) {
574                                 ERROR_WITH_ERRNO("Failed to create empty "
575                                                  "attributes of directory "
576                                                  "\"%s\" in NTFS volume",
577                                                  dentry_full_path(dentry));
578                                 return ret;
579                         }
580                 }
581         }
582         return 0;
583 }
584
585 /* When creating an inode that will have a short (DOS) name, we create it using
586  * the long name associated with the short name.  This ensures that the short
587  * name gets associated with the correct long name.  */
588 static struct wim_dentry *
589 ntfs_3g_first_extraction_alias(struct wim_inode *inode)
590 {
591         struct wim_dentry *dentry;
592
593         inode_for_each_extraction_alias(dentry, inode)
594                 if (dentry_has_short_name(dentry))
595                         return dentry;
596         return inode_first_extraction_dentry(inode);
597 }
598
599 /*
600  * Add a hard link for the NTFS inode @ni at the location corresponding to the
601  * WIM dentry @dentry.
602  *
603  * The parent directory must have already been created on the NTFS volume.
604  *
605  * Returns 0 on success; returns WIMLIB_ERR_NTFS_3G and sets errno on failure.
606  */
607 static int
608 ntfs_3g_add_link(ntfs_inode *ni, struct wim_dentry *dentry)
609 {
610         ntfs_inode *dir_ni;
611         int res;
612
613         /* Open the inode of the parent directory.  */
614         dir_ni = ntfs_inode_open(ni->vol, dentry->d_parent->d_inode->i_mft_no);
615         if (!dir_ni)
616                 goto fail;
617
618         /* Create the link.  */
619         res = ntfs_link(ni, dir_ni, dentry->d_extraction_name,
620                         dentry->d_extraction_name_nchars);
621
622         /* Close the parent directory.  */
623         if (ntfs_inode_close(dir_ni) || res)
624                 goto fail;
625
626         return 0;
627
628 fail:
629         ERROR_WITH_ERRNO("Can't create link \"%s\" in NTFS volume",
630                          dentry_full_path(dentry));
631         return WIMLIB_ERR_NTFS_3G;
632 }
633
634 static int
635 ntfs_3g_create_nondirectory(struct wim_inode *inode,
636                             struct ntfs_3g_apply_ctx *ctx)
637 {
638         struct wim_dentry *first_dentry;
639         ntfs_inode *dir_ni;
640         ntfs_inode *ni;
641         struct wim_dentry *dentry;
642         int ret;
643
644         first_dentry = ntfs_3g_first_extraction_alias(inode);
645
646         /* Create first link.  */
647
648         dir_ni = ntfs_inode_open(ctx->vol, first_dentry->d_parent->d_inode->i_mft_no);
649         if (!dir_ni) {
650                 ERROR_WITH_ERRNO("Can't open \"%s\" in NTFS volume",
651                                  dentry_full_path(first_dentry->d_parent));
652                 return WIMLIB_ERR_NTFS_3G;
653         }
654
655         ni = ntfs_create(dir_ni, 0, first_dentry->d_extraction_name,
656                          first_dentry->d_extraction_name_nchars, S_IFREG);
657
658         if (!ni) {
659                 ERROR_WITH_ERRNO("Can't create \"%s\" in NTFS volume",
660                                  dentry_full_path(first_dentry));
661                 ntfs_inode_close(dir_ni);
662                 return WIMLIB_ERR_NTFS_3G;
663         }
664
665         inode->i_mft_no = ni->mft_no;
666
667         /* Set short name if present.  */
668         if (dentry_has_short_name(first_dentry)) {
669
670                 ret = ntfs_3g_restore_dos_name(ni, dir_ni, first_dentry, ctx->vol);
671
672                 /* ntfs_3g_restore_dos_name() closed both 'ni' and 'dir_ni'.  */
673
674                 if (ret)
675                         return ret;
676
677                 /* Reopen the inode.  */
678                 ni = ntfs_inode_open(ctx->vol, inode->i_mft_no);
679                 if (!ni) {
680                         ERROR_WITH_ERRNO("Failed to reopen \"%s\" "
681                                          "in NTFS volume",
682                                          dentry_full_path(first_dentry));
683                         return WIMLIB_ERR_NTFS_3G;
684                 }
685         } else {
686                 /* Close the directory in which the first link was created.  */
687                 if (ntfs_inode_close(dir_ni)) {
688                         ERROR_WITH_ERRNO("Failed to close \"%s\" in NTFS volume",
689                                          dentry_full_path(first_dentry->d_parent));
690                         ret = WIMLIB_ERR_NTFS_3G;
691                         goto out_close_ni;
692                 }
693         }
694
695         /* Create additional links if present.  */
696         inode_for_each_extraction_alias(dentry, inode) {
697                 if (dentry != first_dentry) {
698                         ret = ntfs_3g_add_link(ni, dentry);
699                         if (ret)
700                                 goto out_close_ni;
701                 }
702         }
703
704         /* Set metadata.  */
705         ret = ntfs_3g_set_metadata(ni, inode, ctx);
706         if (ret)
707                 goto out_close_ni;
708
709         ret = ntfs_3g_create_empty_attributes(ni, inode, ctx);
710
711 out_close_ni:
712         /* Close the inode.  */
713         if (ntfs_inode_close(ni) && !ret) {
714                 ERROR_WITH_ERRNO("Error closing \"%s\" in NTFS volume",
715                                  dentry_full_path(first_dentry));
716                 ret = WIMLIB_ERR_NTFS_3G;
717         }
718         return ret;
719 }
720
721 /* For each WIM dentry in the @dentry_list that represents a nondirectory file,
722  * create the corresponding nondirectory file in the NTFS volume.
723  *
724  * Directories must have already been created.  */
725 static int
726 ntfs_3g_create_nondirectories(struct list_head *dentry_list,
727                               struct ntfs_3g_apply_ctx *ctx)
728 {
729         struct wim_dentry *dentry;
730         struct wim_inode *inode;
731         int ret;
732
733         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
734                 inode = dentry->d_inode;
735                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY)
736                         continue;
737                 if (dentry == inode_first_extraction_dentry(inode)) {
738                         ret = ntfs_3g_create_nondirectory(inode, ctx);
739                         if (ret)
740                                 return ret;
741                 }
742                 ret = report_file_created(&ctx->common);
743                 if (ret)
744                         return ret;
745         }
746         return 0;
747 }
748
749 static int
750 ntfs_3g_begin_extract_blob_instance(struct blob_descriptor *blob,
751                                     ntfs_inode *ni,
752                                     struct wim_inode *inode,
753                                     const struct wim_inode_stream *strm,
754                                     struct ntfs_3g_apply_ctx *ctx)
755 {
756         struct wim_dentry *one_dentry = inode_first_extraction_dentry(inode);
757         ntfschar *stream_name;
758         size_t stream_name_nchars;
759         ntfs_attr *attr;
760
761         if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
762
763                 if (blob->size > REPARSE_DATA_MAX_SIZE) {
764                         ERROR("Reparse data of \"%s\" has size "
765                               "%"PRIu64" bytes (exceeds %u bytes)",
766                               dentry_full_path(one_dentry),
767                               blob->size, REPARSE_DATA_MAX_SIZE);
768                         return WIMLIB_ERR_INVALID_REPARSE_DATA;
769                 }
770                 ctx->reparse_ptr = ctx->rpbuf.rpdata;
771                 ctx->ntfs_reparse_inodes[ctx->num_reparse_inodes] = ni;
772                 ctx->wim_reparse_inodes[ctx->num_reparse_inodes] = inode;
773                 ctx->num_reparse_inodes++;
774                 return 0;
775         }
776
777         /* It's a data stream (may be unnamed or named).  */
778         wimlib_assert(strm->stream_type == STREAM_TYPE_DATA);
779
780         if (unlikely(stream_is_named(strm))) {
781                 stream_name = strm->stream_name;
782                 stream_name_nchars = utf16le_len_chars(stream_name);
783
784                 if (ntfs_attr_add(ni, AT_DATA, stream_name,
785                                   stream_name_nchars, NULL, 0))
786                 {
787                         ERROR_WITH_ERRNO("Failed to create named data stream of \"%s\"",
788                                          dentry_full_path(one_dentry));
789                         return WIMLIB_ERR_NTFS_3G;
790                 }
791         } else {
792                 /* Don't pass an empty string other than AT_UNNAMED to
793                  * ntfs_attr_open() --- it violates assumptions made by
794                  * libntfs-3g.  */
795                 stream_name = AT_UNNAMED;
796                 stream_name_nchars = 0;
797         }
798
799         /* This should be ensured by extract_blob_list()  */
800         wimlib_assert(ctx->num_open_attrs < MAX_OPEN_FILES);
801
802         attr = ntfs_attr_open(ni, AT_DATA, stream_name, stream_name_nchars);
803         if (!attr) {
804                 ERROR_WITH_ERRNO("Failed to open data stream of \"%s\"",
805                                  dentry_full_path(one_dentry));
806                 return WIMLIB_ERR_NTFS_3G;
807         }
808         ctx->open_attrs[ctx->num_open_attrs++] = attr;
809         ntfs_attr_truncate_solid(attr, blob->size);
810         return 0;
811 }
812
813 static int
814 ntfs_3g_cleanup_blob_extract(struct ntfs_3g_apply_ctx *ctx)
815 {
816         int ret = 0;
817
818         for (unsigned i = 0; i < ctx->num_open_attrs; i++) {
819                 if (ntfs_attr_pclose(ctx->open_attrs[i]))
820                         ret = -1;
821                 ntfs_attr_close(ctx->open_attrs[i]);
822         }
823
824         ctx->num_open_attrs = 0;
825
826         for (unsigned i = 0; i < ctx->num_open_inodes; i++) {
827                 if (ntfs_inode_close(ctx->open_inodes[i]))
828                         ret = -1;
829         }
830         ctx->num_open_inodes = 0;
831
832         ctx->offset = 0;
833         ctx->reparse_ptr = NULL;
834         ctx->num_reparse_inodes = 0;
835         return ret;
836 }
837
838 static ntfs_inode *
839 ntfs_3g_open_inode(struct wim_inode *inode, struct ntfs_3g_apply_ctx *ctx)
840 {
841         ntfs_inode *ni;
842
843         /* If the same blob is being extracted to multiple streams of the same
844          * inode, then we must only open the inode once.  */
845         if (unlikely(inode->i_num_streams > 1)) {
846                 for (unsigned i = 0; i < ctx->num_open_inodes; i++) {
847                         if (ctx->open_inodes[i]->mft_no == inode->i_mft_no) {
848                                 return ctx->open_inodes[i];
849                         }
850                 }
851         }
852
853         ni = ntfs_inode_open(ctx->vol, inode->i_mft_no);
854         if (unlikely(!ni)) {
855                 ERROR_WITH_ERRNO("Can't open \"%s\" in NTFS volume",
856                                  dentry_full_path(
857                                         inode_first_extraction_dentry(inode)));
858                 return NULL;
859         }
860
861         ctx->open_inodes[ctx->num_open_inodes++] = ni;
862         return ni;
863 }
864
865 static int
866 ntfs_3g_begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
867 {
868         struct ntfs_3g_apply_ctx *ctx = _ctx;
869         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
870         int ret;
871         ntfs_inode *ni;
872
873         for (u32 i = 0; i < blob->out_refcnt; i++) {
874                 ret = WIMLIB_ERR_NTFS_3G;
875                 ni = ntfs_3g_open_inode(targets[i].inode, ctx);
876                 if (!ni)
877                         goto out_cleanup;
878
879                 ret = ntfs_3g_begin_extract_blob_instance(blob, ni,
880                                                           targets[i].inode,
881                                                           targets[i].stream, ctx);
882                 if (ret)
883                         goto out_cleanup;
884         }
885         ret = 0;
886         goto out;
887
888 out_cleanup:
889         ntfs_3g_cleanup_blob_extract(ctx);
890 out:
891         return ret;
892 }
893
894 /* Note: contrary to its documentation, ntfs_attr_pwrite() can return a short
895  * count in non-error cases --- specifically, when writing to a compressed
896  * attribute and the requested count exceeds the size of an NTFS "compression
897  * block".  Therefore, we must continue calling ntfs_attr_pwrite() until all
898  * bytes have been written or a real error has occurred.  */
899 static bool
900 ntfs_3g_full_pwrite(ntfs_attr *na, u64 offset, size_t size, const u8 *data)
901 {
902         while (size) {
903                 s64 res = ntfs_attr_pwrite(na, offset, size, data);
904                 if (unlikely(res <= 0))
905                         return false;
906                 wimlib_assert(res <= size);
907                 offset += res;
908                 size -= res;
909                 data += res;
910         }
911         return true;
912 }
913
914 static int
915 ntfs_3g_extract_chunk(const void *chunk, size_t size, void *_ctx)
916 {
917         struct ntfs_3g_apply_ctx *ctx = _ctx;
918
919         for (unsigned i = 0; i < ctx->num_open_attrs; i++) {
920                 if (!ntfs_3g_full_pwrite(ctx->open_attrs[i],
921                                          ctx->offset, size, chunk))
922                 {
923                         ERROR_WITH_ERRNO("Error writing data to NTFS volume");
924                         return WIMLIB_ERR_NTFS_3G;
925                 }
926         }
927         if (ctx->reparse_ptr)
928                 ctx->reparse_ptr = mempcpy(ctx->reparse_ptr, chunk, size);
929         ctx->offset += size;
930         return 0;
931 }
932
933 static int
934 ntfs_3g_end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
935 {
936         struct ntfs_3g_apply_ctx *ctx = _ctx;
937         int ret;
938
939         if (status) {
940                 ret = status;
941                 goto out;
942         }
943
944         for (u32 i = 0; i < ctx->num_reparse_inodes; i++) {
945                 ret = ntfs_3g_restore_reparse_point(ctx->ntfs_reparse_inodes[i],
946                                                     ctx->wim_reparse_inodes[i],
947                                                     blob->size, ctx);
948                 if (ret)
949                         goto out;
950         }
951         ret = 0;
952 out:
953         if (ntfs_3g_cleanup_blob_extract(ctx) && !ret) {
954                 ERROR_WITH_ERRNO("Error writing data to NTFS volume");
955                 ret = WIMLIB_ERR_NTFS_3G;
956         }
957         return ret;
958 }
959
960 static u64
961 ntfs_3g_count_dentries(const struct list_head *dentry_list)
962 {
963         const struct wim_dentry *dentry;
964         u64 count = 0;
965
966         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
967                 count++;
968                 if ((dentry->d_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) &&
969                     dentry_has_short_name(dentry))
970                 {
971                         count++;
972                 }
973         }
974
975         return count;
976 }
977
978 static int
979 ntfs_3g_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
980 {
981         struct ntfs_3g_apply_ctx *ctx = (struct ntfs_3g_apply_ctx *)_ctx;
982         ntfs_volume *vol;
983         struct wim_dentry *root;
984         int ret;
985
986         /* For NTFS-3g extraction mode we require that the dentries to extract
987          * form a single tree.  */
988         root = list_first_entry(dentry_list, struct wim_dentry,
989                                 d_extraction_list_node);
990
991         /* Mount the NTFS volume.  */
992         vol = ntfs_mount(ctx->common.target, 0);
993         if (!vol) {
994                 ERROR_WITH_ERRNO("Failed to mount \"%s\" with NTFS-3g",
995                                  ctx->common.target);
996                 return WIMLIB_ERR_NTFS_3G;
997         }
998         ctx->vol = vol;
999
1000         /* Create all inodes and aliases, including short names, and set
1001          * metadata (attributes, security descriptors, and timestamps).  */
1002
1003         ret = start_file_structure_phase(&ctx->common,
1004                                          ntfs_3g_count_dentries(dentry_list));
1005         if (ret)
1006                 goto out_unmount;
1007
1008         ret = ntfs_3g_create_directories(root, dentry_list, ctx);
1009         if (ret)
1010                 goto out_unmount;
1011
1012         ret = ntfs_3g_create_nondirectories(dentry_list, ctx);
1013         if (ret)
1014                 goto out_unmount;
1015
1016         ret = end_file_structure_phase(&ctx->common);
1017         if (ret)
1018                 goto out_unmount;
1019
1020         /* Extract blobs.  */
1021         struct read_blob_callbacks cbs = {
1022                 .begin_blob     = ntfs_3g_begin_extract_blob,
1023                 .consume_chunk  = ntfs_3g_extract_chunk,
1024                 .end_blob       = ntfs_3g_end_extract_blob,
1025                 .ctx            = ctx,
1026         };
1027         ret = extract_blob_list(&ctx->common, &cbs);
1028
1029         /* We do not need a final pass to set timestamps because libntfs-3g does
1030          * not update timestamps automatically (exception:
1031          * ntfs_set_ntfs_dos_name() does, but we handle this elsewhere).  */
1032
1033 out_unmount:
1034         if (ntfs_umount(ctx->vol, FALSE) && !ret) {
1035                 ERROR_WITH_ERRNO("Failed to unmount \"%s\" with NTFS-3g",
1036                                  ctx->common.target);
1037                 ret = WIMLIB_ERR_NTFS_3G;
1038         }
1039         return ret;
1040 }
1041
1042 const struct apply_operations ntfs_3g_apply_ops = {
1043         .name                   = "NTFS-3g",
1044         .get_supported_features = ntfs_3g_get_supported_features,
1045         .extract                = ntfs_3g_extract,
1046         .context_size           = sizeof(struct ntfs_3g_apply_ctx),
1047         .single_tree_only       = true,
1048 };
1049
1050 void
1051 libntfs3g_global_init(void)
1052 {
1053        ntfs_set_char_encoding(setlocale(LC_ALL, ""));
1054 }