]> wimlib.net Git - wimlib/blob - src/unix_apply.c
configure.ac: generate version number from git commit and tags
[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-2018 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 #ifdef HAVE_SYS_XATTR_H
33 #  include <sys/xattr.h>
34 #endif
35 #include <unistd.h>
36
37 #include "wimlib/apply.h"
38 #include "wimlib/assert.h"
39 #include "wimlib/blob_table.h"
40 #include "wimlib/dentry.h"
41 #include "wimlib/error.h"
42 #include "wimlib/file_io.h"
43 #include "wimlib/reparse.h"
44 #include "wimlib/timestamp.h"
45 #include "wimlib/unix_data.h"
46 #include "wimlib/xattr.h"
47
48 /* We don't require O_NOFOLLOW, but the advantage of having it is that if we
49  * need to extract a file to a location at which there exists a symbolic link,
50  * open(..., O_NOFOLLOW | ...) recognizes the symbolic link rather than
51  * following it and creating the file somewhere else.  (Equivalent to
52  * FILE_OPEN_REPARSE_POINT on Windows.)  */
53 #ifndef O_NOFOLLOW
54 #  define O_NOFOLLOW 0
55 #endif
56
57 static int
58 unix_get_supported_features(const char *target,
59                             struct wim_features *supported_features)
60 {
61         supported_features->sparse_files = 1;
62         supported_features->hard_links = 1;
63         supported_features->symlink_reparse_points = 1;
64         supported_features->unix_data = 1;
65         supported_features->timestamps = 1;
66         supported_features->case_sensitive_filenames = 1;
67 #ifdef HAVE_LINUX_XATTR_SUPPORT
68         supported_features->xattrs = 1;
69 #endif
70         return 0;
71 }
72
73 #define NUM_PATHBUFS 2  /* We need 2 when creating hard links  */
74
75 struct unix_apply_ctx {
76         /* Extract flags, the pointer to the WIMStruct, etc.  */
77         struct apply_ctx common;
78
79         /* Buffers for building extraction paths (allocated).  */
80         char *pathbufs[NUM_PATHBUFS];
81
82         /* Index of next pathbuf to use  */
83         unsigned which_pathbuf;
84
85         /* Currently open file descriptors for extraction  */
86         struct filedes open_fds[MAX_OPEN_FILES];
87
88         /* Number of currently open file descriptors in open_fds, starting from
89          * the beginning of the array.  */
90         unsigned num_open_fds;
91
92         /* For each currently open file, whether we're writing to it in "sparse"
93          * mode or not.  */
94         bool is_sparse_file[MAX_OPEN_FILES];
95
96         /* Whether is_sparse_file[] is true for any currently open file  */
97         bool any_sparse_files;
98
99         /* Buffer for reading reparse point data into memory  */
100         u8 reparse_data[REPARSE_DATA_MAX_SIZE];
101
102         /* Pointer to the next byte in @reparse_data to fill  */
103         u8 *reparse_ptr;
104
105         /* Absolute path to the target directory (allocated buffer).  Only set
106          * if needed for absolute symbolic link fixups.  */
107         char *target_abspath;
108
109         /* Number of characters in target_abspath.  */
110         size_t target_abspath_nchars;
111
112         /* Number of special files we couldn't create due to EPERM  */
113         unsigned long num_special_files_ignored;
114 };
115
116 /* Returns the number of characters needed to represent the path to the
117  * specified @dentry when extracted, not including the null terminator or the
118  * path to the target directory itself.  */
119 static size_t
120 unix_dentry_path_length(const struct wim_dentry *dentry)
121 {
122         size_t len = 0;
123         const struct wim_dentry *d;
124
125         d = dentry;
126         do {
127                 len += d->d_extraction_name_nchars + 1;
128                 d = d->d_parent;
129         } while (!dentry_is_root(d) && will_extract_dentry(d));
130
131         return len;
132 }
133
134 /* Returns the maximum number of characters needed to represent the path to any
135  * dentry in @dentry_list when extracted, including the null terminator and the
136  * path to the target directory itself.  */
137 static size_t
138 unix_compute_path_max(const struct list_head *dentry_list,
139                       const struct unix_apply_ctx *ctx)
140 {
141         size_t max = 0;
142         size_t len;
143         const struct wim_dentry *dentry;
144
145         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
146                 len = unix_dentry_path_length(dentry);
147                 if (len > max)
148                         max = len;
149         }
150
151         /* Account for target and null terminator.  */
152         return ctx->common.target_nchars + max + 1;
153 }
154
155 /* Builds and returns the filesystem path to which to extract @dentry.
156  * This cycles through NUM_PATHBUFS different buffers.  */
157 static const char *
158 unix_build_extraction_path(const struct wim_dentry *dentry,
159                            struct unix_apply_ctx *ctx)
160 {
161         char *pathbuf;
162         char *p;
163         const struct wim_dentry *d;
164
165         pathbuf = ctx->pathbufs[ctx->which_pathbuf];
166         ctx->which_pathbuf = (ctx->which_pathbuf + 1) % NUM_PATHBUFS;
167
168         p = &pathbuf[ctx->common.target_nchars +
169                      unix_dentry_path_length(dentry)];
170         *p = '\0';
171         d = dentry;
172         do {
173                 p -= d->d_extraction_name_nchars;
174                 if (d->d_extraction_name_nchars)
175                         memcpy(p, d->d_extraction_name,
176                                d->d_extraction_name_nchars);
177                 *--p = '/';
178                 d = d->d_parent;
179         } while (!dentry_is_root(d) && will_extract_dentry(d));
180
181         return pathbuf;
182 }
183
184 /* This causes the next call to unix_build_extraction_path() to use the same
185  * path buffer as the previous call.  */
186 static void
187 unix_reuse_pathbuf(struct unix_apply_ctx *ctx)
188 {
189         ctx->which_pathbuf = (ctx->which_pathbuf - 1) % NUM_PATHBUFS;
190 }
191
192 /* Builds and returns the filesystem path to which to extract an unspecified
193  * alias of the @inode.  This cycles through NUM_PATHBUFS different buffers.  */
194 static const char *
195 unix_build_inode_extraction_path(const struct wim_inode *inode,
196                                  struct unix_apply_ctx *ctx)
197 {
198         return unix_build_extraction_path(inode_first_extraction_dentry(inode), ctx);
199 }
200
201 /* Should the specified file be extracted as a directory on UNIX?  We extract
202  * the file as a directory if FILE_ATTRIBUTE_DIRECTORY is set and the file does
203  * not have a symlink or junction reparse point.  It *may* have a different type
204  * of reparse point.  */
205 static inline bool
206 should_extract_as_directory(const struct wim_inode *inode)
207 {
208         return (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) &&
209                 !inode_is_symlink(inode);
210 }
211
212 /* Sets the timestamps on a file being extracted.
213  *
214  * Either @fd or @path must be specified (not -1 and not NULL, respectively).
215  */
216 static int
217 unix_set_timestamps(int fd, const char *path, u64 atime, u64 mtime)
218 {
219         {
220                 struct timespec times[2];
221
222                 times[0] = wim_timestamp_to_timespec(atime);
223                 times[1] = wim_timestamp_to_timespec(mtime);
224
225                 errno = ENOSYS;
226 #ifdef HAVE_FUTIMENS
227                 if (fd >= 0 && !futimens(fd, times))
228                         return 0;
229 #endif
230 #ifdef HAVE_UTIMENSAT
231                 if (fd < 0 && !utimensat(AT_FDCWD, path, times, AT_SYMLINK_NOFOLLOW))
232                         return 0;
233 #endif
234                 if (errno != ENOSYS)
235                         return WIMLIB_ERR_SET_TIMESTAMPS;
236         }
237         {
238                 struct timeval times[2];
239
240                 times[0] = wim_timestamp_to_timeval(atime);
241                 times[1] = wim_timestamp_to_timeval(mtime);
242
243                 if (fd >= 0 && !futimes(fd, times))
244                         return 0;
245                 if (fd < 0 && !lutimes(path, times))
246                         return 0;
247                 return WIMLIB_ERR_SET_TIMESTAMPS;
248         }
249 }
250
251 static int
252 unix_set_owner_and_group(int fd, const char *path, uid_t uid, gid_t gid)
253 {
254         if (fd >= 0 && !fchown(fd, uid, gid))
255                 return 0;
256         if (fd < 0 && !lchown(path, uid, gid))
257                 return 0;
258         return WIMLIB_ERR_SET_SECURITY;
259 }
260
261 static int
262 unix_set_mode(int fd, const char *path, mode_t mode)
263 {
264         if (fd >= 0 && !fchmod(fd, mode))
265                 return 0;
266         if (fd < 0 && !chmod(path, mode))
267                 return 0;
268         return WIMLIB_ERR_SET_SECURITY;
269 }
270
271 #ifdef HAVE_LINUX_XATTR_SUPPORT
272 /* Apply extended attributes to a file */
273 static int
274 apply_linux_xattrs(int fd, const struct wim_inode *inode,
275                    const char *path, struct unix_apply_ctx *ctx,
276                    const void *entries, size_t entries_size, bool is_old_format)
277 {
278         const void * const entries_end = entries + entries_size;
279         char name[WIM_XATTR_NAME_MAX + 1];
280
281         for (const void *entry = entries;
282              entry < entries_end;
283              entry = is_old_format ? (const void *)old_xattr_entry_next(entry) :
284                                      (const void *)xattr_entry_next(entry))
285         {
286                 bool valid;
287                 u16 name_len;
288                 const void *value;
289                 u32 value_len;
290                 int res;
291
292                 if (is_old_format) {
293                         valid = old_valid_xattr_entry(entry,
294                                                       entries_end - entry);
295                 } else {
296                         valid = valid_xattr_entry(entry, entries_end - entry);
297                 }
298                 if (!valid) {
299                         if (!path) {
300                                 path = unix_build_inode_extraction_path(inode,
301                                                                         ctx);
302                         }
303                         ERROR("\"%s\": extended attribute is corrupt or unsupported",
304                               path);
305                         return WIMLIB_ERR_INVALID_XATTR;
306                 }
307                 if (is_old_format) {
308                         const struct wimlib_xattr_entry_old *e = entry;
309
310                         name_len = le16_to_cpu(e->name_len);
311                         memcpy(name, e->name, name_len);
312                         value = e->name + name_len;
313                         value_len = le32_to_cpu(e->value_len);
314                 } else {
315                         const struct wim_xattr_entry *e = entry;
316
317                         name_len = e->name_len;
318                         memcpy(name, e->name, name_len);
319                         value = e->name + name_len + 1;
320                         value_len = le16_to_cpu(e->value_len);
321                 }
322                 name[name_len] = '\0';
323
324                 if (fd >= 0)
325                         res = fsetxattr(fd, name, value, value_len, 0);
326                 else
327                         res = lsetxattr(path, name, value, value_len, 0);
328
329                 if (unlikely(res != 0)) {
330                         if (!path) {
331                                 path = unix_build_inode_extraction_path(inode,
332                                                                         ctx);
333                         }
334                         if (is_linux_security_xattr(name) &&
335                             (ctx->common.extract_flags &
336                              WIMLIB_EXTRACT_FLAG_STRICT_ACLS))
337                         {
338                                 ERROR_WITH_ERRNO("\"%s\": unable to set extended attribute \"%s\"",
339                                                  path, name);
340                                 return WIMLIB_ERR_SET_XATTR;
341                         }
342                         WARNING_WITH_ERRNO("\"%s\": unable to set extended attribute \"%s\"",
343                                            path, name);
344                 }
345         }
346         return 0;
347 }
348 #endif /* HAVE_LINUX_XATTR_SUPPORT */
349
350 /*
351  * Apply UNIX-specific metadata to a file if available.  This includes standard
352  * UNIX permissions (uid, gid, and mode) and possibly extended attributes too.
353  *
354  * Note that some xattrs which grant privileges, e.g. security.capability, are
355  * cleared by Linux on chown(), even when running as root.  Also, when running
356  * as non-root, if we need to chmod() the file to readonly, we can't do that
357  * before setting xattrs because setxattr() requires write permission.  These
358  * restrictions result in the following ordering which we follow: chown(),
359  * setxattr(), then chmod().
360  *
361  * N.B. the file may be specified by either 'fd' (for regular files) or 'path',
362  * and it may be a symlink.  For symlinks we need lchown() and lsetxattr() but
363  * need to skip the chmod(), since mode bits are not meaningful for symlinks.
364  */
365 static int
366 apply_unix_metadata(int fd, const struct wim_inode *inode,
367                     const char *path, struct unix_apply_ctx *ctx)
368 {
369         bool have_dat;
370         struct wimlib_unix_data dat;
371 #ifdef HAVE_LINUX_XATTR_SUPPORT
372         const void *entries;
373         u32 entries_size;
374         bool is_old_format;
375 #endif
376         int ret;
377
378         have_dat = inode_get_unix_data(inode, &dat);
379
380         if (have_dat) {
381                 ret = unix_set_owner_and_group(fd, path, dat.uid, dat.gid);
382                 if (ret) {
383                         if (!path)
384                                 path = unix_build_inode_extraction_path(inode, ctx);
385                         if (ctx->common.extract_flags &
386                             WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
387                         {
388                                 ERROR_WITH_ERRNO("\"%s\": unable to set uid=%"PRIu32" and gid=%"PRIu32,
389                                                  path, dat.uid, dat.gid);
390                                 return ret;
391                         }
392                         WARNING_WITH_ERRNO("\"%s\": unable to set uid=%"PRIu32" and gid=%"PRIu32,
393                                            path, dat.uid, dat.gid);
394                 }
395         }
396
397 #ifdef HAVE_LINUX_XATTR_SUPPORT
398         entries = inode_get_linux_xattrs(inode, &entries_size, &is_old_format);
399         if (entries) {
400                 ret = apply_linux_xattrs(fd, inode, path, ctx,
401                                          entries, entries_size, is_old_format);
402                 if (ret)
403                         return ret;
404         }
405 #endif
406
407         if (have_dat && !inode_is_symlink(inode)) {
408                 ret = unix_set_mode(fd, path, dat.mode);
409                 if (ret) {
410                         if (!path)
411                                 path = unix_build_inode_extraction_path(inode, ctx);
412                         if (ctx->common.extract_flags &
413                             WIMLIB_EXTRACT_FLAG_STRICT_ACLS)
414                         {
415                                 ERROR_WITH_ERRNO("\"%s\": unable to set mode=0%"PRIo32,
416                                                  path, dat.mode);
417                                 return ret;
418                         }
419                         WARNING_WITH_ERRNO("\"%s\": unable to set mode=0%"PRIo32,
420                                            path, dat.mode);
421                 }
422         }
423
424         return 0;
425 }
426
427 /*
428  * Set metadata on an extracted file.
429  *
430  * @fd is an open file descriptor to the extracted file, or -1.  @path is the
431  * path to the extracted file, or NULL.  If valid, this function uses @fd.
432  * Otherwise, if valid, it uses @path.  Otherwise, it calculates the path to one
433  * alias of the extracted file and uses it.
434  */
435 static int
436 unix_set_metadata(int fd, const struct wim_inode *inode,
437                   const char *path, struct unix_apply_ctx *ctx)
438 {
439         int ret;
440
441         if (fd < 0 && !path)
442                 path = unix_build_inode_extraction_path(inode, ctx);
443
444         if (ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) {
445                 ret = apply_unix_metadata(fd, inode, path, ctx);
446                 if (ret)
447                         return ret;
448         }
449
450         ret = unix_set_timestamps(fd, path, inode->i_last_access_time,
451                                   inode->i_last_write_time);
452         if (ret) {
453                 if (!path)
454                         path = unix_build_inode_extraction_path(inode, ctx);
455                 if (ctx->common.extract_flags &
456                     WIMLIB_EXTRACT_FLAG_STRICT_TIMESTAMPS)
457                 {
458                         ERROR_WITH_ERRNO("\"%s\": unable to set timestamps", path);
459                         return ret;
460                 }
461                 WARNING_WITH_ERRNO("\"%s\": unable to set timestamps", path);
462         }
463
464         return 0;
465 }
466
467 /* Extract all needed aliases of the @inode, where one alias, corresponding to
468  * @first_dentry, has already been extracted to @first_path.  */
469 static int
470 unix_create_hardlinks(const struct wim_inode *inode,
471                       const struct wim_dentry *first_dentry,
472                       const char *first_path, struct unix_apply_ctx *ctx)
473 {
474         const struct wim_dentry *dentry;
475         const char *newpath;
476
477         inode_for_each_extraction_alias(dentry, inode) {
478                 if (dentry == first_dentry)
479                         continue;
480
481                 newpath = unix_build_extraction_path(dentry, ctx);
482         retry_link:
483                 if (link(first_path, newpath)) {
484                         if (errno == EEXIST && !unlink(newpath))
485                                 goto retry_link;
486                         ERROR_WITH_ERRNO("Can't create hard link "
487                                          "\"%s\" => \"%s\"", newpath, first_path);
488                         return WIMLIB_ERR_LINK;
489                 }
490                 unix_reuse_pathbuf(ctx);
491         }
492         return 0;
493 }
494
495 /* If @dentry represents a directory, create it.  */
496 static int
497 unix_create_if_directory(const struct wim_dentry *dentry,
498                          struct unix_apply_ctx *ctx)
499 {
500         const char *path;
501         struct stat stbuf;
502
503         if (!should_extract_as_directory(dentry->d_inode))
504                 return 0;
505
506         path = unix_build_extraction_path(dentry, ctx);
507         if (mkdir(path, 0755) &&
508             /* It's okay if the path already exists, as long as it's a
509              * directory.  */
510             !(errno == EEXIST && !lstat(path, &stbuf) && S_ISDIR(stbuf.st_mode)))
511         {
512                 ERROR_WITH_ERRNO("Can't create directory \"%s\"", path);
513                 return WIMLIB_ERR_MKDIR;
514         }
515
516         return report_file_created(&ctx->common);
517 }
518
519 /* If @dentry represents an empty regular file or a special file, create it, set
520  * its metadata, and create any needed hard links.  */
521 static int
522 unix_extract_if_empty_file(const struct wim_dentry *dentry,
523                            struct unix_apply_ctx *ctx)
524 {
525         const struct wim_inode *inode;
526         struct wimlib_unix_data unix_data;
527         const char *path;
528         int ret;
529
530         inode = dentry->d_inode;
531
532         /* Extract all aliases only when the "first" comes up.  */
533         if (dentry != inode_first_extraction_dentry(inode))
534                 return 0;
535
536         /* Is this a directory, a symbolic link, or any type of nonempty file?
537          */
538         if (should_extract_as_directory(inode) || inode_is_symlink(inode) ||
539             inode_get_blob_for_unnamed_data_stream_resolved(inode))
540                 return 0;
541
542         /* Recognize special files in UNIX_DATA mode  */
543         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_UNIX_DATA) &&
544             inode_get_unix_data(inode, &unix_data) &&
545             !S_ISREG(unix_data.mode))
546         {
547                 path = unix_build_extraction_path(dentry, ctx);
548         retry_mknod:
549                 if (mknod(path, unix_data.mode, unix_data.rdev)) {
550                         if (errno == EPERM) {
551                                 WARNING_WITH_ERRNO("Can't create special "
552                                                    "file \"%s\"", path);
553                                 ctx->num_special_files_ignored++;
554                                 return 0;
555                         }
556                         if (errno == EEXIST && !unlink(path))
557                                 goto retry_mknod;
558                         ERROR_WITH_ERRNO("Can't create special file \"%s\"",
559                                          path);
560                         return WIMLIB_ERR_MKNOD;
561                 }
562                 /* On special files, we can set timestamps immediately because
563                  * we don't need to write any data to them.  */
564                 ret = unix_set_metadata(-1, inode, path, ctx);
565         } else {
566                 int fd;
567
568                 path = unix_build_extraction_path(dentry, ctx);
569         retry_create:
570                 fd = open(path, O_EXCL | O_CREAT | O_WRONLY | O_NOFOLLOW, 0644);
571                 if (fd < 0) {
572                         if (errno == EEXIST && !unlink(path))
573                                 goto retry_create;
574                         ERROR_WITH_ERRNO("Can't create regular file \"%s\"", path);
575                         return WIMLIB_ERR_OPEN;
576                 }
577                 /* On empty files, we can set timestamps immediately because we
578                  * don't need to write any data to them.  */
579                 ret = unix_set_metadata(fd, inode, path, ctx);
580                 if (close(fd) && !ret) {
581                         ERROR_WITH_ERRNO("Error closing \"%s\"", path);
582                         ret = WIMLIB_ERR_WRITE;
583                 }
584         }
585         if (ret)
586                 return ret;
587
588         ret = unix_create_hardlinks(inode, dentry, path, ctx);
589         if (ret)
590                 return ret;
591
592         return report_file_created(&ctx->common);
593 }
594
595 static int
596 unix_create_dirs_and_empty_files(const struct list_head *dentry_list,
597                                  struct unix_apply_ctx *ctx)
598 {
599         const struct wim_dentry *dentry;
600         int ret;
601
602         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
603                 ret = unix_create_if_directory(dentry, ctx);
604                 if (ret)
605                         return ret;
606         }
607         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
608                 ret = unix_extract_if_empty_file(dentry, ctx);
609                 if (ret)
610                         return ret;
611         }
612         return 0;
613 }
614
615 static void
616 unix_count_dentries(const struct list_head *dentry_list,
617                     u64 *dir_count_ret, u64 *empty_file_count_ret)
618 {
619         const struct wim_dentry *dentry;
620         u64 dir_count = 0;
621         u64 empty_file_count = 0;
622
623         list_for_each_entry(dentry, dentry_list, d_extraction_list_node) {
624
625                 const struct wim_inode *inode = dentry->d_inode;
626
627                 if (should_extract_as_directory(inode))
628                         dir_count++;
629                 else if ((dentry == inode_first_extraction_dentry(inode)) &&
630                          !inode_is_symlink(inode) &&
631                          !inode_get_blob_for_unnamed_data_stream_resolved(inode))
632                         empty_file_count++;
633         }
634
635         *dir_count_ret = dir_count;
636         *empty_file_count_ret = empty_file_count;
637 }
638
639 static int
640 unix_create_symlink(const struct wim_inode *inode, const char *path,
641                     size_t rpdatalen, struct unix_apply_ctx *ctx)
642 {
643         char target[REPARSE_POINT_MAX_SIZE];
644         struct blob_descriptor blob_override;
645         int ret;
646
647         blob_set_is_located_in_attached_buffer(&blob_override,
648                                                ctx->reparse_data, rpdatalen);
649
650         ret = wim_inode_readlink(inode, target, sizeof(target) - 1,
651                                  &blob_override,
652                                  ctx->target_abspath,
653                                  ctx->target_abspath_nchars);
654         if (unlikely(ret < 0)) {
655                 errno = -ret;
656                 return WIMLIB_ERR_READLINK;
657         }
658         target[ret] = '\0';
659
660 retry_symlink:
661         if (symlink(target, path)) {
662                 if (errno == EEXIST && !unlink(path))
663                         goto retry_symlink;
664                 return WIMLIB_ERR_LINK;
665         }
666         return 0;
667 }
668
669 static void
670 unix_cleanup_open_fds(struct unix_apply_ctx *ctx, unsigned offset)
671 {
672         for (unsigned i = offset; i < ctx->num_open_fds; i++)
673                 filedes_close(&ctx->open_fds[i]);
674         ctx->num_open_fds = 0;
675         ctx->any_sparse_files = false;
676 }
677
678 static int
679 unix_begin_extract_blob_instance(const struct blob_descriptor *blob,
680                                  const struct wim_inode *inode,
681                                  const struct wim_inode_stream *strm,
682                                  struct unix_apply_ctx *ctx)
683 {
684         const struct wim_dentry *first_dentry;
685         const char *first_path;
686         int fd;
687
688         if (unlikely(strm->stream_type == STREAM_TYPE_REPARSE_POINT)) {
689                 /* On UNIX, symbolic links must be created with symlink(), which
690                  * requires that the full link target be available.  */
691                 if (blob->size > REPARSE_DATA_MAX_SIZE) {
692                         ERROR_WITH_ERRNO("Reparse data of \"%s\" has size "
693                                          "%"PRIu64" bytes (exceeds %u bytes)",
694                                          inode_any_full_path(inode),
695                                          blob->size, REPARSE_DATA_MAX_SIZE);
696                         return WIMLIB_ERR_INVALID_REPARSE_DATA;
697                 }
698                 ctx->reparse_ptr = ctx->reparse_data;
699                 return 0;
700         }
701
702         wimlib_assert(stream_is_unnamed_data_stream(strm));
703
704         /* Unnamed data stream of "regular" file  */
705
706         /* This should be ensured by extract_blob_list()  */
707         wimlib_assert(ctx->num_open_fds < MAX_OPEN_FILES);
708
709         first_dentry = inode_first_extraction_dentry(inode);
710         first_path = unix_build_extraction_path(first_dentry, ctx);
711 retry_create:
712         fd = open(first_path, O_EXCL | O_CREAT | O_WRONLY | O_NOFOLLOW, 0644);
713         if (fd < 0) {
714                 if (errno == EEXIST && !unlink(first_path))
715                         goto retry_create;
716                 ERROR_WITH_ERRNO("Can't create regular file \"%s\"", first_path);
717                 return WIMLIB_ERR_OPEN;
718         }
719         if (inode->i_attributes & FILE_ATTRIBUTE_SPARSE_FILE) {
720                 ctx->is_sparse_file[ctx->num_open_fds] = true;
721                 ctx->any_sparse_files = true;
722         } else {
723                 ctx->is_sparse_file[ctx->num_open_fds] = false;
724 #ifdef HAVE_POSIX_FALLOCATE
725                 posix_fallocate(fd, 0, blob->size);
726 #endif
727         }
728         filedes_init(&ctx->open_fds[ctx->num_open_fds++], fd);
729         return unix_create_hardlinks(inode, first_dentry, first_path, ctx);
730 }
731
732 /* Called when starting to read a blob for extraction  */
733 static int
734 unix_begin_extract_blob(struct blob_descriptor *blob, void *_ctx)
735 {
736         struct unix_apply_ctx *ctx = _ctx;
737         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
738
739         for (u32 i = 0; i < blob->out_refcnt; i++) {
740                 int ret = unix_begin_extract_blob_instance(blob,
741                                                            targets[i].inode,
742                                                            targets[i].stream,
743                                                            ctx);
744                 if (ret) {
745                         ctx->reparse_ptr = NULL;
746                         unix_cleanup_open_fds(ctx, 0);
747                         return ret;
748                 }
749         }
750         return 0;
751 }
752
753 /* Called when the next chunk of a blob has been read for extraction  */
754 static int
755 unix_extract_chunk(const struct blob_descriptor *blob, u64 offset,
756                    const void *chunk, size_t size, void *_ctx)
757 {
758         struct unix_apply_ctx *ctx = _ctx;
759         const void * const end = chunk + size;
760         const void *p;
761         bool zeroes;
762         size_t len;
763         unsigned i;
764         int ret;
765
766         /*
767          * For sparse files, only write nonzero regions.  This lets the
768          * filesystem use holes to represent zero regions.
769          */
770         for (p = chunk; p != end; p += len, offset += len) {
771                 zeroes = maybe_detect_sparse_region(p, end - p, &len,
772                                                     ctx->any_sparse_files);
773                 for (i = 0; i < ctx->num_open_fds; i++) {
774                         if (!zeroes || !ctx->is_sparse_file[i]) {
775                                 ret = full_pwrite(&ctx->open_fds[i],
776                                                   p, len, offset);
777                                 if (ret)
778                                         goto err;
779                         }
780                 }
781         }
782
783         if (ctx->reparse_ptr)
784                 ctx->reparse_ptr = mempcpy(ctx->reparse_ptr, chunk, size);
785         return 0;
786
787 err:
788         ERROR_WITH_ERRNO("Error writing data to filesystem");
789         return ret;
790 }
791
792 /* Called when a blob has been fully read for extraction  */
793 static int
794 unix_end_extract_blob(struct blob_descriptor *blob, int status, void *_ctx)
795 {
796         struct unix_apply_ctx *ctx = _ctx;
797         int ret;
798         unsigned j;
799         const struct blob_extraction_target *targets = blob_extraction_targets(blob);
800
801         ctx->reparse_ptr = NULL;
802
803         if (status) {
804                 unix_cleanup_open_fds(ctx, 0);
805                 return status;
806         }
807
808         j = 0;
809         ret = 0;
810         for (u32 i = 0; i < blob->out_refcnt; i++) {
811                 struct wim_inode *inode = targets[i].inode;
812
813                 if (inode_is_symlink(inode)) {
814                         /* We finally have the symlink data, so we can create
815                          * the symlink.  */
816                         const char *path;
817
818                         path = unix_build_inode_extraction_path(inode, ctx);
819                         ret = unix_create_symlink(inode, path, blob->size, ctx);
820                         if (ret) {
821                                 ERROR_WITH_ERRNO("Can't create symbolic link "
822                                                  "\"%s\"", path);
823                                 break;
824                         }
825                         ret = unix_set_metadata(-1, inode, path, ctx);
826                         if (ret)
827                                 break;
828                 } else {
829                         struct filedes *fd = &ctx->open_fds[j];
830
831                         /* If the file is sparse, extend it to its final size. */
832                         if (ctx->is_sparse_file[j] && ftruncate(fd->fd, blob->size)) {
833                                 ERROR_WITH_ERRNO("Error extending \"%s\" to final size",
834                                                  unix_build_inode_extraction_path(inode, ctx));
835                                 ret = WIMLIB_ERR_WRITE;
836                                 break;
837                         }
838
839                         /* Set metadata on regular file just before closing.  */
840                         ret = unix_set_metadata(fd->fd, inode, NULL, ctx);
841                         if (ret)
842                                 break;
843
844                         if (filedes_close(fd)) {
845                                 ERROR_WITH_ERRNO("Error closing \"%s\"",
846                                                  unix_build_inode_extraction_path(inode, ctx));
847                                 ret = WIMLIB_ERR_WRITE;
848                                 break;
849                         }
850                         j++;
851                 }
852         }
853         unix_cleanup_open_fds(ctx, j);
854         return ret;
855 }
856
857 static int
858 unix_set_dir_metadata(struct list_head *dentry_list, struct unix_apply_ctx *ctx)
859 {
860         const struct wim_dentry *dentry;
861         int ret;
862
863         list_for_each_entry_reverse(dentry, dentry_list, d_extraction_list_node) {
864                 if (should_extract_as_directory(dentry->d_inode)) {
865                         ret = unix_set_metadata(-1, dentry->d_inode, NULL, ctx);
866                         if (ret)
867                                 return ret;
868                         ret = report_file_metadata_applied(&ctx->common);
869                         if (ret)
870                                 return ret;
871                 }
872         }
873         return 0;
874 }
875
876 static int
877 unix_extract(struct list_head *dentry_list, struct apply_ctx *_ctx)
878 {
879         int ret;
880         struct unix_apply_ctx *ctx = (struct unix_apply_ctx *)_ctx;
881         size_t path_max;
882         u64 dir_count;
883         u64 empty_file_count;
884
885         /* Compute the maximum path length that will be needed, then allocate
886          * some path buffers.  */
887         path_max = unix_compute_path_max(dentry_list, ctx);
888
889         for (unsigned i = 0; i < NUM_PATHBUFS; i++) {
890                 ctx->pathbufs[i] = MALLOC(path_max);
891                 if (!ctx->pathbufs[i]) {
892                         ret = WIMLIB_ERR_NOMEM;
893                         goto out;
894                 }
895                 /* Pre-fill the target in each path buffer.  We'll just append
896                  * the rest of the paths after this.  */
897                 memcpy(ctx->pathbufs[i],
898                        ctx->common.target, ctx->common.target_nchars);
899         }
900
901         /* Extract directories and empty regular files.  Directories are needed
902          * because we can't extract any other files until their directories
903          * exist.  Empty files are needed because they don't have
904          * representatives in the blob list.  */
905
906         unix_count_dentries(dentry_list, &dir_count, &empty_file_count);
907
908         ret = start_file_structure_phase(&ctx->common, dir_count + empty_file_count);
909         if (ret)
910                 goto out;
911
912         ret = unix_create_dirs_and_empty_files(dentry_list, ctx);
913         if (ret)
914                 goto out;
915
916         ret = end_file_structure_phase(&ctx->common);
917         if (ret)
918                 goto out;
919
920         /* Get full path to target if needed for absolute symlink fixups.  */
921         if ((ctx->common.extract_flags & WIMLIB_EXTRACT_FLAG_RPFIX) &&
922             ctx->common.required_features.symlink_reparse_points)
923         {
924                 ctx->target_abspath = realpath(ctx->common.target, NULL);
925                 if (!ctx->target_abspath) {
926                         ret = WIMLIB_ERR_NOMEM;
927                         goto out;
928                 }
929                 ctx->target_abspath_nchars = strlen(ctx->target_abspath);
930         }
931
932         /* Extract nonempty regular files and symbolic links.  */
933
934         struct read_blob_callbacks cbs = {
935                 .begin_blob     = unix_begin_extract_blob,
936                 .continue_blob  = unix_extract_chunk,
937                 .end_blob       = unix_end_extract_blob,
938                 .ctx            = ctx,
939         };
940         ret = extract_blob_list(&ctx->common, &cbs);
941         if (ret)
942                 goto out;
943
944
945         /* Set directory metadata.  We do this last so that we get the right
946          * directory timestamps.  */
947         ret = start_file_metadata_phase(&ctx->common, dir_count);
948         if (ret)
949                 goto out;
950
951         ret = unix_set_dir_metadata(dentry_list, ctx);
952         if (ret)
953                 goto out;
954
955         ret = end_file_metadata_phase(&ctx->common);
956         if (ret)
957                 goto out;
958
959         if (ctx->num_special_files_ignored) {
960                 WARNING("%lu special files were not extracted due to EPERM!",
961                         ctx->num_special_files_ignored);
962         }
963 out:
964         for (unsigned i = 0; i < NUM_PATHBUFS; i++)
965                 FREE(ctx->pathbufs[i]);
966         FREE(ctx->target_abspath);
967         return ret;
968 }
969
970 const struct apply_operations unix_apply_ops = {
971         .name                   = "UNIX",
972         .get_supported_features = unix_get_supported_features,
973         .extract                = unix_extract,
974         .context_size           = sizeof(struct unix_apply_ctx),
975 };