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