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