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