]> wimlib.net Git - wimlib/blob - src/unix_apply.c
ntfs-3g_apply.c: inform user about yet another possible NTFS-3G bug
[wimlib] / src / unix_apply.c
1 /*
2  * unix_apply.c - Code to apply files from a WIM image on UNIX.
3  */
4
5 /*
6  * Copyright (C) 2012-2016 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdlib.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33
34 #include "wimlib/apply.h"
35 #include "wimlib/assert.h"
36 #include "wimlib/blob_table.h"
37 #include "wimlib/dentry.h"
38 #include "wimlib/error.h"
39 #include "wimlib/file_io.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/timestamp.h"
42 #include "wimlib/unix_data.h"
43
44 /* We don't require O_NOFOLLOW, but the advantage of having it is that if we
45  * need to extract a file to a location at which there exists a symbolic link,
46  * open(..., O_NOFOLLOW | ...) recognizes the symbolic link rather than
47  * following it and creating the file somewhere else.  (Equivalent to
48  * FILE_OPEN_REPARSE_POINT on Windows.)  */
49 #ifndef O_NOFOLLOW
50 #  define O_NOFOLLOW 0
51 #endif
52
53 static int
54 unix_get_supported_features(const char *target,
55                             struct wim_features *supported_features)
56 {
57         supported_features->hard_links = 1;
58         supported_features->symlink_reparse_points = 1;
59         supported_features->unix_data = 1;
60         supported_features->timestamps = 1;
61         supported_features->case_sensitive_filenames = 1;
62         return 0;
63 }
64
65 #define NUM_PATHBUFS 2  /* We need 2 when creating hard links  */
66
67 struct unix_apply_ctx {
68         /* Extract flags, the pointer to the WIMStruct, etc.  */
69         struct apply_ctx common;
70
71         /* Buffers for building extraction paths (allocated).  */
72         char *pathbufs[NUM_PATHBUFS];
73
74         /* Index of next pathbuf to use  */
75         unsigned which_pathbuf;
76
77         /* Currently open file descriptors for extraction  */
78         struct filedes open_fds[MAX_OPEN_FILES];
79
80         /* Number of currently open file descriptors in open_fds, starting from
81          * the beginning of the array.  */
82         unsigned num_open_fds;
83
84         /* Buffer for reading reparse point data into memory  */
85         u8 reparse_data[REPARSE_DATA_MAX_SIZE];
86
87         /* Pointer to the next byte in @reparse_data to fill  */
88         u8 *reparse_ptr;
89
90         /* Absolute path to the target directory (allocated buffer).  Only set
91          * if needed for absolute symbolic link fixups.  */
92         char *target_abspath;
93
94         /* Number of characters in target_abspath.  */
95         size_t target_abspath_nchars;
96
97         /* Number of special files we couldn't create due to EPERM  */
98         unsigned long num_special_files_ignored;
99 };
100
101 /* Returns the number of characters needed to represent the path to the
102  * specified @dentry when extracted, not including the null terminator or the
103  * path to the target directory itself.  */
104 static size_t
105 unix_dentry_path_length(const struct wim_dentry *dentry)
106 {
107         size_t len = 0;
108         const struct wim_dentry *d;
109
110         d = dentry;
111         do {
112                 len += d->d_extraction_name_nchars + 1;
113                 d = d->d_parent;
114         } while (!dentry_is_root(d) && will_extract_dentry(d));
115
116         return len;
117 }
118
119 /* Returns the maximum number of characters needed to represent the path to any
120  * dentry in @dentry_list when extracted, including the null terminator and the
121  * path to the target directory itself.  */
122 static size_t
123 unix_compute_path_max(const struct list_head *dentry_list,
124                       const struct unix_apply_ctx *ctx)
125 {
126         size_t max = 0;
127         size_t len;
128         const struct wim_dentry *dentry;
129
130         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
131                 len = unix_dentry_path_length(dentry);
132                 if (len > max)
133                         max = len;
134         }
135
136         /* Account for target and null terminator.  */
137         return ctx->common.target_nchars + max + 1;
138 }
139
140 /* Builds and returns the filesystem path to which to extract @dentry.
141  * This cycles through NUM_PATHBUFS different buffers.  */
142 static const char *
143 unix_build_extraction_path(const struct wim_dentry *dentry,
144                            struct unix_apply_ctx *ctx)
145 {
146         char *pathbuf;
147         char *p;
148         const struct wim_dentry *d;
149
150         pathbuf = ctx->pathbufs[ctx->which_pathbuf];
151         ctx->which_pathbuf = (ctx->which_pathbuf + 1) % NUM_PATHBUFS;
152
153         p = &pathbuf[ctx->common.target_nchars +
154                      unix_dentry_path_length(dentry)];
155         *p = '\0';
156         d = dentry;
157         do {
158                 p -= d->d_extraction_name_nchars;
159                 if (d->d_extraction_name_nchars)
160                         memcpy(p, d->d_extraction_name,
161                                d->d_extraction_name_nchars);
162                 *--p = '/';
163                 d = d->d_parent;
164         } while (!dentry_is_root(d) && will_extract_dentry(d));
165
166         return pathbuf;
167 }
168
169 /* This causes the next call to unix_build_extraction_path() to use the same
170  * path buffer as the previous call.  */
171 static void
172 unix_reuse_pathbuf(struct unix_apply_ctx *ctx)
173 {
174         ctx->which_pathbuf = (ctx->which_pathbuf - 1) % NUM_PATHBUFS;
175 }
176
177 /* Builds and returns the filesystem path to which to extract an unspecified
178  * alias of the @inode.  This cycles through NUM_PATHBUFS different buffers.  */
179 static const char *
180 unix_build_inode_extraction_path(const struct wim_inode *inode,
181                                  struct unix_apply_ctx *ctx)
182 {
183         return unix_build_extraction_path(inode_first_extraction_dentry(inode), ctx);
184 }
185
186 /* Should the specified file be extracted as a directory on UNIX?  We extract
187  * the file as a directory if FILE_ATTRIBUTE_DIRECTORY is set and the file does
188  * not have a symlink or junction reparse point.  It *may* have a different type
189  * of reparse point.  */
190 static inline bool
191 should_extract_as_directory(const struct wim_inode *inode)
192 {
193         return (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) &&
194                 !inode_is_symlink(inode);
195 }
196
197 /* Sets the timestamps on a file being extracted.
198  *
199  * Either @fd or @path must be specified (not -1 and not NULL, respectively).
200  */
201 static int
202 unix_set_timestamps(int fd, const char *path, u64 atime, u64 mtime)
203 {
204         {
205                 struct timespec times[2];
206
207                 times[0] = wim_timestamp_to_timespec(atime);
208                 times[1] = wim_timestamp_to_timespec(mtime);
209
210                 errno = ENOSYS;
211 #ifdef HAVE_FUTIMENS
212                 if (fd >= 0 && !futimens(fd, times))
213                         return 0;
214 #endif
215 #ifdef HAVE_UTIMENSAT
216                 if (fd < 0 && !utimensat(AT_FDCWD, path, times, AT_SYMLINK_NOFOLLOW))
217                         return 0;
218 #endif
219                 if (errno != ENOSYS)
220                         return WIMLIB_ERR_SET_TIMESTAMPS;
221         }
222         {
223                 struct timeval times[2];
224
225                 times[0] = wim_timestamp_to_timeval(atime);
226                 times[1] = wim_timestamp_to_timeval(mtime);
227
228                 if (fd >= 0 && !futimes(fd, times))
229                         return 0;
230                 if (fd < 0 && !lutimes(path, times))
231                         return 0;
232                 return WIMLIB_ERR_SET_TIMESTAMPS;
233         }
234 }
235
236 static int
237 unix_set_owner_and_group(int fd, const char *path, uid_t uid, gid_t gid)
238 {
239         if (fd >= 0 && !fchown(fd, uid, gid))
240                 return 0;
241         if (fd < 0 && !lchown(path, uid, gid))
242                 return 0;
243         return WIMLIB_ERR_SET_SECURITY;
244 }
245
246 static int
247 unix_set_mode(int fd, const char *path, mode_t mode)
248 {
249         if (fd >= 0 && !fchmod(fd, mode))
250                 return 0;
251         if (fd < 0 && !chmod(path, mode))
252                 return 0;
253         return WIMLIB_ERR_SET_SECURITY;
254 }
255
256 /*
257  * Set metadata on an extracted file.
258  *
259  * @fd is an open file descriptor to the extracted file, or -1.  @path is the
260  * path to the extracted file, or NULL.  If valid, this function uses @fd.
261  * Otherwise, if valid, it uses @path.  Otherwise, it calculates the path to one
262  * alias of the extracted file and uses it.
263  */
264 static int
265 unix_set_metadata(int fd, const struct wim_inode *inode,
266                   const char *path, struct unix_apply_ctx *ctx)
267 {
268         int ret;
269         struct wimlib_unix_data unix_data;
270
271         if (fd < 0 && !path)
272                 path = unix_build_inode_extraction_path(inode, ctx);
273
274         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA)
275             && inode_get_unix_data(inode, &unix_data))
276         {
277                 u32 uid = unix_data.uid;
278                 u32 gid = unix_data.gid;
279                 u32 mode = unix_data.mode;
280
281                 ret = unix_set_owner_and_group(fd, path, uid, gid);
282                 if (ret) {
283                         if (!path)
284                                 path = unix_build_inode_extraction_path(inode, ctx);
285                         if (ctx->common.extract_flags &
286                             WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
287                         {
288                                 ERROR_WITH_ERRNO("Can't set uid=%"PRIu32" and "
289                                                  "gid=%"PRIu32" on \"%s\"",
290                                                  uid, gid, path);
291                                 return ret;
292                         } else {
293                                 WARNING_WITH_ERRNO("Can't set uid=%"PRIu32" and "
294                                                    "gid=%"PRIu32" on \"%s\"",
295                                                    uid, gid, path);
296                         }
297                 }
298
299                 ret = 0;
300                 if (!inode_is_symlink(inode))
301                         ret = unix_set_mode(fd, path, mode);
302                 if (ret) {
303                         if (!path)
304                                 path = unix_build_inode_extraction_path(inode, ctx);
305                         if (ctx->common.extract_flags &
306                             WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
307                         {
308                                 ERROR_WITH_ERRNO("Can't set mode=0%"PRIo32" "
309                                                  "on \"%s\"", mode, path);
310                                 return ret;
311                         } else {
312                                 WARNING_WITH_ERRNO("Can't set mode=0%"PRIo32" "
313                                                    "on \"%s\"", mode, path);
314                         }
315                 }
316         }
317
318         ret = unix_set_timestamps(fd, path,
319                                   inode->i_last_access_time,
320                                   inode->i_last_write_time);
321         if (ret) {
322                 if (!path)
323                         path = unix_build_inode_extraction_path(inode, ctx);
324                 if (ctx->common.extract_flags &
325                     WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS)
326                 {
327                         ERROR_WITH_ERRNO("Can't set timestamps on \"%s\"", path);
328                         return ret;
329                 } else {
330                         WARNING_WITH_ERRNO("Can't set timestamps on \"%s\"", path);
331                 }
332         }
333         return 0;
334 }
335
336 /* Extract all needed aliases of the @inode, where one alias, corresponding to
337  * @first_dentry, has already been extracted to @first_path.  */
338 static int
339 unix_create_hardlinks(const struct wim_inode *inode,
340                       const struct wim_dentry *first_dentry,
341                       const char *first_path, struct unix_apply_ctx *ctx)
342 {
343         const struct wim_dentry *dentry;
344         const char *newpath;
345
346         inode_for_each_extraction_alias(dentry, inode) {
347                 if (dentry == first_dentry)
348                         continue;
349
350                 newpath = unix_build_extraction_path(dentry, ctx);
351         retry_link:
352                 if (link(first_path, newpath)) {
353                         if (errno == EEXIST && !unlink(newpath))
354                                 goto retry_link;
355                         ERROR_WITH_ERRNO("Can't create hard link "
356                                          "\"%s\" => \"%s\"", newpath, first_path);
357                         return WIMLIB_ERR_LINK;
358                 }
359                 unix_reuse_pathbuf(ctx);
360         }
361         return 0;
362 }
363
364 /* If @dentry represents a directory, create it.  */
365 static int
366 unix_create_if_directory(const struct wim_dentry *dentry,
367                          struct unix_apply_ctx *ctx)
368 {
369         const char *path;
370         struct stat stbuf;
371
372         if (!should_extract_as_directory(dentry->d_inode))
373                 return 0;
374
375         path = unix_build_extraction_path(dentry, ctx);
376         if (mkdir(path, 0755) &&
377             /* It's okay if the path already exists, as long as it's a
378              * directory.  */
379             !(errno == EEXIST && !lstat(path, &stbuf) && S_ISDIR(stbuf.st_mode)))
380         {
381                 ERROR_WITH_ERRNO("Can't create directory \"%s\"", path);
382                 return WIMLIB_ERR_MKDIR;
383         }
384
385         return report_file_created(&ctx->common);
386 }
387
388 /* If @dentry represents an empty regular file or a special file, create it, set
389  * its metadata, and create any needed hard links.  */
390 static int
391 unix_extract_if_empty_file(const struct wim_dentry *dentry,
392                            struct unix_apply_ctx *ctx)
393 {
394         const struct wim_inode *inode;
395         struct wimlib_unix_data unix_data;
396         const char *path;
397         int ret;
398
399         inode = dentry->d_inode;
400
401         /* Extract all aliases only when the "first" comes up.  */
402         if (dentry != inode_first_extraction_dentry(inode))
403                 return 0;
404
405         /* Is this a directory, a symbolic link, or any type of nonempty file?
406          */
407         if (should_extract_as_directory(inode) || inode_is_symlink(inode) ||
408             inode_get_blob_for_unnamed_data_stream_resolved(inode))
409                 return 0;
410
411         /* Recognize special files in UNIX_DATA mode  */
412         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
413             inode_get_unix_data(inode, &unix_data) &&
414             !S_ISREG(unix_data.mode))
415         {
416                 path = unix_build_extraction_path(dentry, ctx);
417         retry_mknod:
418                 if (mknod(path, unix_data.mode, unix_data.rdev)) {
419                         if (errno == EPERM) {
420                                 WARNING_WITH_ERRNO("Can't create special "
421                                                    "file \"%s\"", path);
422                                 ctx->num_special_files_ignored++;
423                                 return 0;
424                         }
425                         if (errno == EEXIST && !unlink(path))
426                                 goto retry_mknod;
427                         ERROR_WITH_ERRNO("Can't create special file \"%s\"",
428                                          path);
429                         return WIMLIB_ERR_MKNOD;
430                 }
431                 /* On special files, we can set timestamps immediately because
432                  * we don't need to write any data to them.  */
433                 ret = unix_set_metadata(-1, inode, path, ctx);
434         } else {
435                 int fd;
436
437                 path = unix_build_extraction_path(dentry, ctx);
438         retry_create:
439                 fd = open(path, O_EXCL | O_CREAT | O_WRONLY | O_NOFOLLOW, 0644);
440                 if (fd < 0) {
441                         if (errno == EEXIST && !unlink(path))
442                                 goto retry_create;
443                         ERROR_WITH_ERRNO("Can't create regular file \"%s\"", path);
444                         return WIMLIB_ERR_OPEN;
445                 }
446                 /* On empty files, we can set timestamps immediately because we
447                  * don't need to write any data to them.  */
448                 ret = unix_set_metadata(fd, inode, path, ctx);
449                 if (close(fd) && !ret) {
450                         ERROR_WITH_ERRNO("Error closing \"%s\"", path);
451                         ret = WIMLIB_ERR_WRITE;
452                 }
453         }
454         if (ret)
455                 return ret;
456
457         ret = unix_create_hardlinks(inode, dentry, path, ctx);
458         if (ret)
459                 return ret;
460
461         return report_file_created(&ctx->common);
462 }
463
464 static int
465 unix_create_dirs_and_empty_files(const struct list_head *dentry_list,
466                                  struct unix_apply_ctx *ctx)
467 {
468         const struct wim_dentry *dentry;
469         int ret;
470
471         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
472                 ret = unix_create_if_directory(dentry, ctx);
473                 if (ret)
474                         return ret;
475         }
476         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
477                 ret = unix_extract_if_empty_file(dentry, ctx);
478                 if (ret)
479                         return ret;
480         }
481         return 0;
482 }
483
484 static void
485 unix_count_dentries(const struct list_head *dentry_list,
486                     u64 *dir_count_ret, u64 *empty_file_count_ret)
487 {
488         const struct wim_dentry *dentry;
489         u64 dir_count = 0;
490         u64 empty_file_count = 0;
491
492         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
493
494                 const struct wim_inode *inode = dentry->d_inode;
495
496                 if (should_extract_as_directory(inode))
497                         dir_count++;
498                 else if ((dentry == inode_first_extraction_dentry(inode)) &&
499                          !inode_is_symlink(inode) &&
500                          !inode_get_blob_for_unnamed_data_stream_resolved(inode))
501                         empty_file_count++;
502         }
503
504         *dir_count_ret = dir_count;
505         *empty_file_count_ret = empty_file_count;
506 }
507
508 static int
509 unix_create_symlink(const struct wim_inode *inode, const char *path,
510                     size_t rpdatalen, struct unix_apply_ctx *ctx)
511 {
512         char target[REPARSE_POINT_MAX_SIZE];
513         struct blob_descriptor blob_override;
514         int ret;
515
516         blob_set_is_located_in_attached_buffer(&blob_override,
517                                                ctx->reparse_data, rpdatalen);
518
519         ret = wim_inode_readlink(inode, target, sizeof(target) - 1,
520                                  &blob_override,
521                                  ctx->target_abspath,
522                                  ctx->target_abspath_nchars);
523         if (unlikely(ret < 0)) {
524                 errno = -ret;
525                 return WIMLIB_ERR_READLINK;
526         }
527         target[ret] = '\0';
528
529 retry_symlink:
530         if (symlink(target, path)) {
531                 if (errno == EEXIST && !unlink(path))
532                         goto retry_symlink;
533                 return WIMLIB_ERR_LINK;
534         }
535         return 0;
536 }
537
538 static void
539 unix_cleanup_open_fds(struct unix_apply_ctx *ctx, unsigned offset)
540 {
541         for (unsigned i = offset; i < ctx->num_open_fds; i++)
542                 filedes_close(&ctx->open_fds[i]);
543         ctx->num_open_fds = 0;
544 }
545
546 static int
547 unix_begin_extract_blob_instance(const struct blob_descriptor *blob,
548                                  const struct wim_inode *inode,
549                                  const struct wim_inode_stream *strm,
550                                  struct unix_apply_ctx *ctx)
551 {
552         const struct wim_dentry *first_dentry;
553         const char *first_path;
554         int fd;
555
556         if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
557                 /* On UNIX, symbolic links must be created with symlink(), which
558                  * requires that the full link target be available.  */
559                 if (blob->size > REPARSE_DATA_MAX_SIZE) {
560                         ERROR_WITH_ERRNO("Reparse data of \"%s\" has size "
561                                          "%"PRIu64" bytes (exceeds %u bytes)",
562                                          inode_any_full_path(inode),
563                                          blob->size, REPARSE_DATA_MAX_SIZE);
564                         return WIMLIB_ERR_INVALID_REPARSE_DATA;
565                 }
566                 ctx->reparse_ptr = ctx->reparse_data;
567                 return 0;
568         }
569
570         wimlib_assert(stream_is_unnamed_data_stream(strm));
571
572         /* Unnamed data stream of "regular" file  */
573
574         /* This should be ensured by extract_blob_list()  */
575         wimlib_assert(ctx->num_open_fds < MAX_OPEN_FILES);
576
577         first_dentry = inode_first_extraction_dentry(inode);
578         first_path = unix_build_extraction_path(first_dentry, ctx);
579 retry_create:
580         fd = open(first_path, O_EXCL | O_CREAT | O_WRONLY | O_NOFOLLOW, 0644);
581         if (fd < 0) {
582                 if (errno == EEXIST && !unlink(first_path))
583                         goto retry_create;
584                 ERROR_WITH_ERRNO("Can't create regular file \"%s\"", first_path);
585                 return WIMLIB_ERR_OPEN;
586         }
587         filedes_init(&ctx->open_fds[ctx->num_open_fds++], fd);
588         return unix_create_hardlinks(inode, first_dentry, first_path, ctx);
589 }
590
591 /* Called when starting to read a blob for extraction  */
592 static int
593 unix_begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
594 {
595         struct unix_apply_ctx *ctx = _ctx;
596         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
597
598         for (u32 i = 0; i < blob->out_refcnt; i++) {
599                 int ret = unix_begin_extract_blob_instance(blob,
600                                                            targets[i].inode,
601                                                            targets[i].stream,
602                                                            ctx);
603                 if (ret) {
604                         ctx->reparse_ptr = NULL;
605                         unix_cleanup_open_fds(ctx, 0);
606                         return ret;
607                 }
608         }
609         return 0;
610 }
611
612 /* Called when the next chunk of a blob has been read for extraction  */
613 static int
614 unix_extract_chunk(const void *chunk, size_t size, void *_ctx)
615 {
616         struct unix_apply_ctx *ctx = _ctx;
617         int ret;
618
619         for (unsigned i = 0; i < ctx->num_open_fds; i++) {
620                 ret = full_write(&ctx->open_fds[i], chunk, size);
621                 if (ret) {
622                         ERROR_WITH_ERRNO("Error writing data to filesystem");
623                         return ret;
624                 }
625         }
626         if (ctx->reparse_ptr)
627                 ctx->reparse_ptr = mempcpy(ctx->reparse_ptr, chunk, size);
628         return 0;
629 }
630
631 /* Called when a blob has been fully read for extraction  */
632 static int
633 unix_end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
634 {
635         struct unix_apply_ctx *ctx = _ctx;
636         int ret;
637         unsigned j;
638         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
639
640         ctx->reparse_ptr = NULL;
641
642         if (status) {
643                 unix_cleanup_open_fds(ctx, 0);
644                 return status;
645         }
646
647         j = 0;
648         ret = 0;
649         for (u32 i = 0; i < blob->out_refcnt; i++) {
650                 struct wim_inode *inode = targets[i].inode;
651
652                 if (inode_is_symlink(inode)) {
653                         /* We finally have the symlink data, so we can create
654                          * the symlink.  */
655                         const char *path;
656
657                         path = unix_build_inode_extraction_path(inode, ctx);
658                         ret = unix_create_symlink(inode, path, blob->size, ctx);
659                         if (ret) {
660                                 ERROR_WITH_ERRNO("Can't create symbolic link "
661                                                  "\"%s\"", path);
662                                 break;
663                         }
664                         ret = unix_set_metadata(-1, inode, path, ctx);
665                         if (ret)
666                                 break;
667                 } else {
668                         /* Set metadata on regular file just before closing it.
669                          */
670                         struct filedes *fd = &ctx->open_fds[j];
671
672                         ret = unix_set_metadata(fd->fd, inode, NULL, ctx);
673                         if (ret)
674                                 break;
675
676                         if (filedes_close(fd)) {
677                                 ERROR_WITH_ERRNO("Error closing \"%s\"",
678                                                  unix_build_inode_extraction_path(inode, ctx));
679                                 ret = WIMLIB_ERR_WRITE;
680                                 break;
681                         }
682                         j++;
683                 }
684         }
685         unix_cleanup_open_fds(ctx, j);
686         return ret;
687 }
688
689 static int
690 unix_set_dir_metadata(struct list_head *dentry_list, struct unix_apply_ctx *ctx)
691 {
692         const struct wim_dentry *dentry;
693         int ret;
694
695         list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node) {
696                 if (should_extract_as_directory(dentry->d_inode)) {
697                         ret = unix_set_metadata(-1, dentry->d_inode, NULL, ctx);
698                         if (ret)
699                                 return ret;
700                         ret = report_file_metadata_applied(&ctx->common);
701                         if (ret)
702                                 return ret;
703                 }
704         }
705         return 0;
706 }
707
708 static int
709 unix_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
710 {
711         int ret;
712         struct unix_apply_ctx *ctx = (struct unix_apply_ctx *)_ctx;
713         size_t path_max;
714         u64 dir_count;
715         u64 empty_file_count;
716
717         /* Compute the maximum path length that will be needed, then allocate
718          * some path buffers.  */
719         path_max = unix_compute_path_max(dentry_list, ctx);
720
721         for (unsigned i = 0; i < NUM_PATHBUFS; i++) {
722                 ctx->pathbufs[i] = MALLOC(path_max);
723                 if (!ctx->pathbufs[i]) {
724                         ret = WIMLIB_ERR_NOMEM;
725                         goto out;
726                 }
727                 /* Pre-fill the target in each path buffer.  We'll just append
728                  * the rest of the paths after this.  */
729                 memcpy(ctx->pathbufs[i],
730                        ctx->common.target, ctx->common.target_nchars);
731         }
732
733         /* Extract directories and empty regular files.  Directories are needed
734          * because we can't extract any other files until their directories
735          * exist.  Empty files are needed because they don't have
736          * representatives in the blob list.  */
737
738         unix_count_dentries(dentry_list, &dir_count, &empty_file_count);
739
740         ret = start_file_structure_phase(&ctx->common, dir_count + empty_file_count);
741         if (ret)
742                 goto out;
743
744         ret = unix_create_dirs_and_empty_files(dentry_list, ctx);
745         if (ret)
746                 goto out;
747
748         ret = end_file_structure_phase(&ctx->common);
749         if (ret)
750                 goto out;
751
752         /* Get full path to target if needed for absolute symlink fixups.  */
753         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
754             ctx->common.required_features.symlink_reparse_points)
755         {
756                 ctx->target_abspath = realpath(ctx->common.target, NULL);
757                 if (!ctx->target_abspath) {
758                         ret = WIMLIB_ERR_NOMEM;
759                         goto out;
760                 }
761                 ctx->target_abspath_nchars = strlen(ctx->target_abspath);
762         }
763
764         /* Extract nonempty regular files and symbolic links.  */
765
766         struct read_blob_callbacks cbs = {
767                 .begin_blob     = unix_begin_extract_blob,
768                 .consume_chunk  = unix_extract_chunk,
769                 .end_blob       = unix_end_extract_blob,
770                 .ctx            = ctx,
771         };
772         ret = extract_blob_list(&ctx->common, &cbs);
773         if (ret)
774                 goto out;
775
776
777         /* Set directory metadata.  We do this last so that we get the right
778          * directory timestamps.  */
779         ret = start_file_metadata_phase(&ctx->common, dir_count);
780         if (ret)
781                 goto out;
782
783         ret = unix_set_dir_metadata(dentry_list, ctx);
784         if (ret)
785                 goto out;
786
787         ret = end_file_metadata_phase(&ctx->common);
788         if (ret)
789                 goto out;
790
791         if (ctx->num_special_files_ignored) {
792                 WARNING("%lu special files were not extracted due to EPERM!",
793                         ctx->num_special_files_ignored);
794         }
795 out:
796         for (unsigned i = 0; i < NUM_PATHBUFS; i++)
797                 FREE(ctx->pathbufs[i]);
798         FREE(ctx->target_abspath);
799         return ret;
800 }
801
802 const struct apply_operations unix_apply_ops = {
803         .name                   = "UNIX",
804         .get_supported_features = unix_get_supported_features,
805         .extract                = unix_extract,
806         .context_size           = sizeof(struct unix_apply_ctx),
807 };